Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(studio): localize remaining UI text and enforce i18n checks (#6292)
yufengf5ea83b647c5
diff --git a/web-studio/CONTRIBUTING_CN.md b/web-studio/CONTRIBUTING_CN.mdindex 51eedfd2c..7cecf0450 100644--- a/web-studio/CONTRIBUTING_CN.md+++ b/web-studio/CONTRIBUTING_CN.md@@ -112,7 +112,18 @@ i18n.language.startsWith('zh') ? '刷新' : 'Refresh'- 较长的中文在支持的页面宽度下不会遮挡数值或控件。- 解析器或本地化适配器会影响运行结果时,有对应的目标测试。-当前配置的 `i18next/no-literal-string` ESLint 规则可以发现不少 JSX 字面量,但无法覆盖所有 TypeScript 工具函数、条件表达式、服务端响应和动态生成的标签。因此,Lint 只是检查项之一,不能证明功能已经完整本地化。+国际化检查以错误级别运行,覆盖所有业务 TypeScript/TSX 和 `components/ui`。测试、生成代码及语言资源不参与硬编码检查。++- `i18next/no-literal-string` 检查 JSX 文本以及标题、占位符、帮助文字和无障碍标签。+- `studio-i18n/no-literal-message` 检查 `Error`、`OvClientError`、非取消型 `DOMException`、Toast、错误状态 setter,以及 JSX 中模板字符串的固定文案;也会追踪消息参数引用的本地 `const` 常量。+- `studio-i18n/explicit-locale` 禁止显示日期和数字时省略 locale。组件可使用当前 `i18n.resolvedLanguage`,公共工具可使用 `#/i18n/format`。独立组件还应通过 `useTranslation()` 订阅语言变化。+- 全量语言包测试检查键集合、空翻译和插值变量一致性;编辑器测试检查切换语言后文档、选区和撤销历史不丢失。++`npm run build` 会先运行 Lint 和 `npm run test:i18n`,检查失败时构建终止。`npm run lint` 同样会执行上述规则。++命令、文件名、技术标识符和开发者诊断信息确实需要保留原样时,应在对应行使用 `eslint-disable-next-line`,指明具体规则并用 `--` 写明原因;不要整文件禁用。`AbortError` 是取消控制流信号,可保留原值。++静态检查无法判断任意服务端输出、跨模块数据流和第三方组件的全部显示文案。仍须审查动态标签和服务端枚举,并进行双语界面验收。原始诊断可保留,但面向用户的摘要必须本地化。## 验证@@ -122,6 +133,7 @@ i18n.language.startsWith('zh') ? '刷新' : 'Refresh'cd web-studionpm run formatnpm run lint+npm run test:i18nnpm test -- <relevant-test-files>```diff --git a/web-studio/eslint.config.js b/web-studio/eslint.config.jsindex 5341fda43..0b6de214f 100644--- a/web-studio/eslint.config.js+++ b/web-studio/eslint.config.js@@ -2,33 +2,55 @@import { tanstackConfig } from '@tanstack/eslint-config'import i18next from 'eslint-plugin-i18next'+import studioI18n from './script/eslint-i18n.mjs'const LINT_FILES = ['src/**/*.{ts,tsx}']-const GENERATED_IGNORES = ['src/gen/**', 'src/routeTree.gen.ts', 'src/components/ui/**']+const GENERATED_IGNORES = ['src/gen/**', 'src/routeTree.gen.ts']+const I18N_IGNORES = [+ ...GENERATED_IGNORES,+ 'src/**/*.test.{ts,tsx}',+ 'src/test/**',+ 'src/i18n/locales/**',+]export default [...tanstackConfig.map((config) => ({...config,files: LINT_FILES,- ignores: [...(config.ignores ?? []), ...GENERATED_IGNORES],+ ignores: [+ ...(config.ignores ?? []),+ ...GENERATED_IGNORES,+ 'src/components/ui/**',+ ],})),{- files: ['src/components/**/*.tsx', 'src/routes/**/*.tsx'],- ignores: GENERATED_IGNORES,+ files: LINT_FILES,+ ignores: I18N_IGNORES,+ languageOptions: tanstackConfig.find(+ (config) => config.name === 'tanstack/javascript',+ ).languageOptions,plugins: {i18next,+ 'studio-i18n': studioI18n,},rules: {- 'i18next/no-literal-string': ['warn', {- framework: 'react',- mode: 'jsx-only',- 'jsx-components': {- exclude: ['^Trans$'],- },- 'jsx-attributes': {- include: ['^(title|placeholder|label|tooltip|description|aria-label|aria-description)$'],+ 'studio-i18n/no-literal-message': 'error',+ 'studio-i18n/explicit-locale': 'error',+ 'i18next/no-literal-string': [+ 'error',+ {+ framework: 'react',+ mode: 'jsx-only',+ 'jsx-components': {+ exclude: ['^Trans$'],+ },+ 'jsx-attributes': {+ include: [+ '^(title|placeholder|label|tooltip|description|alt|aria-label|aria-description|ariaLabel|helperText|emptyText)$',+ ],+ },},- }],+ ],},},{diff --git a/web-studio/package.json b/web-studio/package.jsonindex 7da667e94..02d3e076b 100644--- a/web-studio/package.json+++ b/web-studio/package.json@@ -10,10 +10,12 @@"build": "vite build","preview": "vite preview","test": "vitest run",- "lint": "eslint src --ignore-pattern 'src/gen/**' --ignore-pattern 'src/routeTree.gen.ts' --ignore-pattern 'src/components/ui/**'",+ "lint": "eslint src --ignore-pattern 'src/gen/**' --ignore-pattern 'src/routeTree.gen.ts'","format": "prettier --check 'src/**/*.{ts,tsx}'",- "check": "prettier --write 'src/**/*.{ts,tsx}' && eslint src --fix --ignore-pattern 'src/gen/**' --ignore-pattern 'src/routeTree.gen.ts' --ignore-pattern 'src/components/ui/**'",- "gen-server-client": "sh ./script/gen-server-client/gen-server-client.sh"+ "check": "prettier --write 'src/**/*.{ts,tsx}' && eslint src --fix --ignore-pattern 'src/gen/**' --ignore-pattern 'src/routeTree.gen.ts'",+ "gen-server-client": "sh ./script/gen-server-client/gen-server-client.sh",+ "test:i18n": "vitest run src/i18n src/components/code-editor.test.tsx script/eslint-i18n.test.ts",+ "prebuild": "npm run lint && npm run test:i18n"},"dependencies": {"@base-ui/react": "^1.3.0",diff --git a/web-studio/script/eslint-i18n.d.mts b/web-studio/script/eslint-i18n.d.mtsnew file mode 100644index 000000000..5686e9c7c--- /dev/null+++ b/web-studio/script/eslint-i18n.d.mts@@ -0,0 +1,7 @@+import type { Rule } from 'eslint'++export const noLiteralMessage: Rule.RuleModule+export const explicitLocale: Rule.RuleModule++declare const plugin: { rules: Record<string, Rule.RuleModule> }+export default plugindiff --git a/web-studio/script/eslint-i18n.mjs b/web-studio/script/eslint-i18n.mjsnew file mode 100644index 000000000..a275f54f7--- /dev/null+++ b/web-studio/script/eslint-i18n.mjs@@ -0,0 +1,198 @@+// Checks semantic message boundaries outside JSX. Arbitrary protocol strings,+// user content and server diagnostics are deliberately not translated here.+function literalText(node) {+ if (!node) return false+ if (node.type === 'Literal')+ return typeof node.value === 'string' && /\p{L}/u.test(node.value)+ if (node.type === 'TemplateLiteral')+ return node.quasis.some((part) =>+ /\p{L}/u.test(part.value.cooked ?? part.value.raw),+ )+ if (node.type === 'ConditionalExpression')+ return literalText(node.consequent) || literalText(node.alternate)+ if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression')+ return literalText(node.left) || literalText(node.right)+ return false+}++export const noLiteralMessage = {+ meta: {+ type: 'problem',+ schema: [],+ messages: {+ translate:+ 'Move user-visible messages to both language resources and use t(). For internal diagnostics, disable this rule on the line with a reason.',+ },+ },+ create(context) {+ function check(node, reportNode = node) {+ const seen = new Set()+ function containsText(value) {+ if (!value || seen.has(value)) return false+ seen.add(value)+ if (value.type === 'Identifier') {+ for (+ let scope = context.sourceCode.getScope(value);+ scope;+ scope = scope.upper+ ) {+ const variable = scope.set.get(value.name)+ if (!variable) continue+ const definition = variable.defs[0]+ return (+ definition?.parent?.kind === 'const' &&+ containsText(definition.node.init)+ )+ }+ }+ if (value.type === 'ConditionalExpression')+ return containsText(value.consequent) || containsText(value.alternate)+ if (+ value.type === 'LogicalExpression' ||+ value.type === 'BinaryExpression'+ )+ return containsText(value.left) || containsText(value.right)+ return literalText(value)+ }+ if (containsText(node))+ context.report({ node: reportNode, messageId: 'translate' })+ }+ return {+ JSXExpressionContainer(node) {+ const parent = node.parent+ if (+ parent.type === 'JSXAttribute' &&+ !/^(title|placeholder|label|tooltip|description|alt|aria-label|aria-description|ariaLabel|helperText|emptyText)$/.test(+ parent.name.name,+ )+ )+ return+ // The upstream JSX rule handles literals. Also check template fragments+ // without mistaking interpolated identifiers or translation keys for text.+ function template(expr) {+ if (expr.type === 'TemplateLiteral') check(expr)+ else if (expr.type === 'ConditionalExpression') {+ template(expr.consequent)+ template(expr.alternate)+ } else if (expr.type === 'LogicalExpression') {+ template(expr.left)+ template(expr.right)+ }+ }+ template(node.expression)+ },+ NewExpression(node) {+ if (+ node.callee.type === 'Identifier' &&+ ['Error', 'DOMException', 'OvClientError'].includes(node.callee.name)+ ) {+ // AbortError is a control-flow signal, never a user-facing failure.+ if (+ node.callee.name === 'DOMException' &&+ node.arguments[1]?.value === 'AbortError'+ )+ return+ const arg = node.arguments[0]+ if (arg?.type === 'ObjectExpression') {+ for (const prop of arg.properties) {+ if (+ prop.type === 'Property' &&+ (prop.key.name ?? prop.key.value) === 'message'+ )+ check(prop.value, node)+ }+ } else check(arg, node)+ }+ },+ CallExpression(node) {+ const callee = node.callee+ if (+ callee.type === 'Identifier' &&+ /^set\w*(Error|Message)$/.test(callee.name)+ )+ check(node.arguments[0])+ if (+ (callee.type === 'Identifier' && callee.name === 'toast') ||+ (callee.type === 'MemberExpression' &&+ callee.object.type === 'Identifier' &&+ callee.object.name === 'toast' &&+ (callee.computed ? callee.property.value : callee.property.name) !==+ 'dismiss')+ ) {+ check(node.arguments[0])+ const options = node.arguments[1]+ if (options?.type === 'ObjectExpression') {+ for (const prop of options.properties) {+ if (+ prop.type === 'Property' &&+ (prop.key.name ?? prop.key.value) === 'description'+ )+ check(prop.value)+ }+ }+ }+ },+ }+ },+}++export const explicitLocale = {+ meta: {+ type: 'problem',+ schema: [],+ messages: {+ locale:+ 'Display dates and numbers with the Studio language (or use #/i18n/format), not the browser default.',+ },+ },+ create(context) {+ return {+ CallExpression(node) {+ const callee = node.callee+ const dateMethod =+ callee.type === 'MemberExpression' &&+ !callee.computed &&+ /^toLocale(String|DateString|TimeString)$/.test(callee.property.name)+ const intlFormat =+ callee.type === 'MemberExpression' &&+ callee.object.name === 'Intl' &&+ /^(DateTimeFormat|NumberFormat|RelativeTimeFormat|ListFormat)$/.test(+ callee.property.name,+ )+ if (!dateMethod && !intlFormat) return+ const locale = node.arguments[0]+ if (+ !locale ||+ (locale.type === 'Identifier' && locale.name === 'undefined') ||+ (locale.type === 'ArrayExpression' && !locale.elements.length)+ ) {+ context.report({ node, messageId: 'locale' })+ }+ },+ NewExpression(node) {+ if (+ node.callee.type !== 'MemberExpression' ||+ node.callee.object.name !== 'Intl' ||+ !/^(DateTimeFormat|NumberFormat|RelativeTimeFormat|ListFormat)$/.test(+ node.callee.property.name,+ )+ )+ return+ const locale = node.arguments[0]+ if (+ !locale ||+ (locale.type === 'Identifier' && locale.name === 'undefined') ||+ (locale.type === 'ArrayExpression' && !locale.elements.length)+ )+ context.report({ node, messageId: 'locale' })+ },+ }+ },+}++export default {+ rules: {+ 'no-literal-message': noLiteralMessage,+ 'explicit-locale': explicitLocale,+ },+}diff --git a/web-studio/script/eslint-i18n.test.ts b/web-studio/script/eslint-i18n.test.tsnew file mode 100644index 000000000..ead581423--- /dev/null+++ b/web-studio/script/eslint-i18n.test.ts@@ -0,0 +1,140 @@+import { ESLint, Linter } from 'eslint'+import { describe, expect, it } from 'vitest'+import plugin from './eslint-i18n.mjs'++function check(code: string, rule: string) {+ return new Linter().verify(code, [+ {+ languageOptions: {+ ecmaVersion: 'latest',+ sourceType: 'module',+ parserOptions: { ecmaFeatures: { jsx: true } },+ },+ plugins: { 'studio-i18n': plugin },+ rules: { [`studio-i18n/${rule}`]: 'error' },+ },+ ])+}++describe('i18n lint boundaries', () => {+ it.each([+ 'throw new Error("Failed to save")',+ 'toast.error(`Could not save ${name}`)',+ 'toast("Upload failed")',+ 'toast(t("failed"), { description: "Try again" })',+ 'const message = "Upload failed"; toast(message)',+ 'toast.success(ok ? "Saved" : "Skipped")',+ 'toast.error(t("failed"), { description: "Try again" })',+ 'const message = "Failed to save"; throw new Error(message)',+ 'const first = "Failed"; const second = first; toast.error(second)',+ 'new OvClientError({ code: "FAILED", message: "Failed to save" })',+ 'setError("Invalid value")',+ 'const v = <span>{`Found ${count} results`}</span>',+ 'const v = <button aria-label={`Delete ${name}`} />',+ ])('rejects a hardcoded message: %s', (code) => {+ const messages = check(code, 'no-literal-message')+ expect(+ messages.some((m) => m.ruleId === 'studio-i18n/no-literal-message'),+ ).toBe(true)+ })++ it('reports both hardcoded title and description in a direct toast call', () => {+ const messages = check(+ 'toast("Upload failed", { description: "Try again" })',+ 'no-literal-message',+ )+ expect(messages.map((message) => message.ruleId)).toEqual([+ 'studio-i18n/no-literal-message',+ 'studio-i18n/no-literal-message',+ ])+ })++ it.each([+ 'throw new Error(t("failed"))',+ 'toast.error(error.message)',+ 'toast(t("saved"), { description: t("details") })',+ 'toast(error.message)',+ 'toast.dismiss("upload-id")',+ 'const id = "upload-id"; toast.dismiss(id)',+ 'toast["dismiss"]("upload-id")',+ 'const a = "first"; const b = "second"; const v = <span>{`${a} · ${b}`}</span>',+ 'const v = <div className={`grid ${className}`} />',+ 'new DOMException("Aborted", "AbortError")',+ 'const command = "ov status"',+ 'const message = t("failed"); toast.error(message)',+ ])(+ 'preserves translated text, raw diagnostics and protocol strings: %s',+ (code) => {+ expect(check(code, 'no-literal-message')).toEqual([])+ },+ )++ it.each([+ 'date.toLocaleString()',+ 'date.toLocaleDateString(undefined, options)',+ 'date.toLocaleString([], options)',+ 'new Intl.NumberFormat()',+ 'Intl.DateTimeFormat()',+ ])('requires an explicit display locale: %s', (code) => {+ expect(check(code, 'explicit-locale')).toHaveLength(1)+ })++ it.each([+ 'date.toLocaleString(i18n.resolvedLanguage)',+ 'new Intl.DateTimeFormat(locale, options)',+ 'text.toLocaleLowerCase()',+ 'formatDateTime(date)',+ ])('accepts explicit locale or unrelated methods: %s', (code) => {+ expect(check(code, 'explicit-locale')).toEqual([])+ })++ it.each([+ 'src/components/ui/dialog.tsx',+ 'src/routes/__root.tsx',+ 'src/lib/clipboard.ts',+ ])(+ 'enforces i18n in the actual project config: %s',+ async (filePath) => {+ const jsx = filePath.endsWith('.tsx')+ const code = jsx+ ? 'export const value = <button title="Delete item">Delete</button>'+ : 'throw new Error("Failed to save")'+ const config: Linter.Config = await new ESLint().calculateConfigForFile(+ filePath,+ )+ const rule = jsx+ ? 'i18next/no-literal-string'+ : 'studio-i18n/no-literal-message'+ const rules = config.rules ?? {}+ const setting = rules[rule]+ expect(Array.isArray(setting) ? setting[0] : setting).toBe(2)+ // Exercise the configured i18n rules without building an unrelated full+ // TypeScript program for each synthetic snippet.+ const messages = new Linter().verify(+ code,+ [+ {+ files: ['**/*.{ts,tsx}'],+ languageOptions: {+ parser: config.languageOptions?.parser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ },+ plugins: config.plugins,+ rules: Object.fromEntries(+ Object.entries(rules).filter(+ ([key]) =>+ key.startsWith('i18next/') || key.startsWith('studio-i18n/'),+ ),+ ),+ },+ ],+ { filename: filePath },+ )+ expect(+ messages.filter((m) => m.ruleId === rule && m.severity === 2).length,+ JSON.stringify(messages),+ ).toBeGreaterThan(0)+ },+ 15000,+ )+})diff --git a/web-studio/src/components/code-editor.test.tsx b/web-studio/src/components/code-editor.test.tsxnew file mode 100644index 000000000..b58685e04--- /dev/null+++ b/web-studio/src/components/code-editor.test.tsx@@ -0,0 +1,126 @@+// @vitest-environment jsdom+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'+import { afterEach, beforeEach, expect, it } from 'vitest'+import { EditorView } from '@codemirror/view'+import { gotoLine, openSearchPanel } from '@codemirror/search'+import { undoDepth } from '@codemirror/commands'+import i18n from '#/i18n'+import { useTranslation } from 'react-i18next'+import { CodeEditor } from './code-editor'++// jsdom has no layout engine; CodeMirror still schedules range measurements.+beforeEach(() => {+ Object.defineProperty(Range.prototype, 'getClientRects', {+ configurable: true,+ value: () => [],+ })+ Object.defineProperty(Range.prototype, 'getBoundingClientRect', {+ configurable: true,+ value: () => new DOMRect(),+ })+})++function LocalizedEditor() {+ const { t } = useTranslation('studio')+ return (+ <CodeEditor+ initialContent="alpha"+ filename="sample.txt"+ ariaLabel={t('codeEditor.find')}+ enableLanguageSupport={false}+ />+ )+}++afterEach(async () => {+ cleanup()+ await i18n.changeLanguage('en')+})++it('switches the search panel language without losing editor content, selection or undo history', async () => {+ await i18n.changeLanguage('en')+ const { container } = render(<LocalizedEditor />)+ await waitFor(() =>+ expect(container.querySelector('.cm-editor')).not.toBeNull(),+ )+ const view = EditorView.findFromDOM(+ container.querySelector<HTMLElement>('.cm-editor')!,+ )!+ act(() => {+ view.dispatch({+ changes: { from: 5, insert: ' beta' },+ selection: { anchor: 10 },+ })+ openSearchPanel(view)+ })+ expect(screen.getByPlaceholderText('Find')).toBeTruthy()+ const history = undoDepth(view.state)+ await act(async () => {+ await i18n.changeLanguage('zh-CN')+ })+ expect(screen.getByPlaceholderText('查找')).toBeTruthy()+ expect(+ EditorView.findFromDOM(container.querySelector<HTMLElement>('.cm-editor')!),+ ).toBe(view)+ expect(view.state.doc.toString()).toBe('alpha beta')+ expect(view.state.selection.main.anchor).toBe(10)+ expect(undoDepth(view.state)).toBe(history)+ await act(async () => {+ await i18n.changeLanguage('en')+ })+ expect(screen.getByPlaceholderText('Find')).toBeTruthy()+})++it('localizes an open goto dialog while preserving the draft, selection and navigation', async () => {+ await i18n.changeLanguage('en')+ const { container } = render(+ <CodeEditor+ initialContent={'one\ntwo\nthree'}+ filename="sample.txt"+ enableLanguageSupport={false}+ />,+ )+ await waitFor(() =>+ expect(container.querySelector('.cm-editor')).not.toBeNull(),+ )+ const view = EditorView.findFromDOM(+ container.querySelector<HTMLElement>('.cm-editor')!,+ )!+ act(() => {+ gotoLine(view)+ })+ const input = screen.getByRole<HTMLInputElement>('textbox', {+ name: 'Go to line:',+ })+ fireEvent.change(input, { target: { value: '3' } })+ input.setSelectionRange(0, 1)+ await act(async () => {+ await i18n.changeLanguage('zh-CN')+ })+ const translated = screen.getByRole<HTMLInputElement>('textbox', {+ name: '跳转到行:',+ })+ expect(translated.value).toBe('3')+ expect(translated.selectionStart).toBe(0)+ expect(translated.selectionEnd).toBe(1)+ expect(screen.getByRole('button', { name: '跳转' })).toBeTruthy()+ await act(async () => {+ await i18n.changeLanguage('en')+ })+ expect(+ screen.getByRole<HTMLInputElement>('textbox', { name: 'Go to line:' })+ .value,+ ).toBe('3')+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'go' }))+ })+ expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(3)+ expect(screen.queryByRole('textbox', { name: 'Go to line:' })).toBeNull()+})diff --git a/web-studio/src/components/code-editor.tsx b/web-studio/src/components/code-editor.tsxindex a19045dcc..c8328375f 100644--- a/web-studio/src/components/code-editor.tsx+++ b/web-studio/src/components/code-editor.tsx@@ -1,7 +1,16 @@-import { useEffect, useRef, useImperativeHandle, forwardRef } from 'react'+import { editorPhrases } from '#/i18n/editor-phrases'+import { useTranslation } from 'react-i18next'+import {+ useEffect,+ useMemo,+ useRef,+ useImperativeHandle,+ forwardRef,+} from 'react'import { Compartment, EditorState } from '@codemirror/state'import {EditorView,+ getDialog,keymap,lineNumbers,highlightActiveLine,@@ -150,6 +159,14 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(},ref,) {+ const { t } = useTranslation('studio')+ const phrases = useMemo(() => editorPhrases(t), [t])+ const phrasesRef = useRef(phrases)+ phrasesRef.current = phrases+ const phrasesCompartment = useRef(new Compartment())+ const attributesRef = useRef(ariaLabel)+ attributesRef.current = ariaLabel+ const attributesCompartment = useRef(new Compartment())const containerRef = useRef<HTMLDivElement>(null)const viewRef = useRef<EditorView | null>(null)const onChangeRef = useRef(onChange)@@ -176,9 +193,6 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(drawSelection(),syntaxHighlighting(defaultHighlightStyle, { fallback: true }),history(),- EditorView.contentAttributes.of(- ariaLabel ? { 'aria-label': ariaLabel } : {},- ),EditorView.updateListener.of((update) => {if (update.docChanged && !syncingRef.current)onChangeRef.current?.(update.state.doc.toString())@@ -255,6 +269,16 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(if (destroyed) returnextensions.push(+ phrasesCompartment.current.of(+ EditorState.phrases.of(phrasesRef.current),+ ),+ attributesCompartment.current.of(+ EditorView.contentAttributes.of(+ attributesRef.current+ ? { 'aria-label': attributesRef.current }+ : {},+ ),+ ),accessRef.current.of(accessExtensions(readOnlyRef.current)),)const state = EditorState.create({@@ -284,9 +308,65 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(isDark,lineWrapping,language,- ariaLabel,])+ useEffect(() => {+ const view = viewRef.current+ if (!view) return+ // CodeMirror's built-in gotoLine dialog captures its text and initial+ // value when opened. Phrase reconfiguration recreates that panel from+ // the old configuration, so restore its draft and refresh captured text.+ const input = getDialog(+ view,+ 'cm-dialog',+ )?.dom.querySelector<HTMLInputElement>('input[name="line"]')+ const draft = input+ ? {+ value: input.value,+ start: input.selectionStart,+ end: input.selectionEnd,+ direction: input.selectionDirection,+ }+ : undefined+ const activeElement = view.dom.ownerDocument.activeElement+ view.dispatch({+ effects: [+ attributesCompartment.current.reconfigure(+ EditorView.contentAttributes.of(+ ariaLabel ? { 'aria-label': ariaLabel } : {},+ ),+ ),+ phrasesCompartment.current.reconfigure(+ EditorState.phrases.of(phrases),+ ),+ ],+ })+ if (!draft) return+ const panel = getDialog(view, 'cm-dialog')?.dom+ const nextInput =+ panel?.querySelector<HTMLInputElement>('input[name="line"]')+ if (!nextInput) return+ nextInput.value = draft.value+ nextInput.setSelectionRange(+ draft.start,+ draft.end,+ draft.direction ?? undefined,+ )+ const label = nextInput.closest('label')?.firstChild+ if (label?.nodeType === Node.TEXT_NODE)+ label.textContent = `${view.state.phrase('Go to line')}: `+ const submit = panel?.querySelector<HTMLButtonElement>(+ 'button[type="submit"]',+ )+ if (submit) submit.textContent = view.state.phrase('go')+ if (activeElement === input) nextInput.focus()+ else if (+ activeElement instanceof HTMLElement &&+ activeElement.isConnected+ )+ activeElement.focus()+ }, [ariaLabel, phrases])+useEffect(() => {const view = viewRef.currentif (!view || view.state.doc.toString() === initialContent) returndiff --git a/web-studio/src/components/studio-setup.test.tsx b/web-studio/src/components/studio-setup.test.tsxindex ef21995ff..4b4ec9ef5 100644--- a/web-studio/src/components/studio-setup.test.tsx+++ b/web-studio/src/components/studio-setup.test.tsx@@ -306,7 +306,7 @@ it('offers the local development service when only a hosted link is saved', () =fireEvent.click(screen.getByLabelText('studio:providers.opensource'))expect(screen.getByRole('combobox', { name: 'connectionChoice' }).textContent,- ).toContain('Local OpenViking')+ ).toContain('studio:localConnection')expect(screen.getAllByTitle('http://127.0.0.1:1933').length).toBeGreaterThan(0,)diff --git a/web-studio/src/components/studio-setup.tsx b/web-studio/src/components/studio-setup.tsxindex 9fd9cd901..89c0696b1 100644--- a/web-studio/src/components/studio-setup.tsx+++ b/web-studio/src/components/studio-setup.tsx@@ -124,7 +124,7 @@ export function StudioSetup({) {profiles.push({id: 'local-openviking',- name: 'Local OpenViking',+ name: 'local-openviking',connection: {...newConnectionDraft('opensource'),baseUrl: 'http://127.0.0.1:1933',@@ -171,9 +171,16 @@ export function StudioSetup({Partial<Record<(typeof PROVIDERS)[number][0], string>>>({})const [verified, setVerified] = useState<ConnectionDraft | null>(null)- const providerConnections = savedConnections.filter(- (profile) => profile.connection.serviceSelection === draft.serviceSelection,- )+ const providerConnections = savedConnections+ .map((profile) =>+ profile.id === 'local-openviking'+ ? { ...profile, name: t('studio:localConnection') }+ : profile,+ )+ .filter(+ (profile) =>+ profile.connection.serviceSelection === draft.serviceSelection,+ )const selectedProfile = providerConnections.find((profile) => profile.id === selectedConnectionId,)diff --git a/web-studio/src/components/ui/dialog.tsx b/web-studio/src/components/ui/dialog.tsxindex f631f5ef3..1f0bb7ec3 100644--- a/web-studio/src/components/ui/dialog.tsx+++ b/web-studio/src/components/ui/dialog.tsx@@ -100,6 +100,7 @@ function DialogFooter({}: React.ComponentProps<"div"> & {showCloseButton?: boolean}) {+ const { t } = useTranslation('common')return (<divdata-slot="dialog-footer"@@ -112,7 +113,7 @@ function DialogFooter({{children}{showCloseButton && (<DialogPrimitive.Close render={<Button variant="outline" />}>- Close+ {t('ui.close')}</DialogPrimitive.Close>)}</div>diff --git a/web-studio/src/components/ui/pixel-blast.tsx b/web-studio/src/components/ui/pixel-blast.tsxindex 536f85d5c..147444c2a 100644--- a/web-studio/src/components/ui/pixel-blast.tsx+++ b/web-studio/src/components/ui/pixel-blast.tsx@@ -59,6 +59,7 @@ const createTouchTexture = (): TouchTexture => {canvas.width = size;canvas.height = size;const ctx = canvas.getContext('2d');+ // eslint-disable-next-line studio-i18n/no-literal-message -- Developer invariant; retain the diagnostic for debugging.if (!ctx) throw new Error('2D context not available');ctx.fillStyle = 'black';ctx.fillRect(0, 0, canvas.width, canvas.height);@@ -703,7 +704,7 @@ const PixelBlast: React.FC<PixelBlastProps> = ({ref={containerRef}className={`w-full h-full relative overflow-hidden ${className ?? ''}`}style={style}- aria-label="PixelBlast interactive background"+ aria-hidden="true"/>);};diff --git a/web-studio/src/components/ui/sidebar.tsx b/web-studio/src/components/ui/sidebar.tsxindex 703e7f803..b1703da42 100644--- a/web-studio/src/components/ui/sidebar.tsx+++ b/web-studio/src/components/ui/sidebar.tsx@@ -70,6 +70,7 @@ const SidebarContext = React.createContext<SidebarContextProps | null>(null)function useSidebar() {const context = React.useContext(SidebarContext)if (!context) {+ // eslint-disable-next-line studio-i18n/no-literal-message -- Developer invariant; retain the diagnostic for debugging.throw new Error("useSidebar must be used within a SidebarProvider.")}diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 4e8afe326..368f5a25f 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -505,6 +505,7 @@ export function summarizeConnectionIdentity(export function useAppConnection(): AppConnectionContextValue {const context = React.useContext(AppConnectionContext)if (!context) {+ // eslint-disable-next-line studio-i18n/no-literal-message -- Developer invariant; retain the diagnostic for debugging.throw new Error('useAppConnection must be used within AppConnectionProvider.',)diff --git a/web-studio/src/i18n/core.ts b/web-studio/src/i18n/core.tsnew file mode 100644index 000000000..ac3177e83--- /dev/null+++ b/web-studio/src/i18n/core.ts@@ -0,0 +1,27 @@+import i18n from 'i18next'+import LanguageDetector from 'i18next-browser-languagedetector'++import { defaultLanguage, resources, supportedLanguages } from './resources'++i18n.use(LanguageDetector).init({+ defaultNS: 'common',+ fallbackLng: defaultLanguage,+ interpolation: {+ escapeValue: false,+ },+ ns: Object.keys(resources[defaultLanguage]),+ resources,+ returnNull: false,+ supportedLngs: supportedLanguages,+})++export default i18n++function syncDocumentLanguage() {+ if (typeof document !== 'undefined') {+ document.documentElement.lang = i18n.resolvedLanguage ?? defaultLanguage+ }+}++i18n.on('languageChanged', syncDocumentLanguage)+syncDocumentLanguage()diff --git a/web-studio/src/i18n/editor-phrases.ts b/web-studio/src/i18n/editor-phrases.tsnew file mode 100644index 000000000..e3e57026e--- /dev/null+++ b/web-studio/src/i18n/editor-phrases.ts@@ -0,0 +1,35 @@+import type { TFunction } from 'i18next'++// CodeMirror requires its English phrases as protocol keys. Keep those keys+// in this adapter; the language resources use semantic keys.+export function editorPhrases(t: TFunction<'studio'>): Record<string, string> {+ return {+ Completions: t('codeEditor.completions'),+ 'Folded lines': t('codeEditor.foldedLines'),+ 'Unfolded lines': t('codeEditor.unfoldedLines'),+ to: t('codeEditor.to'),+ 'folded code': t('codeEditor.foldedCode'),+ unfold: t('codeEditor.unfold'),+ 'Fold line': t('codeEditor.foldLine'),+ 'Unfold line': t('codeEditor.unfoldLine'),+ 'Selection deleted': t('codeEditor.selectionDeleted'),+ 'Control character': t('codeEditor.controlCharacter'),+ Find: t('codeEditor.find'),+ Replace: t('codeEditor.replaceInput'),+ next: t('codeEditor.next'),+ previous: t('codeEditor.previous'),+ all: t('codeEditor.selectAll'),+ 'match case': t('codeEditor.matchCase'),+ regexp: t('codeEditor.regexp'),+ 'by word': t('codeEditor.wholeWord'),+ replace: t('codeEditor.replace'),+ 'replace all': t('codeEditor.replaceAll'),+ close: t('codeEditor.close'),+ 'Go to line': t('codeEditor.goToLine'),+ go: t('codeEditor.go'),+ 'current match': t('codeEditor.currentMatch'),+ 'on line': t('codeEditor.onLine'),+ 'replaced match on line $': t('codeEditor.replacedOnLine'),+ 'replaced $ matches': t('codeEditor.replacedMatches'),+ }+}diff --git a/web-studio/src/i18n/format.ts b/web-studio/src/i18n/format.tsnew file mode 100644index 000000000..79a11861d--- /dev/null+++ b/web-studio/src/i18n/format.ts@@ -0,0 +1,12 @@+import i18n from './core'++export function formatNumber(value: number): string {+ return value.toLocaleString(i18n.resolvedLanguage ?? i18n.language)+}++export function formatDateTime(+ value: Date,+ options?: Intl.DateTimeFormatOptions,+): string {+ return value.toLocaleString(i18n.resolvedLanguage ?? i18n.language, options)+}diff --git a/web-studio/src/i18n/index.ts b/web-studio/src/i18n/index.tsindex a8adc79e3..5da961768 100644--- a/web-studio/src/i18n/index.ts+++ b/web-studio/src/i18n/index.ts@@ -1,22 +1,8 @@-import i18n from 'i18next'import { initReactI18next } from 'react-i18next'-import LanguageDetector from 'i18next-browser-languagedetector'+import i18n from './core'-import { defaultLanguage, resources, supportedLanguages } from './resources'--i18n- .use(LanguageDetector)- .use(initReactI18next)- .init({- defaultNS: 'common',- fallbackLng: defaultLanguage,- interpolation: {- escapeValue: false,- },- ns: Object.keys(resources[defaultLanguage]),- resources,- returnNull: false,- supportedLngs: supportedLanguages,- })+// The framework-independent instance is also used by API and formatting helpers.+// Attach the React adapter once at the application entry point.+initReactI18next.init(i18n)export default i18ndiff --git a/web-studio/src/i18n/locales/en/studio.ts b/web-studio/src/i18n/locales/en/studio.tsindex 3417cdee3..217b04ace 100644--- a/web-studio/src/i18n/locales/en/studio.ts+++ b/web-studio/src/i18n/locales/en/studio.ts@@ -1,4 +1,75 @@const studio = {+ duration: { milliseconds: '{{value}}ms', seconds: '{{value}}s' },+ errors: {+ botHealth: 'Bot health check failed ({{status}})',+ botSteer: 'Bot steer failed ({{status}})',+ botInterrupt: 'Bot interrupt failed ({{status}})',+ expectedEventStream: 'Expected {{contentType}} response',+ sseFailed: 'SSE request failed ({{status}}): {{detail}}',+ imageLoadFailed: 'Image failed to load',+ invalidMessage: '{{location}}: invalid message',+ sessionMessages: 'Session messages',+ messageLocation: '{{location}}, message {{index}}',+ invalidJsonl: '{{archiveId}}: expected JSONL content',+ archiveLine: '{{archiveId}}: line {{index}}',+ invalidJson: '{{location}}: invalid JSON',+ clipboardUnavailable: 'Clipboard is unavailable',+ clipboardFailed: 'Clipboard copy failed',+ missingServerUrl: 'Missing server URL',+ invalidServerUrl: 'Invalid server URL',+ connectionChanged: 'Active request belongs to a different connection',+ noActiveRequest: 'Session has no active request to steer',+ inputRejected: 'Bot did not accept the input',+ restartTimeout: 'Restart timed out',+ modelResponseUnavailable: 'Model configuration response is unavailable',+ invalidTaskResponse: 'Invalid task response',+ invalidDirectoryResponse: 'Invalid fs/ls response',+ emptyBlob: 'empty blob',+ invalidSvg: 'Mermaid returned invalid SVG markup.',+ invalidConfigObject: 'ov.conf must contain a JSON object',+ configUpdateFailed: 'Could not update ov.conf',+ gatewayUnavailable: 'Gateway is unavailable for this connection',+ botAccountRequired: 'Select an account before managing bots',+ waitUsage: 'Usage: /wait [--timeout seconds]',+ unknown: 'Unknown error',+ requestFailed: 'OpenViking request failed',+ sessionUriMissing: 'Session URI is missing',+ invalidFlag: 'Invalid --{{key}}: {{value}}',+ missingApiKeyHint: 'Please go to Settings and set X-API-Key.',+ httpStatus: 'Request failed with status {{status}}',+ truncated: '... (truncated, {{count}} chars total)',+ },+ codeEditor: {+ completions: 'Completions',+ foldedLines: 'Folded lines',+ unfoldedLines: 'Unfolded lines',+ to: 'to',+ foldedCode: 'folded code',+ unfold: 'unfold',+ foldLine: 'Fold line',+ unfoldLine: 'Unfold line',+ selectionDeleted: 'Selection deleted',+ controlCharacter: 'Control character',+ find: 'Find',+ replaceInput: 'Replace',+ next: 'next',+ previous: 'previous',+ selectAll: 'all',+ matchCase: 'match case',+ regexp: 'regexp',+ wholeWord: 'by word',+ replace: 'replace',+ replaceAll: 'replace all',+ close: 'close',+ goToLine: 'Go to line',+ go: 'go',+ currentMatch: 'current match',+ onLine: 'on line',+ replacedOnLine: 'replaced match on line $',+ replacedMatches: 'replaced $ matches',+ },+ oauthClient: 'MCP client',+ localConnection: 'Local OpenViking',profiles: {connectionChanged:'The connection changed. Select the identity again on the active connection.',diff --git a/web-studio/src/i18n/locales/zh-CN/studio.ts b/web-studio/src/i18n/locales/zh-CN/studio.tsindex befe7026c..f1617a46f 100644--- a/web-studio/src/i18n/locales/zh-CN/studio.ts+++ b/web-studio/src/i18n/locales/zh-CN/studio.ts@@ -1,4 +1,75 @@const studio = {+ duration: { milliseconds: '{{value}} 毫秒', seconds: '{{value}} 秒' },+ errors: {+ botHealth: 'Bot 健康检查失败({{status}})',+ botSteer: '追加 Bot 输入失败({{status}})',+ botInterrupt: '中断 Bot 失败({{status}})',+ expectedEventStream: '响应格式应为 {{contentType}}',+ sseFailed: 'SSE 请求失败({{status}}):{{detail}}',+ imageLoadFailed: '图片加载失败',+ invalidMessage: '{{location}}:消息无效',+ sessionMessages: '会话消息',+ messageLocation: '{{location}},第 {{index}} 条消息',+ invalidJsonl: '{{archiveId}}:需要 JSONL 格式内容',+ archiveLine: '{{archiveId}}:第 {{index}} 行',+ invalidJson: '{{location}}:JSON 格式无效',+ clipboardUnavailable: '剪贴板不可用',+ clipboardFailed: '复制到剪贴板失败',+ missingServerUrl: '请填写服务地址',+ invalidServerUrl: '服务地址无效',+ connectionChanged: '当前请求属于其他连接,请切换到原连接后重试',+ noActiveRequest: '当前会话没有可追加输入的请求',+ inputRejected: 'Bot 未接受本次输入',+ restartTimeout: '重启超时',+ modelResponseUnavailable: '未能获取模型配置响应',+ invalidTaskResponse: '任务响应无效',+ invalidDirectoryResponse: '目录列表响应无效',+ emptyBlob: '文件内容为空',+ invalidSvg: 'Mermaid 返回了无效的 SVG 内容。',+ invalidConfigObject: 'ov.conf 必须包含 JSON 对象',+ configUpdateFailed: '无法更新 ov.conf',+ gatewayUnavailable: '当前连接不可使用网关',+ botAccountRequired: '请先选择账号,再管理 Bot',+ waitUsage: '用法:/wait [--timeout seconds]',+ unknown: '未知错误',+ requestFailed: 'OpenViking 请求失败',+ sessionUriMissing: '缺少会话 URI',+ invalidFlag: '参数 --{{key}} 无效:{{value}}',+ missingApiKeyHint: '请前往设置配置 X-API-Key。',+ httpStatus: '请求失败,状态码:{{status}}',+ truncated: '…(已截断,共 {{count}} 个字符)',+ },+ codeEditor: {+ completions: '补全建议',+ foldedLines: '已折叠行',+ unfoldedLines: '已展开行',+ to: '至',+ foldedCode: '已折叠的代码',+ unfold: '展开',+ foldLine: '折叠行',+ unfoldLine: '展开行',+ selectionDeleted: '已删除选中内容',+ controlCharacter: '控制字符',+ find: '查找',+ replaceInput: '替换',+ next: '下一个',+ previous: '上一个',+ selectAll: '全部',+ matchCase: '区分大小写',+ regexp: '正则表达式',+ wholeWord: '全词匹配',+ replace: '替换',+ replaceAll: '全部替换',+ close: '关闭',+ goToLine: '跳转到行',+ go: '跳转',+ currentMatch: '当前匹配',+ onLine: '所在行',+ replacedOnLine: '已替换第 $ 行的匹配项',+ replacedMatches: '已替换 $ 个匹配项',+ },+ oauthClient: 'MCP 客户端',+ localConnection: '本地 OpenViking',profiles: {connectionChanged: '连接已切换,请在当前连接上重新选择身份。',identityPending: '身份待确认',diff --git a/web-studio/src/i18n/resources.test.ts b/web-studio/src/i18n/resources.test.tsnew file mode 100644index 000000000..db2f52f68--- /dev/null+++ b/web-studio/src/i18n/resources.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest'+import { resources } from './resources'++function flatten(value: unknown, prefix = ''): Record<string, string> {+ if (typeof value === 'string') return { [prefix]: value }+ return Object.assign(+ {},+ ...Object.entries(value as Record<string, unknown>).map(([key, child]) =>+ flatten(child, prefix ? `${prefix}.${key}` : key),+ ),+ )+}++function placeholders(text: string): string[] {+ return [...text.matchAll(/\{\{-?\s*([^},\s]+)[^}]*\}\}/g)]+ .map((match) => match[1])+ .sort()+}++describe('all Studio translation resources', () => {+ const english = flatten(resources.en)+ const chinese = flatten(resources['zh-CN'])++ it('registers matching keys in both languages', () => {+ expect(Object.keys(chinese).sort()).toEqual(Object.keys(english).sort())+ })++ it('has no empty translations or mismatched interpolation variables', () => {+ for (const [key, text] of Object.entries(english)) {+ expect(text.trim(), key).not.toBe('')+ expect(chinese[key].trim(), key).not.toBe('')+ expect(placeholders(chinese[key] ?? ''), key).toEqual(placeholders(text))+ }+ })+})diff --git a/web-studio/src/i18n/runtime.test.ts b/web-studio/src/i18n/runtime.test.tsnew file mode 100644index 000000000..cf897b41c--- /dev/null+++ b/web-studio/src/i18n/runtime.test.ts@@ -0,0 +1,49 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest'+import i18n from './index'+import { formatDateTime, formatNumber } from './format'+import { OvClientError, normalizeOvClientError } from '#/lib/ov-client/errors'++afterEach(async () => {+ await i18n.changeLanguage('en')+})++describe('Studio language at runtime', () => {+ it('synchronizes document language on every switch', async () => {+ for (const language of ['zh-CN', 'en']) {+ await i18n.changeLanguage(language)+ expect(document.documentElement.lang).toBe(language)+ }+ })++ it('formats dates and numbers with the UI language instead of the browser default', async () => {+ const date = new Date('2026-10-19T08:30:00Z')+ const options = { month: 'short', day: 'numeric', timeZone: 'UTC' } as const+ for (const language of ['zh-CN', 'en']) {+ await i18n.changeLanguage(language)+ expect(formatDateTime(date, options)).toBe(+ new Intl.DateTimeFormat(language, options).format(date),+ )+ expect(formatNumber(12345)).toBe(+ new Intl.NumberFormat(language).format(12345),+ )+ }+ })++ it('localizes API-key guidance and keeps server diagnostics intact', async () => {+ await i18n.changeLanguage('zh-CN')+ const error = new OvClientError({+ code: 'UNAUTHENTICATED',+ message: 'Missing API key',+ details: { trace: 'raw' },+ })+ expect(error.message).toBe('Missing API key 请前往设置配置 X-API-Key。')+ expect(error.details).toEqual({ trace: 'raw' })+ expect(normalizeOvClientError(error)).toBe(error)+ await i18n.changeLanguage('en')+ expect(+ new OvClientError({ code: 'UNAUTHENTICATED', message: 'Missing API key' })+ .message,+ ).toBe('Missing API key Please go to Settings and set X-API-Key.')+ })+})diff --git a/web-studio/src/lib/clipboard.ts b/web-studio/src/lib/clipboard.tsindex 027c8825e..7a4724cf6 100644--- a/web-studio/src/lib/clipboard.ts+++ b/web-studio/src/lib/clipboard.ts@@ -1,3 +1,5 @@+import i18n from '#/i18n/core'+export async function copyTextToClipboard(value: string): Promise<void> {try {await navigator.clipboard.writeText(value)@@ -7,7 +9,7 @@ export async function copyTextToClipboard(value: string): Promise<void> {}if (typeof document === 'undefined') {- throw new Error('Clipboard is unavailable')+ throw new Error(i18n.t('studio:errors.clipboardUnavailable'))}const textArea = document.createElement('textarea')@@ -23,7 +25,7 @@ export async function copyTextToClipboard(value: string): Promise<void> {try {const copied = document.execCommand('copy')if (!copied) {- throw new Error('Clipboard copy failed')+ throw new Error(i18n.t('studio:errors.clipboardFailed'))}} finally {document.body.removeChild(textArea)diff --git a/web-studio/src/lib/connection/health.ts b/web-studio/src/lib/connection/health.tsindex 8a0098cbf..73c9acc7d 100644--- a/web-studio/src/lib/connection/health.ts+++ b/web-studio/src/lib/connection/health.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import type { ConnectionDraft } from './types'import { createConnectionHealthHeaders } from './auth'import { getHealth } from '#/lib/ov-client'@@ -47,7 +48,7 @@ export async function fetchServerHealth(): Promise<Record<string, unknown>> {const normalizedBaseUrl = normalizeBaseUrl(baseUrl)if (!normalizedBaseUrl) {- throw new Error('Missing server URL')+ throw new Error(i18n.t('studio:errors.missingServerUrl'))}const key = JSON.stringify([diff --git a/web-studio/src/lib/connection/onboarding.ts b/web-studio/src/lib/connection/onboarding.tsindex 702b39613..55b4e4bce 100644--- a/web-studio/src/lib/connection/onboarding.ts+++ b/web-studio/src/lib/connection/onboarding.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { resolveConnectionDataRoot } from './probe'import type { ConnectionDraft } from '#/lib/connection/types'import { createConnectionHealthHeaders } from './auth'@@ -146,7 +147,7 @@ export async function verifyStudioSetup(adminApiKey: draft.adminApiKey.trim(),})if (!isValidConnectionUrl(connection.baseUrl))- throw new Error('Invalid server URL')+ throw new Error(i18n.t('studio:errors.invalidServerUrl'))if (connection.serviceSelection === 'volcengine') connection.adminApiKey = ''const health = await fetchConnectionHealth(connection, signal).catch((error: unknown) => {diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.tsindex b134bdfd6..687342499 100644--- a/web-studio/src/lib/ov-client/client.ts+++ b/web-studio/src/lib/ov-client/client.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import axios, { AxiosHeaders } from 'axios'import { resolveApiKeyAuth } from '#/lib/connection/auth'import type { InternalAxiosRequestConfig } from 'axios'@@ -229,7 +230,7 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {if (isEnvelopeError(response.data)) {const { error } = response.data- const message = error.message || 'OpenViking request failed'+ const message = error.message || i18n.t('studio:errors.requestFailed')throw new OvClientError({code: error.code || 'ERROR',diff --git a/web-studio/src/lib/ov-client/errors.ts b/web-studio/src/lib/ov-client/errors.tsindex 2c289700b..40f83c299 100644--- a/web-studio/src/lib/ov-client/errors.ts+++ b/web-studio/src/lib/ov-client/errors.ts@@ -1,8 +1,8 @@+import i18n from '#/i18n/core'import axios, { AxiosError } from 'axios'import type { OvClientErrorOptions, OvErrorEnvelope, OvResponse } from './types'-const MISSING_API_KEY_HINT = ' Please go to Settings and set X-API-Key.'const MAX_ERROR_TEXT_LENGTH = 2000function isRecord(value: unknown): value is Record<string, unknown> {@@ -17,7 +17,7 @@ function truncateText(if (text.length <= maxLength) {return text}- return `${text.slice(0, maxLength)}\n... (truncated, ${text.length} chars total)`+ return `${text.slice(0, maxLength)}\n${i18n.t('studio:errors.truncated', { count: text.length })}`}function withMissingApiKeyHint(code: string, message: string): string {@@ -25,7 +25,7 @@ function withMissingApiKeyHint(code: string, message: string): string {code === 'UNAUTHENTICATED' &&message.toLowerCase().includes('missing api key')) {- return `${message}${MISSING_API_KEY_HINT}`+ return `${message} ${i18n.t('studio:errors.missingApiKeyHint')}`}return message}@@ -99,7 +99,7 @@ export function normalizeOvClientError(error: unknown): OvClientError {details: envelope.error.details ?? envelope.error.detail,message:envelope.error.message ||- `Request failed with status ${statusCode ?? 'unknown'}`,+ i18n.t('studio:errors.httpStatus', { status: statusCode ?? i18n.t('studio:errors.unknown') }),requestId: getRequestId(axiosError.response?.headers),responseBody: rawBody,statusCode,@@ -133,7 +133,7 @@ export function normalizeOvClientError(error: unknown): OvClientError {: 'HTTP_ERROR',message:axiosError.message ||- `Request failed with status ${statusCode ?? 'unknown'}`,+ i18n.t('studio:errors.httpStatus', { status: statusCode ?? i18n.t('studio:errors.unknown') }),requestId: getRequestId(axiosError.response?.headers),responseBody: rawBody,statusCode,@@ -175,7 +175,7 @@ export function unwrapOvResponse<TResult>(response: unknown): TResult {throw new OvClientError({code: error?.code || 'ERROR',details: error?.details ?? error?.detail,- message: error?.message || 'OpenViking request failed',+ message: error?.message || i18n.t('studio:errors.requestFailed'),requestId: getRequestId(response.headers),responseBody: payload,statusCode: response.status,diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.tsindex ae6d588f0..03efed735 100644--- a/web-studio/src/lib/sessions/api.ts+++ b/web-studio/src/lib/sessions/api.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { parseSessionArchive, parseSessionMessages } from './parse-messages'import {deleteSessionBySessionId,@@ -109,7 +110,7 @@ async function fetchArchiveFileMessages(if (!session.uri) {throw new OvClientError({code: 'INVALID_SESSION_ARCHIVE',- message: 'Session URI is missing',+ message: i18n.t('studio:errors.sessionUriMissing'),})}const result = await getOvResult<unknown>(@@ -453,7 +454,7 @@ export async function fetchBotHealth(): Promise<unknown> {code: response.status === 503 ? 'BOT_MODE_DISABLED' : 'BOT_HEALTH_FAILED',message: extractErrorMessage(text,- `Bot health check failed (${response.status})`,+ i18n.t('studio:errors.botHealth', { status: response.status }),),responseBody: text,statusCode: response.status,@@ -536,7 +537,7 @@ export async function steerChatSession(code: 'BOT_STEER_FAILED',message: extractErrorMessage(text,- `Bot steer failed (${response.status})`,+ i18n.t('studio:errors.botSteer', { status: response.status }),),responseBody: text,statusCode: response.status,@@ -564,7 +565,7 @@ export async function interruptChatSession(code: 'BOT_INTERRUPT_FAILED',message: extractErrorMessage(text,- `Bot interrupt failed (${response.status})`,+ i18n.t('studio:errors.botInterrupt', { status: response.status }),),responseBody: text,statusCode: response.status,diff --git a/web-studio/src/lib/sessions/parse-messages.ts b/web-studio/src/lib/sessions/parse-messages.tsindex e93251761..8beb39461 100644--- a/web-studio/src/lib/sessions/parse-messages.ts+++ b/web-studio/src/lib/sessions/parse-messages.ts@@ -1,22 +1,23 @@+import i18n from '#/i18n/core'import { OvClientError } from '#/lib/ov-client/errors'import type { Message } from './types/message'function invalidMessage(location: string): never {throw new OvClientError({code: 'INVALID_SESSION_MESSAGE',- message: `${location}: invalid message`,+ message: i18n.t('studio:errors.invalidMessage', { location }),})}/** Both API and persisted JSONL messages cross the same validation seam. */export function parseSessionMessages(value: unknown,- location = 'Session messages',+ location = i18n.t('studio:errors.sessionMessages'),): Message[] {if (value === undefined) return []if (!Array.isArray(value)) invalidMessage(location)return value.flatMap((message: unknown, index): Message[] => {- const at = `${location}, message ${index + 1}`+ const at = i18n.t('studio:errors.messageLocation', { location, index: index + 1 })if (!message ||typeof message !== 'object' ||@@ -66,19 +67,19 @@ export function parseSessionArchive(if (typeof value !== 'string') {throw new OvClientError({code: 'INVALID_SESSION_ARCHIVE',- message: `${archiveId}: expected JSONL content`,+ message: i18n.t('studio:errors.invalidJsonl', { archiveId }),})}return value.split(/\r?\n/).flatMap((line, index) => {if (!line.trim()) return []- const at = `${archiveId}: line ${index + 1}`+ const at = i18n.t('studio:errors.archiveLine', { archiveId, index: index + 1 })let message: unknowntry {message = JSON.parse(line)} catch {throw new OvClientError({code: 'INVALID_SESSION_ARCHIVE',- message: `${at}: invalid JSON`,+ message: i18n.t('studio:errors.invalidJson', { location: at }),})}return parseSessionMessages([message], at)diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.tsindex e96f9e26e..0e4acfa40 100644--- a/web-studio/src/lib/sessions/use-chat.ts+++ b/web-studio/src/lib/sessions/use-chat.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { useCallback, useEffect, useRef, useState } from 'react'import type { ChatStatus, StreamToolCall } from './types/chat'@@ -367,12 +368,12 @@ export function useChat(options: UseChatOptions): UseChatReturn {if (abortRef.current) {const activeController = abortRef.currentif (activeConnectionRef.current !== connectionSnapshot) {- throw new Error('Active request belongs to a different connection')+ throw new Error(i18n.t('studio:errors.connectionChanged'))}setError(undefined)const appendInput = appendInputRef.currentif (!appendInput) {- throw new Error('Session has no active request to steer')+ throw new Error(i18n.t('studio:errors.noActiveRequest'))}let resolveAccepted!: (accepted: boolean) => voidconst accepted = new Promise<boolean>((resolve) => {@@ -381,7 +382,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {const appended = appendInput(userMsg, accepted)try {const result = await steerChatSession(sessionId, { message })- if (!result.accepted) throw new Error('Bot did not accept the input')+ if (!result.accepted) throw new Error(i18n.t('studio:errors.inputRejected'))resolveAccepted(true)await appended} catch (err) {diff --git a/web-studio/src/lib/sse.ts b/web-studio/src/lib/sse.tsindex 895546799..825b1abda 100644--- a/web-studio/src/lib/sse.ts+++ b/web-studio/src/lib/sse.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import {EventStreamContentType,fetchEventSource,@@ -24,8 +25,8 @@ export class SseResponseError extends Error {constructor(response: Response, responseBody: string) {super(response.ok- ? `Expected ${EventStreamContentType} response`- : `SSE request failed (${response.status}): ${responseBody}`,+ ? i18n.t('studio:errors.expectedEventStream', { contentType: EventStreamContentType })+ : i18n.t('studio:errors.sseFailed', { status: response.status, detail: responseBody }),)this.name = 'SseResponseError'this.response = responsediff --git a/web-studio/src/routes/__root.tsx b/web-studio/src/routes/__root.tsxindex 69d08b67f..5f46a54c8 100644--- a/web-studio/src/routes/__root.tsx+++ b/web-studio/src/routes/__root.tsx@@ -54,7 +54,8 @@ function DevtoolsSlot() {function RootErrorComponent({ error, reset }: ErrorComponentProps) {const { t } = useTranslation('common')- const message = error instanceof Error ? error.message : 'Unknown error'+ const message =+ error instanceof Error ? error.message : t('studio:errors.unknown')return (<>diff --git a/web-studio/src/routes/agent-experience/-lib/api.ts b/web-studio/src/routes/agent-experience/-lib/api.tsindex 408a70a13..dee0f076f 100644--- a/web-studio/src/routes/agent-experience/-lib/api.ts+++ b/web-studio/src/routes/agent-experience/-lib/api.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { getOvResult, isOvClientError, ovClient } from '#/lib/ov-client'import {@@ -39,7 +40,8 @@ export async function fetchExperiences(options: {url: '/api/v1/fs/ls',}),)- if (!Array.isArray(result)) throw new Error('Invalid fs/ls response')+ if (!Array.isArray(result))+ throw new Error(i18n.t('studio:errors.invalidDirectoryResponse'))return {items: normalizeExperienceFiles(result.slice(0, pageSize)),hasMore: result.length > pageSize,diff --git a/web-studio/src/routes/compile/-components/args-editor.tsx b/web-studio/src/routes/compile/-components/args-editor.tsxindex d3776de9b..ceb576914 100644--- a/web-studio/src/routes/compile/-components/args-editor.tsx+++ b/web-studio/src/routes/compile/-components/args-editor.tsx@@ -6,6 +6,9 @@ import { Input } from '#/components/ui/input'import { Textarea } from '#/components/ui/textarea'import { parseArgs } from '../-lib/commands'+// Copyable JSON syntax example; preserve the protocol keys and values.+const ARGS_EXAMPLE = JSON.stringify({ key: 'value' }, null, 2)+type Row = { id: number; key: string; type: string; value: string }const TYPES = ['string', 'number', 'boolean', 'json'] as constfunction decode(value: string): Row[] {@@ -142,7 +145,7 @@ export function ArgsEditor({value={value}rows={6}className="font-mono text-xs"- placeholder={JSON.stringify({ key: 'value' }, null, 2)}+ placeholder={ARGS_EXAMPLE}onChange={(e) => {emit(e.target.value)try {diff --git a/web-studio/src/routes/compile/-lib/api.ts b/web-studio/src/routes/compile/-lib/api.tsindex 92bc2e92a..7357fc64f 100644--- a/web-studio/src/routes/compile/-lib/api.ts+++ b/web-studio/src/routes/compile/-lib/api.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { getOvResult, ovClient, OvClientError } from '#/lib/ov-client'import type { TaskRecord } from '#/routes/tasks/-lib/task-record'@@ -65,8 +66,7 @@ export async function fetchCompileTasks(if (!Array.isArray(page.items))throw new OvClientError({code: 'PAGINATION_UNSUPPORTED',- message:- 'The server does not support paginated tasks. Update OpenViking and retry.',+ message: i18n.t('compile:errors.upgrade'),})return { ...page, items: page.items.map(normalizeCompileTask) }}diff --git a/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx b/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsxindex dff15cd4a..3b59a1243 100644--- a/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx+++ b/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx@@ -45,6 +45,7 @@ vi.mock('#/lib/sessions/api', () => ({sendChatStream: m.stream,addMessage: vi.fn(),serializeParts: vi.fn(),+ interruptChatSession: vi.fn().mockResolvedValue({ interrupted: false }),}))beforeEach(() => {Element.prototype.scrollIntoView = vi.fn()diff --git a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx b/web-studio/src/routes/filesystem/-components/terminal-panel.tsxindex f6cacd04e..291a9049f 100644--- a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx+++ b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { prepareCompileHandoff } from '#/routes/compile/-lib/handoff'import { useQuery } from '@tanstack/react-query'import { fetchCompileSkills } from '#/routes/compile/-lib/api'@@ -218,7 +219,10 @@ const SESSION_SUBCOMMANDS_BY_KEY = new Map()type TerminalSuggestionGroup =- TerminalCommandGroup | 'history' | 'resource' | 'subcommand'+ | TerminalCommandGroup+ | 'history'+ | 'resource'+ | 'subcommand'type TerminalSuggestion = Omit<TerminalCommandView, 'group'> & {group: TerminalSuggestionGroup@@ -334,7 +338,7 @@ function parseWaitTimeout(body: string): number | undefined {if (!trimmed) return undefinedconst match = trimmed.match(/^(?:--timeout\s+)?(\d+(?:\.\d+)?)$/)if (!match) {- throw new Error('Usage: /wait [--timeout seconds]')+ throw new Error(i18n.t('studio:errors.waitUsage'))}return Number(match[1])}@@ -390,7 +394,7 @@ function getNumberFlag(if (value === undefined || value === 'true') return undefinedconst parsed = Number(value)if (!Number.isFinite(parsed)) {- throw new Error(`Invalid --${key}: ${value}`)+ throw new Error(i18n.t('studio:errors.invalidFlag', { key, value }))}return parsed}diff --git a/web-studio/src/routes/gateway/-lib/enable-gateway.ts b/web-studio/src/routes/gateway/-lib/enable-gateway.tsindex 21343f1ed..019f2ca79 100644--- a/web-studio/src/routes/gateway/-lib/enable-gateway.ts+++ b/web-studio/src/routes/gateway/-lib/enable-gateway.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { isConfigFileObject } from '#/routes/settings/-lib/config-file-api'/** A gateway management key in the format `openviking-server init` generates. */@@ -143,7 +144,7 @@ export function enableGatewayContent(managementKey?: string,): string {if (!isConfigFileObject(content))- throw new Error('ov.conf must contain a JSON object')+ throw new Error(i18n.t('studio:errors.invalidConfigObject'))const fields: Array<[string, string]> = [['enabled', 'true']]if (managementKey)fields.push(['management_key', JSON.stringify(managementKey)])@@ -175,7 +176,8 @@ export function enableGatewayContent(let result = contentfor (const edit of edits.sort((left, right) => right.at - left.at))result = result.slice(0, edit.at) + edit.text + result.slice(edit.end)- if (!isConfigFileObject(result)) throw new Error('Could not update ov.conf')+ if (!isConfigFileObject(result))+ throw new Error(i18n.t('studio:errors.configUpdateFailed'))return result}diff --git a/web-studio/src/routes/gateway/-lib/use-gateway.ts b/web-studio/src/routes/gateway/-lib/use-gateway.tsindex 489e719a1..c2b815539 100644--- a/web-studio/src/routes/gateway/-lib/use-gateway.ts+++ b/web-studio/src/routes/gateway/-lib/use-gateway.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { useCallback, useMemo } from 'react'import { useQuery, useQueryClient } from '@tanstack/react-query'import type { UseQueryOptions } from '@tanstack/react-query'@@ -149,8 +150,7 @@ function useGatewayQuery<T>(...options,queryKey: gatewayQueryKey(scope, resource, ...params),queryFn: () => {- if (!allowed)- throw new Error('Gateway is unavailable for this connection')+ if (!allowed) throw new Error(i18n.t('studio:errors.gatewayUnavailable'))return load(connection)},enabled: allowed && options.enabled !== false,diff --git a/web-studio/src/routes/home/-components/metric-panels.tsx b/web-studio/src/routes/home/-components/metric-panels.tsxindex 8434a402f..f055579fa 100644--- a/web-studio/src/routes/home/-components/metric-panels.tsx+++ b/web-studio/src/routes/home/-components/metric-panels.tsx@@ -77,7 +77,7 @@ function MetricPanel({const tick = (now: number) => {const progress = Math.min(1, (now - startedAt) / duration)const next = current + (target - current) * easeOutCubic(progress)- el.textContent = Math.round(next).toLocaleString()+ el.textContent = formatNumber(Math.round(next))if (progress < 1) {frame = requestAnimationFrame(tick)} else {diff --git a/web-studio/src/routes/home/-components/token-trend-chart.tsx b/web-studio/src/routes/home/-components/token-trend-chart.tsxindex 89e22c1fe..a49b3b1a3 100644--- a/web-studio/src/routes/home/-components/token-trend-chart.tsx+++ b/web-studio/src/routes/home/-components/token-trend-chart.tsx@@ -110,7 +110,7 @@ export function TokenTrendChart({axisLine={false}className="text-muted-foreground"tick={{ fill: 'currentColor', fontSize: 12 }}- tickFormatter={(value) => Number(value).toLocaleString()}+ tickFormatter={(value) => formatNumber(Number(value))}tickLine={false}width="auto"/>diff --git a/web-studio/src/routes/home/-lib/format.ts b/web-studio/src/routes/home/-lib/format.tsindex a051907ad..ad1ab7bd9 100644--- a/web-studio/src/routes/home/-lib/format.ts+++ b/web-studio/src/routes/home/-lib/format.ts@@ -1,3 +1,5 @@+import i18n from '#/i18n/core'+export function asRecord(v: unknown): Record<string, unknown> {return v !== null && typeof v === 'object' && !Array.isArray(v)? (v as Record<string, unknown>)@@ -17,7 +19,7 @@ export function asString(v: unknown): string {}export function formatNumber(value: unknown): string {- return asNumber(value).toLocaleString()+ return asNumber(value).toLocaleString(i18n.resolvedLanguage ?? i18n.language)}export function parseDateKey(value: string | undefined): Date {@@ -32,6 +34,7 @@ export function getViewerTimezone(): string {// Falls back to UTC when Intl is unavailable or returns an empty string// (e.g. very old Safari, jest jsdom edge cases).try {+ // eslint-disable-next-line studio-i18n/explicit-locale -- Read the browser timezone; no date is displayed.return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'} catch {return 'UTC'@@ -73,7 +76,7 @@ export function formatShortDate(value: string): string {if (!value) return '--'const date = new Date(`${value}T00:00:00`)if (Number.isNaN(date.getTime())) return value- return date.toLocaleDateString(undefined, {+ return date.toLocaleDateString(i18n.resolvedLanguage ?? i18n.language, {day: '2-digit',month: '2-digit',})diff --git a/web-studio/src/routes/monitoring/-components/queue-status-card.tsx b/web-studio/src/routes/monitoring/-components/queue-status-card.tsxindex ed078eb60..f74cc9868 100644--- a/web-studio/src/routes/monitoring/-components/queue-status-card.tsx+++ b/web-studio/src/routes/monitoring/-components/queue-status-card.tsx@@ -1,3 +1,4 @@+import { formatNumber } from '#/i18n/format'import * as React from 'react'import { useTranslation } from 'react-i18next'import { Card, CardTitle } from '#/components/ui/card'@@ -121,7 +122,7 @@ export function QueueStatusCard({ title, status = '', isHealthy = true, customRo: 'text-muted-foreground/60',)}>- {row.completed.toLocaleString()}+ {formatNumber(row.completed)}</span>{/* 错误数 */}diff --git a/web-studio/src/routes/oauth/consent.tsx b/web-studio/src/routes/oauth/consent.tsxindex 01016274d..e56e004e4 100644--- a/web-studio/src/routes/oauth/consent.tsx+++ b/web-studio/src/routes/oauth/consent.tsx@@ -249,7 +249,9 @@ function ConsentPage() {}const clientName =- pendingInfo?.client_name || pendingInfo?.client_id || 'MCP client'+ pendingInfo?.client_name ||+ pendingInfo?.client_id ||+ t('studio:oauthClient')const fallbackHref = `/oauth/authorize/page?pending=${encodeURIComponent(pending)}`const hasAnyKey = Boolean(resolveEffectiveApiKey(identityValue, connection.apiKey),diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsxindex a58cb2909..0ec431feb 100644--- a/web-studio/src/routes/resources/-components/file-preview.tsx+++ b/web-studio/src/routes/resources/-components/file-preview.tsx@@ -1,3 +1,5 @@+import { formatDateTime } from '#/i18n/format'+import i18n from '#/i18n/core'import {isValidElement,useEffect,@@ -481,7 +483,7 @@ function MarkdownImage({if (!alive) returnconst blob = response.data as Blobif (blob.size === 0) {- throw new Error('empty blob')+ throw new Error(i18n.t('studio:errors.emptyBlob'))}created = URL.createObjectURL(blob)setObjectUrl(created)@@ -1008,7 +1010,7 @@ function formatJsonlTime(value: string): string {if (!value) return ''const date = new Date(value)if (Number.isNaN(date.getTime())) return value- return date.toLocaleString([], {+ return formatDateTime(date, {day: 'numeric',hour: '2-digit',minute: '2-digit',@@ -1529,7 +1531,7 @@ export function FilePreview({const blob = response.data as Blobif (blob.size === 0) {- throw new Error('empty blob')+ throw new Error(i18n.t('studio:errors.emptyBlob'))}const nextUrl = URL.createObjectURL(blob)@@ -1928,7 +1930,9 @@ export function FilePreview({src={imageSrc}alt={file.name}className="max-h-[70vh] max-w-full rounded-md object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"- onError={() => setImageError('direct img failed')}+ onError={() =>+ setImageError(t('studio:errors.imageLoadFailed'))+ }/>{imageError ? (<div className="text-xs text-muted-foreground">diff --git a/web-studio/src/routes/resources/-components/mermaid-diagram.tsx b/web-studio/src/routes/resources/-components/mermaid-diagram.tsxindex d60ea0a1e..080afd785 100644--- a/web-studio/src/routes/resources/-components/mermaid-diagram.tsx+++ b/web-studio/src/routes/resources/-components/mermaid-diagram.tsx@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { mermaid } from '@streamdown/mermaid'import { Loader2, TriangleAlert } from 'lucide-react'import { useEffect, useId, useRef, useState } from 'react'@@ -13,7 +14,7 @@ function prepareSvg(svg: string): { svg: string; width: number } {const document = new DOMParser().parseFromString(svg, 'image/svg+xml')const root = document.documentElementif (root.localName !== 'svg') {- throw new Error('Mermaid returned invalid SVG markup.')+ throw new Error(i18n.t('studio:errors.invalidSvg'))}const viewBox = rootdiff --git a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsxindex a7d40a4eb..a37e95dee 100644--- a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx+++ b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx@@ -196,6 +196,7 @@ function createRemoteTaskName(url: string): string {export function useResourceUpload(): ResourceUploadContextValue {const context = React.useContext(ResourceUploadContext)if (!context) {+ // eslint-disable-next-line studio-i18n/no-literal-message -- Developer invariant; retain the diagnostic for debugging.throw new Error('useResourceUpload must be used within ResourceUploadProvider.',)diff --git a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsxindex f57398de5..5caa13b54 100644--- a/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx+++ b/web-studio/src/routes/retrieval/-components/retrieval-controls.tsx@@ -290,6 +290,7 @@ function SemanticAdvancedControls({<CheckPillchecked={options.levels.includes(level)}key={level}+ // eslint-disable-next-line studio-i18n/no-literal-message -- L plus a number is the retrieval level identifier.label={`L${level}`}onCheckedChange={(checked) => toggleLevel(level, checked)}/>diff --git a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx b/web-studio/src/routes/retrieval/-components/retrieval-results.tsxindex 4a1cb32c0..b0ac16342 100644--- a/web-studio/src/routes/retrieval/-components/retrieval-results.tsx+++ b/web-studio/src/routes/retrieval/-components/retrieval-results.tsx@@ -386,6 +386,7 @@ function ResultRowContent({) : null}<spanclassName="shrink-0 font-mono text-[10px] font-medium tabular-nums text-muted-foreground/45"+ // eslint-disable-next-line studio-i18n/no-literal-message -- Keep the retrieval level identifier after the translated label.title={`${t('detail.level')}: L${item.item.level}`}>L{item.item.level}diff --git a/web-studio/src/routes/settings/-components/model-connection-test.tsx b/web-studio/src/routes/settings/-components/model-connection-test.tsxindex 6c173d959..80b3846e9 100644--- a/web-studio/src/routes/settings/-components/model-connection-test.tsx+++ b/web-studio/src/routes/settings/-components/model-connection-test.tsx@@ -61,6 +61,7 @@ export function ModelConnectionTest({setTesting(true)setResult(null)const timer = setTimeout(() => {+ // eslint-disable-next-line studio-i18n/no-literal-message -- TimeoutError is mapped to the translated connection-test summary below.controller.abort(new DOMException('Timed out', 'TimeoutError'))}, 30_000)try {diff --git a/web-studio/src/routes/settings/-components/model-fields.tsx b/web-studio/src/routes/settings/-components/model-fields.tsxindex 901df3b61..1fed630ae 100644--- a/web-studio/src/routes/settings/-components/model-fields.tsx+++ b/web-studio/src/routes/settings/-components/model-fields.tsx@@ -118,7 +118,7 @@ function JsonField({parsed !== null &&(typeof parsed !== 'object' || Array.isArray(parsed)))- throw new Error('Expected JSON object')+ throw new Error(t('models.invalidJsonObject'))input.setCustomValidity('')onChange(parsed)} catch {diff --git a/web-studio/src/routes/settings/-lib/config-file-api.ts b/web-studio/src/routes/settings/-lib/config-file-api.tsindex a6561b62b..a7c2dd50e 100644--- a/web-studio/src/routes/settings/-lib/config-file-api.ts+++ b/web-studio/src/routes/settings/-lib/config-file-api.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { createOvClient, getOvResult, OvClientError } from '#/lib/ov-client'import type { ConnectionDraft } from '#/hooks/use-app-connection'@@ -56,7 +57,7 @@ export async function waitForServerRestart(}await new Promise((resolve) => setTimeout(resolve, 1000))}- throw new Error('Restart timed out')+ throw new Error(i18n.t('studio:errors.restartTimeout'))}export const embeddingModes = ['dense', 'sparse', 'hybrid'] as constexport const embeddingCredentialFields = [@@ -181,7 +182,7 @@ export function createConfigFileApi(!models ||modelKinds.some((kind) => !models[kind]))- throw new Error('Model configuration response is unavailable')+ throw new Error(i18n.t('studio:errors.modelResponseUnavailable'))return { ...result, models: models as ConfigFileConfiguration['models'] }},preview: (content: string, changes: ModelChanges = {}) =>diff --git a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsxindex 2ca5440fc..2f7210ae5 100644--- a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx+++ b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx@@ -1,3 +1,4 @@+import studioI18n from '#/i18n/core'import * as React from 'react'import { useQuery } from '@tanstack/react-query'import {@@ -24,7 +25,12 @@ import {SheetTitle,} from '#/components/ui/sheet'import { getOvResult, getTaskByTaskId } from '#/lib/ov-client'-import { formatTaskDuration, formatTaskProcessingDuration, formatTaskWaitingDuration, getTaskDate } from '#/routes/tasks/-lib/task-time'+import {+ formatTaskDuration,+ formatTaskProcessingDuration,+ formatTaskWaitingDuration,+ getTaskDate,+} from '#/routes/tasks/-lib/task-time'import {hasTaskResult,@@ -51,7 +57,7 @@ async function fetchTask(taskId: string): Promise<TaskRecord> {)const task = normalizeTaskRecord(result)if (task) return task- throw new Error('Invalid task response')+ throw new Error(studioI18n.t('studio:errors.invalidTaskResponse'))}export function TaskDetailSheet({@@ -204,13 +210,19 @@ export function TaskDetailSheet({<DetailFieldicon={<TimerResetIcon />}label={t('labels.processingDuration')}- value={formatTaskProcessingDuration(task) ?? t('labels.timingUnavailable')}+ value={+ formatTaskProcessingDuration(task) ??+ t('labels.timingUnavailable')+ }mono/><DetailFieldicon={<TimerResetIcon />}label={t('labels.waitingDuration')}- value={formatTaskWaitingDuration(task) ?? t('labels.timingUnavailable')}+ value={+ formatTaskWaitingDuration(task) ??+ t('labels.timingUnavailable')+ }mono/><DetailField@@ -227,9 +239,7 @@ export function TaskDetailSheet({const steps = getTaskPipelineSteps(task, t)return (- <DetailSection- title={t('pipeline.steps')}- >+ <DetailSection title={t('pipeline.steps')}><div className="rounded-xl border bg-muted/20 p-3 text-xs"><div className="grid gap-1.5">{steps.map((st, i) => {diff --git a/web-studio/src/routes/tasks/route.tsx b/web-studio/src/routes/tasks/route.tsxindex 58e3a4567..2aad6480e 100644--- a/web-studio/src/routes/tasks/route.tsx+++ b/web-studio/src/routes/tasks/route.tsx@@ -644,8 +644,12 @@ function TasksRoute() {{kpiData.avgDurationSec === undefined? '-': kpiData.avgDurationSec < 1- ? `${(kpiData.avgDurationSec * 1000).toFixed(0)}ms`- : `${kpiData.avgDurationSec.toFixed(1)}s`}+ ? t('studio:duration.milliseconds', {+ value: (kpiData.avgDurationSec * 1000).toFixed(0),+ })+ : t('studio:duration.seconds', {+ value: kpiData.avgDurationSec.toFixed(1),+ })}</span></div><p className="text-[11px] text-muted-foreground truncate">diff --git a/web-studio/src/routes/users/-components/memory-policy-picker.tsx b/web-studio/src/routes/users/-components/memory-policy-picker.tsxindex 3cd07ed14..53226a8e4 100644--- a/web-studio/src/routes/users/-components/memory-policy-picker.tsx+++ b/web-studio/src/routes/users/-components/memory-policy-picker.tsx@@ -238,6 +238,7 @@ export function MemoryDirectoryPreview({<FolderIcon className="mt-0.5 size-4 shrink-0" />)}<span>+ {/* eslint-disable-next-line studio-i18n/no-literal-message -- Display the actual filename and extension. */}{['profile', 'identity', 'soul'].includes(type) ? `${type}.md` : type}<span className="ml-2 text-xs text-muted-foreground">{t(`memoryPolicy.directories.${type}`, { defaultValue: '' })}diff --git a/web-studio/src/routes/vikingbot/-api.ts b/web-studio/src/routes/vikingbot/-api.tsindex 67dc3f723..2e0bb8b1c 100644--- a/web-studio/src/routes/vikingbot/-api.ts+++ b/web-studio/src/routes/vikingbot/-api.ts@@ -1,3 +1,4 @@+import i18n from '#/i18n/core'import { getOvResult, ovClient } from '#/lib/ov-client'import type { ServerMode } from '#/lib/connection/health'@@ -37,7 +38,7 @@ export type PlatformMessage = {}export function botAccountBase() {const { accountId } = ovClient.getConnection()- if (!accountId) throw new Error('Select an account before managing bots')+ if (!accountId) throw new Error(i18n.t('studio:errors.botAccountRequired'))return `/api/v1/admin/accounts/${encodeURIComponent(accountId)}/bot`}export function getCapabilities() {@@ -131,7 +132,7 @@ export function rotateCredentials(export async function getBotUsers(serverMode: ServerMode) {const { accountId } = ovClient.getConnection()- if (!accountId) throw new Error('Select an account before managing bots')+ if (!accountId) throw new Error(i18n.t('studio:errors.botAccountRequired'))const users = await getOvResult<Array<{ user_id: string; api_key_available: boolean }>>(diff --git a/web-studio/src/routes/vikingbot/-components/channels.tsx b/web-studio/src/routes/vikingbot/-components/channels.tsxindex 9cf2447d1..d01f34e18 100644--- a/web-studio/src/routes/vikingbot/-components/channels.tsx+++ b/web-studio/src/routes/vikingbot/-components/channels.tsx@@ -1,3 +1,4 @@+import { formatDateTime } from '#/i18n/format'import {Dialog,DialogContent,@@ -246,9 +247,9 @@ export function Channels({{t('lastReceived')}</dt><dd>- {new Date(- connection.status.last_received,- ).toLocaleString()}+ {formatDateTime(+ new Date(connection.status.last_received),+ )}</dd></div>)}@@ -258,9 +259,9 @@ export function Channels({{t('lastSent')}</dt><dd>- {new Date(- connection.status.last_sent,- ).toLocaleString()}+ {formatDateTime(+ new Date(connection.status.last_sent),+ )}</dd></div>)}diff --git a/web-studio/src/routes/vikingbot/-components/conversation-row.tsx b/web-studio/src/routes/vikingbot/-components/conversation-row.tsxindex a882a8df3..336992efe 100644--- a/web-studio/src/routes/vikingbot/-components/conversation-row.tsx+++ b/web-studio/src/routes/vikingbot/-components/conversation-row.tsx@@ -1,3 +1,5 @@+import { useTranslation } from 'react-i18next'+import { formatDateTime } from '#/i18n/format'import type { ReactNode } from 'react'export function ConversationRow({@@ -17,6 +19,7 @@ export function ConversationRow({onSelect: () => voidaction?: ReactNode}) {+ useTranslation()const date =time && !Number.isNaN(Date.parse(time)) ? new Date(time) : undefinedreturn (@@ -41,9 +44,9 @@ export function ConversationRow({<timeclassName="shrink-0"dateTime={time}- title={date.toLocaleString()}+ title={formatDateTime(date)}>- {date.toLocaleString(undefined, {+ {formatDateTime(date, {month: 'numeric',day: 'numeric',hour: '2-digit',diff --git a/web-studio/src/routes/vikingbot/-components/platform-history.tsx b/web-studio/src/routes/vikingbot/-components/platform-history.tsxindex 181150aa8..0dc40cee5 100644--- a/web-studio/src/routes/vikingbot/-components/platform-history.tsx+++ b/web-studio/src/routes/vikingbot/-components/platform-history.tsx@@ -1,3 +1,4 @@+import { formatDateTime } from '#/i18n/format'import { useInfiniteQuery, useQuery } from '@tanstack/react-query'import { UsersIcon } from 'lucide-react'import { useTranslation } from 'react-i18next'@@ -68,7 +69,7 @@ export function PlatformHistory({><div className="mb-2 flex flex-wrap justify-between gap-2 text-xs text-muted-foreground"><span>{message.sender || t('unknownSender')}</span>- <time>{new Date(message.time).toLocaleString()}</time>+ <time>{formatDateTime(new Date(message.time))}</time></div><p className="whitespace-pre-wrap break-words text-sm leading-7">{message.content}diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsxindex 2523df753..9ebd50db3 100644--- a/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx+++ b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx@@ -1,3 +1,4 @@+import { formatDateTime } from '#/i18n/format'import { useState } from 'react'import { useMutation } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'@@ -60,7 +61,7 @@ export function GroupSetup({</dt><dd className="text-sm">{connection.status[key]- ? new Date(connection.status[key]).toLocaleString()+ ? formatDateTime(new Date(connection.status[key])): t('noActivity')}</dd></div>