From 6ea4b3ff296f39e6ab2ead4a7c4c3b15092e89f2 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 07:14:15 +0000 Subject: [PATCH] fix(web): translate English UI copy split by inline markup and cover page copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit English mode left large parts of the UI in Chinese. Two causes in web/i18n.js and web/i18n-en.js: - The dictionary entries for many page descriptions, empty states and hints (Runs concurrency tooltip, Projects, Sandboxes, Knowledge, AI schedules, Assistant settings, Access keys, Approvals) were missing, so those strings had nothing to match. - Copy such as "平台所有项目共用执行名额,默认 10 条…" is split across text nodes by inline markup, so a whole-sentence key could never match a single text node even when it existed. Now inline runs inside one block are matched against the dictionary as a whole, and a run is only rewritten when keys cover all of it; rendered controls and subtrees containing ids, form controls or handlers are never rewritten, so app bindings such as #workflowSelect keep working. Text nodes inside such subtrees still get exact and fragment translation. Counter copy like "共 1 条" now reads "1 item". Co-Authored-By: Claude Code --- web/i18n-en.js | 70 ++++++++++++++++ web/i18n.js | 110 ++++++++++++++++++++++---- webtest/tests/i18n-page-copy.test.mjs | 91 +++++++++++++++++++++ 3 files changed, 254 insertions(+), 17 deletions(-) create mode 100644 webtest/tests/i18n-page-copy.test.mjs diff --git a/web/i18n-en.js b/web/i18n-en.js index bcbb89c8d..db53c1702 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -1095,3 +1095,73 @@ Object.assign(window.LF_I18N_EN, { "在对话里澄清和改代码": "Clarify and change code in chat", "这条需求不使用 LOOP,在对话里澄清需求、直接改代码;定时任务不会自动认领它。": "This requirement uses no LOOP: clarify and change code in chat; scheduled jobs won't pick it up.", }); + +// Page descriptions, empty states and hints that were still falling back to +// Chinese on the Runs, Projects, Sandboxes, Knowledge, AI schedules, Assistant, +// Access keys, Approvals and Requirements pages. +Object.assign(window.LF_I18N_EN, { + "并发规则": "Concurrency rules", + "平台所有项目共用执行名额,默认 10 条顶层 LOOP,平台管理员可在「执行机器」调整。个人和共享机器按各自上限计数。": "Execution slots are shared by all projects: 10 top-level LOOPs by default; platform admins can adjust this in Runners. Personal and shared runners count against their own limits.", + "超出名额后按排队顺序启动。开启自动分配的 LOOP 等待兼容的执行机器,子 LOOP 共用父流程名额。": "Runs beyond the limit start in queue order. LOOPs with auto-assignment wait for a compatible runner, and sub-LOOPs share the parent run's slot.", + "失败、暂停、待确认的 LOOP 空闲 1 小时后自动归档工作区并释放名额,继续或重试时自动恢复。已开始的 LOOP 取消后,工作区清理完成即释放名额。": "A failed, paused or pending-confirmation LOOP archives its workspace and frees its slot after 1 hour idle, and restores it on resume or retry. A cancelled LOOP frees its slot once workspace cleanup finishes.", + "平台执行机器默认同时运行 10 条顶层 LOOP,所有项目共用,平台管理员可调整。": "Platform runners run 10 top-level LOOPs at a time by default, shared by all projects and adjustable by platform admins.", + "暂无进行中的运行": "No LOOPs in progress", + "换个关键词,或到需求列表查看对应需求的执行结果。": "Try another keyword, or open Requirements to see the result of each requirement.", + "项目是需求、仓库、团队和默认 LOOP 的统一边界。点击项目进入详情配置。": "A project is the shared boundary for requirements, repositories, the team and the default LOOP. Open a project to configure it.", + "项目是需求、仓库与团队的统一边界,先创建第一个项目。": "A project is the shared boundary for requirements, repositories and the team. Create the first one.", + "我参与的": "I'm in", + "待完善": "Needs setup", + "未绑定代码仓库": "No repository bound", + "维护当前项目的运行沙箱:隔离方式、Dockerfile 和环境变量。": "Maintain this project's run sandboxes: isolation, Dockerfile and environment variables.", + "维护当前项目的运行沙箱。": "Maintain this project's run sandboxes.", + "本项目沙箱": "Project sandboxes", + "沙箱决定 LOOP 节点和对话工作区在什么隔离环境里执行:docker 沙箱自带 Dockerfile,native 沙箱使用执行机器上已安装的工具。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。": "A sandbox decides where LOOP nodes and conversation workspaces run: a Docker sandbox carries its own Dockerfile, while a native sandbox uses the tools installed on the runner. Pick it in the LOOP settings once created, or use a ready-made Shared profile.", + "接入并管理仅你本人可见的外部只读知识库连接器,供 AI 对话与 SOP 运行按需引用。": "Connect and manage external read-only knowledge connectors only you can see, for AI chat and LOOP runs to cite on demand.", + "个人隔离": "Personal isolation", + ":连接器与凭据仅归属当前账号,其他成员无法查看或调用。": ": connectors and credentials belong to this account only; other members cannot see or call them.", + "只读安全代理": "Read-only secure proxy", + ":密钥 AES-GCM 加密托管,沙箱通过无状态代理检索并标注出处,支持按工具白名单精准放行只读工具。": ": keys are hosted with AES-GCM encryption; sandboxes search through a stateless proxy that cites sources and allows only read-only tools on an explicit allowlist.", + "还没有接入个人知识库连接器": "No personal knowledge connector yet", + "可从上方常用知识库模板快速配置,或选择一个连接器类型接入你的自有知识库;配置仅对你本人可见,可在 AI 对话、SOP 节点与手动运行中引用。": "Start from a common knowledge template above, or pick a connector type to connect your own knowledge base. The configuration is visible only to you and can be cited in AI chat, LOOP nodes and manual runs.", + "共享任务市场": "Shared task marketplace", + "执行记录": "Executions", + "任务以最后保存人的身份和完全权限执行。关闭页面后,任务会继续运行。": "The task runs as the last saver with full permissions. It keeps running after you close the page.", + "当前项目还没有 AI 定时任务,点击右上角「新建 AI 定时任务」。": "This project has no AI scheduled task yet. Click New AI scheduled task in the top right.", + "AI 工作台里和你对话、帮你动手的助手。设置消息发送方式、角色与 LOOP 的主动派发,以及每次对话都要遵守的规则;只对你自己生效。": "The assistant that talks with you and gets things done in the AI workspace. Configure message delivery, role and LOOP dispatch, and the rules every conversation follows. Only applies to you.", + "消息发送": "Message delivery", + "生成中发送消息": "Send while generating", + "排队会等当前回复结束;立即发送会打断当前回复,保留已输出内容并继续处理新消息。": "Queue waits for the current reply to finish; Send now interrupts it, keeps the output so far and handles the new message.", + "还没有访问密钥,创建后即可接入 REST API 和 MCP。": "No access key yet. Create one to use the REST API and MCP.", + "没有需要你拍板的需求": "Nothing needs your decision", + "流程停在人工确认节点时会出现在这里。": "LOOPs waiting at a human approval step appear here.", + "批量操作": "Bulk actions" +}); + +// Page copy that spans inline markup and the remaining per-page hints. +Object.assign(window.LF_I18N_EN, { + "常用知识库 · 快速接入": "Common knowledge bases · Quick setup", + "常用知识库模板": "Common knowledge base templates", + "快速配置": "Quick setup", + "接入此类型": "Connect this type", + "通过只读 REST API 接入个人或团队 WeKnora 实例(支持列子库、混合检索与分块原文读取)": "Connect a personal or team WeKnora instance over its read-only REST API (sub-library listing, hybrid search and chunk text reading).", + "接入遵循 Streamable HTTP MCP 协议的任意只读知识库服务 (含 LightCloud 等), 仅放行 readOnlyHint Tool": "Connect any read-only knowledge base that speaks Streamable HTTP MCP (including LightCloud); only tools marked readOnlyHint are allowed.", + "接入遵循 Streamable HTTP MCP 协议的任意只读知识库服务(含 LightCloud 等),仅放行 readOnlyHint Tool": "Connect any read-only knowledge base that speaks Streamable HTTP MCP (including LightCloud); only tools marked readOnlyHint are allowed.", + "帮我批准审查模型": "Review model for approvals", + "打开后 AI 助手会更主动地把事情交给角色或 LOOP。派角色不需要确认;走 LOOP 在「请求批准」下先征求同意,「帮我批准」下由 AI 审查直接裁决,「完全权限」下直接启动。": "When on, the AI assistant hands work to roles or LOOPs more eagerly. Assigning a role needs no confirmation; for LOOPs it asks first under \"Ask for approval\", decides directly under \"Approve for me\", and starts at once under \"Full access\".", + "「帮我批准」模式由 AI 独立审查平台及外部操作并直接放行或拒绝,无需人工审批。默认沿用当前对话的 CLI 与模型(最低思考强度);也可指定已配置的 CLI 模型或独立轻量 API 节省 Token。": "In \"Approve for me\" mode the AI reviews platform and external operations on its own and either allows or denies them without human approval. By default it reuses the CLI and model of the current conversation (lowest thinking effort); you can also pick a configured CLI model or a separate lightweight API to save tokens.", + "快捷选择": "Quick pick", + "帮我批准审查方式": "Approval review method", + "跟随当前对话 CLI 和模型": "Follow the current conversation CLI and model", + "更多": "More", + "共 0 个项目": "0 projects", +}); + +Object.assign(window.LF_I18N_EN, { + "派角色不需要确认": "Assigning a role needs no confirmation", + "个任务": " tasks", +}); + +Object.assign(window.LF_I18N_EN, { + "排队": "Queue", + "立即发送": "Send now", +}); diff --git a/web/i18n.js b/web/i18n.js index a0efcdc7f..8ee74be01 100644 --- a/web/i18n.js +++ b/web/i18n.js @@ -109,6 +109,7 @@ [/(\d{4})年(\d{1,2})月/g, (_, y, m) => `${MONTHS[m - 1] || m} ${y}`], [/(^|[^\d])(\d{1,2})月(?![\u3400-\u9fff])/g, (_, pre, m) => pre + (MONTHS[m - 1] || m)], [/共\s*(\d+)\s*(?=[A-Za-z])/g, '$1 '], + [/共\s*(\d+)\s*(条|个|项)/g, (_, n) => `${n} ${Number(n) === 1 ? 'item' : 'items'}`], [/(\d{4}-\d{2}-\d{2})\s*至\s*(\d{4}-\d{2}-\d{2})/g, '$1 – $2'], [/(\d+(?:\.\d+)?)\s*(次|步|个|台|条|篇)(?![\u3400-\u9fff])/g, (_, n, u) => { const word = UNITS[u][Number(n) === 1 ? 0 : 1]; @@ -122,14 +123,17 @@ return trimmed && Object.prototype.hasOwnProperty.call(dict, trimmed) ? text.replace(trimmed, dict[trimmed]) : text; } - function translate(text) { + function translate(text, exactOnly) { if (!text || !HAN.test(text)) return text; - const hit = cache.get(text); + const cacheKey = exactOnly ? '=' + text : text; + const hit = cache.get(cacheKey); if (hit !== undefined) return hit; const trimmed = text.trim(); let out; if (Object.prototype.hasOwnProperty.call(dict, trimmed)) { out = text.replace(trimmed, dict[trimmed]); + } else if (exactOnly) { + return text; } else { out = fragmentRE ? text.replace(fragmentRE, m => dict[m]) : text; if (sentenceRE && HAN.test(out)) out = out.replace(sentenceRE, m => dict[m]); @@ -142,7 +146,7 @@ if (/\s$/.test(text) === false) out = out.replace(/\s+$/, ''); } if (cache.size > 20000) cache.clear(); - cache.set(text, out); + cache.set(cacheKey, out); return out; } window.lfTranslate = translate; @@ -150,10 +154,10 @@ function skipped(el) { return !el || SKIP.has(el.tagName) || (el.closest && el.closest(SKIP_SEL)); } - function translateText(node) { + function translateText(node, partial) { const parent = node.parentElement; if (skipped(parent)) return; - const next = parent.closest(DATA_SEL) ? translateExact(node.nodeValue) : translate(node.nodeValue); + const next = parent.closest(DATA_SEL) ? translateExact(node.nodeValue) : translate(node.nodeValue, partial); if (next !== node.nodeValue) node.nodeValue = next; } function translateAttrs(el) { @@ -167,23 +171,95 @@ } if (el.tagName === 'INPUT' && /^(button|submit|reset)$/i.test(el.type) && HAN.test(el.value)) el.value = translate(el.value); } + // Copy such as "平台所有项目共用执行名额,默认 10 条…" arrives + // split over several text nodes by inline markup, so a dictionary key for the + // whole sentence can never match a single node. Collect runs of text nodes and + // plain inline wrappers inside one block and match dictionary keys across them, + // replacing the run with the translation only when keys cover all of it. + const INLINE = new Set(['A', 'B', 'BR', 'CITE', 'CODE', 'EM', 'I', 'MARK', 'SMALL', 'SPAN', 'STRONG', 'TIME', 'U']); + const byInitial = new Map(); + for (const key of fragments) { + const first = key[0]; + if (!byInitial.has(first)) byInitial.set(first, []); + byInitial.get(first).push(key); + } + const KEEP_ATTRS = new Set(['class', 'style', 'title', 'aria-label', 'aria-hidden', 'role', 'lang', 'dir', 'data-i18n-skip']); + function inlineOnly(el) { + if (!INLINE.has(el.tagName) || !el.childNodes.length) return false; + for (const attr of el.attributes) if (!KEEP_ATTRS.has(attr.name) && !attr.name.startsWith('data-i18n')) return false; + for (const child of el.childNodes) { + if (child.nodeType === 3) continue; + if (child.nodeType !== 1 || !INLINE.has(child.tagName) || !inlineOnly(child)) return false; + } + return !el.closest(SKIP_SEL) && !el.closest(DATA_SEL); + } + function flatten(nodes) { + return nodes.map(node => { + if (node.nodeType === 3) return node.nodeValue; + return node.childNodes.length ? flatten([...node.childNodes]) : (node.textContent || ''); + }).join(''); + } + function matchRun(text) { + const out = []; + let i = 0; + let covered = 0; + let leftover = ''; + while (i < text.length) { + const keys = byInitial.get(text[i]); + let best = null; + if (keys) for (const key of keys) if (text.startsWith(key, i)) { best = key; break; } + if (best) { + out.push(dict[best]); + covered += best.length; + i += best.length; + } else { + out.push(text[i]); + leftover += text[i]; + i += 1; + } + } + // Only merge when the dictionary covers the whole run; a partial match would + // flatten markup around copy that still needs its own translation. + return covered && !leftover.trim() ? out.join('') : null; + } + function mergeRuns(el) { + // Never rewrite rendered controls or observable subtrees: app code binds to + // their ids and the run replacement would drop those elements. Only text + // nodes and plain inline wrappers are safe to merge. + if (el.closest(SKIP_SEL) || el.closest(DATA_SEL) || el.querySelector('[id],input,select,textarea,button,img,svg,iframe,[onclick],[onchange],[oninput]')) return; + const runs = []; + let run = null; + for (const child of el.childNodes) { + if (child.nodeType === 3 || (child.nodeType === 1 && inlineOnly(child))) { + if (!run) { run = []; runs.push(run); } + run.push(child); + } else { + run = null; + } + } + for (const nodes of runs) { + if (nodes.length < 2) continue; + const text = flatten(nodes); + if (!HAN.test(text)) continue; + const hit = matchRun(text); + if (!hit) continue; + let anchor = nodes[0]; + if (anchor.nodeType === 1) { + anchor = document.createTextNode(''); + nodes[0].replaceWith(anchor); + nodes[0] = anchor; + } + anchor.nodeValue = translate(hit); + for (const node of nodes.slice(1)) node.remove(); + } + } function walk(node) { if (node.nodeType === 3) return translateText(node); if (node.nodeType !== 1) return; if (skipped(node)) { if (node.tagName === 'TEXTAREA') translateAttrs(node); return; } translateAttrs(node); - const tw = document.createTreeWalker(node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, { - acceptNode: n => { - if (n.nodeType !== 1 || !skipped(n)) return NodeFilter.FILTER_ACCEPT; - if (n.tagName === 'TEXTAREA') translateAttrs(n); - return NodeFilter.FILTER_REJECT; - }, - }); - let n; - while ((n = tw.nextNode())) { - if (n.nodeType === 3) translateText(n); - else translateAttrs(n); - } + mergeRuns(node); + for (const child of [...node.childNodes]) walk(child); } function translateTitle() { const next = translate(document.title); diff --git a/webtest/tests/i18n-page-copy.test.mjs b/webtest/tests/i18n-page-copy.test.mjs new file mode 100644 index 000000000..b38bc6069 --- /dev/null +++ b/webtest/tests/i18n-page-copy.test.mjs @@ -0,0 +1,91 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import vm from 'node:vm'; +import { JSDOM } from 'jsdom'; +import { WEB_ROOT } from '../lib/load-app.mjs'; + +const HAN = /[㐀-鿿]/; + +// The page descriptions, empty states and hints that used to stay Chinese in +// English mode (Runs, Projects, Sandboxes, Knowledge, AI schedules, Assistant, +// Access keys, Approvals and Requirements). +const COPY = [ + '平台所有项目共用执行名额,默认 10 条顶层 LOOP,平台管理员可在「执行机器」调整。个人和共享机器按各自上限计数。', + '超出名额后按排队顺序启动。开启自动分配的 LOOP 等待兼容的执行机器,子 LOOP 共用父流程名额。', + '失败、暂停、待确认的 LOOP 空闲 1 小时后自动归档工作区并释放名额,继续或重试时自动恢复。已开始的 LOOP 取消后,工作区清理完成即释放名额。', + '暂无进行中的运行', + '换个关键词,或到需求列表查看对应需求的执行结果。', + '项目是需求、仓库、团队和默认 LOOP 的统一边界。点击项目进入详情配置。', + '我参与的', '待完善', '未绑定代码仓库', + '维护当前项目的运行沙箱:隔离方式、Dockerfile 和环境变量。', + '本项目沙箱', + '沙箱决定 LOOP 节点和对话工作区在什么隔离环境里执行:docker 沙箱自带 Dockerfile,native 沙箱使用执行机器上已安装的工具。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。', + '接入并管理仅你本人可见的外部只读知识库连接器,供 AI 对话与 SOP 运行按需引用。', + '个人隔离', '只读安全代理', '还没有接入个人知识库连接器', + '可从上方常用知识库模板快速配置,或选择一个连接器类型接入你的自有知识库;配置仅对你本人可见,可在 AI 对话、SOP 节点与手动运行中引用。', + '共享任务市场', '执行记录', + '任务以最后保存人的身份和完全权限执行。关闭页面后,任务会继续运行。', + '当前项目还没有 AI 定时任务,点击右上角「新建 AI 定时任务」。', + 'AI 工作台里和你对话、帮你动手的助手。设置消息发送方式、角色与 LOOP 的主动派发,以及每次对话都要遵守的规则;只对你自己生效。', + '消息发送', '生成中发送消息', + '排队会等当前回复结束;立即发送会打断当前回复,保留已输出内容并继续处理新消息。', + '还没有访问密钥,创建后即可接入 REST API 和 MCP。', + '没有需要你拍板的需求', '流程停在人工确认节点时会出现在这里。', + '批量操作', +]; + +async function englishWindow() { + const dom = new JSDOM('', { + runScripts: 'outside-only', url: 'http://127.0.0.1/', + }); + for (const file of ['i18n-en.js', 'i18n.js']) { + new vm.Script(await readFile(path.join(WEB_ROOT, file), 'utf8'), { filename: file }) + .runInContext(dom.getInternalVMContext()); + } + return dom; +} + +test('English mode translates the page copy and empty states of every tested page', async () => { + const dom = await englishWindow(); + const window = dom.window; + const untranslated = COPY.filter(zh => HAN.test(window.lfTranslate(zh))); + assert.deepEqual(untranslated, []); + assert.equal(window.lfTranslate('暂无进行中的运行'), 'No LOOPs in progress'); + assert.equal(window.lfTranslate('批量操作'), 'Bulk actions'); + assert.equal(window.lfTranslate('我参与的'), "I'm in"); + window.close(); +}); + +test('the new page copy leaves user-authored names alone', async () => { + const dom = await englishWindow(); + const window = dom.window; + // A person's Chinese display name is data, not UI copy; the dictionary must + // not claim it, so a whole-string lookup leaves it unchanged. + assert.equal(window.lfTranslate('走查账号'), '走查账号'); + assert.equal(window.LF_I18N_EN['走查账号'], undefined); + window.close(); +}); + +test('English mode translates copy split by inline markup as one sentence', async () => { + const dom = await englishWindow(); + const { window } = dom; + const { document } = window; + document.body.innerHTML = ` +
平台所有项目共用执行名额,默认 10 条顶层 LOOP,平台管理员可在「执行机器」调整。个人和共享机器按各自上限计数。
+

打开后 AI 助手会更主动地把事情交给角色或 LOOP。派角色不需要确认;走 LOOP 在「请求批准」下先征求同意,「帮我批准」下由 AI 审查直接裁决,「完全权限」下直接启动。

+
UI 走查:parse_amount 应拒绝 "1.2.3" 这类非法金额。
`; + const tip = document.getElementById('tip'); + const split = document.getElementById('split'); + // The initial pass ran on an empty body, so re-inserting the nodes replays the + // same MutationObserver path the app uses for asynchronously rendered views. + document.body.appendChild(tip); + document.body.appendChild(split); + await new Promise(r => setTimeout(r, 20)); + assert.ok(!/[㐀-鿿]/.test(tip.textContent), `tip still Chinese: ${tip.textContent}`); + assert.ok(!/[㐀-鿿]/.test(split.textContent), `split still Chinese: ${split.textContent}`); + assert.match(split.textContent, /hands work to roles or LOOPs more eagerly/); + assert.match(document.getElementById('data').textContent, /UI 走查/); + window.close(); +});