diff --git a/web/app/knowledge-refs.js b/web/app/knowledge-refs.js index 1fec29e73..12242b16f 100644 --- a/web/app/knowledge-refs.js +++ b/web/app/knowledge-refs.js @@ -76,7 +76,7 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) for (const ref of (refs || [])) { const rid = getRefId(ref); if (rid && !options.some(s => s.id === rid)) { - options.push({ id: rid, name: rid + '(已失效或无权限)', missing: true }); + options.push({ id: rid, name: rid + lfT('(已失效或无权限)', ' (expired or unauthorized)'), missing: true }); } } @@ -92,6 +92,7 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) enabled.type = 'checkbox'; const previous = (refs || []).find(r => getRefId(r) === s.id); enabled.checked = !!previous; + srvTitle.dataset.i18nData = ''; srvTitle.append(enabled, document.createTextNode(s.name || s.id)); const srvId = document.createElement('span'); srvId.className = 'kr-service-id'; @@ -135,7 +136,8 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) const sourcesInput = document.createElement('input'); sourcesInput.className = 'kr-control'; sourcesInput.placeholder = '来源 ID,以逗号分隔'; - sourcesInput.setAttribute('aria-label', (s.name || s.id) + '允许的来源 ID'); + sourcesInput.dataset.i18nData = ''; + sourcesInput.setAttribute('aria-label', lfT(`${s.name || s.id}允许的来源 ID`, `Allowed source IDs for ${s.name || s.id}`)); sourcesInput.value = (previous?.sources || []).join(', '); adv.append(advSum, sourcesInput); @@ -163,7 +165,7 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) allowCount.textContent = '请选择至少一个子知识库'; allowCount.className = 'kr-count warn'; } else { - allowCount.textContent = `已选 ${ids.size} 个子知识库`; + allowCount.textContent = lfT(`已选 ${ids.size} 个子知识库`, `${ids.size} ${ids.size === 1 ? 'sub-source' : 'sub-sources'} selected`); allowCount.className = 'kr-count ok'; } } else { @@ -203,10 +205,12 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) box.className = 'kr-source-info'; const nm = document.createElement('span'); nm.className = 'kr-source-name'; + nm.dataset.i18nData = ''; nm.textContent = info.name; const meta = document.createElement('span'); meta.className = 'kr-source-meta'; - meta.textContent = info.space ? `空间:${info.space}` : source.id; + meta.dataset.i18nData = ''; + meta.textContent = info.space ? lfT(`空间:${info.space}`, `Space: ${info.space}`) : source.id; box.append(nm, meta); row.append(cb, box); @@ -248,7 +252,7 @@ window.editKnowledgeRefs = async function editKnowledgeRefs(project, refs, save) const selected = mode.value === 'allowlist' ? [...selectedSet()] : []; if (mode.value === 'allowlist' && !selected.length) { if (silent) return { error: '请选择至少一个子知识库' }; - throw new Error(`请为「${s.name || s.id}」选择至少一个子知识库`); + throw new Error(lfT(`请为「${s.name || s.id}」选择至少一个子知识库`, `Select at least one sub-source for “${s.name || s.id}”`)); } return { connectorId: s.id, mode: mode.value, sources: selected }; }); diff --git a/web/app/knowledge.js b/web/app/knowledge.js index dad2c0fdf..e9ba37edf 100644 --- a/web/app/knowledge.js +++ b/web/app/knowledge.js @@ -292,6 +292,11 @@ ]; } + // English count phrase: "1 doc" / "2 docs". + function kbPlural(n, one, many) { + return `${n} ${Number(n) === 1 ? one : many}`; + } + function kbEsc(s) { return String(s == null ? '' : s) .replace(/&/g, '&') @@ -505,7 +510,7 @@ const toolsHTML = tools.length ? `
只读工具:${tools.map(t => `${kbEsc(t)}`).join('')}
` : ''; - const srcNote = sources.length ? ` · 发现 ${sources.length} 个子知识库` : ''; + const srcNote = sources.length ? lfT(` · 发现 ${sources.length} 个子知识库`, ` · ${kbPlural(sources.length, 'sub-source', 'sub-sources')} found`) : ''; return `
探测通过 · 连接正常 · ${latency} ms${srcNote}
@@ -521,12 +526,12 @@ } return `
-
可用子知识库共 ${sources.length} 项
+
可用子知识库${lfT(`共 ${sources.length} 项`, `${sources.length} total`)}
${sources.map(src => `
-
${kbEsc(src.name || src.id)}
-
${kbEsc(src.id)}${src.docCount != null ? ` · ${Number(src.docCount)} 篇文档` : ''}
+
${kbEsc(src.name || src.id)}
+
${kbEsc(src.id)}${src.docCount != null ? ` · ${lfT(`${Number(src.docCount)} 篇文档`, kbPlural(Number(src.docCount), 'doc', 'docs'))}` : ''}
`).join('')}
@@ -687,7 +692,7 @@ const typeOptions = types.map(t => ``).join(''); const guideHTML = vendorMeta?.guide - ? `
${kbEsc(vendorMeta.name)}接入指引(${kbEsc(vendorMeta.badge)})${kbEsc(vendorMeta.guide)}
` + ? `
${lfT(`${kbEsc(vendorMeta.name)}接入指引(${kbEsc(vendorMeta.badge)})`, `Setup guide: ${kbEsc(vendorMeta.name)} (${kbEsc(vendorMeta.badge)})`)}${kbEsc(vendorMeta.guide)}
` : ''; const bodyHTML = ` @@ -870,12 +875,12 @@
-

${kbEsc(conn.name)}

+

${kbEsc(conn.name)}

${kbEsc(meta?.name || conn.type)} ${conn.enabled ? '已启用' : '已停用'} ${renderConnectorAuthBadgeHTML(conn)} - ${kbState.usage ? `` : ''} + ${kbState.usage ? `` : ''}
@@ -891,7 +896,7 @@
服务地址:${kbEsc(conn.endpoint)}
ID: ${kbEsc(conn.id)} - ${conn.config?.timeoutSec ? `超时: ${Number(conn.config.timeoutSec)}s` : ''} + ${conn.config?.timeoutSec ? `${lfT('超时', 'Timeout')}: ${Number(conn.config.timeoutSec)}s` : ''}
${renderConnectorExtraHTML(conn, meta)} ${checkRes ? renderCheckBannerHTML(checkRes) : ''} @@ -930,7 +935,7 @@ ${statusBadgeHTML}

${kbEsc(v.desc)}

- ${isConfigured ? `
已绑定连接器:${kbEsc(conn.name)}
` : ''} + ${isConfigured ? `
${lfT('已绑定连接器:', 'Connector: ')}${kbEsc(conn.name)}
` : ''}
@@ -982,11 +987,11 @@ function formatUsageCallerKindLabel(kind) { switch (String(kind || '').toLowerCase()) { case 'sop': return 'SOP'; - case 'space': return '协作空间'; - case 'clarify': return '需求澄清'; - case 'scheduled': return '定时任务'; - case 'report': return '分析报告'; - default: return '个人对话'; + case 'space': return lfT('协作空间', 'Workspace'); + case 'clarify': return lfT('需求澄清', 'Requirement clarification'); + case 'scheduled': return lfT('定时任务', 'Scheduled task'); + case 'report': return lfT('分析报告', 'Analysis report'); + default: return lfT('个人对话', 'Personal chat'); } } @@ -1003,25 +1008,48 @@ const kind = String(c.kind || 'chat').toLowerCase(); const kindLabel = formatUsageCallerKindLabel(kind); if (kind === 'sop') { - const label = c.workflowName || c.workflowId || 'SOP 运行'; + const label = c.workflowName || c.workflowId || lfT('SOP 运行', 'SOP run'); const subParts = []; if (c.agentName || c.agentId) subParts.push(c.agentName || c.agentId); if (c.nodeName || c.nodeId) subParts.push(c.nodeName || c.nodeId); - return { kind, kindLabel, label, subLabel: subParts.join(' · ') }; + return { kind, kindLabel, label, subLabel: callerSubLabel(subParts.join(' · '), kind) }; } if (kind === 'space') { - return { kind, kindLabel, label: c.spaceTitle || c.spaceId || '协作空间', subLabel: '' }; + return { kind, kindLabel, label: c.spaceTitle || c.spaceId || kindLabel, subLabel: '' }; } if (kind === 'clarify') { - return { kind, kindLabel, label: c.issueTitle || c.sessionTitle || c.issueId || '需求澄清', subLabel: '' }; + return { kind, kindLabel, label: c.issueTitle || c.sessionTitle || c.issueId || kindLabel, subLabel: '' }; } if (kind === 'scheduled') { - return { kind, kindLabel, label: c.sessionTitle || '定时任务', subLabel: '' }; + return { kind, kindLabel, label: c.sessionTitle || kindLabel, subLabel: '' }; } if (kind === 'report') { - return { kind, kindLabel, label: c.sessionTitle || c.issueTitle || '分析报告', subLabel: '' }; + return { kind, kindLabel, label: c.sessionTitle || c.issueTitle || kindLabel, subLabel: '' }; } - return { kind, kindLabel, label: c.sessionTitle || '个人对话', subLabel: '' }; + return { kind, kindLabel, label: c.sessionTitle || kindLabel, subLabel: '' }; + } + + // The caller badge already names the kind, and built-in LOOPs often give the + // role and the node the same name, so drop parts that would only repeat + // ("开发实现 · 开发实现", or the server's "个人对话" next to the 个人对话 badge). + const CALLER_KIND_ZH = { space: '协作空间', clarify: '需求澄清', scheduled: '定时任务', report: '分析报告', chat: '个人对话' }; + function callerSubLabel(subLabel, kind) { + const kindNames = [formatUsageCallerKindLabel(kind), kind === 'sop' ? '' : (CALLER_KIND_ZH[kind] || CALLER_KIND_ZH.chat)]; + const parts = []; + for (const part of String(subLabel || '').split(' · ').map(p => p.trim())) { + if (!part || parts.includes(part) || kindNames.includes(part)) continue; + parts.push(part); + } + return parts.join(' · '); + } + + // Top callers come from the server, which falls back to the Chinese kind name + // (or "SOP 运行") when a caller has no title; show the localized name instead. + function callerPillLabel(label, kind) { + const text = String(label || '').trim(); + if (!text || text === (CALLER_KIND_ZH[kind] || CALLER_KIND_ZH.chat)) return formatUsageCallerKindLabel(kind); + if (kind === 'sop' && text === 'SOP 运行') return lfT('SOP 运行', 'SOP run'); + return text; } function callerJumpAttrs(target) { @@ -1101,14 +1129,17 @@ return `
${callers.map(c => { - const kindLabel = formatUsageCallerKindLabel(c.kind); + const kind = String(c.kind || 'chat').toLowerCase(); + const kindLabel = formatUsageCallerKindLabel(kind); + const label = callerPillLabel(c.label, kind); + const subLabel = callerSubLabel(c.subLabel, kind); const countText = Number(c.callCount || 0) > 1 ? ` ×${Number(c.callCount)}` : ''; - const titleText = c.subLabel ? `${kindLabel} · ${c.label} (${c.subLabel})` : `${kindLabel} · ${c.label}`; + const titleText = subLabel ? `${kindLabel} · ${label} (${subLabel})` : `${kindLabel} · ${label}`; const jumpAttr = callerJumpAttrs(c); if (jumpAttr) { - return ``; + return ``; } - return `${kbEsc(kindLabel)}${kbEsc(c.label)}${c.subLabel ? ` · ${kbEsc(c.subLabel)}` : ''}${countText ? `${kbEsc(countText)}` : ''}`; + return `${kbEsc(kindLabel)}${kbEsc(label)}${subLabel ? ` · ${kbEsc(subLabel)}` : ''}${countText ? `${kbEsc(countText)}` : ''}`; }).join('')}
`; @@ -1141,11 +1172,11 @@ - ${subLabel ? `
${kbEsc(subLabel)}
` : ''} + ${subLabel ? `
${kbEsc(subLabel)}
` : ''} - ${kbEsc(connLabel)} + ${kbEsc(connLabel)} ${renderTopCallersHTML(doc.topCallers)} ${Number(doc.searchHitCount || 0)} ${Number(doc.readCount || 0)} @@ -1167,7 +1198,7 @@ const hasFilter = Boolean(f.connectorId || f.documentId || f.callerKind || f.query); const connOptions = kbState.connectors.map(c => - `` + `` ).join(''); const filterBarHTML = ` @@ -1183,7 +1214,7 @@ - ${f.documentId ? `文档:${kbEsc(f.documentLabel || f.documentId)}` : ''} + ${f.documentId ? `${lfT('文档:', 'Document: ')}${kbEsc(f.documentLabel || f.documentId)}` : ''} ${hasFilter ? '' : ''}
`; @@ -1215,8 +1246,8 @@ const jumpAttr = callerJumpAttrs(ev.caller); const actionLabel = ev.action === 'read' ? '正文读取' : '检索命中'; const callerLabelHTML = jumpAttr - ? `` - : `
${kbEsc(callerInfo.label)}
${callerInfo.subLabel ? `
${kbEsc(callerInfo.subLabel)}
` : ''}`; + ? `` + : `
${kbEsc(callerInfo.label)}
${callerInfo.subLabel ? `
${kbEsc(callerInfo.subLabel)}
` : ''}
`; return ` ${kbEsc(formatUsageTime(ev.calledAt))} @@ -1227,8 +1258,8 @@
-
${kbEsc(docLabel)}
- ${docSub ? `
${kbEsc(docSub)}
` : ''} +
${kbEsc(docLabel)}
+ ${docSub ? `
${kbEsc(docSub)}
` : ''}
@@ -1244,7 +1275,7 @@
- 已显示 ${items.length} / 共 ${Number(events.total || items.length)} 条(单用户保留最近 30 天内最多 2000 条) + ${lfT(`已显示 ${items.length} / 共 ${Number(events.total || items.length)} 条(单用户保留最近 30 天内最多 2000 条)`, `Showing ${items.length} of ${Number(events.total || items.length)} (up to 2,000 records from the last 30 days are kept per user)`)} ${events.hasMore ? `` : ''}
`; @@ -1271,7 +1302,7 @@

知识库与文档调用统计

-

累计调用 ${totalCalls} 次 · 文档命中/读取 ${totalDocCalls} 次 · 已引用 ${totalCited} 次

+

${lfT(`累计调用 ${totalCalls} 次 · 文档命中/读取 ${totalDocCalls} 次 · 已引用 ${totalCited} 次`, `${kbPlural(totalCalls, 'call', 'calls')} in total · ${kbPlural(totalDocCalls, 'document hit/read', 'document hits/reads')} · cited ${kbPlural(totalCited, 'time', 'times')}`)}

@@ -1330,8 +1361,8 @@ const notice = `
- 个人隔离:连接器与凭据仅归属当前账号,其他成员无法查看或调用。 - 只读安全代理:密钥 AES-GCM 加密托管,沙箱通过无状态代理检索并标注出处,支持按工具白名单精准放行只读工具。 + ${lfT('个人隔离:连接器与凭据仅归属当前账号,其他成员无法查看或调用。', 'Private to you: connectors and credentials belong to your account only; other members cannot view or use them.')} + ${lfT('只读安全代理:密钥 AES-GCM 加密托管,沙箱通过无状态代理检索并标注出处,支持按工具白名单精准放行只读工具。', 'Read-only secure proxy: keys are stored with AES-GCM encryption; the sandbox searches through a stateless proxy that labels every source, and a tool allowlist can admit only the read-only tools you choose.')}
`; @@ -1421,7 +1452,7 @@ }); kbState.checksByConn[id] = res; if (Array.isArray(res?.sources)) kbState.sourcesByConn[id] = res.sources; - kbToast(res.ok ? `连接正常(${res.latencyMs || 0} ms)` : (res.error || '连接失败'), !res.ok); + kbToast(res.ok ? lfT(`连接正常(${res.latencyMs || 0} ms)`, `Connection OK (${res.latencyMs || 0} ms)`) : (res.error || '连接失败'), !res.ok); renderKnowledgeView(); } catch (err) { kbState.checksByConn[id] = { ok: false, error: err.message }; diff --git a/web/i18n-en.js b/web/i18n-en.js index a45637a32..53894367e 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -1164,6 +1164,81 @@ 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.", }); +// Personal knowledge connectors (我的知识库): copy added with the connector +// gallery, usage statistics and node/chat knowledge references. +Object.assign(window.LF_I18N_EN, { + "接入并管理仅你本人可见的外部只读知识库连接器,供 AI 对话与 SOP 运行按需引用。": "Connect and manage read-only external knowledge connectors that only you can see, for AI chat and SOP runs to cite on demand.", + "常用知识库模板": "Popular knowledge base templates", + "常用知识库 · 快速接入": "Popular knowledge bases · Quick setup", + "快速配置": "Set up", + "编辑配置": "Edit settings", + "已绑定连接器:": "Connector: ", + "还没有接入个人知识库连接器": "No personal knowledge connectors yet", + "可从上方常用知识库模板快速配置,或选择一个连接器类型接入你的自有知识库;配置仅对你本人可见,可在 AI 对话、SOP 节点与手动运行中引用。": "Set one up from the popular templates above, or pick a connector type to link your own knowledge base. Settings are visible only to you and can be cited in AI chat, SOP nodes and manual runs.", + "接入此类型": "Use this type", + "正在加载个人知识库连接器…": "Loading personal knowledge connectors…", + "加载个人知识库连接器失败": "Failed to load personal knowledge connectors", + "服务地址:": "Endpoint: ", + "免鉴权 / 无密钥": "No auth / no key", + "工具白名单:": "Tool allowlist: ", + "连接失败": "Connection failed", + "只读工具:": "Read-only tools: ", + "可用子知识库": "Available sub-sources", + "当前连接器未返回可细分列表(默认按全局范围只读检索)。": "This connector returned no sub-source list (searches the whole scope read-only by default).", + "正在探测连接器…": "Probing connector…", + "连接器类型": "Connector type", + "连接器名称": "Connector name", + "请填写连接器名称": "Enter a connector name", + "启用此连接器(供 AI 对话和 SOP 选用)": "Enable this connector (available to AI chat and SOPs)", + "请求超时(秒)": "Request timeout (seconds)", + "默认 60": "Default 60", + "清除已保存的密钥(勾选后将移除原加密凭据)": "Clear the saved key (removes the stored encrypted credential)", + "该连接器类型无需额外字段。": "This connector type needs no extra fields.", + "已配置密钥,留空则保持不变": "Key configured; leave blank to keep it", + "连接器已添加": "Connector added", + "连接器已更新": "Connector updated", + "连接器已删除": "Connector deleted", + "已启用连接器": "Connector enabled", + "已停用连接器": "Connector disabled", + "文档": "Document", + "文档:": "Document: ", + "来源 ID,以逗号分隔": "Source IDs, comma-separated", + "在 Obsidian 安装并启用社区插件 Local REST API,复制 API Key 填入下方密钥框;HTTPS 默认端口 27124(本地自签证书自动信任),Docker 部署请在插件设置中绑定 0.0.0.0。": "Install and enable the Local REST API community plugin in Obsidian, then paste its API Key into the key field below. HTTPS uses port 27124 by default (the local self-signed certificate is trusted automatically); for Docker, bind 0.0.0.0 in the plugin settings.", + "前往 notion.so/profile/integrations 创建只读 Internal Integration 并复制 ntn_... 密钥;然后在目标页面右上角 ••• → Connections 关联该集成。": "Create a read-only Internal Integration at notion.so/profile/integrations and copy its ntn_... secret, then connect the integration from ••• → Connections at the top right of the target page.", + "在飞书开放平台创建企业自建应用、开启机器人能力并开通 wiki:wiki:readonly 与 docx:document:readonly 权限,发布后将机器人添加为目标知识空间的可阅读成员。": "Create a custom app on the Feishu Open Platform, enable its bot and grant wiki:wiki:readonly and docx:document:readonly; after publishing, add the bot to the target wiki space as a reader.", + "Local REST API 地址(HTTPS 默认 27124,HTTP 默认 27123;Docker 部署需在插件设置绑定 0.0.0.0)": "Local REST API URL (HTTPS defaults to 27124, HTTP to 27123; for Docker, bind 0.0.0.0 in the plugin settings)", + "填写 Local REST API Key(编辑留空则保留原密钥)": "Enter the Local REST API Key (leave blank when editing to keep the saved key)", + "在 Obsidian「设置 → Local REST API → Copy API Key」获取": "Get it in Obsidian under Settings → Local REST API → Copy API Key", + "默认 true(仅对本地/内网地址生效),用于直连插件默认的 27124 自签名 HTTPS 端口": "Defaults to true (local/intranet addresses only), for the plugin's default self-signed HTTPS port 27124", + "默认 https://api.notion.com,留空自动使用官方地址": "Defaults to https://api.notion.com; leave blank for the official endpoint", + "填入 Notion Internal Integration Secret,并在目标页面右上角 ••• → Connections 添加该集成": "Enter the Notion Internal Integration Secret, and add the integration from ••• → Connections at the top right of the target page", + "思源笔记服务地址;Docker 部署请开启思源「设置 → 关于 → 网络伺服」": "SiYuan server URL; for Docker, turn on Settings → About → Network serving in SiYuan", + "填写思源 API Token(编辑留空则保留原密钥)": "Enter the SiYuan API Token (leave blank when editing to keep the saved key)", + "在思源笔记「设置 → 关于 → API token」复制,使用 Authorization: Token 鉴权": "Copy it in SiYuan under Settings → About → API token; sent as Authorization: Token", + "默认 https://open.feishu.cn(国际版 Lark 请填 https://open.larksuite.com)": "Defaults to https://open.feishu.cn (use https://open.larksuite.com for Lark)", + "飞书开放平台企业自建应用的 App ID": "App ID of the custom app on the Feishu Open Platform", + "填写自建应用 App Secret(加密存储,自动换取并续期访问令牌)": "Enter the custom app's App Secret (stored encrypted; access tokens are fetched and renewed automatically)", + "开启应用机器人能力并开通 wiki:wiki:readonly、docx:document:readonly 后,将机器人添加为目标知识空间成员": "Enable the app's bot and grant wiki:wiki:readonly and docx:document:readonly, then add the bot as a member of the target wiki space", + "通过只读 REST API 接入个人或团队 WeKnora 实例(支持列子库、混合检索与分块原文读取)": "Connect a personal or team WeKnora instance through its read-only REST API (lists knowledge bases, hybrid search and chunk reading)", + "WeKnora 服务地址": "WeKnora URL", + "填写 WeKnora 基础地址(例如 http://host:8080,不能带查询参数)": "Enter the WeKnora base URL (for example http://host:8080, no query string)", + "填写 WeKnora API Key(编辑留空则保留原密钥)": "Enter the WeKnora API Key (leave blank when editing to keep the saved key)", + "使用 X-API-Key 请求头鉴权,保存后 AES-GCM 加密存储": "Sent in the X-API-Key header and stored with AES-GCM encryption", + "通用知识 MCP(Streamable HTTP)": "Generic knowledge MCP (Streamable HTTP)", + "接入遵循 Streamable HTTP MCP 协议的只读知识库服务(免授权 / 静态 Token / 本地桥接)": "Connect a read-only knowledge service that speaks Streamable HTTP MCP (no auth, static token or local bridge)", + "接入遵循 Streamable HTTP MCP 协议的任意只读知识库服务(含 LightCloud 等),仅放行 readOnlyHint 工具": "Connect any read-only knowledge service that speaks Streamable HTTP MCP (LightCloud and others); only readOnlyHint tools are allowed", + "MCP 服务地址": "MCP server URL", + "填写 http(s):// Streamable HTTP MCP Endpoint(不能内嵌账号密码)": "Enter the http(s):// Streamable HTTP MCP endpoint (no embedded username or password)", + "Bearer Token(可选)": "Bearer Token (optional)", + "Bearer Token(留空则不发送或使用自定义请求头)": "Bearer Token (leave blank to send none or use custom headers)", + "将自动放入 Authorization: Bearer 头,保存后 AES-GCM 加密存储": "Sent as an Authorization: Bearer header and stored with AES-GCM encryption", + "认证请求头(可选)": "Auth headers (optional)", + "每行填写一个 Header: Value(例如 Authorization: 或 X-Lark-MCP-TAT: xxx),保存后加密存储": "One Header: Value per line (for example Authorization: or X-Lark-MCP-TAT: xxx); stored encrypted", + "允许工具白名单(可选)": "Tool allowlist (optional)", + "例如:fetch-doc, search-doc 或 manage.search_file, get_content": "For example: fetch-doc, search-doc or manage.search_file, get_content", + "逗号或换行分隔;留空按默认只读策略放行,配置后仅放行列表内的工具(推荐用于飞书远程端点与腾讯文档)": "Comma- or newline-separated. Leave blank to use the default read-only policy; once set, only the listed tools are allowed (recommended for Feishu remote endpoints and Tencent Docs)", +}); + // 执行机器 page: static copy in index.html. runners.js renders its dynamic copy with lfT. Object.assign(window.LF_I18N_EN, { "连接电脑或 CVM,可将机器共享给多个项目。": "Connect a computer or CVM and share it with multiple projects.", diff --git a/webtest/tests/i18n-knowledge.test.mjs b/webtest/tests/i18n-knowledge.test.mjs new file mode 100644 index 000000000..81c42df97 --- /dev/null +++ b/webtest/tests/i18n-knowledge.test.mjs @@ -0,0 +1,172 @@ +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 { loadApp, settle, WEB_ROOT } from '../lib/load-app.mjs'; + +const HAN = /[㐀-鿿]/; +const ATTRS = ['placeholder', 'title', 'aria-label', 'data-tip', 'data-tooltip']; + +async function englishPage() { + 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.window; +} + +// Chinese left in product copy; user data (data-i18n-data) may stay Chinese. +function leftoverChinese(root) { + const left = []; + for (const el of [root, ...root.querySelectorAll('*')]) { + if (el.closest('[data-i18n-data],[data-i18n-skip],code')) continue; + for (const node of el.childNodes) if (node.nodeType === 3 && HAN.test(node.nodeValue)) left.push(node.nodeValue.trim()); + for (const name of ATTRS) { + const value = el.getAttribute(name); + if (value && HAN.test(value)) left.push(`${name}="${value}"`); + } + } + return left; +} + +const CHAT_TITLE = '先查一下库存估值相关的规则(INV-RULE-9),然后实现'; +const ROUTES = [ + { method: 'GET', path: '/api/knowledge/connectors', body: [{ + id: 'kb_obs', name: '团队 Obsidian 笔记', type: 'obsidian', endpoint: 'http://127.0.0.1:27123', + enabled: true, secretConfigured: true, config: { timeoutSec: 30 }, + }] }, + { method: 'GET', path: '/api/knowledge/usage', body: { + totalCalls: 6, totalDocumentCalls: 4, totalCitedCount: 1, + connectors: [{ connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', callCount: 6 }], + documents: [{ + connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', sourceName: '库存系统', documentId: 'doc-1', + title: '库存估值说明', searchHitCount: 2, readCount: 2, citedCount: 1, callCount: 4, + topCallers: [ + { kind: 'sop', label: '库存缺陷修复 LOOP', subLabel: '开发实现 · 开发实现', callCount: 2, runId: 'run-1', nodeId: 'implement' }, + { kind: 'chat', label: CHAT_TITLE, subLabel: '个人对话', callCount: 1, sessionId: 'ses-1' }, + ], + }, { + connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', sourceName: '库存系统', documentId: 'doc-2', + title: '发布与回滚', searchHitCount: 1, readCount: 0, citedCount: 0, callCount: 2, + // Callers without a title: the server falls back to the Chinese kind name. + topCallers: [ + { kind: 'scheduled', label: '定时任务', subLabel: '定时任务', callCount: 1 }, + { kind: 'chat', label: '个人对话', subLabel: '个人对话', callCount: 1 }, + ], + }], + } }, + { method: 'GET', path: /^\/api\/knowledge\/usage\/events/, body: { + total: 2, hasMore: false, + items: [ + { id: 1, connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', sourceName: '库存系统', documentId: 'doc-1', + title: '库存估值说明', action: 'read', query: '库存估值', cited: true, calledAt: '2026-11-27T10:30:00Z', + caller: { kind: 'sop', workflowName: '库存缺陷修复 LOOP', agentName: '开发实现', nodeName: '开发实现', runId: 'run-1', nodeId: 'implement' } }, + { id: 2, connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', documentId: 'doc-1', title: '库存估值说明', + action: 'search', calledAt: '2026-11-27T10:31:00Z', caller: { kind: 'chat', sessionTitle: CHAT_TITLE, sessionId: 'ses-1' } }, + ], + } }, +]; + +async function renderEnglishKnowledge(t, prepare) { + const app = await loadApp({ routes: ROUTES }); + t.after(app.close); + // The app page runs i18n.js in Chinese; switch its lfT to English like a page loaded with data-lang="en". + app.evaluate("window.lfT = (zh, en) => en; toast = () => {};"); + app.evaluate("switchView('knowledge')"); + await settle(12); + if (prepare) await prepare(app); + const en = await englishPage(); + t.after(() => en.close()); + const root = en.document.createElement('div'); + root.innerHTML = app.document.querySelector('#kbHeadDesc').outerHTML + app.document.querySelector('#knowledgeRoot').innerHTML; + en.document.body.append(root); + await new Promise(resolve => en.setTimeout(resolve, 0)); + return { app, root }; +} + +test('English mode leaves no Chinese copy in 我的知识库 (gallery, connector card, usage by document)', async (t) => { + const { root } = await renderEnglishKnowledge(t); + assert.deepEqual(leftoverChinese(root), []); + const text = root.textContent.replace(/\s+/g, ' '); + assert.match(text, /6 calls in total · 4 document hits\/reads · cited 1 time\b/); + // Connector card: the label keeps its space before the user-named connector. + assert.match(text, /Connector: 团队 Obsidian 笔记/); + assert.match(text, /Timeout: 30s/); + assert.match(text, /Popular knowledge bases · Quick setup/); + // User data is shown as written, not run through fragment translation. + assert.ok(root.querySelector('.kb-card h3, h3[data-i18n-data]').textContent.includes('团队 Obsidian 笔记')); + const pills = [...root.querySelectorAll('.kb-usage-caller-name')].map(el => el.textContent); + assert.deepEqual(pills, ['库存缺陷修复 LOOP · 开发实现', CHAT_TITLE, 'Scheduled task', 'Personal chat']); +}); + +test('English mode leaves no Chinese copy in the knowledge call history and keeps user titles intact', async (t) => { + const { root } = await renderEnglishKnowledge(t, async (app) => { + app.document.querySelector('[data-kb-usage-tab="events"]').click(); + await settle(12); + }); + assert.ok(root.querySelector('[data-kb-usage-events-table]')); + assert.deepEqual(leftoverChinese(root), []); + const text = root.textContent.replace(/\s+/g, ' '); + assert.match(text, /Showing 2 of 2 \(up to 2,000 records from the last 30 days are kept per user\)/); + const callers = [...root.querySelectorAll('.kb-usage-caller-main')].map(el => el.textContent); + assert.deepEqual(callers, ['库存缺陷修复 LOOP', CHAT_TITLE]); + const subs = [...root.querySelectorAll('.kb-usage-caller-jump .kb-usage-doc-sub')].map(el => el.textContent); + assert.deepEqual(subs, ['Implementation']); +}); + +test('caller sub-labels drop repeated role/node names and the kind already shown on the badge', async (t) => { + const app = await loadApp({ routes: ROUTES }); + t.after(app.close); + app.evaluate("switchView('knowledge')"); + await settle(12); + const names = [...app.document.querySelectorAll('.kb-usage-caller-name')].map(el => el.textContent); + assert.deepEqual(names, ['库存缺陷修复 LOOP · 开发实现', CHAT_TITLE, '定时任务', '个人对话']); +}); + +test('English caller pills translate server fallback names and use the shared dictionary wording', async (t) => { + const { root } = await renderEnglishKnowledge(t); + const pills = [...root.querySelectorAll('.kb-usage-caller-pill')]; + const scheduled = pills.find(el => el.querySelector('.kb-usage-caller-tag').textContent === 'Scheduled task'); + const chat = pills.filter(el => el.querySelector('.kb-usage-caller-tag').textContent === 'Personal chat').pop(); + assert.ok(scheduled && chat); + assert.equal(scheduled.querySelector('.kb-usage-caller-name').textContent, 'Scheduled task'); + assert.equal(scheduled.getAttribute('title'), 'Scheduled task · Scheduled task'); + assert.equal(chat.querySelector('.kb-usage-caller-name').textContent, 'Personal chat'); + assert.equal(chat.getAttribute('title'), 'Personal chat · Personal chat'); + assert.deepEqual(leftoverChinese(root), []); +}); + +test('English counts use singular forms for one item', async (t) => { + const app = await loadApp({ routes: ROUTES.map(r => r.path === '/api/knowledge/usage' + ? { ...r, body: { ...r.body, totalCalls: 1, totalDocumentCalls: 1, totalCitedCount: 1, connectors: [{ connectorId: 'kb_obs', connectorName: '团队 Obsidian 笔记', callCount: 1 }] } } + : r) }); + t.after(app.close); + app.evaluate("window.lfT = (zh, en) => en; toast = () => {};"); + app.evaluate("switchView('knowledge')"); + await settle(12); + const text = app.document.querySelector('#knowledgeRoot').textContent.replace(/\s+/g, ' '); + assert.match(text, /1 call in total · 1 document hit\/read · cited 1 time\b/); + assert.match(text, /\b1 call\b/); + assert.doesNotMatch(text, /\b1 (calls|times|docs)\b/); +}); + +test('English 关联知识库 dialog keeps the unavailable-connector suffix in English', async (t) => { + const app = await loadApp({ routes: [{ method: 'GET', path: '/api/knowledge/reference-options', body: [] }] }); + t.after(app.close); + app.evaluate("window.lfT = (zh, en) => en; toast = () => {};"); + app.evaluate("window.editKnowledgeRefs('', [{ connectorId: 'kb_gone' }], async () => {})"); + await settle(12); + const en = await englishPage(); + t.after(() => en.close()); + const root = en.document.createElement('div'); + const modal = app.document.querySelector('.kr-service')?.closest('.modal, [role="dialog"], .kr-modal') || app.document.querySelector('.kr-service').parentElement; + root.innerHTML = modal.outerHTML; + en.document.body.append(root); + await new Promise(resolve => en.setTimeout(resolve, 0)); + const titles = [...root.querySelectorAll('.kr-service-title')].map(el => el.textContent); + assert.deepEqual(titles, ['kb_gone (expired or unauthorized)']); + const aria = root.querySelector('.kr-control[aria-label]').getAttribute('aria-label'); + assert.equal(aria, 'Allowed source IDs for kb_gone (expired or unauthorized)'); +});