Python
feat(memhub): add extensible Chinese, English, and Spanish UI (#142)
feitianxiang366befc2aac8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 98acf6a..4641c34 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,6 +40,10 @@ Hy Memory and MemHub are versioned and released independently.## Unreleased+- Added an extensible MemHub interface-localization layer with Simplified+ Chinese, English, and Spanish catalogs shared by Web and Electron-native+ surfaces. Interface language remains independent from memory content and+ model processing language.- `search(..., layers=["l1_raw"])` now explicitly searches SDK raw records inpro/ultra mode and keeps existing user/agent/session/source filters; defaultsearch continues to hide raw.diff --git a/memhub/CONTRIBUTING.md b/memhub/CONTRIBUTING.mdindex 4cbec37..9ee6849 100644--- a/memhub/CONTRIBUTING.md+++ b/memhub/CONTRIBUTING.md@@ -1,6 +1,6 @@# Contributing-感谢你参与 One Memory。+感谢你参与 MemHub。## 开发环境@@ -27,3 +27,10 @@ pnpm check涉及外部源码时,必须记录项目、固定版本或 commit、许可证、采用文件和修改说明。不得提交密钥、内部地址、真实对话、个人路径、模型权重或签名证书。++## 界面翻译++新增或修改界面语言时遵循+[`docs/LOCALIZATION.md`](docs/LOCALIZATION.md):使用稳定语义 key,保持所有+locale 的 key 与占位符一致,不翻译用户内容、路径、标识符或外部错误正文。语言+catalog 与无关产品行为应拆成不同 PR。diff --git a/memhub/README.md b/memhub/README.mdindex 9b9f3f5..7f13a7c 100644--- a/memhub/README.md+++ b/memhub/README.md@@ -50,11 +50,14 @@ Linux 制品由 GitHub Actions 在原生架构 runner 上构建并完成生命- `apps/web`:React / TypeScript 管理界面。- `apps/desktop`:Electron 桌面壳与图形安装入口。- `packages/contracts`:公共 API 类型。+- `packages/i18n`:Web 与 Electron 共用的界面语言合同和 catalog。- `packages/host-bridge`:AI App 的 Skill、Hook、插件和 MCP 接入。- `packages/runtime-control`:Core、Host Gateway 和 Runtime 生命周期控制。架构详情见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) 和[`docs/contracts/runtime-unification.md`](docs/contracts/runtime-unification.md)。+界面语言架构与社区翻译规则见+[`docs/LOCALIZATION.md`](docs/LOCALIZATION.md)。产品、测试和一线支持排查导入与记忆沉淀时,使用[`docs/PRODUCT_LOG_TROUBLESHOOTING.md`](docs/PRODUCT_LOG_TROUBLESHOOTING.md)。diff --git a/memhub/SBOM.spdx.json b/memhub/SBOM.spdx.jsonindex ebef371..6794e68 100644--- a/memhub/SBOM.spdx.json+++ b/memhub/SBOM.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "one-memory",- "documentNamespace": "https://one-memory.local/spdx/2026-10-17T13:52:48Z",+ "documentNamespace": "https://one-memory.local/spdx/2026-10-22T08:09:31Z","creationInfo": {- "created": "2026-10-17T13:52:48Z",+ "created": "2026-10-22T08:09:31Z","creators": ["Tool: one-memory-generate-sbom"]@@ -88,6 +88,23 @@}]},+ {+ "SPDXID": "SPDXRef-Package-npm-i18next",+ "name": "i18next",+ "versionInfo": "25.10.10",+ "downloadLocation": "NOASSERTION",+ "filesAnalyzed": false,+ "licenseConcluded": "NOASSERTION",+ "licenseDeclared": "NOASSERTION",+ "copyrightText": "NOASSERTION",+ "externalRefs": [+ {+ "referenceCategory": "PACKAGE-MANAGER",+ "referenceType": "purl",+ "referenceLocator": "pkg:npm/[email protected]"+ }+ ]+ },{"SPDXID": "SPDXRef-Package-npm-lucide-react","name": "lucide-react",@@ -2380,6 +2397,11 @@"relationshipType": "DEPENDS_ON","relatedSpdxElement": "SPDXRef-Package-npm-https-proxy-agent"},+ {+ "spdxElementId": "SPDXRef-Package-one-memory",+ "relationshipType": "DEPENDS_ON",+ "relatedSpdxElement": "SPDXRef-Package-npm-i18next"+ },{"spdxElementId": "SPDXRef-Package-one-memory","relationshipType": "DEPENDS_ON",diff --git a/memhub/THIRD_PARTY_NOTICES.md b/memhub/THIRD_PARTY_NOTICES.mdindex f2b9506..dd7a6bb 100644--- a/memhub/THIRD_PARTY_NOTICES.md+++ b/memhub/THIRD_PARTY_NOTICES.md@@ -2,7 +2,7 @@MemHub itself is licensed under Apache-2.0 (see `LICENSE`).It bundles the runtime dependencies listed below.-Generated from the installed dependency tree on 2026-10-17T13:52:48Z+Generated from the installed dependency tree on 2026-10-22T08:09:31Zby `python3 scripts/generate_sbom.py`. Do not edit by hand.Per-package license texts are not reproduced here yet; the license@@ -112,12 +112,13 @@ Adaptation boundary:No Memmy brand, icon, font or mascot assets are distributed.-## JavaScript (npm) — 10 packages+## JavaScript (npm) — 11 packages- @tanstack/react-query 5.103.2- axios 1.20.0- fflate 0.8.3- https-proxy-agent 7.0.0+- i18next 25.10.10- lucide-react 1.43.0- proxy-from-env 2.1.0- react 19.2.8diff --git a/memhub/apps/desktop/package.json b/memhub/apps/desktop/package.jsonindex 7942674..742eefe 100644--- a/memhub/apps/desktop/package.json+++ b/memhub/apps/desktop/package.json@@ -84,6 +84,7 @@"dependencies": {"@one-memory/contracts": "workspace:*","@one-memory/host-bridge": "workspace:*",+ "@one-memory/i18n": "workspace:*","@one-memory/runtime-control": "workspace:*","axios": "^1.20.0"}diff --git a/memhub/apps/desktop/src/application-menu.test.ts b/memhub/apps/desktop/src/application-menu.test.tsindex 9ebd62b..70d5de0 100644--- a/memhub/apps/desktop/src/application-menu.test.ts+++ b/memhub/apps/desktop/src/application-menu.test.ts@@ -1,7 +1,46 @@+import type { LanguageSnapshot } from "@one-memory/i18n";import { expect, it, vi } from "vitest";import { installApplicationMenu } from "./application-menu";+it("rebuilds translated labels from committed language updates without exporting", () => {+ let change: (() => void) | undefined;+ const snapshot: LanguageSnapshot = {+ preference: "es",+ locale: "es",+ revision: 1,+ };+ const unsubscribe = vi.fn();+ const read = vi.fn(() => snapshot);+ const buildMenu = vi.fn(() => ({}) as never);+ const dispose = installApplicationMenu({+ productName: "MemHub",+ buildMenu,+ setMenu: vi.fn(),+ exportLogs: async () => {},+ reportError: vi.fn(),+ language: {+ read,+ subscribe: (listener) => {+ change = () => listener(snapshot);+ return unsubscribe;+ },+ },+ });+ expect(buildMenu).toHaveBeenLastCalledWith(+ expect.arrayContaining([expect.objectContaining({ label: "Ayuda" })]),+ );+ snapshot.locale = "zh-CN";+ change?.();+ expect(read).toHaveBeenCalledTimes(2);+ expect(buildMenu).toHaveBeenCalledTimes(2);+ expect(buildMenu).toHaveBeenLastCalledWith(+ expect.arrayContaining([expect.objectContaining({ label: "帮助" })]),+ );+ dispose();+ expect(unsubscribe).toHaveBeenCalledTimes(1);+});+it("exports logs from Help without requiring a renderer window", async () => {const exportLogs = vi.fn(async () => undefined);let template: Array<Record<string, unknown>> = [];diff --git a/memhub/apps/desktop/src/application-menu.ts b/memhub/apps/desktop/src/application-menu.tsindex ad1413c..0efb260 100644--- a/memhub/apps/desktop/src/application-menu.ts+++ b/memhub/apps/desktop/src/application-menu.ts@@ -1,36 +1,49 @@+import { translate } from "@one-memory/i18n";import type { Menu, MenuItemConstructorOptions } from "electron";+import type { NativeLanguageSource } from "./native-language";export function installApplicationMenu(options: {productName: string;+ language?: NativeLanguageSource;buildMenu(template: MenuItemConstructorOptions[]): Menu;setMenu(menu: Menu): void;exportLogs(): Promise<void>;reportError(message: string): void;-}): void {+}): () => void {const runExport = async () => {try {await options.exportLogs();} catch {- options.reportError("日志未能导出,请稍后重试。");+ options.reportError(+ translate(+ options.language?.read().locale ?? "zh-CN",+ "nativeExportError",+ ),+ );}};- options.setMenu(- options.buildMenu([- {- label: options.productName,- submenu: [{ role: "about" }, { type: "separator" }, { role: "quit" }],- },- { role: "editMenu" },- { role: "windowMenu" },- {- label: "帮助",- submenu: [- {- label: "导出日志(发给开发排查)",- click: runExport,- },- ],- },- ]),- );+ const refresh = () => {+ const locale = options.language?.read().locale ?? "zh-CN";+ options.setMenu(+ options.buildMenu([+ {+ label: options.productName,+ submenu: [{ role: "about" }, { type: "separator" }, { role: "quit" }],+ },+ { role: "editMenu" },+ { role: "windowMenu" },+ {+ label: translate(locale, "nativeHelp"),+ submenu: [+ {+ label: translate(locale, "nativeExportLogs"),+ click: runExport,+ },+ ],+ },+ ]),+ );+ };+ refresh();+ return options.language?.subscribe(refresh) ?? (() => {});}diff --git a/memhub/apps/desktop/src/background-tray.test.ts b/memhub/apps/desktop/src/background-tray.test.tsindex de9c348..dd3657f 100644--- a/memhub/apps/desktop/src/background-tray.test.ts+++ b/memhub/apps/desktop/src/background-tray.test.ts@@ -1,4 +1,5 @@import { EventEmitter } from "node:events";+import type { LanguageSnapshot } from "@one-memory/i18n";import type {App,Menu,@@ -25,6 +26,12 @@ function fixture(enabled: false,status: "disabled",};+ let changed: (() => void) | undefined;+ const languageSnapshot: LanguageSnapshot = {+ preference: "zh-CN",+ locale: "zh-CN",+ revision: 1,+ };const app = { isPackaged: packaged, quit: vi.fn() };const tray = Object.assign(new EventEmitter(), {setToolTip: vi.fn(),@@ -49,6 +56,15 @@ function fixture(installBackgroundTray({app: app as unknown as App,platform,+ language: {+ read: () => languageSnapshot,+ subscribe: (listener) => {+ changed = () => listener(languageSnapshot);+ return () => {+ changed = undefined;+ };+ },+ },resourcesPath: "/bundle/Contents/Resources",appPath: "/repo/apps/desktop",createImage: vi.fn(() => image as unknown as NativeImage),@@ -80,6 +96,10 @@ function fixture(install,menu,click,+ changeLanguage(locale: LanguageSnapshot["locale"]) {+ languageSnapshot.locale = locale;+ changed?.();+ },setState(value: LoginPreference) {state = value;},@@ -87,6 +107,26 @@ function fixture(}describe("native macOS background tray", () => {+ it("rebuilds Spanish and Chinese labels without changing login or stopping services", async () => {+ const f = fixture();+ f.install();+ await flush();+ f.changeLanguage("es");+ await flush();+ expect(f.menu()[0]?.label).toBe("Abrir MemHub");+ expect(f.menu()[1]?.label).toBe("Iniciar MemHub al iniciar sesión");+ expect(f.menu()[3]?.label).toBe(+ "Salir de MemHub (el servicio sigue en segundo plano)",+ );+ expect(f.setLoginPreference).not.toHaveBeenCalled();+ f.click(0);+ expect(f.open).toHaveBeenCalledOnce();+ f.changeLanguage("zh-CN");+ await flush();+ expect(f.menu()[0]?.label).toBe("打开 MemHub");+ f.click(3);+ expect(f.app.quit).toHaveBeenCalledOnce();+ });it("reads and changes the unified Runtime login preference", async () => {const f = fixture();const dispose = f.install();diff --git a/memhub/apps/desktop/src/background-tray.ts b/memhub/apps/desktop/src/background-tray.tsindex 9b015ec..ea02794 100644--- a/memhub/apps/desktop/src/background-tray.ts+++ b/memhub/apps/desktop/src/background-tray.ts@@ -1,4 +1,5 @@import path from "node:path";+import { type MessageKey, translate } from "@one-memory/i18n";import type {App,Menu,@@ -7,6 +8,7 @@ import type {Tray,} from "electron";import type { LoginPreference } from "./login-preference";+import type { NativeLanguageSource } from "./native-language";export const LOGIN_SERVICE_NAME = "com.tencent.onememory.runtime.plist";@@ -24,6 +26,7 @@ interface TrayOptions {setLoginPreference(enabled: boolean): Promise<LoginPreference>;allowLoginStartup?: boolean;productName?: string;+ language?: NativeLanguageSource;}export function installBackgroundTray(options: TrayOptions): () => void {@@ -41,29 +44,32 @@ export function installBackgroundTray(options: TrayOptions): () => void {let generation = 0;const refresh = async () => {if (disposed) return;+ const locale = options.language?.read().locale ?? "zh-CN";+ const t = (key: MessageKey) =>+ translate(locale, key, { product: productName });const current = ++generation;let checked = false;let enabled = app.isPackaged && options.allowLoginStartup !== false;- let label = `登录时启动 ${productName}`;+ let label = t("nativeLogin");if (options.allowLoginStartup === false) {- label += "(阶段包不可用)";+ label += t("nativeTrialUnavailable");} else if (app.isPackaged) {try {const state = await options.readLoginPreference();if (disposed || current !== generation) return;checked = state.enabled;enabled = state.supported;- if (state.status === "managed-by-cli") label += "(由 CLI 管理)";+ if (state.status === "managed-by-cli") label += t("nativeCliManaged");} catch {- label += "(状态不可用)";+ label += t("nativeStatusUnavailable");enabled = false;}} else {- label += "(开发模式不可用)";+ label += t("nativeDevelopmentUnavailable");}tray.setContextMenu(options.buildMenu([- { label: `打开 ${productName}`, click: options.open },+ { label: t("nativeOpen"), click: options.open },{label,type: "checkbox",@@ -74,14 +80,19 @@ export function installBackgroundTray(options: TrayOptions): () => void {void options.setLoginPreference(item.checked).catch(() =>- options.reportError("无法更改登录启动设置,请重试。"),+ options.reportError(+ translate(+ options.language?.read().locale ?? "zh-CN",+ "nativeLoginError",+ ),+ ),).finally(() => void refresh());},},{ type: "separator" },{- label: `退出 ${productName}(后台服务继续运行)`,+ label: t("nativeQuit"),click: () => {if (!disposed) app.quit();},@@ -89,6 +100,7 @@ export function installBackgroundTray(options: TrayOptions): () => void {]),);};+ const unsubscribeLanguage = options.language?.subscribe(() => void refresh());try {void refresh();// Refresh before the native menu opens, including changes made in Settings.@@ -101,6 +113,7 @@ export function installBackgroundTray(options: TrayOptions): () => void {return () => {if (disposed) return;disposed = true;+ unsubscribeLanguage?.();tray.removeAllListeners("mouse-down");tray.removeAllListeners("right-click");tray.destroy();diff --git a/memhub/apps/desktop/src/desktop-lifecycle.test.ts b/memhub/apps/desktop/src/desktop-lifecycle.test.tsindex 2f357f4..9ad3303 100644--- a/memhub/apps/desktop/src/desktop-lifecycle.test.ts+++ b/memhub/apps/desktop/src/desktop-lifecycle.test.ts@@ -50,6 +50,7 @@ interface Overrides {whenReady?: Promise<void>;windowGate?: Promise<void>;windowError?: Error;+ beforeNativeUi?: () => Promise<void>;/** Give the lifecycle a startup placeholder, as the packaged App does. */startupWindow?: boolean;startupWindowError?: Error;@@ -94,6 +95,7 @@ function fixture(background = false, lock = true, overrides: Overrides = {}) {platform: overrides.platform ?? "darwin",background,prepare,+ beforeNativeUi: overrides.beforeNativeUi,initialize,stop,dispose,@@ -148,6 +150,35 @@ function fixture(background = false, lock = true, overrides: Overrides = {}) {}describe("desktop background lifecycle with injected Electron", () => {+ it("awaits the post-readiness language hook before menus, tray and runtime", async () => {+ const gate = deferred();+ const beforeNativeUi = vi.fn(() => gate.promise);+ const f = fixture(false, true, { beforeNativeUi });+ expect(beforeNativeUi).not.toHaveBeenCalled();+ f.ready.resolve();+ await f.flush();+ expect(beforeNativeUi).toHaveBeenCalledTimes(1);+ expect(f.installTray).not.toHaveBeenCalled();+ expect(f.initialize).not.toHaveBeenCalled();+ gate.resolve();+ f.starting.resolve();+ await f.flush();+ expect(f.installTray).toHaveBeenCalledTimes(1);+ expect(f.windows).toHaveLength(1);+ });+ it("does not install native UI after quitting during the language hook", async () => {+ const gate = deferred();+ const f = fixture(false, true, { beforeNativeUi: () => gate.promise });+ f.ready.resolve();+ await f.flush();+ f.quit();+ gate.resolve();+ await f.flush();+ expect(f.installTray).not.toHaveBeenCalled();+ expect(f.initialize).not.toHaveBeenCalled();+ f.stopping.resolve();+ await f.flush();+ });it("starts services and tray without a window in background mode", async () => {const f = fixture(true);await f.boot();diff --git a/memhub/apps/desktop/src/desktop-lifecycle.ts b/memhub/apps/desktop/src/desktop-lifecycle.tsindex e7de675..dc50659 100644--- a/memhub/apps/desktop/src/desktop-lifecycle.ts+++ b/memhub/apps/desktop/src/desktop-lifecycle.ts@@ -18,6 +18,7 @@ interface LifecycleOptions {platform: NodeJS.Platform;background: boolean;prepare(): void;+ beforeNativeUi?(): Promise<void>;initialize(isQuitting: () => boolean): Promise<void>;stop(): Promise<void>;dispose(): void;@@ -152,6 +153,8 @@ export function startDesktopLifecycle(options: LifecycleOptions): void {.then(async () => {if (quitting) return;startup = Promise.resolve().then(async () => {+ if (quitting) return;+ await options.beforeNativeUi?.();if (quitting) return;options.installTray(open);// A window first, services second. Startup can take tens of seconds;diff --git a/memhub/apps/desktop/src/display-preferences-ipc.test.ts b/memhub/apps/desktop/src/display-preferences-ipc.test.tsindex 0ad56b9..ca91e79 100644--- a/memhub/apps/desktop/src/display-preferences-ipc.test.ts+++ b/memhub/apps/desktop/src/display-preferences-ipc.test.ts@@ -1,4 +1,8 @@import { EventEmitter } from "node:events";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { translate } from "@one-memory/i18n";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";interface FakeFrame {@@ -11,13 +15,17 @@ interface FakeFrame {const fake = vi.hoisted(() => ({ready: undefined as (() => Promise<void>) | undefined,- handlers: new Map<string, (event: unknown) => unknown>(),+ handlers: new Map<string, (event: unknown, ...args: unknown[]) => unknown>(),windows: [] as FakeWindow[],app: undefined as unknown as EventEmitter,theme: undefined as unknown as EventEmitter,renderer: undefined as unknown as EventEmitter,unload: undefined as unknown as EventTarget,packaged: true,+ userData: "",+ preferred: vi.fn(() => ["es-MX", "zh-CN"]),+ locale: vi.fn(() => "zh-CN"),+ menu: vi.fn(),loadFailure: false,reduceMotion: false as unknown,reduceTransparency: false as unknown,@@ -93,7 +101,10 @@ vi.mock("electron", () => ({}),isPackaged: fake.packaged,getName: () => "One Memory Preview",- getPath: () => "/unused/display-test",+ getPath: (name: string) =>+ name === "userData" ? fake.userData : "/unused/display-test",+ getPreferredSystemLanguages: fake.preferred,+ getLocale: fake.locale,getAppPath: () => "/unused/display-test",quit: vi.fn(),exit: vi.fn(),@@ -119,8 +130,10 @@ vi.mock("electron", () => ({},BrowserWindow: FakeWindow,ipcMain: {- handle: (channel: string, handler: (event: unknown) => unknown) =>- fake.handlers.set(channel, handler),+ handle: (+ channel: string,+ handler: (event: unknown, ...args: unknown[]) => unknown,+ ) => fake.handlers.set(channel, handler),removeHandler: (channel: string) => {fake.removeHandler(channel);fake.handlers.delete(channel);@@ -138,7 +151,7 @@ vi.mock("electron", () => ({session: { defaultSession: {} },clipboard: { writeText: vi.fn() },dialog: { showErrorBox: fake.error },- Menu: { buildFromTemplate: vi.fn(() => ({})), setApplicationMenu: vi.fn() },+ Menu: { buildFromTemplate: vi.fn(() => ({})), setApplicationMenu: fake.menu },shell: { openExternal: vi.fn() },}));vi.mock("@one-memory/host-bridge", () => ({@@ -190,7 +203,8 @@ vi.mock("./core-supervisor", () => ({findAvailablePort: async () => 9999,}));-beforeEach(() => {+beforeEach(async () => {+ fake.userData = await mkdtemp(path.join(os.tmpdir(), "memhub-language-ipc-"));vi.resetModules();vi.resetAllMocks();fake.app = new EventEmitter();@@ -212,8 +226,9 @@ beforeEach(() => {vi.stubEnv("ONE_MEMORY_WEB_URL", "http://127.0.0.1:5173");vi.stubEnv("ONE_MEMORY_SMOKE_QUIT_MS", "0");});-afterEach(() => {+afterEach(async () => {fake.app.emit("will-quit");+ await rm(fake.userData, { recursive: true, force: true });fake.unload.dispatchEvent(new Event("unload"));vi.unstubAllGlobals();vi.unstubAllEnvs();@@ -242,6 +257,91 @@ const eventFor = (window: FakeWindow) => ({senderFrame: window.frame,});+describe("GUI language main IPC", () => {+ it("loads the active profile after ready and before native menus", async () => {+ await writeFile(+ path.join(fake.userData, "gui-language.json"),+ JSON.stringify({ preference: "es" }),+ );+ await import("./main.js");+ expect(fake.preferred).not.toHaveBeenCalled();+ expect(fake.menu).not.toHaveBeenCalled();+ await fake.ready?.();+ expect(fake.preferred).toHaveBeenCalledTimes(1);+ expect(fake.preferred.mock.invocationCallOrder[0]).toBeLessThan(+ fake.menu.mock.invocationCallOrder[0],+ );+ const read = fake.handlers.get("one-memory:get-language-preference");+ if (!read) throw Error("Missing language read handler");+ expect(await read(eventFor(fake.windows[0]))).toEqual({+ preference: "es",+ locale: "es",+ revision: 0,+ });+ });+ it("guards both operations and broadcasts only to live owned main frames", async () => {+ const window = await startup();+ const read = fake.handlers.get("one-memory:get-language-preference");+ if (!read) throw Error("Missing language read handler");+ const write = fake.handlers.get("one-memory:set-language-preference");+ if (!write) throw Error("Missing language write handler");+ const foreign = new FakeWindow();+ for (const event of [+ eventFor(foreign),+ {+ sender: window.webContents,+ senderFrame: { ...window.frame, parent: window.frame },+ },+ { sender: window.webContents, senderFrame: null },+ ]) {+ await expect(read(event)).rejects.toThrow();+ await expect(write(event, "es")).rejects.toThrow();+ }+ window.frame.url = "https://example.invalid";+ await expect(read(eventFor(window))).rejects.toThrow();+ await expect(write(eventFor(window), "es")).rejects.toThrow();+ window.frame.url = "one-memory://app/index.html";+ await write(eventFor(window), "zh-CN");+ expect(window.frame.send).toHaveBeenCalledWith(+ "one-memory:language-preference-changed",+ { preference: "zh-CN", locale: "zh-CN", revision: 1 },+ );+ expect(foreign.frame.send).not.toHaveBeenCalled();+ window.frame.send.mockImplementation(() => {+ throw Error("destroyed during send");+ });+ await expect(write(eventFor(window), "es")).resolves.toMatchObject({+ revision: 2,+ });+ fake.app.emit("will-quit");+ expect(fake.handlers.has("one-memory:get-language-preference")).toBe(false);+ expect(fake.handlers.has("one-memory:set-language-preference")).toBe(false);+ });+ it("does not deliver an admitted write to a document that navigated during persistence", async () => {+ const window = await startup();+ const write = fake.handlers.get("one-memory:set-language-preference");+ const read = fake.handlers.get("one-memory:get-language-preference");+ if (!write || !read) throw Error("Missing language handlers");+ const result = write(eventFor(window), "es");+ window.frame.url = "https://example.invalid";+ await expect(result).rejects.toThrow();+ expect(window.frame.send).not.toHaveBeenCalled();+ window.frame.url = "one-memory://app/index.html";+ expect(await read(eventFor(window))).toMatchObject({+ preference: "es",+ revision: 1,+ });+ });+ it("uses the shared locale for the native error title without translating error codes", async () => {+ fake.loadFailure = true;+ await startup();+ expect(fake.error).toHaveBeenCalledWith(+ translate("es", "nativeErrorTitle"),+ "page_load_failed",+ );+ });+});+describe("display preference main IPC", () => {it("registers background inspection against the fixed data directory and guards navigation", async () => {const window = await startup();@@ -412,6 +512,9 @@ describe("display preference main IPC", () => {interface PreferenceAPI {getBackgroundHealth(): Promise<unknown>;restartBackground(): Promise<{ state: "restarted" }>;+ getLanguagePreference(): Promise<unknown>;+ setLanguagePreference(preference: unknown): Promise<unknown>;+ onLanguagePreferenceChanged(listener: (value: unknown) => void): () => void;getDisplayPreferences(): Promise<{reduceMotion: boolean;reduceTransparency: boolean;@@ -424,6 +527,51 @@ async function preload() {return fake.expose.mock.calls[0][1] as PreferenceAPI;}+describe("language preference preload", () => {+ it("validates writes and snapshots, strips event metadata and cleans subscriptions", async () => {+ const api = await preload();+ const snapshot = { preference: "es", locale: "es", revision: 2 };+ fake.invoke.mockResolvedValue({ ...snapshot, secret: "not exposed" });+ expect(await api.getLanguagePreference()).toEqual(snapshot);+ expect(await api.setLanguagePreference("es")).toEqual(snapshot);+ expect(fake.invoke).toHaveBeenLastCalledWith(+ "one-memory:set-language-preference",+ "es",+ );+ fake.invoke.mockClear();+ await expect(api.setLanguagePreference("fr")).rejects.toThrow();+ expect(fake.invoke).not.toHaveBeenCalled();+ const listener = vi.fn();+ const unsubscribe = api.onLanguagePreferenceChanged(listener);+ for (const invalid of [+ null,+ {},+ { ...snapshot, revision: -1 },+ { ...snapshot, preference: "en" },+ { ...snapshot, locale: "en" },+ ]) {+ fake.invoke.mockResolvedValue(invalid);+ await expect(api.getLanguagePreference()).rejects.toThrow();+ await expect(api.setLanguagePreference("es")).rejects.toThrow();+ fake.renderer.emit("one-memory:language-preference-changed", {}, invalid);+ }+ expect(listener).not.toHaveBeenCalled();+ fake.renderer.emit(+ "one-memory:language-preference-changed",+ { secret: true },+ { ...snapshot, secret: true },+ );+ expect(listener).toHaveBeenCalledExactlyOnceWith(snapshot);+ expect(listener.mock.calls[0][0]).not.toBe(snapshot);+ fake.unload.dispatchEvent(new Event("unload"));+ unsubscribe();+ unsubscribe();+ expect(+ fake.renderer.listenerCount("one-memory:language-preference-changed"),+ ).toBe(0);+ });+});+describe("display preference preload", () => {it("preload exposes a no-argument background health read", async () => {const api = await preload();diff --git a/memhub/apps/desktop/src/early-startup-errors.test.ts b/memhub/apps/desktop/src/early-startup-errors.test.tsindex 39a56b9..5aed9aa 100644--- a/memhub/apps/desktop/src/early-startup-errors.test.ts+++ b/memhub/apps/desktop/src/early-startup-errors.test.ts@@ -2,8 +2,10 @@ import { EventEmitter } from "node:events";import { mkdtemp, readFile, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";+import { translate } from "@one-memory/i18n";import { afterEach, describe, expect, it, vi } from "vitest";import { installEarlyStartupErrorHandler } from "./early-startup-errors";+import { stableRuntimeUserMessage } from "./stable-runtime";const roots: string[] = [];@@ -14,6 +16,40 @@ afterEach(async () => {});describe("early desktop startup errors", () => {+ it.each(["es", "throws"] as const)(+ "uses best-effort language (%s) without changing safe error codes",+ async (language) => {+ const dataDir = await mkdtemp(+ path.join(os.tmpdir(), "desktop-early-language-"),+ );+ roots.push(dataDir);+ const processEvents = new EventEmitter();+ const showError = vi.fn();+ const exit = vi.fn();+ const dispose = installEarlyStartupErrorHandler({+ processEvents,+ dataDir,+ stderr: { write: vi.fn(() => true) },+ showError,+ exit,+ readLocale: () => {+ if (language === "throws") throw new Error("unavailable");+ return "es";+ },+ });+ processEvents.emit(+ "uncaughtException",+ new Error("synthetic_safe_failure"),+ );+ expect(showError).toHaveBeenCalledExactlyOnceWith(+ language === "es" ? "MemHub no pudo iniciarse" : "MemHub 无法启动",+ stableRuntimeUserMessage(new Error("synthetic_safe_failure")),+ );+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);+ dispose();+ },+ );+it("replaces an earlier handler on the same process emitter", () => {const processEvents = new EventEmitter();const options = {@@ -32,6 +68,37 @@ describe("early desktop startup errors", () => {dispose();});+ it.each(["en", "es", undefined] as const)(+ "uses a safe title for initialized locale %s and retains the technical code",+ async (locale) => {+ const dataDir = await mkdtemp(+ path.join(os.tmpdir(), "desktop-early-locale-"),+ );+ roots.push(dataDir);+ const processEvents = new EventEmitter();+ const showError = vi.fn();+ const exit = vi.fn();+ const dispose = installEarlyStartupErrorHandler({+ processEvents,+ dataDir,+ stderr: { write: vi.fn(() => true) },+ showError,+ exit,+ readLocale: () => locale,+ });+ processEvents.emit(+ "uncaughtException",+ new Error("desktop_startup_failed"),+ );+ expect(showError).toHaveBeenCalledExactlyOnceWith(+ translate(locale ?? "zh-CN", "nativeErrorTitle"),+ stableRuntimeUserMessage(new Error("desktop_startup_failed")),+ );+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);+ dispose();+ },+ );+it("writes stderr and diagnostics before showing the fatal dialog", async () => {const dataDir = await mkdtemp(path.join(os.tmpdir(), "desktop-early-error-"),diff --git a/memhub/apps/desktop/src/early-startup-errors.ts b/memhub/apps/desktop/src/early-startup-errors.tsindex 390654c..29e12ae 100644--- a/memhub/apps/desktop/src/early-startup-errors.ts+++ b/memhub/apps/desktop/src/early-startup-errors.ts@@ -1,4 +1,5 @@import type { EventEmitter } from "node:events";+import { type GuiLocale, translate } from "@one-memory/i18n";import {diagnosticError,writeDiagnosticEventSync,@@ -12,6 +13,8 @@ interface EarlyStartupErrorHandlerOptions {showError(title: string, message: string): void;exit(code: number): void;afterDiagnosticWrite?: () => void;+ /** Only already initialized preferences; never read configuration during a fatal error. */+ readLocale?: () => GuiLocale | undefined;}const SAFE_ERROR_CODE = /^[a-z][a-z0-9_]{0,127}$/;@@ -56,7 +59,16 @@ export function installEarlyStartupErrorHandler(// The dialog is the only part of this a person ever reads, so it gets the// explanation, not the code. The code stays in the diagnostic event,// where support can still match it against a known failure.- options.showError("MemHub 无法启动", stableRuntimeUserMessage(error));+ let locale: GuiLocale = "zh-CN";+ try {+ locale = options.readLocale?.() ?? "zh-CN";+ } catch {+ // Preferences may not exist yet; do not read files or guess the locale.+ }+ options.showError(+ translate(locale, "nativeErrorTitle"),+ stableRuntimeUserMessage(error),+ );options.exit(1);}};diff --git a/memhub/apps/desktop/src/language-preferences-ipc.test.ts b/memhub/apps/desktop/src/language-preferences-ipc.test.tsnew file mode 100644index 0000000..1b0e028--- /dev/null+++ b/memhub/apps/desktop/src/language-preferences-ipc.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from "vitest";+import { LanguagePreferences } from "./language-preferences";+import { installLanguagePreferencesIpc } from "./language-preferences-ipc";++describe("language preference IPC", () => {+ it("guards reads/writes, validates payloads, broadcasts commits and disposes", async () => {+ const handlers = new Map<+ string,+ (event: string, ...args: unknown[]) => Promise<unknown>+ >();+ const save = vi.fn(async () => {});+ const preferences = await LanguagePreferences.open(+ "/synthetic/profile",+ "es",+ { read: async () => "{}", save },+ );+ const broadcast = vi.fn();+ const dispose = installLanguagePreferencesIpc({+ ipc: {+ handle: (name, handler) => handlers.set(name, handler),+ removeHandler: (name) => {+ handlers.delete(name);+ },+ },+ preferences,+ requireTrustedWindow: (event: string) => {+ if (event !== "trusted") throw Error("untrusted");+ },+ broadcast,+ });+ const read = handlers.get("one-memory:get-language-preference");+ const write = handlers.get("one-memory:set-language-preference");+ if (!read || !write) throw Error("Missing language handlers");+ await expect(read("foreign")).rejects.toThrow("untrusted");+ await expect(write("iframe", "es")).rejects.toThrow("untrusted");+ await expect(write("trusted", "fr")).rejects.toThrow();+ await expect(write("trusted", "es", "extra")).rejects.toThrow();+ expect(save).not.toHaveBeenCalled();+ expect(await read("trusted")).toEqual({+ preference: "system",+ locale: "es",+ revision: 0,+ });+ await write("trusted", "en");+ expect(broadcast).toHaveBeenCalledExactlyOnceWith({+ preference: "en",+ locale: "en",+ revision: 1,+ });+ dispose();+ dispose();+ expect(handlers.size).toBe(0);+ await expect(write("trusted", "es")).rejects.toThrow();+ });+});diff --git a/memhub/apps/desktop/src/language-preferences-ipc.ts b/memhub/apps/desktop/src/language-preferences-ipc.tsnew file mode 100644index 0000000..a8e7151--- /dev/null+++ b/memhub/apps/desktop/src/language-preferences-ipc.ts@@ -0,0 +1,47 @@+import { isLanguagePreference, type LanguageSnapshot } from "@one-memory/i18n";+import type { LanguagePreferences } from "./language-preferences";++const GET = "one-memory:get-language-preference";+const SET = "one-memory:set-language-preference";++export function installLanguagePreferencesIpc<Event>(options: {+ ipc: {+ handle(+ name: string,+ handler: (event: Event, ...args: unknown[]) => Promise<unknown>,+ ): unknown;+ removeHandler(name: string): void;+ };+ preferences: LanguagePreferences;+ requireTrustedWindow(event: Event): unknown;+ broadcast(snapshot: LanguageSnapshot): void;+}): () => void {+ let closed = false;+ const requireTrusted = (event: Event) => {+ if (closed) throw Error("language_preferences_closed");+ options.requireTrustedWindow(event);+ };+ options.ipc.handle(GET, async (event, ...args) => {+ requireTrusted(event);+ if (args.length) throw Error("invalid_language_preference_arguments");+ return options.preferences.read();+ });+ options.ipc.handle(SET, async (event, ...args) => {+ requireTrusted(event);+ if (args.length !== 1 || !isLanguagePreference(args[0]))+ throw Error("invalid_language_preference");+ const snapshot = await options.preferences.set(args[0]);+ requireTrusted(event);+ return snapshot;+ });+ const unsubscribe = options.preferences.subscribe((snapshot) => {+ if (!closed) options.broadcast(snapshot);+ });+ return () => {+ if (closed) return;+ closed = true;+ unsubscribe();+ options.ipc.removeHandler(GET);+ options.ipc.removeHandler(SET);+ };+}diff --git a/memhub/apps/desktop/src/language-preferences.test.ts b/memhub/apps/desktop/src/language-preferences.test.tsnew file mode 100644index 0000000..faf6b40--- /dev/null+++ b/memhub/apps/desktop/src/language-preferences.test.ts@@ -0,0 +1,141 @@+import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ LanguagePreferences,+ preferredSystemLanguage,+} from "./language-preferences";++const roots: string[] = [];+async function profile() {+ const root = await mkdtemp(path.join(os.tmpdir(), "memhub-language-"));+ roots.push(root);+ return root;+}+afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++describe("GUI language preferences", () => {+ it("defaults to system, persists only the preference in the active profile and reloads", async () => {+ const root = await profile();+ const store = await LanguagePreferences.open(root, "es-MX");+ expect(store.read()).toEqual({+ preference: "system",+ locale: "es",+ revision: 0,+ });+ expect(await readdir(root)).toEqual([]);+ expect(await store.set("zh-CN")).toEqual({+ preference: "zh-CN",+ locale: "zh-CN",+ revision: 1,+ });+ expect(+ JSON.parse(await readFile(path.join(root, "gui-language.json"), "utf8")),+ ).toEqual({ preference: "zh-CN" });+ expect((await LanguagePreferences.open(root, "es")).read().preference).toBe(+ "zh-CN",+ );+ expect(+ (await LanguagePreferences.open(await profile(), "es")).read().preference,+ ).toBe("system");+ expect(await readdir(root)).toEqual(["gui-language.json"]);+ });+ it.each(["{broken", '{"preference":"fr"}', "null", "[]"])(+ "does not overwrite invalid input %s while loading",+ async (content) => {+ const root = await profile();+ const file = path.join(root, "gui-language.json");+ await writeFile(file, content);+ const store = await LanguagePreferences.open(root, "es");+ expect(store.read().preference).toBe("system");+ expect(await readFile(file, "utf8")).toBe(content);+ },+ );+ it("survives failed reads and preserves the snapshot on failed writes, then recovers", async () => {+ const save = vi+ .fn()+ .mockRejectedValueOnce(new Error("disk full"))+ .mockResolvedValue(undefined);+ const store = await LanguagePreferences.open("/synthetic/profile", "es", {+ read: async () => {+ throw new Error("unreadable");+ },+ save,+ });+ const listener = vi.fn();+ store.subscribe(listener);+ await expect(store.set("zh-CN")).rejects.toThrow(+ "language_preference_save_failed",+ );+ expect(store.read()).toEqual({+ preference: "system",+ locale: "es",+ revision: 0,+ });+ expect(listener).not.toHaveBeenCalled();+ await store.set("zh-CN");+ expect(store.read().revision).toBe(1);+ expect(listener).toHaveBeenCalledTimes(1);+ });+ it("serializes racing writes and emits only committed snapshots", async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const save = vi+ .fn()+ .mockImplementationOnce(() => gate)+ .mockResolvedValue(undefined);+ const store = await LanguagePreferences.open("/synthetic/profile", "es", {+ read: async () => "{}",+ save,+ });+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);+ const first = store.set("zh-CN");+ const second = store.set("es");+ await vi.waitFor(() => expect(save).toHaveBeenCalledTimes(1));+ expect(store.read().revision).toBe(0);+ release();+ expect((await first).revision).toBe(1);+ expect(await second).toEqual({+ preference: "es",+ locale: "es",+ revision: 2,+ });+ expect(listener.mock.calls.map(([value]) => value.revision)).toEqual([+ 1, 2,+ ]);+ unsubscribe();+ await store.set("system");+ expect(listener).toHaveBeenCalledTimes(2);+ await expect(store.set("invalid" as "es")).rejects.toThrow();+ });+ it("uses only the primary preferred language, falling back to locale if unavailable", () => {+ expect(+ preferredSystemLanguage({+ getPreferredSystemLanguages: () => ["en", "es"],+ getLocale: () => "es",+ }),+ ).toBe("en");+ expect(+ preferredSystemLanguage({+ getPreferredSystemLanguages: () => [],+ getLocale: () => "es",+ }),+ ).toBe("es");+ expect(+ preferredSystemLanguage({+ getPreferredSystemLanguages: () => {+ throw Error();+ },+ getLocale: () => "es",+ }),+ ).toBe("es");+ });+});diff --git a/memhub/apps/desktop/src/language-preferences.ts b/memhub/apps/desktop/src/language-preferences.tsnew file mode 100644index 0000000..56ee673--- /dev/null+++ b/memhub/apps/desktop/src/language-preferences.ts@@ -0,0 +1,135 @@+import { randomUUID } from "node:crypto";+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import path from "node:path";+import {+ isLanguagePreference,+ type LanguagePreference,+ type LanguageSnapshot,+ resolveGuiLocale,+} from "@one-memory/i18n";++interface Storage {+ read(file: string): Promise<string>;+ save(file: string, content: string): Promise<void>;+}+const storage: Storage = {+ read: (file) => readFile(file, "utf8"),+ async save(file, content) {+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });+ const temporary = `${file}.${randomUUID()}.tmp`;+ try {+ await writeFile(temporary, content, {+ encoding: "utf8",+ mode: 0o600,+ flag: "wx",+ });+ await rename(temporary, file);+ } finally {+ await rm(temporary, { force: true }).catch(() => {});+ }+ },+};++/** GUI-only preferences, scoped to the active Electron userData profile. */+export class LanguagePreferences {+ private queue: Promise<unknown> = Promise.resolve();+ private readonly listeners = new Set<(snapshot: LanguageSnapshot) => void>();+ private snapshot: LanguageSnapshot;++ private constructor(+ private readonly file: string,+ private readonly systemLanguage: string | undefined,+ private readonly io: Storage,+ preference: LanguagePreference,+ ) {+ this.snapshot = {+ preference,+ locale: resolveGuiLocale(preference, systemLanguage),+ revision: 0,+ };+ }++ static async open(+ userData: string,+ systemLanguage?: string,+ io: Storage = storage,+ ): Promise<LanguagePreferences> {+ const file = path.join(userData, "gui-language.json");+ let preference: LanguagePreference = "system";+ try {+ const data: unknown = JSON.parse(await io.read(file));+ if (+ data &&+ typeof data === "object" &&+ "preference" in data &&+ isLanguagePreference(data.preference)+ ) {+ preference = data.preference;+ }+ } catch {+ // Missing, unreadable or corrupt preferences never block startup or get rewritten.+ }+ return new LanguagePreferences(file, systemLanguage, io, preference);+ }++ read(): LanguageSnapshot {+ return { ...this.snapshot };+ }++ set(preference: LanguagePreference): Promise<LanguageSnapshot> {+ if (!isLanguagePreference(preference))+ return Promise.reject(Error("invalid_language_preference"));+ const operation = this.queue.then(async () => {+ if (preference === this.snapshot.preference) return this.read();+ try {+ await this.io.save(this.file, `${JSON.stringify({ preference })}\n`);+ } catch {+ throw Error("language_preference_save_failed");+ }+ this.snapshot = {+ preference,+ locale: resolveGuiLocale(preference, this.systemLanguage),+ revision: this.snapshot.revision + 1,+ };+ for (const listener of this.listeners) {+ try {+ listener(this.read());+ } catch {+ /* A closed consumer cannot undo a committed save. */+ }+ }+ return this.read();+ });+ this.queue = operation.catch(() => {});+ return operation;+ }++ subscribe(listener: (snapshot: LanguageSnapshot) => void): () => void {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }++ async drain(): Promise<void> {+ await this.queue;+ }+}++/** Call only after Electron readiness: later preferred languages are not fallbacks. */+export function preferredSystemLanguage(app: {+ getPreferredSystemLanguages(): string[];+ getLocale(): string;+}): string | undefined {+ try {+ const primary = app.getPreferredSystemLanguages()[0];+ if (primary) return primary;+ } catch {+ /* Older/unavailable platform API: use Electron's locale. */+ }+ try {+ return app.getLocale() || undefined;+ } catch {+ return undefined;+ }+}diff --git a/memhub/apps/desktop/src/main.ts b/memhub/apps/desktop/src/main.tsindex 0f8b686..341c5e0 100644--- a/memhub/apps/desktop/src/main.ts+++ b/memhub/apps/desktop/src/main.ts@@ -9,6 +9,7 @@ import {renderCustomHarnessSkill,verifyRecallInstall,} from "@one-memory/host-bridge/installer";+import { type GuiLocale, translate } from "@one-memory/i18n";import {claimRuntimeServiceForApp,claimRuntimeServiceForCli,@@ -91,6 +92,11 @@ import {resolvePackagedBuildNumber,resolvePackagedCommit,} from "./isolated-runtime";+import {+ LanguagePreferences,+ preferredSystemLanguage,+} from "./language-preferences";+import { installLanguagePreferencesIpc } from "./language-preferences-ipc";import {disableLegacyLoginItem,wasOpenedByLegacyLoginItem,@@ -125,6 +131,9 @@ let runtimeSupervisor: RuntimeSupervisor | null = null;let runtimeDataDir: string | null = null;let preserveManagedRuntimeOnQuit = false;let disposeTray: (() => void) | null = null;+let disposeApplicationMenu: (() => void) | null = null;+let languagePreferences: LanguagePreferences | null = null;+let disposeLanguagePreferences: (() => void) | null = null;const displayWindows = new Set<BrowserWindow>();let disposeDisplayPreferences: (() => void) | null = null;let disposeSourceDirectoryPicker: (() => void) | null = null;@@ -146,6 +155,7 @@ installEarlyStartupErrorHandler({process.env.ONE_MEMORY_DATA_DIR?.trim() ||path.join(app.getPath("home"), ".one-memory"),stderr: process.stderr,+ readLocale: () => languagePreferences?.read().locale ?? "zh-CN",showError: (title, message) => dialog.showErrorBox(title, message),exit: (code) => app.exit(code),});@@ -274,7 +284,16 @@ let appProtocolInstalled = false;function installPackagedWebProtocol(): void {if (!app.isPackaged || appProtocolInstalled) return;installAppProtocol(path.join(process.resourcesPath, "web"), {- startupScreen: startupScreenHtml,+ // Preferences are open by now: beforeNativeUi runs before this window.+ startupScreen: () => {+ let locale: GuiLocale = "zh-CN";+ try {+ locale = languagePreferences?.read().locale ?? "zh-CN";+ } catch {+ // An unreadable preference keeps the Chinese placeholder.+ }+ return startupScreenHtml(locale);+ },});appProtocolInstalled = true;}@@ -1076,6 +1095,26 @@ async function initialize(isQuitting: () => boolean): Promise<void> {};try {+ if (languagePreferences) {+ disposeLanguagePreferences = installLanguagePreferencesIpc({+ ipc: ipcMain,+ preferences: languagePreferences,+ requireTrustedWindow,+ broadcast: (snapshot) => {+ for (const window of displayWindows) {+ try {+ assertTrustedWindow(window);+ window.webContents.mainFrame.send(+ "one-memory:language-preference-changed",+ snapshot,+ );+ } catch {+ // Navigation/destruction races must never leak to another document.+ }+ }+ },+ });+ }disposeDisplayPreferences = installDisplayPreferences();disposeSourceDirectoryPicker = installSourceDirectoryPicker();if (appManagedRuntime) {@@ -1292,10 +1331,20 @@ async function initialize(isQuitting: () => boolean): Promise<void> {});void dialog.showMessageBox({type: "warning",- message: "请先将 MemHub 拖到“应用程序”文件夹",- detail:- "从“应用程序”重新打开后,MemHub 才会接入其他应用并安装命令行工具。",- buttons: ["知道了"],+ message: translate(+ languagePreferences?.read().locale ?? "zh-CN",+ "nativeMoveTitle",+ ),+ detail: translate(+ languagePreferences?.read().locale ?? "zh-CN",+ "nativeMoveDetail",+ ),+ buttons: [+ translate(+ languagePreferences?.read().locale ?? "zh-CN",+ "nativeAcknowledge",+ ),+ ],});} else if (trialProfile === null &&@@ -1462,14 +1511,21 @@ if (desktopVersion !== null) {platform: process.platform,background: desktopBackgroundLaunch,prepare: prepareProtocol,+ beforeNativeUi: async () => {+ languagePreferences = await LanguagePreferences.open(+ app.getPath("userData"),+ preferredSystemLanguage(app),+ );+ },initialize,createWindow,showStartupWindow: createStartupWindow,revealStartupWindow,getWindows: () => [...displayWindows],installTray: (open) => {- installApplicationMenu({+ disposeApplicationMenu = installApplicationMenu({productName: app.getName(),+ language: languagePreferences ?? undefined,buildMenu: (template) => Menu.buildFromTemplate(template),setMenu: (menu) => Menu.setApplicationMenu(menu),exportLogs: async () => {@@ -1481,6 +1537,7 @@ if (desktopVersion !== null) {});disposeTray = installBackgroundTray({app,+ language: languagePreferences ?? undefined,platform: process.platform,resourcesPath: process.resourcesPath,appPath: app.getAppPath(),@@ -1525,6 +1582,9 @@ if (desktopVersion !== null) {...(coreSupervisor ? { instance_id: coreSupervisor.instanceId } : {}),});// An admitted native effect must settle and journal before Runtime detach.+ disposeLanguagePreferences?.();+ disposeLanguagePreferences = null;+ await languagePreferences?.drain();await connectionSetup?.drain();// BUG-12: stopping the supervisor only releases this process's handles. In// a packaged build the Runtime is its own process and was left running@@ -1573,6 +1633,10 @@ if (desktopVersion !== null) {});},dispose: () => {+ disposeLanguagePreferences?.();+ disposeLanguagePreferences = null;+ disposeApplicationMenu?.();+ disposeApplicationMenu = null;connectionSetup?.dispose();disposeDiagnostics?.();disposeDiagnostics = null;@@ -1594,7 +1658,10 @@ if (desktopVersion !== null) {error instanceof Error ? error.name : "UnknownError",);dialog.showErrorBox(- "MemHub 无法启动",+ translate(+ languagePreferences?.read().locale ?? "zh-CN",+ "nativeErrorTitle",+ ),error instanceof Error ? error.message : "desktop_unavailable",);},diff --git a/memhub/apps/desktop/src/native-language.ts b/memhub/apps/desktop/src/native-language.tsnew file mode 100644index 0000000..25b4c5d--- /dev/null+++ b/memhub/apps/desktop/src/native-language.ts@@ -0,0 +1,7 @@+import type { LanguageSnapshot } from "@one-memory/i18n";++/** Shared committed GUI language for native menus, tray, and dialogs. */+export interface NativeLanguageSource {+ read(): LanguageSnapshot;+ subscribe(listener: (snapshot: LanguageSnapshot) => void): () => void;+}diff --git a/memhub/apps/desktop/src/preload-sandbox.test.ts b/memhub/apps/desktop/src/preload-sandbox.test.tsindex c7daa6f..13c41fe 100644--- a/memhub/apps/desktop/src/preload-sandbox.test.ts+++ b/memhub/apps/desktop/src/preload-sandbox.test.ts@@ -59,6 +59,9 @@ it("loads the production preload in a sandbox with Electron as its only module",const bridge = exposed as unknown as Record<string, unknown>;expect(bridge.getApiBaseUrl).toBeTypeOf("function");expect(bridge.getApiToken).toBeTypeOf("function");+ expect(bridge.getLanguagePreference).toBeTypeOf("function");+ expect(bridge.setLanguagePreference).toBeTypeOf("function");+ expect(bridge.onLanguagePreferenceChanged).toBeTypeOf("function");} finally {rmSync(output, { recursive: true, force: true });}diff --git a/memhub/apps/desktop/src/preload.ts b/memhub/apps/desktop/src/preload.tsindex 3b8c2a3..6b8140c 100644--- a/memhub/apps/desktop/src/preload.ts+++ b/memhub/apps/desktop/src/preload.ts@@ -10,6 +10,12 @@ import type {RecallInstallPreview,RecallUninstallPreview,} from "@one-memory/host-bridge/installer";+import {+ isLanguagePreference,+ isLanguageSnapshot,+ type LanguagePreference,+ type LanguageSnapshot,+} from "@one-memory/i18n";import type { BackgroundHealth } from "@one-memory/runtime-control";import { contextBridge, ipcRenderer } from "electron";import type { DebugLogSnapshot } from "./diagnostics-ipc";@@ -34,12 +40,60 @@ declare const __ONE_MEMORY_VERSION__: string;declare const __ONE_MEMORY_BUILD_NUMBER__: string;declare const __ONE_MEMORY_COMMIT__: string;+function languageSnapshot(payload: unknown): LanguageSnapshot {+ if (!isLanguageSnapshot(payload))+ throw Error("language_preferences_unavailable");+ return {+ preference: payload.preference,+ locale: payload.locale,+ revision: payload.revision,+ };+}+contextBridge.exposeInMainWorld("oneMemory", {getBuildInfo: () => ({version: __ONE_MEMORY_VERSION__,buildNumber: __ONE_MEMORY_BUILD_NUMBER__,commit: __ONE_MEMORY_COMMIT__,}),+ getLanguagePreference: async (): Promise<LanguageSnapshot> =>+ languageSnapshot(+ await ipcRenderer.invoke("one-memory:get-language-preference"),+ ),+ setLanguagePreference: async (+ preference: LanguagePreference,+ ): Promise<LanguageSnapshot> => {+ if (!isLanguagePreference(preference))+ throw Error("invalid_language_preference");+ return languageSnapshot(+ await ipcRenderer.invoke(+ "one-memory:set-language-preference",+ preference,+ ),+ );+ },+ onLanguagePreferenceChanged: (+ listener: (value: LanguageSnapshot) => void,+ ): (() => void) => {+ if (typeof listener !== "function")+ throw Error("invalid_language_preference_listener");+ const handler = (_event: unknown, payload: unknown) => {+ if (isLanguageSnapshot(payload)) listener(languageSnapshot(payload));+ };+ let subscribed = true;+ const unsubscribe = () => {+ if (!subscribed) return;+ subscribed = false;+ ipcRenderer.removeListener(+ "one-memory:language-preference-changed",+ handler,+ );+ window.removeEventListener("unload", unsubscribe);+ };+ ipcRenderer.on("one-memory:language-preference-changed", handler);+ window.addEventListener("unload", unsubscribe, { once: true });+ return unsubscribe;+ },getDebugLogs: (): Promise<DebugLogSnapshot> =>ipcRenderer.invoke("one-memory:get-debug-logs"),logUiTrace: (input: {diff --git a/memhub/apps/desktop/src/startup-screen.test.ts b/memhub/apps/desktop/src/startup-screen.test.tsindex 4d485da..fe2c2b6 100644--- a/memhub/apps/desktop/src/startup-screen.test.ts+++ b/memhub/apps/desktop/src/startup-screen.test.ts@@ -11,6 +11,16 @@ describe("startup screen", () => {expect(html).not.toContain("oneMemory");expect(html).not.toContain("ipcRenderer");});+ it("speaks the interface language and keeps Chinese by default", () => {+ expect(startupScreenHtml()).toContain('<html lang="zh-CN">');+ expect(startupScreenHtml()).toContain("正在启动,正在准备记忆服务…");+ const spanish = startupScreenHtml("es");+ expect(spanish).toContain('<html lang="es">');+ expect(spanish).toContain(+ "Iniciando y preparando el servicio de memorias…",+ );+ expect(spanish).not.toMatch(/[一-鿿]/);+ });it("is served from the app origin, not from the web bundle", () => {expect(STARTUP_SCREEN_URL).toBe("one-memory://app/__startup");});diff --git a/memhub/apps/desktop/src/startup-screen.ts b/memhub/apps/desktop/src/startup-screen.tsindex ea56aa0..1b06000 100644--- a/memhub/apps/desktop/src/startup-screen.ts+++ b/memhub/apps/desktop/src/startup-screen.ts@@ -1,3 +1,4 @@+import { type GuiLocale, translate } from "@one-memory/i18n";import { APP_ORIGIN, STARTUP_SCREEN_PATH } from "./app-protocol";export const STARTUP_SCREEN_URL = `${APP_ORIGIN}${STARTUP_SCREEN_PATH}`;@@ -10,9 +11,9 @@ export const STARTUP_SCREEN_URL = `${APP_ORIGIN}${STARTUP_SCREEN_PATH}`;* the gap. It deliberately makes no IPC calls: it renders before `initialize`* has registered any handler, and anything it asked for would fail.*/-export function startupScreenHtml(): string {+export function startupScreenHtml(locale: GuiLocale = "zh-CN"): string {return `<!doctype html>-<html lang="zh-CN">+<html lang="${locale}"><head><meta charset="utf-8" /><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'" />@@ -102,7 +103,7 @@ export function startupScreenHtml(): string {<body><main><h1>MemHub</h1>- <p>正在启动,正在准备记忆服务…</p>+ <p>${translate(locale, "startupPreparing")}</p><div class="bar"><span></span></div></main></body>diff --git a/memhub/apps/desktop/tsup.config.ts b/memhub/apps/desktop/tsup.config.tsindex 4db4528..4589632 100644--- a/memhub/apps/desktop/tsup.config.ts+++ b/memhub/apps/desktop/tsup.config.ts@@ -34,8 +34,10 @@ export default defineConfig({noExternal: ["@one-memory/host-bridge","@one-memory/contracts",+ "@one-memory/i18n","@one-memory/runtime-control","axios",+ "i18next","https-proxy-agent","proxy-from-env",],diff --git a/memhub/apps/web/package.json b/memhub/apps/web/package.jsonindex 24a0cd0..0e82d76 100644--- a/memhub/apps/web/package.json+++ b/memhub/apps/web/package.json@@ -11,6 +11,7 @@},"dependencies": {"@one-memory/contracts": "workspace:*",+ "@one-memory/i18n": "workspace:*","@one-memory/operations": "workspace:*","@tanstack/react-query": "^5.103.2","axios": "^1.20.0",diff --git a/memhub/apps/web/src/App.r6.test.tsx b/memhub/apps/web/src/App.r6.test.tsxindex cc33510..a188e02 100644--- a/memhub/apps/web/src/App.r6.test.tsx+++ b/memhub/apps/web/src/App.r6.test.tsx@@ -9,6 +9,31 @@ import {import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { App } from "./App";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";++it("localizes shared navigation and footer in Spanish", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <App />+ </LanguageProvider>,+ );+ const nav = await screen.findByRole("navigation", {+ name: "Navegación principal",+ });+ expect(+ within(nav)+ .getAllByRole("button")+ .map((button) => button.textContent),+ ).toEqual(["Aplicaciones", "Memorias", "Configuración"]);+ expect(within(nav).getByRole("button", { name: "Configuración" }).title).toBe(+ "Configuración",+ );+ expect(screen.getAllByText("Almacenamiento local").length).toBeGreaterThan(0);+ expect(+ screen.getByRole("link", { name: "Saltar al contenido principal" }),+ ).toBeTruthy();+});const memoryProps = vi.hoisted(() => vi.fn());diff --git a/memhub/apps/web/src/App.tsx b/memhub/apps/web/src/App.tsxindex fd53128..0faf529 100644--- a/memhub/apps/web/src/App.tsx+++ b/memhub/apps/web/src/App.tsx@@ -22,10 +22,12 @@ import {CALL_HISTORY_ENTRY_VISIBLE,} from "./ApplicationsHome";import { getOnboarding } from "./api";+import { useApplicationsLanguage } from "./applications-language";import { CallHistory } from "./CallHistory";import { DebugLogPanel } from "./DebugLogPanel";import { DesktopFrame } from "./DesktopFrame";import { FirstUseGuide } from "./FirstUseGuide";+import { useGuiLanguage } from "./gui-language";import { HealthPanel } from "./HealthPanel";import { ImportProgressStrip } from "./ImportProgressStrip";import { MatterWorkspace } from "./MatterWorkspace";@@ -64,6 +66,8 @@ export function App() {}function AppContent() {+ const { t } = useGuiLanguage();+ const { a } = useApplicationsLanguage();const [onboarding, setOnboarding] = useState<OnboardingState | null>(null);const [startupRead, setStartupRead] = useState<"loading" | "ready" | "error">("loading",@@ -216,19 +220,19 @@ function AppContent() {{startupRead === "error" ? (<div className="boot-status"><p className="error-banner" role="alert">- 暂时无法读取启动状态,请重试。+ {t("startupReadError")}</p><R6ButtononClick={() => {if (!startupFlight.current) readStartup();}}>- 重新读取+ {t("startupRetry")}</R6Button></div>) : (<p className="boot-status" aria-live="polite">- 正在打开 MemHub…+ {t("startupOpening")}</p>)}</main>@@ -264,9 +268,9 @@ function AppContent() {the text it used to contain. */}<header className="r6-titlebar" /><a className="skip-link" href="#main-content">- 跳到主要内容+ {a("skip")}</a>- <nav className="app-rail" aria-label="主要导航">+ <nav className="app-rail" aria-label={a("navigation")}><div className="brand-mark" title="MemHub"><Layers3 size={21} strokeWidth={1.6} aria-hidden="true" /><span>MemHub</span>@@ -285,7 +289,7 @@ function AppContent() {key={destination}active={displayedView === destination}tourId={destination === "sources" ? "nav-sources" : undefined}- label={destination === "memory" ? "记忆" : "应用"}+ label={a(destination === "memory" ? "navMemories" : "apps")}icon={destination === "memory" ? (<Network size={19} />@@ -308,16 +312,13 @@ function AppContent() {<RailButtonactive={displayedView === "settings" || displayedView === "health"}tourId="nav-settings"- label="设置"+ label={t("settings")}icon={<Settings size={18} />}onClick={() => navigate("settings")}/>- <p- className="rail-core"- title="记忆保存在本机;使用云模型整理或交给已授权的助手时,相关内容会发送给对应服务。"- >+ <p className="rail-core" title={a("localHint")}><span aria-hidden="true" />- 本地存储+ {a("local")}</p></div></nav>@@ -439,7 +440,7 @@ function AppContent() {onClick={() => navigate("settings")}><ArrowLeft size={16} />- 设置+ {t("settings")}</button><HealthPanel imports={imports} /></>@@ -511,6 +512,7 @@ function RailButton({className={`rail-button${active ? " active" : ""}`}aria-current={active ? "page" : undefined}data-tour-id={tourId}+ title={label}onClick={onClick}><span className="rail-icon" aria-hidden="true">diff --git a/memhub/apps/web/src/ApplicationDetail.test.tsx b/memhub/apps/web/src/ApplicationDetail.test.tsxindex fd2d699..53ddeab 100644--- a/memhub/apps/web/src/ApplicationDetail.test.tsx+++ b/memhub/apps/web/src/ApplicationDetail.test.tsx@@ -12,6 +12,32 @@ import {import { useState } from "react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { ApplicationDetail } from "./ApplicationDetail";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";++it("translates application detail live without triggering extra reads or writes", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const refresh = vi.fn().mockResolvedValue({ sources: [source] });+ render(+ <LanguageProvider>+ <ApplicationDetail {...props} refresh={refresh} />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("heading", { name: "Detalles de la aplicación" }),+ ).toBeTruthy();+ expect(screen.getByRole("switch", { name: "Sincronización" })).toBeTruthy();+ await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1));+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ await act(async () =>+ window.dispatchEvent(+ new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }),+ ),+ );+ expect(await screen.findByRole("heading", { name: "应用详情" })).toBeTruthy();+ expect(refresh).toHaveBeenCalledTimes(1);+ expect(props.setSync).not.toHaveBeenCalled();+});+import { saveConnectionPreferences } from "./connection-preferences";import { resetConnectionReconcile } from "./connection-reconcile";import { commitSources } from "./source-state";@@ -576,6 +602,109 @@ it("shows insertion still on when neither removal nor revocation succeeded", asy);});+let languageListener: ((snapshot: unknown) => void) | undefined;+function switchLanguage(locale: "es" | "zh-CN", revision: number) {+ act(() => languageListener?.({ preference: locale, locale, revision }));+}+async function failDisconnectInSpanish() {+ const oneMemory = window.oneMemory as unknown as Record<string, unknown>;+ oneMemory.getLanguagePreference = vi.fn(async () => ({+ preference: "es",+ locale: "es",+ revision: 1,+ }));+ oneMemory.onLanguagePreferenceChanged = vi.fn(+ (listener: (snapshot: unknown) => void) => {+ languageListener = listener;+ return () => {};+ },+ );+ render(+ <LanguageProvider>+ <ApplicationDetail+ {...props}+ source={opencode}+ sources={[opencode]}+ refresh={vi.fn().mockResolvedValue({ sources: [opencode] })}+ />+ </LanguageProvider>,+ );+ const insertion = await screen.findByRole("switch", {+ name: "Conectar con un clic",+ });+ await waitFor(() =>+ expect(insertion.getAttribute("aria-checked")).toBe("true"),+ );+ fireEvent.click(insertion);+ return insertion;+}++it("words a failed turn-off with its reason in Spanish, without Chinese punctuation", async () => {+ editedHostBridge({ revokeFails: true });+ await failDisconnectInSpanish();+ const alert = await screen.findByText(/No se pudo eliminar la conexión/);+ expect(alert.textContent).toBe(+ "No se pudo eliminar la conexión ni revocar el permiso. OpenCode aún puede usar memorias. Reintenta. Motivo: El canal de control de la aplicación no está disponible.",+ );+ expect(alert.textContent).not.toMatch(/[。:;,]/);+});++it("re-words a visible failure when the language changes, without new writes", async () => {+ const bridge = editedHostBridge({ revokeFails: true });+ await failDisconnectInSpanish();+ await screen.findByText(/Motivo: El canal de control/);+ const reads = (+ window.oneMemory as unknown as {+ getRecallHosts: ReturnType<typeof vi.fn>;+ }+ ).getRecallHosts;+ const readCount = reads.mock.calls.length;+ const revokes = bridge.revokeRecallPermission.mock.calls.length;+ switchLanguage("zh-CN", 2);+ expect(+ await screen.findByText(+ "连接未能移除,记忆权限也未能撤销,OpenCode 仍可使用记忆,请重试。原因:应用控制通道暂不可用。",+ ),+ ).toBeTruthy();+ switchLanguage("es", 3);+ expect(await screen.findByText(/Motivo: El canal de control/)).toBeTruthy();+ expect(bridge.revokeRecallPermission.mock.calls.length).toBe(revokes);+ expect(bridge.uninstallRecall).not.toHaveBeenCalled();+ expect(reads.mock.calls.length).toBe(readCount);+});++it("omits the reason in Spanish when the failure has no known cause", async () => {+ editedHostBridge({ revokeFails: true });+ const oneMemory = window.oneMemory as unknown as Record<string, unknown>;+ oneMemory.previewRecallUninstall = vi.fn(async () => {+ throw Error("something_unknown");+ });+ oneMemory.revokeRecallPermission = vi.fn(async () => {+ throw Error("something_unknown");+ });+ await failDisconnectInSpanish();+ const alert = await screen.findByText(/No se pudo eliminar la conexión/);+ expect(alert.textContent).toBe(+ "No se pudo eliminar la conexión ni revocar el permiso. OpenCode aún puede usar memorias. Reintenta.",+ );+});++it("adds the failed re-read note in Spanish after the reason", async () => {+ editedHostBridge({ revokeFails: true });+ const oneMemory = window.oneMemory as unknown as Record<string, unknown>;+ const getRecallHosts = oneMemory.getRecallHosts as ReturnType<typeof vi.fn>;+ const revoke = oneMemory.revokeRecallPermission as ReturnType<typeof vi.fn>;+ revoke.mockImplementation(async () => {+ getRecallHosts.mockRejectedValue(Error("offline"));+ throw Error("host_control_unavailable");+ });+ await failDisconnectInSpanish();+ const alert = await screen.findByText(/No se pudo eliminar la conexión/);+ expect(alert.textContent).toBe(+ "No se pudo eliminar la conexión ni revocar el permiso. OpenCode aún puede usar memorias. Reintenta. Motivo: El canal de control de la aplicación no está disponible. Tampoco se pudo volver a leer la conexión; el estado mostrado podría no estar actualizado.",+ );+});+it("explains why an app without a revocable connection cannot be inserted", async () => {const pi = {...source,diff --git a/memhub/apps/web/src/ApplicationDetail.tsx b/memhub/apps/web/src/ApplicationDetail.tsxindex 3b1871f..ec1c591 100644--- a/memhub/apps/web/src/ApplicationDetail.tsx+++ b/memhub/apps/web/src/ApplicationDetail.tsx@@ -1,4 +1,5 @@import type { SourceResponse } from "@one-memory/contracts";+import type { MessageKey } from "@one-memory/i18n";import { useCallback, useEffect, useRef, useState } from "react";import { AppMark } from "./app-mark";import { connectionHostId, preferenceHasSource } from "./connection-hosts";@@ -14,7 +15,6 @@ import {hostCapabilities,hostConnectionApproved,hostConnectionUnsupported,- hostFailureNote,hostRereadFailed,hostWriteReason,matchHost,@@ -24,6 +24,7 @@ import {UNSUPPORTED_NOTE,useRecallHosts,} from "./host-state";+import { useOnboardingTranslation } from "./onboarding-language";import { R6Button, R6Switch } from "./R6Controls";import {latestSource,@@ -32,16 +33,20 @@ import {} from "./source-state";import "./application-detail.css";+/** A failed host write as data: worded only when rendered. */+type HostFailure = { reason: string | null; rereadFailed: boolean };+type InstallError = {+ key: MessageKey;+ params: Record<string, string>;+ failure?: HostFailure;+};+const SYNC_UNCONFIRMED = "此应用的处理开关结果未能确认,其他应用不受影响。";// D97: the single sync switch now governs both taking in new data and// generating memories, so the separate read-permission switch is hidden, not// removed — flip this back to restore it without digging through history.const MEMORY_PERMISSION_SECTION_VISIBLE = false;-function connectFailure(reason: string | null, rereadFailed = false) {- return `此应用的一键接入未完成,其他应用不受影响。${hostFailureNote(reason, rereadFailed)}`;-}-function connectionLabel(input: {approved: boolean;insertionOn: boolean;@@ -85,6 +90,13 @@ export function ApplicationDetail({refresh(): Promise<{ sources: SourceResponse[] }>;onBack(): void;}) {+ const { text, t, locale } = useOnboardingTranslation();+ /** Word a host failure at render time so a language switch re-words it. */+ function failureNote({ reason, rereadFailed }: HostFailure) {+ return `${reason ? t("appFailureReason", { reason: text(reason) }) : ""}${+ rereadFailed ? t("appFailureReread") : ""+ }`;+ }const source = useSource(given);const hosts = useRecallHosts().data;const [read, setRead] = useState<{@@ -98,7 +110,7 @@ export function ApplicationDetail({const [refreshing, setRefreshing] = useState(false);const [refreshError, setRefreshError] = useState(false);const [installing, setInstalling] = useState(false);- const [installError, setInstallError] = useState("");+ const [installError, setInstallError] = useState<string | InstallError>("");const [syncing, setSyncing] = useState(false);const [syncError, setSyncError] = useState("");const [memoryPending, setMemoryPending] = useState(false);@@ -305,7 +317,15 @@ export function ApplicationDetail({});const hostId =host?.hostId ?? connectionHostId(source.source_id) ?? source.source_id;- const hostError = installError;+ const hostError =+ typeof installError === "string"+ ? text(installError)+ : t(installError.key, {+ ...installError.params,+ ...(installError.failure+ ? { reason: failureNote(installError.failure) }+ : {}),+ });async function applyInsertion(enabled: boolean) {const bridge = window.oneMemory;if (!bridge) return;@@ -318,27 +338,30 @@ export function ApplicationDetail({const { outcome } = await disconnectHost(hostId);if (outcome.state === "failed")throw Object.assign(Error("disconnect_failed"), {- note: hostFailureNote(outcome.reason, outcome.rereadFailed),+ failure: {+ reason: outcome.reason,+ rereadFailed: outcome.rereadFailed,+ } satisfies HostFailure,});setLink(null);if (outcome.state === "review")- setInstallError(- `${+ setInstallError({+ key:outcome.permission?.receipt?.status === "revoked"- ? `已撤销记忆权限,${source.display_name} 已查不到记忆。但`- : ""- }无法确认连接已全部移除,需要你手动核对:${outcome.findings- .map((finding) => `${finding.path}(${finding.where})`)- .join(";")}。`,- );+ ? "appRevokedReview"+ : "appRemovalReview",+ params: {+ name: source.display_name,+ paths: outcome.findings+ .map((finding) => `${finding.path}(${finding.where})`)+ .join(";"),+ },+ });if (outcome.state === "revoked")- setInstallError(- `已撤销记忆权限,${source.display_name} 已查不到记忆。${- outcome.configEdited- ? "配置文件被改过,MemHub 没有自动删除;请手动移除其中的 MemHub 连接。"- : "连接文件没有移除,请重新核对。"- }`,- );+ setInstallError({+ key: outcome.configEdited ? "appRevokedModified" : "appRevokedRetained",+ params: { name: source.display_name },+ });}async function changeInsertion(enabled: boolean) {writeConnectionPreference("host", source.source_id, enabled);@@ -364,10 +387,22 @@ export function ApplicationDetail({// shows the grant that is really still there after the re-read.setInstallError(wanted- ? connectFailure(hostWriteReason(error), hostRereadFailed(error))- : `连接未能移除,记忆权限也未能撤销,${source.display_name} 仍可使用记忆,请重试。${- (error as { note?: string }).note ?? ""- }`,+ ? {+ key: "appConnectFailed",+ params: {},+ failure: {+ reason: hostWriteReason(error),+ rereadFailed: hostRereadFailed(error),+ },+ }+ : {+ key: "appDisconnectFailed",+ params: { name: source.display_name },+ failure: (error as { failure?: HostFailure }).failure ?? {+ reason: null,+ rereadFailed: false,+ },+ },);}}@@ -453,12 +488,14 @@ export function ApplicationDetail({);} else if (!wanted) setHostRestartNotice("");} catch (error) {- setInstallError(- `此应用的记忆使用权限未能确认,请重试。${hostFailureNote(- hostWriteReason(error),- hostRereadFailed(error),- )}`,- );+ setInstallError({+ key: "appPermissionFailed",+ params: {},+ failure: {+ reason: hostWriteReason(error),+ rereadFailed: hostRereadFailed(error),+ },+ });}}} finally {@@ -472,11 +509,11 @@ export function ApplicationDetail({return (<sectionclassName="r6-app-detail"- aria-label={`${source.display_name} 应用设置`}+ aria-label={t("appSettingsTitle", { name: source.display_name })}>- <h1 className="r6-app-detail-title">应用详情</h1>+ <h1 className="r6-app-detail-title">{text("应用详情")}</h1><R6Button variant="quiet" onClick={onBack}>- 返回应用+ {text("返回应用")}</R6Button><header><span className="r6-app-detail-icon">@@ -484,31 +521,33 @@ export function ApplicationDetail({</span><div><h2>{source.display_name}</h2>- <p>{syncStatus}</p>+ <p>{text(syncStatus)}</p></div></header><div className="r6-app-settings"><section className="r6-app-setting"><div>- <h2>同步开关</h2>- <p>开启后处理历史待办,并持续接收此应用的新会话。</p>+ <h2>{text("同步开关")}</h2>+ <p>{text("开启后处理历史待办,并持续接收此应用的新会话。")}</p>{syncing && syncChecked && (<p role="status">- 正在读取已有对话,首次开启可能需要一两分钟,请不要重复点击。+ {text(+ "正在读取已有对话,首次开启可能需要一两分钟,请不要重复点击。",+ )}</p>)}{backfillNotice && (<p role="status">- 将补充冻结期间的新对话;原有 pending Job 继续处理。+ {text("将补充冻结期间的新对话;原有 pending Job 继续处理。")}</p>)}{!syncing && authorizationNote && (- <p role="status">{authorizationNote}</p>+ <p role="status">{text(authorizationNote)}</p>)}- {syncError && <p role="alert">{syncError}</p>}+ {syncError && <p role="alert">{text(syncError)}</p>}</div><R6Switch- label="同步开关"+ label={text("同步开关")}checked={syncChecked}pending={syncing}disabled={@@ -520,19 +559,19 @@ export function ApplicationDetail({</section><section className="r6-app-setting"><div>- <h2>一键插入应用</h2>- <p>安装记忆连接,并默认允许此应用使用已授权记忆。</p>+ <h2>{text("一键插入应用")}</h2>+ <p>{text("安装记忆连接,并默认允许此应用使用已授权记忆。")}</p>{unsupported && (- <p>{`${source.display_name} ${UNSUPPORTED_NOTE}`}</p>+ <p>{`${source.display_name} ${text(UNSUPPORTED_NOTE)}`}</p>)}{hostError && <p role="alert">{hostError}</p>}- {appLocationNote && <p role="status">{appLocationNote}</p>}+ {appLocationNote && <p role="status">{text(appLocationNote)}</p>}{hostRestartNotice ? (- <p role="status">{hostRestartNotice}</p>+ <p role="status">{text(hostRestartNotice)}</p>) : null}</div><R6Switch- label="一键插入应用"+ label={text("一键插入应用")}checked={insertionChecked}pending={installing}disabled={@@ -549,11 +588,11 @@ export function ApplicationDetail({{MEMORY_PERMISSION_SECTION_VISIBLE && (<section className="r6-app-setting"><div>- <h2>允许使用记忆</h2>- <p>让 {source.display_name} 查询已授权范围内的记忆。</p>+ <h2>{text("允许使用记忆")}</h2>+ <p>{t("appMemoryScope", { name: source.display_name })}</p></div><R6Switch- label="允许使用记忆"+ label={text("允许使用记忆")}checked={memoryChecked}pending={memoryPending}disabled={@@ -567,30 +606,38 @@ export function ApplicationDetail({)}<section className="r6-app-setting"><div>- <h2>连接状态</h2>+ <h2>{text("连接状态")}</h2>{refreshError && (<p role="alert">- 暂时无法刷新来源状态,请重试;未更改同步或读取权限。+ {text("暂时无法刷新来源状态,请重试;未更改同步或读取权限。")}</p>)}{readFailed && (- <p role="alert">暂时无法读取连接状态,当前状态待核对;请重试。</p>+ <p role="alert">+ {text("暂时无法读取连接状态,当前状态待核对;请重试。")}+ </p>)}{probeState && probeState !== "wired" && (- <p>- {`记忆工具没有进到 ${source.display_name} 当前对话。完全退出 ${source.display_name} 后重新打开,新对话里才会出现。`}- </p>+ <p>{t("appRestart", { name: source.display_name })}</p>)}{probeState === "wired" && (- <p>已接通。已经打开的对话不会中途出现这个工具,请新开一轮。</p>+ <p>+ {text(+ "已接通。已经打开的对话不会中途出现这个工具,请新开一轮。",+ )}+ </p>)}{linkFailed && (<p role="alert">- 本次连接探测失败,当前状态待核对;未把上次读取当作本次成功。+ {text(+ "本次连接探测失败,当前状态待核对;未把上次读取当作本次成功。",+ )}</p>)}{checkedAt && !stale && current?.state === "ready" && (- <small>上次读取:{new Date(checkedAt).toLocaleString()}</small>+ <small>+ {text("上次读取")}: {new Date(checkedAt).toLocaleString(locale)}+ </small>)}</div><div className="r6-app-detail-actions">@@ -600,7 +647,7 @@ export function ApplicationDetail({aria-busy={probing || undefined}onClick={() => void reread()}>- <span>{stateText}</span>+ <span>{text(stateText)}</span>{probing ? (<span className="r6-button-spinner" aria-hidden="true" />) : null}diff --git a/memhub/apps/web/src/ApplicationsHome.test.tsx b/memhub/apps/web/src/ApplicationsHome.test.tsxindex 9e681f7..7bbae2b 100644--- a/memhub/apps/web/src/ApplicationsHome.test.tsx+++ b/memhub/apps/web/src/ApplicationsHome.test.tsx@@ -17,8 +17,54 @@ import {import * as api from "./api";import { saveConnectionPreferences } from "./connection-preferences";import { resetConnectionReconcile } from "./connection-reconcile";+import { LanguageProvider } from "./gui-language";import { queryClient, resetClient } from "./query-client";+it("localizes the whole home live without repeating reads or changing imported text", async () => {+ let change:+ | ((snapshot: {+ preference: "es" | "zh-CN";+ locale: "es" | "zh-CN";+ revision: number;+ }) => void)+ | undefined;+ Object.assign(window.oneMemory ?? {}, {+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn((listener) => {+ change = listener;+ return () => {};+ }),+ });+ render(<LanguageProvider>{mountHome()}</LanguageProvider>);+ await screen.findByRole("heading", { name: "Aplicaciones", level: 1 });+ await screen.findByText("实际治理记忆");+ expect(+ screen.getByRole("region", { name: "Resumen de memorias" }),+ ).toBeTruthy();+ expect(screen.getByText("Servicio activo")).toBeTruthy();+ expect(screen.getByText("2 aplicaciones conectadas")).toBeTruthy();+ expect(screen.getAllByRole("button", { name: "Ver detalles" })).toHaveLength(+ 3,+ );+ const calls = summary.mock.calls.length;+ fireEvent.click(+ screen.getByRole("button", { name: "Ver las 5 aplicaciones" }),+ );+ act(() => change?.({ preference: "zh-CN", locale: "zh-CN", revision: 2 }));+ expect(+ screen.getByRole("heading", { name: "全部应用", level: 1 }),+ ).toBeTruthy();+ expect(screen.getByText("App 4")).toBeTruthy();+ expect(summary).toHaveBeenCalledTimes(calls);+ act(() => change?.({ preference: "es", locale: "es", revision: 3 }));+ expect(+ screen.getByRole("heading", { name: "Todas las aplicaciones", level: 1 }),+ ).toBeTruthy();+ expect(summary).toHaveBeenCalledTimes(calls);+});+const {summary,processing,@@ -114,6 +160,58 @@ beforeEach(() => {]),} as unknown as NonNullable<typeof window.oneMemory>;});+it.each([+ [true, "Organizando", "Organizando nuevas conversaciones"],+ [false, "En pausa", "Se dejó de generar memorias nuevas"],+])(+ "renders the Spanish sedimentation state without extra requests: %s",+ async (enabled, label, detail) => {+ // Task rows still running must not override the sedimentation switch.+ processing.mockResolvedValue({ running: 3, pending: 10 });+ sedimentation.mockResolvedValue({+ enabled,+ pending_retained: true,+ imports_unaffected: true,+ });+ Object.assign(window.oneMemory ?? {}, {+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn(() => () => {}),+ });+ render(<LanguageProvider>{mountHome()}</LanguageProvider>);+ expect(await screen.findAllByText(label)).toHaveLength(2);+ expect(screen.getByText(detail)).toBeTruthy();+ expect(sedimentation).toHaveBeenCalledOnce();+ },+);+it("localizes failure and empty states without leaking errors", async () => {+ summary.mockRejectedValue(new Error("synthetic_private_error"));+ Object.assign(window.oneMemory ?? {}, {+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn(() => () => {}),+ });+ render(+ <LanguageProvider>+ <ApplicationsHome+ imports={{ ...imports, sources: [] }}+ onManage={() => {}}+ onMemories={() => {}}+ onSettings={() => {}}+ />+ </LanguageProvider>,+ );+ expect(+ await screen.findByText("No se puede leer el estado de las memorias"),+ ).toBeTruthy();+ expect(screen.getByText("Aún no hay aplicaciones para mostrar")).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Reintentar lectura" }),+ ).toBeTruthy();+ expect(document.body.textContent).not.toContain("synthetic_private_error");+});it("hides a debug-frame dialogue excerpt from 最近更新 and falls back to memory", async () => {recentConversations.mockResolvedValue({items: [@@ -498,6 +596,41 @@ it("warns only after three consecutive timeouts and keeps them out of app rows",expect(screen.queryByRole("button", { name: "查看记录" })).toBeNull();}});+it("shows the consecutive-timeout warning in Spanish with the host name", async () => {+ history.mockResolvedValue({+ available: true,+ recording_error: false,+ items: Array.from({ length: 3 }, (_, index) => ({+ event_id: `timeout-es-${index}`,+ host_id: "workbuddy",+ tool: "om_recall",+ state: "timed_out",+ occurred_at: new Date(Date.now() - index * 1000).toISOString(),+ memory_count: 0,+ raw_count: 0,+ references: [],+ })),+ });+ Object.assign(window.oneMemory ?? {}, {+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn(() => () => {}),+ });+ render(+ <LanguageProvider>+ <ApplicationsHome+ imports={imports}+ onManage={() => {}}+ onMemories={() => {}}+ onSettings={() => {}}+ onCalls={() => {}}+ />+ </LanguageProvider>,+ );+ const warning = await screen.findByText(/Las últimas consultas de WorkBuddy/);+ expect(warning.textContent).not.toMatch(/[\u4e00-\u9fff]/);+});it("uses live-sync success time for an application row", async () => {liveSync.mockResolvedValue([{@@ -1294,3 +1427,36 @@ describe("运行状态卡:一次失败的刷新不能让卡片继续说在运expect(screen.getByText("601")).toBeTruthy();});});++it("words an automatic sync failure and its reason in Spanish", async () => {+ localStorage.setItem(+ "one-memory.connection-preferences.v1",+ JSON.stringify({ version: 1, syncSourceIds: ["app-0"], hostSourceIds: [] }),+ );+ queryClient.setQueryData(["connection-auto"], {+ running: [],+ attempted: ["app-0"],+ failures: [+ {+ kind: "sync",+ sourceId: "app-0",+ reason: "此应用的读取授权已撤销,请重新授权。",+ },+ ],+ });+ Object.assign(window.oneMemory ?? {}, {+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn(() => () => {}),+ });+ render(<LanguageProvider>{mountHome()}</LanguageProvider>);+ const notice = await screen.findByText(+ /No se pudo activar la sincronización continua de App 0\./,+ );+ expect(notice.textContent).toContain(+ "Se revocó el permiso de lectura de esta aplicación. Vuelve a autorizarla.",+ );+ expect(notice.textContent).not.toMatch(/[一-鿿]/);+ localStorage.removeItem("one-memory.connection-preferences.v1");+});diff --git a/memhub/apps/web/src/ApplicationsHome.tsx b/memhub/apps/web/src/ApplicationsHome.tsxindex 9e2d761..58686cf 100644--- a/memhub/apps/web/src/ApplicationsHome.tsx+++ b/memhub/apps/web/src/ApplicationsHome.tsx@@ -5,6 +5,7 @@ import type {RecentConversationItem,SourceResponse,} from "@one-memory/contracts";+import { type GuiLocale, isMessageKey } from "@one-memory/i18n";import { ArrowLeft, ArrowRight } from "lucide-react";import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";import { flushSync } from "react-dom";@@ -30,6 +31,7 @@ import {retryAutoReconcile,useAutoConnect,} from "./connection-reconcile";+import { useGuiLanguage } from "./gui-language";import { HomeCardBoundary } from "./HomeCardBoundary";import {hostBridgeAvailable,@@ -70,13 +72,15 @@ function presentableDialogue(text: string): boolean {const retainedViews = new WeakMap<object, HomeViewState>();-function clockParts(value: string) {+type Translate = ReturnType<typeof useGuiLanguage>["t"];++function clockParts(value: string, locale: GuiLocale) {const ms = Date.parse(value);if (!Number.isFinite(ms)) return null;const date = new Date(ms);const now = new Date();return {- clock: new Intl.DateTimeFormat("zh-CN", {+ clock: new Intl.DateTimeFormat(locale, {hour: "2-digit",minute: "2-digit",}).format(date),@@ -87,16 +91,17 @@ function clockParts(value: string) {};}-function stamped(value: string, suffix = "") {- const parts = clockParts(value);- if (!parts) return `时间未知${suffix}`;- return `${parts.today ? "今天 " : ""}${parts.clock}${suffix}`;+function stamped(value: string, locale: GuiLocale, t: Translate, suffix = "") {+ const parts = clockParts(value, locale);+ if (!parts) return `${t("apps.unknownTime")}${suffix}`;+ return `${parts.today ? t("apps.today") : ""}${parts.clock}${suffix}`;}-function memoryAction(action: string | undefined) {- if (action === "create") return "新增记忆";- if (action === "correct" || action === "restore") return "更新记忆";- return "记忆已保存";+function memoryAction(action: string | undefined, t: Translate) {+ if (action === "create") return t("apps.newMemory");+ if (action === "correct" || action === "restore")+ return t("apps.updatedMemory");+ return t("apps.saved");}type ActivityChoice = "call" | "update";@@ -135,23 +140,32 @@ function callAttention(events: CallEvent[]) {function sourceActivity(source: SourceResponse,events: CallEvent[],+ locale: GuiLocale,+ t: Translate,callHistoryUnavailable = false,): string {- if (!source.authorized) return "尚未关联";+ if (!source.authorized) return t("apps.unlinked");const latest = events.find((item) =>successfulCall(item) && sourceMatchesHost(source.source_id, item.host_id),);if (!latest) return "";- const time = stamped(latest.occurred_at);- const prefix = callHistoryUnavailable ? "上次读取:" : "";- return `${prefix}${callDetailHeadline(latest, source.display_name)} · ${time}`;+ const time = stamped(latest.occurred_at, locale, t);+ const prefix = callHistoryUnavailable ? t("apps.lastRead") : "";+ return `${prefix}${callDetailHeadline(latest, source.display_name, locale)} · ${time}`;}-function sourceSyncActivity(sourceId: string, sync: LiveSyncHealth[]): string {+function sourceSyncActivity(+ sourceId: string,+ sync: LiveSyncHealth[],+ locale: GuiLocale,+ t: Translate,+): string {const current = sync.find((item) => item.source_id === sourceId);return current?.last_success_at- ? `最近同步 ${stamped(current.last_success_at)}`+ ? t("apps.recentSync", {+ time: stamped(current.last_success_at, locale, t),+ }): "";}@@ -181,6 +195,7 @@ export function ApplicationsHome({onCalls?(): void;active?: boolean;}) {+ const { locale, t, tn } = useGuiLanguage();const hostQuery = useRecallHosts({ poll: active });const hostBridge = hostBridgeAvailable();const hosts = hostQuery.data ?? [];@@ -626,7 +641,7 @@ export function ApplicationsHome({sourceMatchesHost(source.source_id, recentCall?.host_id ?? null),);const attention = callAttention(callEvents);- const attentionHost = attention ? callHostName(attention.host) : null;+ const attentionHost = attention ? callHostName(attention.host, locale) : null;const activity = summaryUnavailable? "unavailable": visible === null@@ -657,16 +672,16 @@ export function ApplicationsHome({);const stateLabel =sedimentation?.enabled === true- ? "整理中"+ ? t("apps.running"): sedimentation?.enabled === false- ? "已暂停"- : "待核对";+ ? t("apps.paused")+ : t("apps.unchecked");const stateDetail =sedimentation?.enabled === false- ? "已停止生成新记忆"+ ? t("apps.stoppedNew"): sedimentation?.enabled === true- ? "新的对话正在整理"- : "正在核对整理状态";+ ? t("apps.organizingNew")+ : t("apps.checkingProcessing");const latestUpdatedAt =latest === null || latest === undefined? null@@ -675,7 +690,9 @@ export function ApplicationsHome({: latest.gmt_created === null? null: new Date(latest.gmt_created * 1000).toISOString();- const latestClock = latestUpdatedAt ? clockParts(latestUpdatedAt) : null;+ const latestClock = latestUpdatedAt+ ? clockParts(latestUpdatedAt, locale)+ : null;const latestSourceIds =latest === null || latest === undefined? []@@ -684,8 +701,8 @@ export function ApplicationsHome({: latest.source? [latest.source]: [];- const time = latestClock?.clock ?? (latest ? "时间未知" : null);- const checked = visible ? clockParts(visible.observed_at) : null;+ const time = latestClock?.clock ?? (latest ? t("apps.unknownTime") : null);+ const checked = visible ? clockParts(visible.observed_at, locale) : null;// A failed read leaves the last health in place on purpose: clearing it would// drop the instance it names, and that instance is what keeps memory writes// and backfill receipts attached to the run that produced them. So the card@@ -701,20 +718,24 @@ export function ApplicationsHome({(!hostBridge && hostState !== "ready") ||(admitted === 0 && hostApplyPending(auto, preferences.hostSourceIds));const accessText = accessPending- ? "正在核对中"+ ? t("apps.checkingNow"): hostReadFailed- ? "待核对"+ ? t("apps.unchecked"): !unchecked.length- ? `${admitted} 个应用已接入`+ ? tn("apps.connectedCount", admitted): admitted- ? `${admitted} 个应用已接入,${unchecked.length} 个待核对`- : `${unchecked.length} 个应用待核对`;+ ? tn("apps.mixedCount", admitted, {+ pending: new Intl.NumberFormat(locale).format(unchecked.length),+ })+ : tn("apps.pendingCount", unchecked.length);const accessUnknownText = accessPending? null: hostReadFailed- ? "应用接入状态暂时没有读到,无法确认有几个应用已接入。"+ ? t("apps.unknownAccess"): unchecked.length- ? `${unchecked.map((host) => host.label).join("、")} 的记忆权限暂时没有读到,无法确认是否已接入。`+ ? t("apps.unknownPermissions", {+ names: unchecked.map((host) => host.label).join(", "),+ }): null;async function restartBackground() {if (restartingBackground) return;@@ -751,11 +772,23 @@ export function ApplicationsHome({source.source_id === failure.sourceId && source.sync_enabled,),);+ const localizeFailureReason = (reason: string | null | undefined) =>+ reason && isMessageKey(reason) ? t(reason) : (reason ?? "");const autoFailureText = autoFailures.map((failure) =>failure.kind === "host"- ? `${nameOf(failure.sourceId)} 未能自动接入${failure.reason ? `:${failure.reason}` : ""}。`- : `${nameOf(failure.sourceId)} 的持续同步未能自动开启。${failure.reason ?? ""}`,+ ? t("apps.autoHostFailed", {+ name: nameOf(failure.sourceId),+ reason: failure.reason+ ? t("apps.failureReason", {+ reason: localizeFailureReason(failure.reason),+ })+ : "",+ })+ : t("apps.autoSyncFailed", {+ name: nameOf(failure.sourceId),+ reason: localizeFailureReason(failure.reason),+ }),).join("");const authorizedSyncSources = imports.sources.filter(@@ -766,12 +799,12 @@ export function ApplicationsHome({(failure) => failure.kind === "sync",);const syncState = authorizedSyncSources.length- ? `${authorizedSyncSources.length} 个应用已开启`+ ? tn("apps.enabledCount", authorizedSyncSources.length): syncApplyFailed- ? "未能开启"+ ? t("apps.enableFailed"): wantsSync || !visible- ? "正在检查状态"- : "尚未开启";+ ? t("apps.checkingState")+ : t("apps.notEnabled");function toggleAll(next: boolean) {transition.current(next);}@@ -779,7 +812,7 @@ export function ApplicationsHome({<sectionclassName="r6-home"ref={root}- aria-label="应用首页"+ aria-label={t("apps.home")}data-expanded={expanded}data-phase={phase}onFocusCapture={(event) => {@@ -788,7 +821,7 @@ export function ApplicationsHome({}}><header className="r6-home-heading">- <h1>{expanded ? "全部应用" : "应用"}</h1>+ <h1>{expanded ? t("apps.allApps") : t("apps.apps")}</h1></header><buttontype="button"@@ -801,7 +834,7 @@ export function ApplicationsHome({><span className="r6-button-label"><ArrowLeft size={16} aria-hidden="true" />- 返回首页+ {t("apps.back")}</span></button><div@@ -810,14 +843,14 @@ export function ApplicationsHome({hidden={expanded}inert={expanded || phase !== "idle"}>- <HomeCardBoundary label="记忆概览">- <section className="r6-home-overview" aria-label="记忆概览">+ <HomeCardBoundary label={t("apps.overview")}>+ <section className="r6-home-overview" aria-label={t("apps.overview")}><header>- <h2>记忆概览</h2>+ <h2>{t("apps.overview")}</h2></header><div className="r6-home-metrics"><div>- <p>已沉淀记忆</p>+ <p>{t("apps.memories")}</p>{/* The figure slot used to hold the word 读取中 while the firstread was in flight, which is how "大数字不可见" (D51) shows upon a slow link: the biggest type on the page spends the first@@ -833,38 +866,41 @@ export function ApplicationsHome({aria-hidden="true"/></p>- <small role="status">正在读取已沉淀记忆数量…</small>+ <small role="status">{t("apps.readingCount")}</small></>) : (<><p className="r6-home-figure"><strong className={visible ? "" : "r6-home-word"}>{visible- ? new Intl.NumberFormat("zh-CN").format(+ ? new Intl.NumberFormat(locale).format(visible.memory_count,)- : "暂无法读取"}+ : t("apps.unreadable")}</strong>- {visible ? <i>条</i> : null}+ {visible && t("apps.unit") ? (+ <i>{t("apps.unit")}</i>+ ) : null}</p>- <small>按应用授权范围使用</small>+ <small>{t("apps.scope")}</small></>)}</div><div>- <p>沉淀状态</p>+ <p>{t("apps.processing")}</p><strong className="r6-home-word">{stateLabel}</strong><small>{stateDetail}</small></div><div>- <p>最近更新</p>+ <p>{t("apps.recentUpdate")}</p><strong className={time ? "r6-home-time" : "r6-home-word"}>- {time ?? (visible ? "尚未生成" : "待核对")}+ {time ??+ (visible ? t("apps.notGenerated") : t("apps.unchecked"))}</strong><small>{time- ? `${latestClock?.today ? "今天 · " : ""}记忆已保存`- : "历史与记忆分别处理"}+ ? `${latestClock?.today ? `${t("apps.today")}· ` : ""}${t("apps.saved")}`+ : t("apps.separate")}</small></div></div>@@ -886,19 +922,21 @@ export function ApplicationsHome({}onClick={() => setActivityView(item)}>- {item === "call" ? "最近调用" : "最近更新"}+ {item === "call"+ ? t("apps.recentCall")+ : t("apps.recentUpdate")}</button>))}</div>) : (<p>{activity === "unavailable"- ? "动态暂不可用"+ ? t("apps.activityUnavailable"): activity === "call"- ? "最近调用"+ ? t("apps.recentCall"): activity === "dialogue" || activity === "memory"- ? "最近更新"- : "首批沉淀"}+ ? t("apps.recentUpdate")+ : t("apps.firstBatch")}</p>)}<div>@@ -938,44 +976,45 @@ export function ApplicationsHome({<h3>{activity === "unavailable"? callState === "unavailable"- ? "暂时无法读取调用记录"- : "暂时无法读取记忆状态"+ ? t("apps.callsUnavailable")+ : t("apps.memoryUnavailable"): activity === "call" && recentCall? callDetailHeadline(recentCall,recentCallHost?.display_name ??- callHostName(recentCall.host_id),+ callHostName(recentCall.host_id, locale),+ locale,): activity === "memory" && latest? `${latest.content}${"truncated" in latest && latest.truncated ? "…" : ""}`: activity === "dialogue" && latestDialogue? `${latestDialogue.excerpt}${latestDialogue.truncated ? "…" : ""}`: activity === "importing"- ? "对话持续导入中,即将沉淀你的记忆"+ ? t("apps.importing"): activity === "first-running"- ? "正在沉淀第一批记忆"+ ? t("apps.firstRunning"): activity === "first-queued"- ? "准备沉淀第一批记忆"+ ? t("apps.firstQueued"): activity === "loading"- ? "正在读取动态"- : "还没有已生成的记忆"}+ ? t("apps.readingActivity")+ : t("apps.emptyMemories")}</h3><small>{activity === "unavailable"? callState === "unavailable"- ? "已有记忆仍可查看;重试不会发起新的调用。"- : "读取失败不会当作没有记忆。"+ ? t("apps.callReadFailure")+ : t("apps.memoryReadFailure"): activity === "call" && recentCall- ? `${stamped(recentCall.occurred_at)} · ${callRowDetail(recentCall)}${callState === "incomplete" ? " · 有几次调用没被记下来,列表可能不全" : ""}`+ ? `${stamped(recentCall.occurred_at, locale, t)} · ${callRowDetail(recentCall, locale)}${callState === "incomplete" ? t("apps.incompleteCalls") : ""}`: activity === "memory" && latest? "revision" in latest- ? `${time} · ${memoryAction(latest.action)} · ${latestSourceIds.map((id) => imports.sources.find((s) => s.source_id === id)?.display_name ?? id).join("、")} · 版本 ${latest.revision}`+ ? `${time} · ${memoryAction(latest.action, t)} · ${latestSourceIds.map((id) => imports.sources.find((s) => s.source_id === id)?.display_name ?? id).join(", ")} · ${t("apps.revision", { count: new Intl.NumberFormat(locale).format(latest.revision) })}`: `${time} · SDK ${latest.layer} · ${latestSourceIds.map((id) => imports.sources.find((s) => s.source_id === id)?.display_name ?? id).join("、")}`: activity === "dialogue" && latestDialogue- ? `${clockParts(latestDialogue.created_at ?? latestDialogue.imported_at)?.clock ?? "时间未知"} ${latestDialogue.time_basis === "conversation" ? "对话时间" : "导入时间"} · ${imports.sources.find((source) => source.source_id === latestDialogue.source_id)?.display_name ?? latestDialogue.source_id}`+ ? `${clockParts(latestDialogue.created_at ?? latestDialogue.imported_at, locale)?.clock ?? t("apps.unknownTime")} ${latestDialogue.time_basis === "conversation" ? t("apps.conversationTime") : t("apps.importTime")} · ${imports.sources.find((source) => source.source_id === latestDialogue.source_id)?.display_name ?? latestDialogue.source_id}`: activity === "importing"- ? "对话正在后台持续保存。"- : "历史已保存,记忆生成后会显示在这里。"}+ ? t("apps.savingConversations")+ : t("apps.waitingMemories")}</small></section>{(activity === "unavailable" ||@@ -996,10 +1035,10 @@ export function ApplicationsHome({}>{activity === "unavailable"- ? "重新读取"+ ? t("apps.reread"): activity === "call"- ? "查看记录"- : "查看记忆"}+ ? t("apps.viewCalls")+ : t("apps.viewMemory")}{activity === "unavailable" ? null : (<ArrowRight size={14} aria-hidden="true" />)}@@ -1013,8 +1052,8 @@ export function ApplicationsHome({<section className="r6-home-auto-failure" role="alert"><p>{attention.kind === "unavailable"- ? "后台服务没有运行,应用暂时查不到记忆"- : `${attentionHost} 最近几次没查到记忆,后台可能正忙,稍后会自动恢复`}+ ? t("apps.backgroundDown")+ : t("apps.timeoutWarning", { host: attentionHost ?? "" })}</p>{attention.kind === "unavailable" || CALL_HISTORY_ENTRY_VISIBLE ? (<R6Button@@ -1028,40 +1067,42 @@ export function ApplicationsHome({: onCalls}>- {attention.kind === "unavailable" ? "重新启动" : "查看记录"}+ {attention.kind === "unavailable"+ ? t("apps.restart")+ : t("apps.viewCalls")}</R6Button>) : null}</section>) : null}- <HomeCardBoundary label="运行状态">+ <HomeCardBoundary label={t("apps.runtime")}><aside className="r6-home-runtime">- <h2>运行状态</h2>+ <h2>{t("apps.runtime")}</h2><h3>{connected- ? "后台运行中"+ ? t("apps.backgroundRunning"): imports.healthStale- ? "连接状态待核对"- : "服务未连接"}+ ? t("apps.connectionUnchecked")+ : t("apps.disconnected")}</h3>- <p>仅处理已授权范围</p>+ <p>{t("apps.authorizedOnly")}</p><dl><div>- <dt>对话同步</dt>+ <dt>{t("apps.sync")}</dt><dd>{syncState}</dd></div><div>- <dt>记忆整理</dt>+ <dt>{t("apps.organizing")}</dt><dd>{stateLabel}</dd></div><div>- <dt>应用访问</dt>+ <dt>{t("apps.access")}</dt><dd>{accessText}</dd></div></dl>{accessUnknownText ? (<divrole="status"- aria-label="应用接入核对"+ aria-label={t("apps.checkingAccess")}className="r6-home-auto-failure"><p>{accessUnknownText}</p>@@ -1071,22 +1112,24 @@ export function ApplicationsHome({disabled={hostQuery.isFetching}onClick={() => void hostQuery.refetch()}>- {hostQuery.isFetching ? "核对中…" : "重新核对"}+ {hostQuery.isFetching+ ? t("apps.checking")+ : t("apps.recheck")}</button></div>) : null}{hostStale ? (<prole="status"- aria-label="应用接入状态"+ aria-label={t("apps.accessState")}className="r6-home-auto-failure">- 应用接入状态暂时读取失败,当前为上次状态。+ {t("apps.staleAccess")}</p>) : null}{autoFailureText ? (<div role="alert" className="r6-home-auto-failure">- <p>{`${autoFailureText}不会自动重试。`}</p>+ <p>{`${autoFailureText}${t("apps.noAutoRetry")}`}</p><buttontype="button"className="r6-home-activity-link"@@ -1099,14 +1142,16 @@ export function ApplicationsHome({})}>- 重新接入+ {t("apps.reconnect")}</button></div>) : null}<p className="r6-home-checked">{!checked- ? "上次核对:待核对"- : `上次核对:${checked.today ? "今天 " : ""}${checked.clock}`}+ ? t("apps.checkedAt", { time: t("apps.unchecked") })+ : t("apps.checkedAt", {+ time: `${checked.today ? t("apps.today") : ""}${checked.clock}`,+ })}</p></aside></HomeCardBoundary>@@ -1114,7 +1159,7 @@ export function ApplicationsHome({<sectionclassName="r6-home-apps"ref={panel}- aria-label="我的应用"+ aria-label={t("apps.myApps")}onWheel={(event) => {if (!expanded && apps.length > 3 && event.deltaY > 10)toggleAll(true);@@ -1145,7 +1190,9 @@ export function ApplicationsHome({}}><header>- <h2>{expanded ? `${apps.length} 个应用` : "我的应用"}</h2>+ <h2>+ {expanded ? tn("apps.appCount", apps.length) : t("apps.myApps")}+ </h2>{apps.length > 3 ? (<buttontype="button"@@ -1157,7 +1204,7 @@ export function ApplicationsHome({className="r6-home-expand"onClick={() => toggleAll(true)}>- 查看全部 {apps.length} 个应用+ {tn("apps.viewAll", apps.length)}</button>) : null}</header>@@ -1165,7 +1212,7 @@ export function ApplicationsHome({className="r6-home-list"ref={list}id={listId}- aria-label="应用列表"+ aria-label={t("apps.list")}tabIndex={expanded ? 0 : -1}onScroll={(event) => {if (expanded)@@ -1174,8 +1221,13 @@ export function ApplicationsHome({>{(expanded ? apps : apps.slice(0, 3)).map((source) => {const activity =- sourceActivity(source, callEvents, callState === "unavailable") ||- sourceSyncActivity(source.source_id, syncHealth);+ sourceActivity(+ source,+ callEvents,+ locale,+ t,+ callState === "unavailable",+ ) || sourceSyncActivity(source.source_id, syncHealth, locale, t);const host = hosts.find((item) =>sourceMatchesHost(source.source_id, item.hostId),);@@ -1187,13 +1239,13 @@ export function ApplicationsHome({<h3>{source.display_name}</h3><p>{source.sync_enabled- ? "持续同步已开启"+ ? t("apps.syncEnabled"): host?.installed &&host.permission?.state === "approved"- ? "允许请求已授权记忆"+ ? t("apps.recallAllowed"): source.authorized- ? "历史读取已授权"- : "连接待完成"}+ ? t("apps.historyAllowed")+ : t("apps.connectionPending")}</p></section>{activity ? (@@ -1204,7 +1256,7 @@ export function ApplicationsHome({data-home-focus={`source:${source.source_id}`}onClick={() => onManage(source.source_id)}>- 查看详情+ {t("apps.details")}</R6Button></div></div>@@ -1212,7 +1264,7 @@ export function ApplicationsHome({})}{!apps.length ? (<p className="r6-home-empty">- {stale ? "应用列表暂时不可读取" : "还没有可显示的应用"}+ {stale ? t("apps.listUnavailable") : t("apps.emptyApps")}</p>) : null}</section>diff --git a/memhub/apps/web/src/CallHistory.test.tsx b/memhub/apps/web/src/CallHistory.test.tsxindex 2c7bd78..f4618d2 100644--- a/memhub/apps/web/src/CallHistory.test.tsx+++ b/memhub/apps/web/src/CallHistory.test.tsx@@ -1,5 +1,6 @@// @vitest-environment jsdom+import { readFileSync } from "node:fs";import {act,cleanup,@@ -10,12 +11,20 @@ import {within,} from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";++it("permite crecer al botón de retorno y ajustar la barra sin cortar el español", () => {+ const css = readFileSync(`${process.cwd()}/src/call-history.css`, "utf8");+ expect(css).toMatch(/\.call-history-back\.r6-button\s*\{[^}]*width:\s*auto/s);+ expect(css).toMatch(/\.call-history-actions\s*\{[^}]*flex-wrap:\s*wrap/s);+});+import { CallHistory } from "./CallHistory";import type {CallEvent,CallHistoryPage,ResolvedCallReference,} from "./call-history-client";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";const { getHistory, clearEvents, clearAllEvents, getReferences } = vi.hoisted(() => ({@@ -138,6 +147,7 @@ beforeEach(() => {afterEach(() => {cleanup();vi.restoreAllMocks();+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);if (originalShowModal)Object.defineProperty(HTMLDialogElement.prototype,@@ -147,6 +157,68 @@ afterEach(() => {else Reflect.deleteProperty(HTMLDialogElement.prototype, "showModal");});+it("traduce el historial en vivo sin cambiar nombres ni contenido importado", async () => {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <CallHistory onBack={vi.fn()} />+ </LanguageProvider>,+ );+ const first = await loaded();+ expect(+ screen.getByRole("heading", { name: "Historial de uso" }),+ ).toBeTruthy();+ expect(first.textContent).toBe("Cursor encontró 3 contenidos relacionados");+ fireEvent.click(first);+ expect(+ screen.getByRole("heading", { name: "Esta consulta de memorias" }),+ ).toBeTruthy();+ expect(screen.getAllByText("Consulta completada")).toHaveLength(2);+ expect(screen.getByText("Consulta de memorias")).toBeTruthy();+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ fireEvent(window, new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }));+ expect(screen.getByRole("heading", { name: "这次查记忆" })).toBeTruthy();+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});++it.each([0, 1, 3])(+ "muestra %i registros con confirmación española y conserva títulos opacos",+ async (count) => {+ getHistory.mockResolvedValue(+ page(+ Array.from({ length: count }, (_, index) =>+ event(`event-${index}`, {+ host_id: "Aplicación 中文",+ references: [],+ }),+ ),+ ),+ );+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <CallHistory onBack={vi.fn()} />+ </LanguageProvider>,+ );+ if (!count) {+ expect(+ await screen.findByText("Todavía no hay registros de uso"),+ ).toBeTruthy();+ return;+ }+ await loaded("event-0");+ expect(screen.getAllByText(/Aplicación 中文 encontró/)).toHaveLength(count);+ fireEvent.click(+ screen.getByRole("button", { name: "Borrar registros de esta página" }),+ );+ expect(screen.getByRole("dialog").textContent).toContain(+ count === 1+ ? "¿Borrar el 1 registro de esta página?"+ : "¿Borrar los 3 registros de esta página?",+ );+ },+);+it("loads a bounded first page and returns to applications", async () => {const pending = deferred<CallHistoryPage>();getHistory.mockReturnValueOnce(pending.promise);@@ -354,7 +426,7 @@ it("does not claim delivery for a call Core never completed", async () => {const detail = screen.getByRole("article", { name: "调用详情" });expect(within(detail).queryByText(/已返回给/)).toBeNull();expect(- within(detail).getByText("One Memory 暂时不可用,这次回答没有带上记忆。"),+ within(detail).getByText("MemHub 暂时不可用,这次回答没有带上记忆。"),).toBeTruthy();});it("does not restate an undelivered result as returned", async () => {@@ -414,7 +486,7 @@ it.each(["查询超时,没有提供记忆","直接调用(诊断) 这次没来得及查到记忆",],- ["unavailable", "One Memory 暂时不可用", "直接调用(诊断) 暂时无法查记忆"],+ ["unavailable", "MemHub 暂时不可用", "直接调用(诊断) 暂时无法查记忆"],["denied", "当前未授权查询", "直接调用(诊断) 未获准查记忆"],] as const)("renders the %s state without claiming external adoption",@@ -471,7 +543,7 @@ it("does not call an unavailable call returned", async () => {const detail = screen.getByRole("article", { name: "调用详情" });expect(within(detail).queryByText(/· 已返回/)).toBeNull();expect(- within(detail).getAllByText(/One Memory 暂时不可用/).length,+ within(detail).getAllByText(/MemHub 暂时不可用/).length,).toBeGreaterThan(0);expect(within(detail).queryByText(/采用未确认|Core/)).toBeNull();});diff --git a/memhub/apps/web/src/CallHistory.tsx b/memhub/apps/web/src/CallHistory.tsxindex 6295fd8..83f37cc 100644--- a/memhub/apps/web/src/CallHistory.tsx+++ b/memhub/apps/web/src/CallHistory.tsx@@ -1,3 +1,4 @@+import type { GuiLocale, MessageKey } from "@one-memory/i18n";import {ArrowLeft,ChevronLeft,@@ -9,7 +10,6 @@ import { useEffect, useId, useRef, useState } from "react";import { getConversation } from "./api";import {CALL_HOSTS,- CALL_TOOLS,type CallEvent,type CallHistoryPage,callDeliveryLabel,@@ -24,27 +24,24 @@ import {type ResolvedCallReference,} from "./call-history-client";import { clockStamp } from "./clock-stamp";+import { useGuiLanguage } from "./gui-language";import { R6Button } from "./R6Controls";import { traceUiAction } from "./ui-trace";import { isDefiniteRefusal } from "./write-outcome";import "./call-history.css";const PAGE_SIZE = 20;-const stateLabels: Record<CallEvent["state"], string> = {- grounded: "查询成功",- empty: "查询成功,没有找到相关记忆",- partial: "查询成功,部分内容还在整理中",- timed_out: "查询超时,没有提供记忆",- unavailable: "One Memory 暂时不可用",- denied: "当前未授权查询",-};+const stateLabels = {+ grounded: "calls.state.grounded",+ empty: "calls.state.empty",+ partial: "calls.state.partial",+ timed_out: "calls.state.timed_out",+ unavailable: "calls.state.unavailable",+ denied: "calls.state.denied",+} as const satisfies Record<CallEvent["state"], MessageKey>;-function toolName(tool: CallEvent["tool"]) {- return CALL_TOOLS[tool];-}--function sourceLabel(id: string | null) {- return id === null ? "未记录" : (CALL_HOSTS[id] ?? id);+function sourceLabel(id: string | null, notRecorded: string) {+ return id === null ? notRecorded : (CALL_HOSTS[id] ?? id);}function CallReferences({@@ -56,6 +53,7 @@ function CallReferences({onOpenMemory?(id: string): void;onOpenEvidence?(id: string): void;}) {+ const { t } = useGuiLanguage();const [result, setResult] = useState<{event: CallEvent;items: ResolvedCallReference[];@@ -101,29 +99,31 @@ function CallReferences({return (<sectionclassName="call-history-references"- aria-label="相关内容"+ aria-label={t("calls.references")}aria-busy={loading}>- <h3>相关内容</h3>- {loading && <p role="status">正在读取相关内容</p>}- {failed && <p role="alert">相关内容暂时无法读取,请刷新重试。</p>}+ <h3>{t("calls.references")}</h3>+ {loading && <p role="status">{t("calls.referencesLoading")}</p>}+ {failed && <p role="alert">{t("calls.referencesFailed")}</p>}{event.references.length ? (<ul>{Array.from(references, ([key, { reference, current }]) => (<li key={key}><div><h4>- {reference.kind === "raw" ? "原文" : "记忆"} ·{" "}+ {t(reference.kind === "raw" ? "calls.raw" : "calls.memory")} ·{" "}{current?.available && current.reason === null? current.title: current?.reason === "changed"- ? "版本已变更"+ ? t("calls.changed"): loading- ? "待核对"- : "不可用"}+ ? t("calls.pending")+ : t("calls.notAvailable")}</h4>{reference.source_id && (- <p>{sourceLabel(reference.source_id)}</p>+ <p>+ {sourceLabel(reference.source_id, t("calls.notRecorded"))}+ </p>)}</div>{current?.available && current.reason === null && (@@ -160,23 +160,29 @@ function CallReferences({});}}>- {reference.kind === "raw" ? "查看原文" : "查看记忆"}+ {t(+ reference.kind === "raw"+ ? "calls.openRaw"+ : "calls.openMemory",+ )}</R6Button>)}</li>))}</ul>) : (- <p>没有找到相关内容</p>+ <p>{t("calls.noReferences")}</p>)}{transcript && (<aside- aria-label="原文正文"+ aria-label={t("calls.rawBody")}aria-busy={transcript.status === "loading"}>- {transcript.status === "loading" && <p role="status">正在读取原文</p>}+ {transcript.status === "loading" && (+ <p role="status">{t("calls.rawLoading")}</p>+ )}{transcript.status === "failed" && (- <p role="alert">原文已不可用或版本已变更。</p>+ <p role="alert">{t("calls.rawFailed")}</p>)}{transcript.status === "ready" &&transcript.messages.map((message) => (@@ -188,8 +194,8 @@ function CallReferences({);}-function shortTime(value: string) {- return clockStamp(value);+function shortTime(value: string, locale: GuiLocale) {+ return clockStamp(value, locale);}function ClearConfirmation({@@ -207,6 +213,7 @@ function ClearConfirmation({onCancel(): void;onConfirm(): void;}) {+ const { t } = useGuiLanguage();const dialog = useRef<HTMLDialogElement>(null);const titleId = useId();const descriptionId = useId();@@ -233,7 +240,7 @@ function ClearConfirmation({<p id={descriptionId}>{description}</p><div className="call-history-actions"><R6Button disabled={pending} onClick={onCancel}>- 取消+ {t("calls.cancel")}</R6Button><R6Button variant="primary" pending={pending} onClick={onConfirm}>{confirmLabel}@@ -252,6 +259,7 @@ export function CallHistory({onOpenMemory?(id: string): void;onOpenEvidence?(id: string): void;}) {+ const { t, tnPlain, locale } = useGuiLanguage();const [request, setRequest] = useState({hostId: "",offset: 0,@@ -267,7 +275,7 @@ export function CallHistory({{ kind: "page"; ids: string[] } | { kind: "all" } | null>(null);const [clearing, setClearing] = useState(false);- const [clearNotice, setClearNotice] = useState("");+ const [clearNotice, setClearNotice] = useState<MessageKey | null>(null);const mounted = useRef(false);const clearFlight = useRef(false);const heading = useRef<HTMLHeadingElement>(null);@@ -334,14 +342,14 @@ export function CallHistory({const clearingAll = confirmation.kind === "all";clearFlight.current = true;setClearing(true);- setClearNotice("");+ setClearNotice(null);const trace = traceUiAction("calls", "confirm");try {if (clearingAll) await clearAllCallEvents(trace.traceId);else await clearCallEvents([...confirmation.ids], trace.traceId);trace.done("succeeded");if (!mounted.current) return;- setClearNotice(clearingAll ? "已清空全部记录。" : "已清除所选记录。");+ setClearNotice(clearingAll ? "calls.clearedAll" : "calls.clearedPage");} catch (reason) {// A 4xx (e.g. `409 call_history_disabled`) is Core answering and// refusing: nothing was deleted, so it is a definite failure, not an@@ -361,9 +369,9 @@ export function CallHistory({setClearNotice(refused? clearingAll- ? "未能清空使用记录,当前记录保持不变。请核对后重试。"- : "未能清除所选记录,当前记录保持不变。请核对后重试。"- : "清除结果未确认,请核对重新读取的记录。未自动重试清除。",+ ? "calls.clearAllFailed"+ : "calls.clearPageFailed"+ : "calls.clearUnknown",);} finally {clearFlight.current = false;@@ -384,7 +392,7 @@ export function CallHistory({<section className="call-history" aria-labelledby={titleId}><header className="call-history-heading"><h1 id={titleId} ref={heading} tabIndex={-1}>- {selectedId === null ? "使用记录" : "这次查记忆"}+ {t(selectedId === null ? "calls.title" : "calls.query")}</h1><R6ButtonclassName="call-history-back"@@ -392,7 +400,7 @@ export function CallHistory({onClick={selectedId === null ? onBack : () => setSelectedId(null)}><ArrowLeft size={16} aria-hidden="true" />- {selectedId === null ? "返回应用" : "返回记录"}+ {t(selectedId === null ? "calls.backApps" : "calls.backHistory")}</R6Button></header><div@@ -401,7 +409,7 @@ export function CallHistory({{selectedId === null ? (<div className="call-history-filter"><label className="call-history-sr-only" htmlFor={filterId}>- 按应用筛选+ {t("calls.filter")}</label><selectid={filterId}@@ -416,7 +424,7 @@ export function CallHistory({}));}}>- <option value="">全部应用</option>+ <option value="">{t("calls.allApps")}</option>{Object.entries(CALL_HOSTS).map(([host, label]) => (<option key={host} value={host}>{label}@@ -428,12 +436,12 @@ export function CallHistory({<span />)}<div className="call-history-actions">- {selectedId === null && <span>最近记录</span>}+ {selectedId === null && <span>{t("calls.recent")}</span>}<R6ButtonclassName="call-history-icon"variant="quiet"- title="刷新记录"- aria-label="刷新记录"+ title={t("calls.refresh")}+ aria-label={t("calls.refresh")}disabled={clearing}onClick={refresh}>@@ -444,8 +452,8 @@ export function CallHistory({<R6ButtonclassName="call-history-icon"variant="quiet"- title="清除本页记录"- aria-label="清除本页记录"+ title={t("calls.clearPage")}+ aria-label={t("calls.clearPage")}disabled={!events.length || clearing}onClick={() =>setConfirmation({@@ -458,12 +466,12 @@ export function CallHistory({</R6Button><R6Buttonvariant="quiet"- title="清空全部记录"- aria-label="清空全部记录"+ title={t("calls.clearAll")}+ aria-label={t("calls.clearAll")}disabled={!page?.total || clearing}onClick={() => setConfirmation({ kind: "all" })}>- 清空全部+ {t("calls.clearAllShort")}</R6Button></>)}@@ -471,55 +479,67 @@ export function CallHistory({</div>{clearNotice && (<p className="call-history-notice" role="status">- {clearNotice}+ {t(clearNotice)}</p>)}<div aria-busy={loading || clearing}>{loading && (<p className="call-history-state" role="status">- 正在读取使用记录+ {t("calls.loading")}</p>)}{clearing && (<p className="call-history-state" role="status">- 正在清除所选记录+ {t("calls.clearing")}</p>)}{failed && (<p className="call-history-state" role="alert">- 记录读取失败,请刷新重试。+ {t("calls.readFailed")}</p>)}{page && !page.available && (<p className="call-history-state" role="alert">- 使用记录暂不可用,请稍后刷新。+ {t("calls.unavailable")}</p>)}{page?.recording_error && (<p className="call-history-notice" role="alert">- 有几次调用没被记下来,列表可能不全。+ {t("calls.incomplete")}</p>)}{page?.available &&(selectedId !== null ? (selected ? (- <article className="call-history-detail" aria-label="调用详情">- <h2>{`${sourceLabel(selected.host_id)} · ${shortTime(selected.occurred_at)}`}</h2>+ <article+ className="call-history-detail"+ aria-label={t("calls.callDetail")}+ >+ <h2>{`${sourceLabel(selected.host_id, t("calls.notRecorded"))} · ${shortTime(selected.occurred_at, locale)}`}</h2><p className="call-history-summary">- {callDetailHeadline(selected)}- {returnedFrom ? ` · 来源 ${sourceLabel(returnedFrom)}` : ""}+ {callDetailHeadline(selected, undefined, locale)}+ {returnedFrom+ ? t("calls.source", {+ source: sourceLabel(+ returnedFrom,+ t("calls.notRecorded"),+ ),+ })+ : ""}</p><p className="call-history-stage">- {stateLabels[selected.state]}+ {t(stateLabels[selected.state])}</p><p className="call-history-stage">- 找到原文 {selected.raw_count} 段 · 记忆{" "}- {selected.memory_count} 条 · 用时{" "}- {(selected.elapsed_ms / 1000).toFixed(1)} 秒+ {t("calls.stats", {+ raw: selected.raw_count,+ memories: selected.memory_count,+ seconds: (selected.elapsed_ms / 1000).toFixed(1),+ })}</p>- {callDeliveryLabel(selected) && (+ {callDeliveryLabel(selected, locale) && (<p className="call-history-stage">- {callDeliveryLabel(selected)}+ {callDeliveryLabel(selected, locale)}</p>)}<CallReferences@@ -527,22 +547,20 @@ export function CallHistory({onOpenMemory={onOpenMemory}onOpenEvidence={onOpenEvidence}/>- {callReturnDeliveryLabel(selected) && (+ {callReturnDeliveryLabel(selected, locale) && (<p className="call-history-adoption">- {callReturnDeliveryLabel(selected)}+ {callReturnDeliveryLabel(selected, locale)}</p>)}<sectionclassName="call-history-metadata"- aria-label="记录详情"+ aria-label={t("calls.metadata")}>- <h3>记录详情</h3>- <p>- 为保护隐私,这里不保存你问的原话和回答,只保存时间、来源和结果。- </p>+ <h3>{t("calls.metadata")}</h3>+ <p>{t("calls.privacy")}</p><dl><div>- <dt>准确时间</dt>+ <dt>{t("calls.exactTime")}</dt><dd><time dateTime={selected.occurred_at}>{selected.occurred_at}@@ -550,27 +568,29 @@ export function CallHistory({</dd></div><div>- <dt>应用</dt>- <dd>{sourceLabel(selected.host_id)}</dd>+ <dt>{t("calls.app")}</dt>+ <dd>+ {sourceLabel(selected.host_id, t("calls.notRecorded"))}+ </dd></div><div>- <dt>类型</dt>- <dd>{toolName(selected.tool)}</dd>+ <dt>{t("calls.type")}</dt>+ <dd>{t("calls.tool")}</dd></div><div>- <dt>结果状态</dt>+ <dt>{t("calls.result")}</dt>{/* The tool above is already humanized in this samepanel ("查记忆", never `om_recall`); printing the raw`grounded`/`partial` enum here leaks the internal statevocabulary the rest of the page translates. */}- <dd>{stateLabels[selected.state]}</dd>+ <dd>{t(stateLabels[selected.state])}</dd></div></dl></section></article>) : (<p className="call-history-state" role="status">- 这条记录已不在当前页,请返回记录查看。+ {t("calls.missingRow")}</p>)) : (@@ -578,12 +598,12 @@ export function CallHistory({<ulref={list}className="call-history-list"- aria-label="调用记录"+ aria-label={t("calls.list")}>{events.map((item) => (<li key={item.event_id}><time dateTime={item.occurred_at} title={item.occurred_at}>- {shortTime(item.occurred_at)}+ {shortTime(item.occurred_at, locale)}</time><div className="call-history-row-content"><h2>@@ -592,23 +612,26 @@ export function CallHistory({data-event-id={item.event_id}onClick={() => setSelectedId(item.event_id)}>- {callRowHeadline(item)}+ {callRowHeadline(item, locale)}</button></h2>- <p>{callRowDetail(item)}</p>+ <p>{callRowDetail(item, locale)}</p></div></li>))}</ul>{!events.length && (<p className="call-history-state" role="status">- {request.offset ? "本页暂无记录" : "暂无使用记录"}+ {t(request.offset ? "calls.emptyPage" : "calls.empty")}</p>)}- <nav className="call-history-pagination" aria-label="记录分页">+ <nav+ className="call-history-pagination"+ aria-label={t("calls.pagination")}+ ><R6Button- aria-label="上一页"- title="上一页"+ aria-label={t("calls.previous")}+ title={t("calls.previous")}disabled={request.offset === 0}onClick={() =>setRequest((current) => ({@@ -626,8 +649,8 @@ export function CallHistory({/ {page.total}</span><R6Button- aria-label="下一页"- title="下一页"+ aria-label={t("calls.next")}+ title={t("calls.next")}disabled={page.offset + PAGE_SIZE >= page.total || !events.length}@@ -648,25 +671,29 @@ export function CallHistory({page.retention_days !== null &&page.max_events !== null && (<p className="call-history-policy">- 保留 {page.retention_days} 天,最多{" "}- {new Intl.NumberFormat("zh-CN").format(page.max_events)} 条记录+ {t("calls.policy", {+ days: page.retention_days,+ count: new Intl.NumberFormat(locale).format(page.max_events),+ })}</p>)}{confirmation && (<ClearConfirmationtitle={confirmation.kind === "all"- ? "清空全部使用记录?"- : `清除本页 ${confirmation.ids.length} 条记录?`+ ? t("calls.confirmAllTitle")+ : tnPlain("calls.confirmPageTitle", confirmation.ids.length)}description={confirmation.kind === "all"- ? "将删除当前保留的全部调用记录,不限于本页或当前筛选。不删除原文或记忆,不更改授权与留存规则。此操作无法撤销。"- : "仅清除这批调用记录,不删除原文或记忆,不更改授权与留存规则。此操作无法撤销。"- }- confirmLabel={- confirmation.kind === "all" ? "确认清空全部" : "确认清除"+ ? t("calls.confirmAllDescription")+ : t("calls.confirmPageDescription")}+ confirmLabel={t(+ confirmation.kind === "all"+ ? "calls.confirmAll"+ : "calls.confirmPage",+ )}pending={clearing}onCancel={() => setConfirmation(null)}onConfirm={() => void confirmClear()}diff --git a/memhub/apps/web/src/ConnectionFallback.test.tsx b/memhub/apps/web/src/ConnectionFallback.test.tsxindex 37dfa4b..9f03557 100644--- a/memhub/apps/web/src/ConnectionFallback.test.tsx+++ b/memhub/apps/web/src/ConnectionFallback.test.tsx@@ -3,12 +3,50 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, describe, expect, it, vi } from "vitest";import { ConnectionFallback } from "./ConnectionFallback";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";afterEach(() => {cleanup();delete window.oneMemory;+ localStorage.clear();});describe("ConnectionFallback", () => {+ it("localizes pairing controls while preserving generated Skill bytes", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const skill = "pair --token '{no-traducir}'";+ window.oneMemory = {+ createCustomHarnessSkill: vi.fn().mockResolvedValue({+ displayName: "Harness 原名",+ expiresAt: "2026-10-19T12:10:00.000Z",+ skill,+ }),+ copyText: vi.fn().mockResolvedValue(undefined),+ getLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 1 }),+ onLanguagePreferenceChanged: vi.fn().mockReturnValue(() => {}),+ } as unknown as Window["oneMemory"];+ render(+ <LanguageProvider>+ <ConnectionFallback />+ </LanguageProvider>,+ );+ const user = userEvent.setup();+ await user.click(await screen.findByText("Conectar otras herramientas"));+ await user.type(+ screen.getByLabelText("Nombre del Harness"),+ "Harness 原名",+ );+ await user.click(+ screen.getByRole("button", {+ name: "Generar Skill de emparejamiento",+ }),+ );+ expect(+ await screen.findByLabelText("Skill de emparejamiento"),+ ).toHaveProperty("value", skill);+ });+it("names an unknown Harness before generating and copying its pairing Skill", async () => {const user = userEvent.setup();const createCustomHarnessSkill = vi.fn().mockResolvedValue({diff --git a/memhub/apps/web/src/ConnectionFallback.tsx b/memhub/apps/web/src/ConnectionFallback.tsxindex 3390797..1ab96bf 100644--- a/memhub/apps/web/src/ConnectionFallback.tsx+++ b/memhub/apps/web/src/ConnectionFallback.tsx@@ -1,16 +1,29 @@import { Copy, RefreshCw } from "lucide-react";-import { useState } from "react";+import { useEffect, useState } from "react";import { copyText } from "./copy-text";+import { useGuiLanguage } from "./gui-language";type Material = { displayName: string; expiresAt: string; skill: string };+type ConnectionMaterial = {+ mcp: string;+ shell: string | null;+ prompt: string;+};+type MaterialBridge = {+ getConnectionMaterial(): Promise<ConnectionMaterial>;+};export function ConnectionFallback() {+ const { locale, t } = useGuiLanguage();const [displayName, setDisplayName] = useState("");const [material, setMaterial] = useState<Material | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState(false);const [notice, setNotice] = useState("");const available = !!window.oneMemory?.createCustomHarnessSkill;+ const materialBridge = window.oneMemory as+ | (Window["oneMemory"] & Partial<MaterialBridge>)+ | undefined;async function generate() {const bridge = window.oneMemory;@@ -30,21 +43,24 @@ export function ConnectionFallback() {return (<details className="connection-fallback">- <summary>连接其他工具</summary>- {!available ? (- <p>本机配对仅在桌面 App 中可用。</p>+ <summary>{t("connectionFallback.title")}</summary>+ {materialBridge?.getConnectionMaterial ? (+ <ConnectionMaterialFallback+ bridge={materialBridge as Window["oneMemory"] & MaterialBridge}+ />+ ) : !available ? (+ <p>{t("connectionFallback.desktopOnly")}</p>) : (<><p className="connection-boundary">- 为未列出的本机 Harness 生成一次性配对- Skill。纯网页聊天、远端容器或另一台机器不能直接连接本机。+ {t("connectionFallback.description")}</p><label className="custom-harness-name">- Harness 名称+ {t("connectionFallback.name")}<inputvalue={displayName}maxLength={80}- placeholder="例如 Kimi Code"+ placeholder={t("connectionFallback.namePlaceholder")}onChange={(event) => {setDisplayName(event.target.value);setMaterial(null);@@ -58,29 +74,37 @@ export function ConnectionFallback() {disabled={loading || !displayName.trim()}onClick={() => void generate()}>- {loading ? "正在生成…" : "生成配对 Skill"}+ {loading+ ? t("connectionFallback.generating")+ : t("connectionFallback.generate")}</button>{error && (<p role="alert">- 未能生成配对 Skill。+ {t("connectionFallback.generateFailed")}<buttontype="button"className="quiet"onClick={() => void generate()}><RefreshCw size={15} aria-hidden="true" />- 重试+ {t("connectionFallback.retry")}</button></p>)}{material && (<><p>- 已为 {material.displayName} 生成一次性配对 Skill,有效期至{" "}- {new Date(material.expiresAt).toLocaleTimeString()}。+ {t("connectionFallback.generated", {+ name: material.displayName,+ time: new Intl.DateTimeFormat(locale, {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ }).format(new Date(material.expiresAt)),+ })}</p><textarea- aria-label="配对 Skill"+ aria-label={t("connectionFallback.skillLabel")}readOnlyvalue={material.skill}spellCheck={false}@@ -91,16 +115,14 @@ export function ConnectionFallback() {onClick={async () => {try {await copyText(material.skill);- setNotice(- "已复制配对 Skill。请粘贴到对应 Harness 中执行。",- );+ setNotice(t("connectionFallback.copied"));} catch {- setNotice("复制失败,可在上方选中文本复制。");+ setNotice(t("connectionFallback.copyFailed"));}}}><Copy size={15} aria-hidden="true" />- 复制 Skill+ {t("connectionFallback.copy")}</button></>)}@@ -110,3 +132,143 @@ export function ConnectionFallback() {</details>);}++function ConnectionMaterialFallback({+ bridge,+}: {+ bridge: Window["oneMemory"] & MaterialBridge;+}) {+ const { locale, t } = useGuiLanguage();+ const [material, setMaterial] = useState<ConnectionMaterial | null>(null);+ const [tab, setTab] = useState<"prompt" | "mcp" | "shell">("prompt");+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(false);+ const [notice, setNotice] = useState("");++ async function load() {+ setLoading(true);+ setError(false);+ try {+ setMaterial(await bridge.getConnectionMaterial());+ } catch {+ setError(true);+ } finally {+ setLoading(false);+ }+ }++ useEffect(() => {+ let current = true;+ void bridge.getConnectionMaterial().then(+ (value) => {+ if (!current) return;+ setMaterial(value);+ setLoading(false);+ },+ () => {+ if (!current) return;+ setError(true);+ setLoading(false);+ },+ );+ // The material is a snapshot. Language changes re-render its presentation+ // without reading paths or snippets again.+ return () => {+ current = false;+ };+ }, [bridge]);++ if (loading && !material)+ return <p role="status">{t("connectionFallback.loading")}</p>;+ if (error && !material)+ return (+ <p role="alert">+ {t("connectionFallback.loadFailed")}+ <button type="button" className="quiet" onClick={() => void load()}>+ <RefreshCw size={15} aria-hidden="true" />+ {t("connectionFallback.retry")}+ </button>+ </p>+ );+ if (!material) return null;++ const shellBlock = material.shell+ ? t("connectionFallback.promptShell", { shell: material.shell })+ : "";+ const prompt =+ locale === "zh-CN"+ ? material.prompt+ : t("connectionFallback.promptTemplate", {+ mcp: material.mcp,+ shellBlock,+ });+ const value =+ tab === "prompt"+ ? prompt+ : tab === "mcp"+ ? material.mcp+ : (material.shell ?? "");+ const copyLabel =+ tab === "prompt"+ ? t("connectionFallback.copyPrompt")+ : tab === "mcp"+ ? t("connectionFallback.copyConfig")+ : t("connectionFallback.copyCommand");++ return (+ <>+ <p className="connection-boundary">+ {t("connectionFallback.localDescription")}+ </p>+ <fieldset>+ <legend>{t("connectionFallback.format")}</legend>+ <div role="tablist">+ {(+ [+ ["prompt", t("connectionFallback.promptTab")],+ ["mcp", t("connectionFallback.mcpTab")],+ ["shell", t("connectionFallback.commandTab")],+ ] as const+ ).map(([value, label]) => (+ <button+ key={value}+ type="button"+ role="tab"+ aria-selected={tab === value}+ disabled={value === "shell" && !material.shell}+ onClick={() => {+ setTab(value);+ setNotice("");+ }}+ >+ {label}+ </button>+ ))}+ </div>+ </fieldset>+ <textarea+ aria-label={t("connectionFallback.materialLabel")}+ readOnly+ value={value}+ spellCheck={false}+ />+ <p>{t("connectionFallback.materialBoundary")}</p>+ <button+ type="button"+ className="secondary"+ onClick={async () => {+ try {+ await copyText(value);+ setNotice(t("connectionFallback.materialCopied"));+ } catch {+ setNotice(t("connectionFallback.copyFailed"));+ }+ }}+ >+ <Copy size={15} aria-hidden="true" />+ {copyLabel}+ </button>+ {notice && <p role="status">{notice}</p>}+ </>+ );+}diff --git a/memhub/apps/web/src/DebugLogPanel.test.tsx b/memhub/apps/web/src/DebugLogPanel.test.tsxindex ad80ee0..ab854fd 100644--- a/memhub/apps/web/src/DebugLogPanel.test.tsx+++ b/memhub/apps/web/src/DebugLogPanel.test.tsx@@ -11,6 +11,11 @@ import {import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { DebugLogPanel } from "./DebugLogPanel";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";import {recordRendererDebugLog,resetRendererDebugLogsForTest,@@ -87,6 +92,7 @@ const snapshot = {};beforeEach(() => {+ window.localStorage.clear();resetRendererDebugLogsForTest();diagnosticLevel.get.mockClear();diagnosticLevel.set.mockClear();@@ -102,6 +108,55 @@ afterEach(() => {vi.useRealTimers();});+function SwitchLanguage() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ Cambiar idioma+ </button>+ );+}++it("translates controls live but preserves events and does not change capture", async () => {+ // A language bridge is not required by this synthetic browser fixture.+ const read = vi.fn().mockResolvedValue(snapshot);+ window.oneMemory = undefined;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const view = render(+ <LanguageProvider>+ <SwitchLanguage />+ <DebugLogPanel />+ </LanguageProvider>,+ );+ window.oneMemory = { getDebugLogs: read } as unknown as NonNullable<+ typeof window.oneMemory+ >;+ view.rerender(+ <LanguageProvider>+ <SwitchLanguage />+ <DebugLogPanel />+ </LanguageProvider>,+ );+ await userEvent.click(+ await screen.findByRole("button", {+ name: "Abrir registros de depuración",+ }),+ );+ await screen.findByText(/source\.scanned/);+ expect(+ screen.getByRole("searchbox", { name: "Buscar registros" }),+ ).toBeTruthy();+ await userEvent.click(+ screen.getByRole("button", { name: "Pausar actualización en vivo" }),+ );+ const count = read.mock.calls.length;+ await userEvent.click(screen.getByRole("button", { name: "Cambiar idioma" }));+ await screen.findByRole("searchbox", { name: "搜索日志" });+ expect(screen.getByText(/source\.scanned/)).toBeTruthy();+ expect(read).toHaveBeenCalledTimes(count);+ expect(diagnosticLevel.set).not.toHaveBeenCalled();+});+it("opens from the floating button and filters by text, level and source", async () => {render(<DebugLogPanel />);await userEvent.click(@@ -255,3 +310,51 @@ it("shows per-minute model usage in a separate tab", async () => {}),).toBeTruthy();});++it("shows the diagnostics tabs and model usage in Spanish without Chinese copy", async () => {+ // Browser-mode language, then the desktop log bridge, as in the test above.+ const bridge = window.oneMemory;+ window.oneMemory = undefined;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const view = render(+ <LanguageProvider>+ <DebugLogPanel />+ </LanguageProvider>,+ );+ window.oneMemory = bridge;+ view.rerender(+ <LanguageProvider>+ <DebugLogPanel />+ </LanguageProvider>,+ );+ await userEvent.click(+ await screen.findByRole("button", {+ name: "Abrir registros de depuración",+ }),+ );+ const panel = await screen.findByRole("complementary", {+ name: "Registros de depuración",+ });+ expect(within(panel).getByText("Diagnóstico")).toBeTruthy();+ expect(+ within(panel).getByRole("button", {+ name: "Mostrar los registros en pantalla completa",+ }),+ ).toBeTruthy();++ await userEvent.click(+ within(panel).getByRole("tab", { name: "Uso del modelo" }),+ );++ await waitFor(() => expect(diagnosticLevel.usage).toHaveBeenCalled());+ expect(within(panel).getByText("Tokens totales")).toBeTruthy();+ expect(+ within(panel).getByText("Uso del modelo que genera memorias"),+ ).toBeTruthy();+ expect(+ within(panel).getByRole("img", {+ name: "Tokens consumidos por minuto de cada prompt",+ }),+ ).toBeTruthy();+ expect(panel.textContent).not.toMatch(/[一-鿿]/);+});diff --git a/memhub/apps/web/src/DebugLogPanel.tsx b/memhub/apps/web/src/DebugLogPanel.tsxindex 2c9d80f..6f6b904 100644--- a/memhub/apps/web/src/DebugLogPanel.tsx+++ b/memhub/apps/web/src/DebugLogPanel.tsx@@ -28,6 +28,7 @@ import type {DebugLogLevel,DebugLogSnapshot,} from "./debug-log-types";+import { useGuiLanguage } from "./gui-language";import { ModelUsageView } from "./ModelUsageView";import {rendererDebugLogs,@@ -53,6 +54,7 @@ const SERVICE_LABELS: Record<DebugLogEntry["service"], string> = {};export function DebugLogPanel() {+ const { t, tnPlain, locale } = useGuiLanguage();const supported = typeof window.oneMemory?.getDebugLogs === "function";const [open, setOpen] = useState(false);const [fullscreen, setFullscreen] = useState(false);@@ -171,23 +173,23 @@ export function DebugLogPanel() {{open ? (<asideclassName={`debug-log-panel${fullscreen ? " is-fullscreen" : ""}`}- aria-label="Debug 日志"+ aria-label={t("debugTitle")}><header className="debug-log-header"><div>- <strong>诊断</strong>+ <strong>{t("debugDiagnostics")}</strong><span>{tab === "logs"- ? `${entries.length} 条日志,本次启动`- : "记忆沉淀模型用量"}+ ? tnPlain("debugCount", entries.length)+ : t("debugUsageSubtitle")}</span></div><div className="debug-log-header-actions"><buttontype="button"className="debug-icon-button"- title={live ? "暂停实时刷新" : "继续实时刷新"}- aria-label={live ? "暂停实时刷新" : "继续实时刷新"}+ title={live ? t("debugPause") : t("debugResume")}+ aria-label={live ? t("debugPause") : t("debugResume")}onClick={() => setLive((value) => !value)}>{live ? <CirclePause size={17} /> : <CirclePlay size={17} />}@@ -195,8 +197,8 @@ export function DebugLogPanel() {<buttontype="button"className="debug-icon-button"- title="立即刷新"- aria-label="立即刷新"+ title={t("debugRefresh")}+ aria-label={t("debugRefresh")}onClick={() => {if (tab === "logs") void refresh();else setUsageRefreshToken((value) => value + 1);@@ -210,8 +212,14 @@ export function DebugLogPanel() {<buttontype="button"className="debug-icon-button"- title={fullscreen ? "退出全屏" : "全屏显示"}- aria-label={fullscreen ? "退出全屏显示日志" : "全屏显示日志"}+ title={t(+ fullscreen ? "debugExitFullscreen" : "debugFullscreen",+ )}+ aria-label={t(+ fullscreen+ ? "debugExitFullscreenLabel"+ : "debugFullscreenLabel",+ )}onClick={() => setFullscreen((value) => !value)}>{fullscreen ? <Minimize2 size={17} /> : <Maximize2 size={17} />}@@ -219,8 +227,8 @@ export function DebugLogPanel() {<buttontype="button"className="debug-icon-button"- title="关闭 Debug 日志"- aria-label="关闭 Debug 日志"+ title={t("debugClose")}+ aria-label={t("debugClose")}onClick={() => {setFullscreen(false);setOpen(false);@@ -233,7 +241,7 @@ export function DebugLogPanel() {<divclassName="debug-panel-tabs"role="tablist"- aria-label="诊断页面"+ aria-label={t("debugTabs")}><buttontype="button"@@ -241,7 +249,7 @@ export function DebugLogPanel() {aria-selected={tab === "logs"}onClick={() => setTab("logs")}>- 日志+ {t("debugLogsTab")}</button><buttontype="button"@@ -249,7 +257,7 @@ export function DebugLogPanel() {aria-selected={tab === "usage"}onClick={() => setTab("usage")}>- 模型用量+ {t("debugUsageTab")}</button></div>{tab === "logs" ? (@@ -261,18 +269,18 @@ export function DebugLogPanel() {type="search"value={query}onChange={(event) => setQuery(event.target.value)}- placeholder="搜索事件、组件、错误码或内容"- aria-label="搜索日志"+ placeholder={t("debugSearchPlaceholder")}+ aria-label={t("debugSearch")}/></label><select- aria-label="日志来源"+ aria-label={t("debugSource")}value={service}onChange={(event) =>setService(event.target.value as typeof service)}>- <option value="all">全部来源</option>+ <option value="all">{t("debugAllSources")}</option>{Object.entries(SERVICE_LABELS).map(([value, label]) => (<option key={value} value={value}>{label}@@ -280,9 +288,9 @@ export function DebugLogPanel() {))}</select><label className="debug-capture-level">- <span>采集级别</span>+ <span>{t("debugCapture")}</span><select- aria-label="采集级别"+ aria-label={t("debugCapture")}value={captureLevel}disabled={capturePending}onChange={(event) => {@@ -303,7 +311,7 @@ export function DebugLogPanel() {</label></div><fieldset className="debug-levels">- <legend>显示级别</legend>+ <legend>{t("debugDisplay")}</legend>{LEVELS.map((option) => (<buttontype="button"@@ -311,16 +319,20 @@ export function DebugLogPanel() {aria-pressed={level === option.value}onClick={() => setLevel(option.value)}>- {option.label}+ {option.value === "all" ? t("debugAll") : option.label}</button>))}</fieldset><div className="debug-log-status" aria-live="polite">- <span>{filtered.length} 条匹配</span>- <span>{live ? "实时刷新" : "已暂停"}</span>- {snapshot?.truncated ? <span>日志过多,已截断</span> : null}+ <span>{tnPlain("debugMatches", filtered.length)}</span>+ <span>{live ? t("debugLive") : t("debugPaused")}</span>+ {snapshot?.truncated ? (+ <span>{t("debugTruncated")}</span>+ ) : null}{readState === "error" ? (- <span className="debug-read-error">读取失败</span>+ <span className="debug-read-error">+ {t("debugReadError")}+ </span>) : null}</div><div@@ -347,7 +359,7 @@ export function DebugLogPanel() {) : (<ChevronRight size={14} />)}- <time>{logTime(entry.timestamp)}</time>+ <time>{logTime(entry.timestamp, locale)}</time><span className="debug-log-level">{entry.level}</span><span className="debug-log-service">{SERVICE_LABELS[entry.service]}@@ -369,8 +381,8 @@ export function DebugLogPanel() {) : (<p className="debug-log-empty">{readState === "loading"- ? "正在读取日志…"- : "没有匹配的日志"}+ ? t("debugLoading")+ : t("debugEmpty")}</p>)}</div>@@ -383,8 +395,8 @@ export function DebugLogPanel() {<buttontype="button"className="debug-fab"- aria-label={open ? "Debug 日志已打开" : "打开 Debug 日志"}- title="打开 Debug 日志"+ aria-label={open ? t("debugOpened") : t("debugOpen")}+ title={t("debugOpen")}onClick={() => setOpen(true)}><Bug size={20} aria-hidden="true" />@@ -400,9 +412,9 @@ function searchableEntry(entry: DebugLogEntry): string {return JSON.stringify(entry).toLocaleLowerCase();}-function logTime(timestamp: string): string {+function logTime(timestamp: string, locale: string): string {const date = new Date(timestamp);return Number.isNaN(date.getTime())? timestamp- : date.toLocaleTimeString("zh-CN", { hour12: false });+ : date.toLocaleTimeString(locale, { hour12: false });}diff --git a/memhub/apps/web/src/DesktopFrame.test.tsx b/memhub/apps/web/src/DesktopFrame.test.tsxindex aab3f0e..deebc25 100644--- a/memhub/apps/web/src/DesktopFrame.test.tsx+++ b/memhub/apps/web/src/DesktopFrame.test.tsx@@ -47,17 +47,18 @@ describe("desktop window frame", () => {container.querySelectorAll(".onboarding-r6-titlebar"),).toHaveLength(1);expect(container.querySelector(".onboarding-r6-traffic")).toBeNull();- // The user removed the mark, the "One Memory" wordmark and the- // "第一次见面" caption on 2026-09-20. The bar stays empty; MemHub is not- // put back into it.+ // Branding stays removed; only the explicit GUI language selector+ // occupies the native titlebar, outside the draggable area.expect(screen.queryByText("MemHub")).toBeNull();expect(screen.queryByText("One Memory")).toBeNull();expect(screen.queryByText("第一次见面")).toBeNull();expect(container.querySelector(".onboarding-r6-titlebar")?.children.length,- ).toBe(0);+ ).toBe(1);+ expect(screen.getByRole("combobox", { name: "界面语言" })).toBeTruthy();const titlebar = declaration(".onboarding-r6-titlebar");- expect(titlebar).toMatch(/flex:\s*0 0 58px/);+ expect(titlebar).toMatch(/flex:\s*0 0 auto/);+ expect(titlebar).toMatch(/min-height:\s*58px/);expect(titlebar).toMatch(/-webkit-app-region:\s*drag/);},);diff --git a/memhub/apps/web/src/FirstImportReview.tsx b/memhub/apps/web/src/FirstImportReview.tsxindex a5cfd16..53d05db 100644--- a/memhub/apps/web/src/FirstImportReview.tsx+++ b/memhub/apps/web/src/FirstImportReview.tsx@@ -2,6 +2,7 @@ import type { ImportJob, SourceResponse } from "@one-memory/contracts";import { Pause, Play } from "lucide-react";import { useEffect, useRef, useState } from "react";import { connectionHostId } from "./connection-hosts";+import { useOnboardingTranslation } from "./onboarding-language";import { R6ColdStartFrame } from "./R6ColdStartFrame";import { R6Button } from "./R6Controls";import { R6ImportProgress } from "./R6ImportProgress";@@ -87,6 +88,7 @@ export function FirstImportReview({onConnectionDraftChange,onContinue,}: FirstImportReviewProps) {+ const { text, t } = useOnboardingTranslation();const stale = sourceSnapshot?.stale === true;const ids = [...new Set(sourceIds)];// Without explicit IDs, capture the initial batch once; later sync/history jobs@@ -120,7 +122,14 @@ export function FirstImportReview({);const progressStale = stale && batch.length === 0;const [changing, setChanging] = useState(false);- const [actionMessage, setActionMessage] = useState("");+ const [actionResult, setActionResult] = useState<{+ stopped: boolean;+ confirmed: number;+ failed: number;+ } | null>(null);+ const actionMessage = actionResult+ ? `${actionResult.stopped ? t("onboardingBatchStopped") : ""}${t("onboardingBatchResult", { confirmed: actionResult.confirmed, failed: actionResult.failed })}${actionResult.failed ? text("已确认项保留,请核对未确认任务后重试。") : ""}`+ : "";const batchFlight = useRef(false),stopBatch = useRef(false),mounted = useRef(true);@@ -196,7 +205,7 @@ export function FirstImportReview({batchFlight.current = true;stopBatch.current = false;setChanging(true);- setActionMessage("");+ setActionResult(null);let confirmed = 0,failed = 0;try {@@ -262,9 +271,7 @@ export function FirstImportReview({}}if (mounted.current)- setActionMessage(- `${stopBatch.current ? "已停止后续操作;已发出的操作仍按回执核对。" : ""}已确认 ${confirmed} 项,${failed} 项未确认。${failed ? "已确认项保留,请核对未确认任务后重试。" : ""}`,- );+ setActionResult({ stopped: stopBatch.current, confirmed, failed });} finally {batchFlight.current = false;if (mounted.current) setChanging(false);@@ -274,21 +281,23 @@ export function FirstImportReview({return (<R6ColdStartFramestep={2}- title={title}- eyebrow="导入进行中 · 顺手连接应用"+ title={text(title)}+ eyebrow={text("导入进行中 · 顺手连接应用")}footer={<><div className="first-import-r6-footer-note"><p>- {allCompleted- ? "对话已保存,记忆尚待生成。"- : displayImporting- ? "导入在后台继续,无需等待。"- : stale- ? "正在重新核对来源;已保存数量仍按任务回执显示。"- : allPaused- ? "本次历史导入已暂停,已保存的对话还在。"- : "导入等待处理,已保存的对话还在。"}+ {text(+ allCompleted+ ? "对话已保存,记忆尚待生成。"+ : displayImporting+ ? "导入在后台继续,无需等待。"+ : stale+ ? "正在重新核对来源;已保存数量仍按任务回执显示。"+ : allPaused+ ? "本次历史导入已暂停,已保存的对话还在。"+ : "导入等待处理,已保存的对话还在。",+ )}</p>{(error || actionMessage) && (<p@@ -307,7 +316,7 @@ export function FirstImportReview({: undefined}>- {error || actionMessage}+ {error ? text(error) : actionMessage}</p>)}</div>@@ -318,7 +327,7 @@ export function FirstImportReview({stopBatch.current = true;}}>- 停止后续操作+ {text("停止后续操作")}</R6Button>) : onChangeJob && (canPause || canResume) ? (<R6Button@@ -330,7 +339,7 @@ export function FirstImportReview({) : (<Play size={16} aria-hidden="true" />)}- {canPause ? "暂停导入" : "继续导入"}+ {text(canPause ? "暂停导入" : "继续导入")}</R6Button>) : null}{recovery ? (@@ -342,18 +351,20 @@ export function FirstImportReview({recovery.onSkip();}}>- {recovery.destination === "sources"- ? "仍进入应用页"- : recovery.destination === "settings"- ? "仍进入设置"- : "仍进入工作台"}+ {text(+ recovery.destination === "sources"+ ? "仍进入应用页"+ : recovery.destination === "settings"+ ? "仍进入设置"+ : "仍进入工作台",+ )}</R6Button><R6Buttonvariant="primary"disabled={busy}onClick={() => leave(recovery.destination)}>- 重试保存并进入+ {text("重试保存并进入")}</R6Button></>) : (@@ -362,7 +373,7 @@ export function FirstImportReview({disabled={busy}onClick={() => leave("settings")}>- 配置模型,沉淀记忆+ {text("配置模型,沉淀记忆")}</R6Button>)}</div>@@ -370,19 +381,25 @@ export function FirstImportReview({}><div className="first-import-r6-layout">- <section className="first-import-r6-main" aria-label="导入与原文">+ <section+ className="first-import-r6-main"+ aria-label={text("导入与原文")}+ ><p className="first-import-r6-intro">- {allCompleted- ? "本次导入已结束。已保存的对话无需重复导入。"- : "对话先保存在本机。你可以同时设置后续连接。"}+ {text(+ allCompleted+ ? "本次导入已结束。已保存的对话无需重复导入。"+ : "对话先保存在本机。你可以同时设置后续连接。",+ )}</p><p className="first-import-r6-subintro">- 导入不会自动开放应用读取权限。配置模型后,才会开始生成记忆。+ {text(+ "导入不会自动开放应用读取权限。配置模型后,才会开始生成记忆。",+ )}</p>{historyWindowLimited && (<p className="first-import-r6-history-window" role="status">- 检测到会话数据量较大。为控制用量并保持各应用时间线一致,本次所有应用仅导入最近- 3 天的对话。+ {t("onboardingHistoryWindow")}</p>)}<R6ImportProgress@@ -391,21 +408,24 @@ export function FirstImportReview({jobs={batch}stale={progressStale}/>- <section className="first-import-r6-feed" aria-label="导入说明">- <h2>正在导入你的会话</h2>+ <section+ className="first-import-r6-feed"+ aria-label={text("导入说明")}+ >+ <h2>{text("正在导入你的会话")}</h2><p className="first-import-r6-feed-status">- 后台将持续为你导入,可以放心进入下一步+ {text("后台将持续为你导入,可以放心进入下一步")}</p>{Object.keys(failedSources).length > 0 && (<sectionclassName="first-import-r6-failures"- aria-label="未开始的导入"+ aria-label={text("未开始的导入")}>{Object.keys(failedSources).map((id) => (<p key={id}>{sources.find((source) => source.source_id === id)?.display_name ?? id}{" "}- 未能开始导入,其他已接受任务不受影响。+ {text("未能开始导入,其他已接受任务不受影响。")}</p>))}<R6Button@@ -413,27 +433,30 @@ export function FirstImportReview({disabled={busy}onClick={() => leave("sources")}>- 查看未导入的应用+ {text("查看未导入的应用")}</R6Button></section>)}</section></section>- <aside className="first-import-r6-options" aria-label="连接应用">- <p className="first-import-r6-eyebrow">让记忆继续生长</p>- <h2>连接你的应用</h2>+ <aside+ className="first-import-r6-options"+ aria-label={text("连接应用")}+ >+ <p className="first-import-r6-eyebrow">{text("让记忆继续生长")}</p>+ <h2>{text("连接你的应用")}</h2><p className="first-import-r6-options-intro">- 适用于本次选择且支持的应用。+ {text("适用于本次选择且支持的应用。")}</p><SelectionTile- title={- hostConnectionAvailable ? "一键接入应用" : "测试实例不接入应用"- }- body={+ title={text(+ hostConnectionAvailable ? "一键接入应用" : "测试实例不接入应用",+ )}+ body={text(hostConnectionAvailable? "安装记忆连接,让所选应用用上 MemHub 中的相关记忆。"- : "当前使用独立测试数据目录,不会修改本机应用的连接配置。"- }+ : "当前使用独立测试数据目录,不会修改本机应用的连接配置。",+ )}checked={hostConnectionAvailable &&!!hostEligible.length &&@@ -456,12 +479,16 @@ export function FirstImportReview({}/>{connectionNote && (- <p className="first-import-r6-options-note">{connectionNote}</p>+ <p className="first-import-r6-options-note">+ {text(connectionNote)}+ </p>)}<p className="first-import-r6-options-note">- {draftReady- ? "点击底部按钮后,后台分别接入各应用;某个应用失败不影响其他应用。"- : "暂时无法连接应用,当前不会安装连接。"}+ {text(+ draftReady+ ? "点击底部按钮后,后台分别接入各应用;某个应用失败不影响其他应用。"+ : "暂时无法连接应用,当前不会安装连接。",+ )}</p></aside></div>diff --git a/memhub/apps/web/src/FirstUseGuide.test.tsx b/memhub/apps/web/src/FirstUseGuide.test.tsxindex f0018c6..452970f 100644--- a/memhub/apps/web/src/FirstUseGuide.test.tsx+++ b/memhub/apps/web/src/FirstUseGuide.test.tsx@@ -1,9 +1,58 @@// @vitest-environment jsdomimport type { MemoryDetail, SourceResponse } from "@one-memory/contracts";-import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { FirstUseGuide, FirstUseInvitation } from "./FirstUseGuide";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";++function GuideLanguageSwitch() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ Cambiar idioma+ </button>+ );+}++it("localizes the supported guide without changing original memory or copying", async () => {+ window.oneMemory = undefined;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <GuideLanguageSwitch />+ <FirstUseGuide sources={[source]} onSources={vi.fn()} onClose={vi.fn()} />+ </LanguageProvider>,+ );+ await screen.findByRole("heading", {+ name: "Retoma tu próxima conversación",+ });+ await screen.findByText(detail.memory.content, { selector: "blockquote" });+ expect(+ screen.getByRole("button", { name: "Copiar mensaje inicial" }),+ ).toBeTruthy();+ const reads = getMemory.mock.calls.length;+ fireEvent.click(screen.getByText("Cambiar idioma"));+ await screen.findByRole("heading", { name: "让下一次对话接得上" });+ expect(getMemory).toHaveBeenCalledTimes(reads);+ expect(+ screen.getByText(detail.memory.content, { selector: "blockquote" }),+ ).toBeTruthy();+ expect(copyText).not.toHaveBeenCalled();+ expect(openHandoff).not.toHaveBeenCalled();+ localStorage.clear();+});const getMemories = vi.fn(),getMemory = vi.fn(),diff --git a/memhub/apps/web/src/FirstUseGuide.tsx b/memhub/apps/web/src/FirstUseGuide.tsxindex 643cb52..2e32ad1 100644--- a/memhub/apps/web/src/FirstUseGuide.tsx+++ b/memhub/apps/web/src/FirstUseGuide.tsx@@ -3,6 +3,7 @@ import type {MemoryDetail,SourceResponse,} from "@one-memory/contracts";+import type { MessageKey } from "@one-memory/i18n";import {ArrowLeft,ArrowRight,@@ -27,6 +28,7 @@ import {sameGuideMemory,} from "./first-use-model";import type { RecallHostStatus } from "./global";+import { useGuiLanguage } from "./gui-language";import { refreshRecallHosts, useRecallHosts } from "./host-state";import { refreshSources } from "./source-state";@@ -41,6 +43,7 @@ export function FirstUseGuide({onSources(): void;onClose(): void;}) {+ const { t, tn, locale } = useGuiLanguage();const [scene, setScene] = useState<GuideScenario>("same");const [route, setRoute] = useState<GuideRoute>("context");const [memories, setMemories] = useState<GovernedMemory[]>([]);@@ -52,11 +55,12 @@ export function FirstUseGuide({const hosts = hostsError ? NO_HOSTS : (hostRead.data ?? NO_HOSTS);const [loading, setLoading] = useState(true);const [detailLoading, setDetailLoading] = useState(false);- const [error, setError] = useState("");+ const [error, setError] = useState<MessageKey | "">("");const [reload, setReload] = useState(0);const [targetId, setTargetId] = useState("");const [topic, setTopic] = useState("");- const [notice, setNotice] = useState("");+ const [notice, setNotice] = useState<MessageKey | "">("");+ const [noticeHost, setNoticeHost] = useState("");const [copiedKey, setCopiedKey] = useState("");const [busy, setBusy] = useState(false);const [reported, setReported] = useState<"ok" | "missing" | null>(null);@@ -108,7 +112,7 @@ export function FirstUseGuide({if (!cancelled) {setMemories([]);setSelectedId("");- setError("暂时无法读取记忆,可稍后重试。");+ setError("guideReadError");}}).finally(() => {@@ -143,7 +147,7 @@ export function FirstUseGuide({);}).catch(() => {- if (!cancelled) setError("这条记忆暂不可读,请换一条或刷新。");+ if (!cancelled) setError("guideDetailError");}).finally(() => {if (!cancelled) setDetailLoading(false);@@ -172,7 +176,12 @@ export function FirstUseGuide({const nameOf = (id: string) =>sources.find((item) => item.source_id === id)?.display_name ??(id === "one-memory-manual" ? "端内添加" : id);+ // The handoff draft is task content, not UI copy: retain its existing wording.const sourceLabel = sourceIds.map(nameOf).join("、") || "原应用";+ const displaySourceLabel =+ sourceIds+ .map((id) => (id === "one-memory-manual" ? t("guideManual") : nameOf(id)))+ .join(t("guideListSeparator")) || t("guideOriginalApp");const draft =available && detail? draftForScenario(scene, effectiveRoute, topic, detail, sourceLabel)@@ -218,7 +227,7 @@ export function FirstUseGuide({) {setDetail(null);setCopiedKey("");- setError("记忆内容或授权已变化,请刷新后重新核对。");+ setError("guideChanged");return;}if (@@ -232,7 +241,7 @@ export function FirstUseGuide({)) {setCopiedKey("");- setNotice("连接状态已变化,尚未复制。请重新选择方式。");+ setNotice("guideConnectionChanged");return;}validated = true;@@ -242,25 +251,24 @@ export function FirstUseGuide({if (open && host?.handoff === "open" && window.oneMemory) {try {const result = await window.oneMemory.openHandoff(host.hostId, draft);- if (current())+ if (current()) {+ setNoticeHost(host.label);setNotice(- result.opened- ? `已复制并请求打开 ${host.label}。尚未发送,请核对输入框。`- : "已完整复制,未能预填。可在目标应用粘贴,尚未发送。",+ result.opened ? "guideCopiedOpened" : "guideCopiedNotFilled",);+ }} catch {- if (current())- setNotice("已完整复制,但未能打开目标应用。尚未发送。");+ if (current()) setNotice("guideCopiedNotOpened");}- } else setNotice("已完整复制。尚未发送,也没有新增读取授权。");+ } else setNotice("guideCopied");} catch {if (current()) {if (!validated) {setDetail(null);setCopiedKey("");- setError("无法核对当前记忆与授权,旧预览已收起。请刷新后重试。");+ setError("guideValidationError");}- setNotice("未能核对最新内容或完成复制。请重试;没有打开目标应用。");+ setNotice("guideCopyError");}} finally {if (current()) setBusy(false);@@ -271,16 +279,16 @@ export function FirstUseGuide({<section className="view first-use-view" aria-labelledby="first-use-title"><header className="first-use-heading"><div>- <p className="first-use-eyebrow">上手体验</p>- <h1 id="first-use-title">让下一次对话接得上</h1>+ <p className="first-use-eyebrow">{t("guideEyebrow")}</p>+ <h1 id="first-use-title">{t("guideTitle")}</h1></div><button type="button" className="quiet" onClick={onClose}><ArrowLeft size={16} aria-hidden="true" />- 返回记忆+ {t("guideBack")}</button></header><fieldset className="first-use-scenarios">- <legend className="sr-only">选择使用场景</legend>+ <legend className="sr-only">{t("guideChooseScene")}</legend>{GUIDE_SCENARIOS.map((item, index) => (<label key={item.id} data-selected={scene === item.id}><input@@ -296,47 +304,61 @@ export function FirstUseGuide({}}/><span className="first-use-number">0{index + 1}</span>- <span>{item.label}</span>+ <span>+ {t(+ item.id === "same"+ ? "guideSame"+ : item.id === "switch"+ ? "guideSwitch"+ : "guideNew",+ )}+ </span></label>))}</fieldset>- <p className="first-use-description">{scenario.description}</p>+ <p className="first-use-description">+ {t(+ scenario.id === "same"+ ? "guideSameDescription"+ : scenario.id === "switch"+ ? "guideSwitchDescription"+ : "guideNewDescription",+ )}+ </p>{importedMessages > 0 && (<p className="first-use-receipt">- 本机已保存 {importedMessages.toLocaleString()} 条原始消息 ·{" "}+ {tn("guideSaved", importedMessages)}{loading- ? "正在读取已整理记忆"- : `本页已加载 ${memories.length} 条可用记忆`}- 。两个阶段分别计数。+ ? t("guideReadingMemories")+ : tn("guideLoaded", memories.length)}+ {t("guideSeparate")}</p>)}<div className="first-use-path">- <span>选择背景</span>+ <span>{t("guideChooseBackground")}</span><ArrowRight size={14} aria-hidden="true" />- <span>核对来源</span>+ <span>{t("guideCheckSources")}</span><ArrowRight size={14} aria-hidden="true" />- <span>到新对话试用</span>+ <span>{t("guideTry")}</span></div>{error && (<p className="error-banner" role="alert">- {error}+ {t(error)}</p>)}{loading ? (- <p role="status">正在读取本机已有记忆…</p>+ <p role="status">{t("guideLoading")}</p>) : !memories.length ? (<section className="first-use-empty"><FileText size={28} aria-hidden="true" />- <h2>先留下一条真正有用的背景</h2>- <p>- 目前没有可用于这次体验的记忆。已导入的原文不等于已经整理好;候选内容也不会被自动带出。- </p>+ <h2>{t("guideEmptyTitle")}</h2>+ <p>{t("guideEmptyDescription")}</p><div><button type="button" onClick={onClose}>- 去添加记忆+ {t("guideAdd")}</button><button type="button" className="secondary" onClick={onSources}>- 查看导入与连接+ {t("guideConnections")}</button><buttontype="button"@@ -344,7 +366,7 @@ export function FirstUseGuide({onClick={() => setReload((n) => n + 1)}><RefreshCw size={15} />- 刷新+ {t("guideRefresh")}</button></div></section>@@ -355,12 +377,12 @@ export function FirstUseGuide({aria-labelledby="guide-background-title"><header>- <h2 id="guide-background-title">这次用到的背景</h2>+ <h2 id="guide-background-title">{t("guideBackgroundTitle")}</h2><buttontype="button"className="quiet"- title="刷新示例"- aria-label="刷新示例"+ title={t("guideRefreshExample")}+ aria-label={t("guideRefreshExample")}onClick={() => {changed();setDetail(null);@@ -372,7 +394,7 @@ export function FirstUseGuide({</button></header><label className="first-use-field">- 选择一条记忆+ {t("guideChooseMemory")}<selectvalue={selectedId}onChange={(event) => {@@ -390,46 +412,51 @@ export function FirstUseGuide({</select></label><p className="first-use-meta">- 从当前已加载的 {memories.length}{" "}- 条可用记忆中选择,不代表全部历史。+ {tn("guideLoadedScope", memories.length)}</p>{detailLoading ? (- <p role="status">正在核对原始依据…</p>+ <p role="status">{t("guideCheckingEvidence")}</p>) : available && detail ? (<><blockquote className="first-use-memory">{detail.memory.content}</blockquote><p className="first-use-meta">- {sourceLabel} · 版本 {detail.memory.revision} ·- 系统整理,需你核对+ {t("guideRevision", {+ source: displaySourceLabel,+ revision: detail.memory.revision.toLocaleString(locale),+ })}</p><p className="first-use-scope">- 适用范围:+ {t("guideScope")}{detail.memory.scopes.includes("all-apps")- ? "已设为跨应用可用,不等于个人偏好"+ ? t("guideAllApps"): detail.memory.scopes.includes("private")- ? "已停止外部记忆召回;手动带出需另行确认"- : "限定范围,未扩大外部召回范围"}+ ? t("guidePrivate")+ : t("guideLimited")}</p><details className="first-use-evidence" open>- <summary>原始依据 · {detail.evidence.length} 段</summary>+ <summary>+ {tn("guideEvidence", detail.evidence.length)}+ </summary>{detail.evidence.map((item) => (<article key={item.evidence_id}><header><span>- {item.source_id ? nameOf(item.source_id) : "未知来源"}+ {item.source_id+ ? nameOf(item.source_id)+ : t("guideUnknownSource")}</span><span>{item.written_by === "person"- ? "你"+ ? t("guideYou"): item.written_by === "agent"? "Agent"- : "作者未识别"}{" "}+ : t("guideUnknownAuthor")}{" "}·{" "}{item.created_at- ? new Date(item.created_at).toLocaleString()- : "时间未知"}+ ? new Date(item.created_at).toLocaleString(locale)+ : t("guideUnknownTime")}</span></header><p>{item.verbatim}</p>@@ -438,18 +465,16 @@ export function FirstUseGuide({</details></>) : (- <p className="first-use-unavailable">- 原文或当前授权不可用。换一条背景或刷新后再试,不会带出这条内容。- </p>+ <p className="first-use-unavailable">{t("guideUnavailable")}</p>)}</section><sectionclassName="first-use-destination"aria-labelledby="guide-draft-title">- <h2 id="guide-draft-title">下一段对话的开场白</h2>+ <h2 id="guide-draft-title">{t("guideDraftTitle")}</h2><label className="first-use-field">- 在哪个应用试用+ {t("guideChooseApp")}<selectvalue={host?.hostId ?? ""}onChange={(event) => {@@ -458,7 +483,7 @@ export function FirstUseGuide({setRoute("context");}}>- <option value="">自行选择应用 · 仅复制</option>+ <option value="">{t("guideCopyOnly")}</option>{destinations.map((item) => (<option key={item.hostId} value={item.hostId}>{item.label}@@ -468,14 +493,14 @@ export function FirstUseGuide({</label><p className="first-use-connection">{hostsError- ? "暂时无法读取连接状态,可重试或仅复制背景。"+ ? t("guideHostsError"): !host- ? "尚未选择已连接的应用。手动带入不等于安装连接。"+ ? t("guideNoApp"): canQuery- ? "上次自检可达,本次是否用对仍需核对。"+ ? t("guideWired"): host.installed- ? "已安装连接,尚未验证读取。"- : "尚未安装读取连接。"}+ ? t("guideInstalled")+ : t("guideNotInstalled")}</p><buttontype="button"@@ -483,10 +508,10 @@ export function FirstUseGuide({onClick={onSources}><Link2 size={15} aria-hidden="true" />- 管理应用连接+ {t("guideManage")}</button><fieldset className="first-use-routes">- <legend className="sr-only">选择带入方式</legend>+ <legend className="sr-only">{t("guideChooseRoute")}</legend><label><inputtype="radio"@@ -497,7 +522,7 @@ export function FirstUseGuide({setRoute("context");}}/>- 带入背景+ {t("guideContext")}</label><label><input@@ -510,12 +535,12 @@ export function FirstUseGuide({setRoute("query");}}/>- 让应用查询+ {t("guideQuery")}</label></fieldset>{effectiveRoute === "query" && (<label className="first-use-field">- 要接续的主题+ {t("guideTopic")}<inputvalue={topic}maxLength={160}@@ -528,17 +553,17 @@ export function FirstUseGuide({)}<p className="first-use-meta">{effectiveRoute === "query"- ? "只带查询,不把上方的预期答案塞进新会话。"+ ? t("guideQueryHint"): scene === "new"- ? "仅带你选择的这一条,不自动生成个人画像。"- : "完整带入这一条背景与引用;这不是自动召回测试。"}+ ? t("guideNewHint")+ : t("guideContextHint")}</p><textareaclassName="first-use-draft"- aria-label="开场白完整预览"+ aria-label={t("guidePreview")}readOnlyvalue={draft}- placeholder="原始依据可用后显示开场白"+ placeholder={t("guidePreviewPlaceholder")}spellCheck={false}/><div className="first-use-actions">@@ -548,7 +573,7 @@ export function FirstUseGuide({onClick={() => void carry(false)}><Copy size={16} aria-hidden="true" />- {busy ? "正在核对…" : "复制开场白"}+ {busy ? t("guideChecking") : t("guideCopy")}</button>{host?.handoff === "open" && (<button@@ -558,18 +583,18 @@ export function FirstUseGuide({onClick={() => void carry(true)}><ExternalLink size={16} aria-hidden="true" />- 复制并打开 {host.label}+ {t("guideCopyOpen", { host: host.label })}</button>)}</div>{notice && (<p className="first-use-notice" role="status">- {notice}+ {t(notice, { host: noticeHost })}</p>)}{copiedKey === contextKey && (<section className="first-use-result">- <p>尚无本次外部调用回执。新对话是否引用了正确的背景?</p>+ <p>{t("guideNoReceipt")}</p><div><buttontype="button"@@ -577,21 +602,21 @@ export function FirstUseGuide({onClick={() => setReported("ok")}><Check size={15} />- 我已核对结果+ {t("guideVerified")}</button><buttontype="button"className="quiet"onClick={() => setReported("missing")}>- 没有找回来+ {t("guideMissing")}</button></div>{reported && (<p role="status">{reported === "ok"- ? "你的反馈:已核对。这不是系统自动验收记录。"- : "你的反馈:没有找回来。先检查来源是否导入、记忆范围与应用连接。"}+ ? t("guideFeedbackOk")+ : t("guideFeedbackMissing")}</p>)}</section>@@ -610,18 +635,19 @@ export function FirstUseInvitation({onOpen(): void;onDismiss(): void;}) {+ const { t } = useGuiLanguage();return (- <aside className="first-use-invitation" aria-label="上手体验邀请">- <span>用一条自己的记忆,试着接续下一次对话。</span>+ <aside className="first-use-invitation" aria-label={t("guideInvitation")}>+ <span>{t("guideInvitationHint")}</span><button type="button" className="quiet" onClick={onOpen}>- 试一次+ {t("guideTryOnce")}<ArrowRight size={15} aria-hidden="true" /></button><buttontype="button"className="quiet"- title="稍后再看"- aria-label="关闭上手邀请"+ title={t("guideLater")}+ aria-label={t("guideDismiss")}onClick={onDismiss}><X size={15} />diff --git a/memhub/apps/web/src/GraphWidthPrompt.test.tsx b/memhub/apps/web/src/GraphWidthPrompt.test.tsxindex be116cd..fb55ae0 100644--- a/memhub/apps/web/src/GraphWidthPrompt.test.tsx+++ b/memhub/apps/web/src/GraphWidthPrompt.test.tsx@@ -13,6 +13,20 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { GraphWidthPrompt } from "./GraphWidthPrompt";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";++function LanguageSwitch() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ Cambiar idioma+ </button>+ );+}const { getGraphWidth, decideGraphWidth } = vi.hoisted(() => ({getGraphWidth: vi.fn(),@@ -47,6 +61,44 @@ describe("GraphWidthPrompt", () => {});});+ it("translates the mismatch and live switch without requesting or confirming twice", async () => {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const user = userEvent.setup();+ render(+ <LanguageProvider>+ <LanguageSwitch />+ <GraphWidthPrompt />+ </LanguageProvider>,+ );+ await screen.findByRole("dialog", {+ name: "La biblioteca y el modelo integrado no coinciden",+ });+ const keep = screen.getByRole("radio", {+ name: /Conservar la biblioteca actual/,+ }) as HTMLInputElement;+ expect(keep.checked).toBe(true);+ await user.click(+ screen.getByRole("radio", { name: /Usar el modelo integrado/ }),+ );+ expect(decideGraphWidth).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Cambiar idioma" }));+ await screen.findByRole("dialog", { name: "现有记忆库和内置模型对不上" });+ expect(+ (screen.getByRole("radio", { name: /改用内置模型/ }) as HTMLInputElement)+ .checked,+ ).toBe(true);+ expect(getGraphWidth).toHaveBeenCalledOnce();+ expect(decideGraphWidth).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "就这么办" }));+ await waitFor(() =>+ expect(decideGraphWidth).toHaveBeenCalledExactlyOnceWith(+ "rebuild_with_new",+ expect.any(String),+ ),+ );+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+ });+it("moves focus into the modal and keeps Tab inside it", async () => {const user = userEvent.setup();render(diff --git a/memhub/apps/web/src/GraphWidthPrompt.tsx b/memhub/apps/web/src/GraphWidthPrompt.tsxindex 7b4efe9..b0c33e1 100644--- a/memhub/apps/web/src/GraphWidthPrompt.tsx+++ b/memhub/apps/web/src/GraphWidthPrompt.tsx@@ -4,6 +4,7 @@ import type {} from "@one-memory/contracts";import { useEffect, useRef, useState } from "react";import { decideGraphWidth, getGraphWidth } from "./api";+import { useGuiLanguage } from "./gui-language";import { traceUiAction } from "./ui-trace";import { isDefiniteRefusal, writeTraceStatus } from "./write-outcome";@@ -20,6 +21,7 @@ export function GraphWidthPrompt({}: {onResolved?(): void;}) {+ const { t, locale } = useGuiLanguage();const [status, setStatus] = useState<GraphWidthStatus | null>(null);const [decision, setDecision] = useState<GraphWidthDecision>("keep_existing");const [busy, setBusy] = useState(false);@@ -88,7 +90,7 @@ export function GraphWidthPrompt({? reason instanceof Error? reason.message: String(reason)- : "宽度选择尚未确认,现有记忆库未被改动。请重试。",+ : "graphWidthUnknown",);} finally {setBusy(false);@@ -98,15 +100,19 @@ export function GraphWidthPrompt({const choices: { value: GraphWidthDecision; label: string }[] = [{value: "keep_existing",- label: `保留现有记忆库(默认):继续用原来的 embedding 配置,${status.memory_count} 条记忆和关系图都不动`,+ label: t("graphWidthKeep", {+ count: status.memory_count.toLocaleString(locale),+ }),},{value: "rebuild_with_new",- label: `改用内置模型:现有关系图会被归档(不删除),${status.memory_count} 条记忆的关系需要重新建一遍`,+ label: t("graphWidthRebuild", {+ count: status.memory_count.toLocaleString(locale),+ }),},{value: "export_first",- label: "先导出再决定:现在什么都不动,导出之后再回来选",+ label: t("graphWidthExport"),},];@@ -115,7 +121,7 @@ export function GraphWidthPrompt({className="graph-width-prompt"role="dialog"aria-modal="true"- aria-label="现有记忆库和内置模型对不上"+ aria-label={t("graphWidthTitle")}ref={panel}onKeyDown={(event) => {if (event.key !== "Tab" || !panel.current) return;@@ -136,9 +142,12 @@ export function GraphWidthPrompt({}}}>- <h2>现有记忆库和内置模型对不上</h2>+ <h2>{t("graphWidthTitle")}</h2><p>- {`你现在的记忆库按 ${stored_width} 维建的,内置模型出的是 ${expected_width} 维。两者接不上,不选一个的话抽取会一直失败。`}+ {t("graphWidthDescription", {+ stored: stored_width.toLocaleString(locale),+ expected: expected_width.toLocaleString(locale),+ })}</p><ul>{choices.map((choice) => (@@ -159,12 +168,16 @@ export function GraphWidthPrompt({</ul>{exportedPath ? (<p className="notice">- 已导出到 <code>{exportedPath}</code>。原库没有动,现在可以再选一次。+ {t("graphWidthExported", { path: exportedPath })}+ </p>+ ) : null}+ {error ? (+ <p className="notice">+ {error === "graphWidthUnknown" ? t("graphWidthUnknown") : error}</p>) : null}- {error ? <p className="notice">{error}</p> : null}<button type="button" disabled={busy} onClick={() => void confirm()}>- 就这么办+ {t("graphWidthConfirm")}</button></div>);diff --git a/memhub/apps/web/src/HandoffBar.test.tsx b/memhub/apps/web/src/HandoffBar.test.tsxindex 8058341..ff8108f 100644--- a/memhub/apps/web/src/HandoffBar.test.tsx+++ b/memhub/apps/web/src/HandoffBar.test.tsx@@ -3,6 +3,7 @@ import type { GovernedMemory } from "@one-memory/contracts";import { cleanup, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { HandoffBar, promptFrom } from "./HandoffBar";function memory(@@ -67,6 +68,27 @@ afterEach(() => {delete window.oneMemory;});+it("traduce la vista previa sin modificar el prompt contractual chino", async () => {+ delete window.oneMemory;+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const memories = [memory("a", { content: "Contenido 中文 opaco" })];+ render(+ <LanguageProvider>+ <HandoffBar memories={memories} matterLabel="Tema 中文" />+ </LanguageProvider>,+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Llevar las memorias seleccionadas" }),+ );+ expect(+ screen.getByRole("heading", { name: "Llevar a otras aplicaciones" }),+ ).toBeTruthy();+ expect((screen.getByRole("textbox") as HTMLTextAreaElement).value).toBe(+ promptFrom(memories, "Tema 中文"),+ );+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});+describe("handoff preview", () => {it("does not open a host after the preview was closed while copying", async () => {let copied: () => void = () => undefined;diff --git a/memhub/apps/web/src/HandoffBar.tsx b/memhub/apps/web/src/HandoffBar.tsxindex f6be45c..6d39a15 100644--- a/memhub/apps/web/src/HandoffBar.tsx+++ b/memhub/apps/web/src/HandoffBar.tsx@@ -2,6 +2,7 @@ import { Copy, ExternalLink, X } from "lucide-react";import { useCallback, useEffect, useId, useRef, useState } from "react";import { copyText } from "./copy-text";import type { RecallHostStatus } from "./global";+import { useGuiLanguage } from "./gui-language";import { useRecallHosts } from "./host-state";const NO_HOSTS: RecallHostStatus[] = [];@@ -23,6 +24,7 @@ export function HandoffBar({answerText?: string;suspended?: boolean;}) {+ const { t } = useGuiLanguage();const hosts = (useRecallHosts({ read: true }).data ?? NO_HOSTS).filter((host) => host.present,);@@ -36,14 +38,14 @@ export function HandoffBar({const prompt = promptFrom(usable, matterLabel, answerText);if (!usable.length) return null;return (- <section className="wb-handoff" aria-label="带出记忆">+ <section className="wb-handoff" aria-label={t("handoff.region")}><buttontype="button"className="quiet"onClick={() => setOpenedFor(prompt)}><ExternalLink size={15} aria-hidden="true" />- {answerText ? "带出回答与引用" : "带出所选记忆"}+ {answerText ? t("handoff.answer") : t("handoff.selected")}</button>{openedFor === prompt && (<HandoffDialog@@ -72,6 +74,7 @@ function HandoffDialog({onClose(): void;suspended?: boolean;}) {+ const { locale, t, tn } = useGuiLanguage();const titleId = useId();const panel = useRef<HTMLElement>(null);const [hostId, setHostId] = useState("");@@ -105,7 +108,7 @@ function HandoffDialog({try {await copyText(prompt);} catch {- setNote("复制失败,未打开任何应用。可在预览中选中文本复制。");+ setNote(t("handoff.copyFailed"));setBusy(false);return;}@@ -115,15 +118,17 @@ function HandoffDialog({const result = await window.oneMemory.openHandoff(host.hostId, prompt);setNote(result.opened- ? `已复制并请求打开 ${host.label}。尚未发送;请核对目标输入框。`- : `已完整复制。${host.label} 未能预填,请在目标应用粘贴;尚未发送。`,+ ? t("handoff.opened", { host: host.label })+ : t("handoff.notPrefilled", { host: host.label }),);} catch {- setNote(`内容已完整复制,但未能打开 ${host.label}。尚未发送。`);+ setNote(t("handoff.openFailed", { host: host.label }));}} else {setNote(- `已完整复制${host ? `,可粘贴到 ${host.label}` : ""}。尚未发送。`,+ t("handoff.copied", {+ target: host ? t("handoff.pasteTarget", { host: host.label }) : "",+ }),);}setBusy(false);@@ -154,28 +159,30 @@ function HandoffDialog({}}><header className="handoff-heading">- <h2 id={titleId}>带到其他应用</h2>+ <h2 id={titleId}>{t("handoff.title")}</h2><buttontype="button"className="quiet"- title="关闭预览"- aria-label="关闭带出预览"+ title={t("handoff.closeTitle")}+ aria-label={t("handoff.close")}onClick={onClose}><X size={18} /></button></header><p>- {count} 条记忆 · {prompt.length.toLocaleString()} 字符 · 未省略+ {tn("handoff.stats", count, {+ characters: new Intl.NumberFormat(locale).format(prompt.length),+ })}</p><textarea- aria-label="将带出的完整内容"+ aria-label={t("handoff.content")}readOnlyvalue={prompt}spellCheck={false}/><label className="handoff-target">- 目标应用+ {t("handoff.target")}<selectvalue={hostId}onChange={(event) => {@@ -183,18 +190,16 @@ function HandoffDialog({setNote("");}}>- <option value="">其他应用 · 仅复制</option>+ <option value="">{t("handoff.other")}</option>{hosts.map((item) => (<option key={item.hostId} value={item.hostId}>{item.label}- {item.handoff !== "open" ? " · 仅复制" : ""}+ {item.handoff !== "open" ? t("handoff.copyOnly") : ""}</option>))}</select></label>- <p>- 仅带出上方内容,不包含原始对话。复制不是授权连接,已带出的副本无法从其他应用撤回。- </p>+ <p>{t("handoff.boundary")}</p><div className="consent-actions"><buttontype="button"@@ -203,7 +208,7 @@ function HandoffDialog({onClick={() => void send(false)}><Copy size={15} aria-hidden="true" />- 复制内容+ {t("handoff.copy")}</button>{host?.handoff === "open" && (<button@@ -212,7 +217,7 @@ function HandoffDialog({onClick={() => void send(true)}><ExternalLink size={15} aria-hidden="true" />- 复制并打开 {host.label}+ {t("handoff.open", { host: host.label })}</button>)}</div>diff --git a/memhub/apps/web/src/HealthPanel.test.tsx b/memhub/apps/web/src/HealthPanel.test.tsxindex 311b469..e406702 100644--- a/memhub/apps/web/src/HealthPanel.test.tsx+++ b/memhub/apps/web/src/HealthPanel.test.tsx@@ -12,6 +12,11 @@ import {import { StrictMode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";import { HealthPanel } from "./HealthPanel";import type { ImportSourcesController } from "./use-import-sources";@@ -25,6 +30,37 @@ vi.mock("./api", () => ({setDetailedLogging: (enabled: boolean) => setDetailedLogging(enabled),}));+function HealthLanguageSwitch() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ Cambiar idioma+ </button>+ );+}++it("shows supported diagnostics in Spanish without toggling logging", async () => {+ window.oneMemory = undefined;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <HealthLanguageSwitch />+ <HealthPanel imports={imports()} />+ </LanguageProvider>,+ );+ await screen.findByRole("heading", { name: "Diagnóstico" });+ expect(+ screen.getByRole("button", { name: "Volver a leer el estado" }),+ ).toBeTruthy();+ expect(screen.getByRole("heading", { name: "Servicio local" })).toBeTruthy();+ const reads = getMemoryProcessing.mock.calls.length;+ fireEvent.click(screen.getByText("Cambiar idioma"));+ await screen.findByRole("heading", { name: "运行诊断" });+ expect(getMemoryProcessing).toHaveBeenCalledTimes(reads);+ expect(setDetailedLogging).not.toHaveBeenCalled();+ localStorage.clear();+});+function source(sourceId: string,overrides: Partial<SourceResponse> = {},@@ -151,7 +187,9 @@ describe("HealthPanel", () => {render(<HealthPanel imports={imports()} />);const details = await screen.findByLabelText("导入与整理详情");- expect(details.textContent).toContain("100000 条原文 · 50000 个完整 turn");+ expect(details.textContent).toContain(+ "100,000 条原文 · 50,000 个完整 turn",+ );expect(details.textContent).toContain("120 次调用 · 100 完成 · 1 结果不确定 · 2 失败 · 3 取消",);@@ -641,6 +679,32 @@ describe("HealthPanel", () => {expect(block.textContent).toContain("暂无需要处理的问题");});+ it("read receipt timestamps follow the Spanish interface language", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ try {+ render(+ <LanguageProvider>+ <HealthPanel imports={imports()} />+ </LanguageProvider>,+ );+ await settle();+ getMemoryProcessing.mockRejectedValue(new Error("offline"));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5_000);+ });+ const stamps = Array.from(+ document.querySelectorAll(".health-stamp time"),+ );+ expect(stamps.length).toBeGreaterThan(0);+ for (const stamp of stamps) {+ expect(stamp.textContent).toMatch(/^Hoy /);+ expect(stamp.textContent).not.toContain("今天");+ }+ } finally {+ localStorage.clear();+ }+ });+it("sourceSnapshot 过期不继续报服务运行中或来源空", async () => {render(<HealthPaneldiff --git a/memhub/apps/web/src/HealthPanel.tsx b/memhub/apps/web/src/HealthPanel.tsxindex 63a5689..15d270c 100644--- a/memhub/apps/web/src/HealthPanel.tsx+++ b/memhub/apps/web/src/HealthPanel.tsx@@ -1,6 +1,6 @@+import { type GuiLocale, translate } from "@one-memory/i18n";import { Download, Flag, RefreshCw } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";-import {getDetailedLogging,getMemoryProcessing,@@ -13,16 +13,16 @@ import {import { clockStamp } from "./clock-stamp";import { exportDiagnosticsFile } from "./diagnostics-export";import type { RecallHostStatus } from "./global";+import { useGuiLanguage } from "./gui-language";import { refreshRecallHosts } from "./host-state";+import { memoryText } from "./memory-language";import {blockReasonLabel,- retryingBlockLabel,splitBlockedStages,taskKindLabel,} from "./memory-processing-labels";import { subscribePoll } from "./poll-scheduler";import { R6Button, R6Switch } from "./R6Controls";-import { LINK_WORDING } from "./recall-host-wording";import type { useImportSources } from "./use-import-sources";type ImportState = ReturnType<typeof useImportSources>;@@ -98,10 +98,11 @@ async function readHosts() {}function ReadTime({ label, value }: { label: string; value: string }) {+ const { locale } = useGuiLanguage();return (<p className="health-stamp">{label}- <time dateTime={value}>{clockStamp(value)}</time>+ <time dateTime={value}>{clockStamp(value, locale)}</time></p>);}@@ -111,23 +112,26 @@ function ReadReceipt({confirmedAt,failedAt,}: Pick<Reading<unknown>, "pending" | "confirmedAt" | "failedAt">) {+ const { t } = useGuiLanguage();return (<>{failedAt ? (<p role="status">- 暂时无法读取- {confirmedAt ? " · 数据已过期,以下为上次读取结果。" : "。"}+ {t("healthReadFailed")}+ {confirmedAt ? t("healthStale") : "。"}</p>) : null}{pending ? (<p role="status">- {confirmedAt ? "正在重新读取,以下为上次读取结果…" : "正在读取状态…"}+ {confirmedAt ? t("healthRereading") : t("healthReading")}</p>) : null}{confirmedAt ? (- <ReadTime label="上次成功读取" value={confirmedAt} />+ <ReadTime label={t("healthReadSuccessTime")} value={confirmedAt} />+ ) : null}+ {failedAt ? (+ <ReadTime label={t("healthReadFailedTime")} value={failedAt} />) : null}- {failedAt ? <ReadTime label="读取失败时间" value={failedAt} /> : null}</>);}@@ -143,6 +147,8 @@ function ReadReceipt({* the table the originating screen already uses.*/export function HealthPanel({ imports }: { imports: ImportState }) {+ const { t, tn, tnPlain, locale } = useGuiLanguage();+ const n = (value: number) => value.toLocaleString(locale);const [detailedLogging, setDetailedLoggingState] = useState(false);const [detailedLoggingPending, setDetailedLoggingPending] = useState(false);const backgroundRead = useDiagnosticRead(readBackgroundHealth);@@ -199,13 +205,13 @@ export function HealthPanel({ imports }: { imports: ImportState }) {async function markIncident() {if (!window.oneMemory?.markDiagnosticIncident) {- setDiagnosticMessage("请在桌面 App 中记录问题时间点。");+ setDiagnosticMessage(t("healthIncidentDesktop"));return;}setDiagnosticAction("incident");setDiagnosticMessage("");try {- const description = window.prompt("简单描述刚才遇到的问题(可不填)", "");+ const description = window.prompt(t("healthIncidentPrompt"), "");if (description === null) {setDiagnosticAction(null);return;@@ -213,9 +219,11 @@ export function HealthPanel({ imports }: { imports: ImportState }) {const receipt =await window.oneMemory.markDiagnosticIncident(description);await window.oneMemory.copyText?.(receipt.incident_id);- setDiagnosticMessage(`问题编号已复制:${receipt.incident_id}`);+ setDiagnosticMessage(+ t("healthIncidentCopied", { id: receipt.incident_id }),+ );} catch {- setDiagnosticMessage("问题时间点未能记录,请重试。");+ setDiagnosticMessage(t("healthIncidentError"));} finally {setDiagnosticAction(null);}@@ -223,13 +231,13 @@ export function HealthPanel({ imports }: { imports: ImportState }) {async function exportDiagnostics() {if (!window.oneMemory?.exportDiagnostics) {- setDiagnosticMessage("请在桌面 App 中导出诊断信息。");+ setDiagnosticMessage(t("diagnosticExportDesktop"));return;}setDiagnosticAction("export");setDiagnosticMessage("");try {- const result = await exportDiagnosticsFile();+ const result = await exportDiagnosticsFile(locale);setDiagnosticMessage(result.message);} finally {setDiagnosticAction(null);@@ -244,20 +252,23 @@ export function HealthPanel({ imports }: { imports: ImportState }) {const sourceReceipt = (<>{imports.loading ? (- <p role="status">正在读取本地服务与来源状态…</p>+ <p role="status">{t("healthReadingSources")}</p>) : sourceUnavailable ? (<p role="status">- 暂时无法读取+ {t("healthReadFailed")}{sourceConfirmedAt || imports.health || imports.sources.length- ? " · 数据已过期,以下为上次读取结果。"+ ? t("healthStale"): "。"}</p>) : null}{sourceConfirmedAt ? (- <ReadTime label="上次成功读取" value={sourceConfirmedAt} />+ <ReadTime+ label={t("healthReadSuccessTime")}+ value={sourceConfirmedAt}+ />) : null}{sourceUnavailable && sourceFailedAt ? (- <ReadTime label="读取失败时间" value={sourceFailedAt} />+ <ReadTime label={t("healthReadFailedTime")} value={sourceFailedAt} />) : null}</>);@@ -274,7 +285,7 @@ export function HealthPanel({ imports }: { imports: ImportState }) {<section className="view health-view" aria-labelledby="health-title"><header className="view-header"><div>- <h1 id="health-title">运行诊断</h1>+ <h1 id="health-title">{t("healthTitle")}</h1></div></header>@@ -285,26 +296,34 @@ export function HealthPanel({ imports }: { imports: ImportState }) {onClick={() => void exportDiagnostics()}><Download size={16} aria-hidden="true" />- 导出日志(发给开发排查)+ {t("nativeExportLogs")}</R6Button></div>- <section className="health-block" aria-label="本地服务">- <h2>本地服务</h2>+ <section className="health-block" aria-label={t("healthLocal")}>+ <h2>{t("healthLocal")}</h2>{sourceReceipt}{imports.health ? (<p>- {`${sourceUnavailable || imports.loading ? "上次读取" : "运行中"} · 版本 ${imports.health.version} · 实例 ${imports.health.instance_id}`}+ {t("healthCoreVersion", {+ state: t(+ sourceUnavailable || imports.loading+ ? "healthPrevious"+ : "healthRunning",+ ),+ version: imports.health.version,+ instance: imports.health.instance_id,+ })}</p>) : !sourceUnavailable && !imports.loading ? (- <p>还没连上本地 Core。</p>+ <p>{t("healthCoreDisconnected")}</p>) : null}</section>- <section className="health-block" aria-label="后台服务">- <h2>后台服务</h2>+ <section className="health-block" aria-label={t("healthBackground")}>+ <h2>{t("healthBackground")}</h2>{backgroundRead.value === "no-bridge" ? (- <p>当前环境无法检查后台服务,请在支持此功能的桌面 App 中查看。</p>+ <p>{t("healthBackgroundUnavailable")}</p>) : (<><ReadReceipt {...backgroundRead} />@@ -312,13 +331,18 @@ export function HealthPanel({ imports }: { imports: ImportState }) {<><p>{backgroundRead.pending || backgroundRead.failedAt- ? "上次读取:"+ ? t("healthPreviousPrefix"): ""}- {backgroundVerdict(backgroundRead.value.state)}+ {backgroundVerdict(backgroundRead.value.state, locale)}</p><p>- Core:{runtimeStateLabel(backgroundRead.value.core)} ·- 宿主桥接:{runtimeStateLabel(backgroundRead.value.broker)}+ {t("healthRuntime", {+ core: runtimeStateLabel(backgroundRead.value.core, locale),+ broker: runtimeStateLabel(+ backgroundRead.value.broker,+ locale,+ ),+ })}</p></>) : null}@@ -326,8 +350,8 @@ export function HealthPanel({ imports }: { imports: ImportState }) {)}</section>- <section className="health-block" aria-label="各来源累计条数">- <h2>各来源累计条数</h2>+ <section className="health-block" aria-label={t("healthSources")}>+ <h2>{t("healthSources")}</h2>{sourceReceipt}{imports.sources.length ? (<dl>@@ -335,41 +359,70 @@ export function HealthPanel({ imports }: { imports: ImportState }) {<div key={source.source_id}><dt>{source.display_name}</dt><dd>- {`${source.imported_conversations} 个会话 · ${source.imported_messages} 条消息`}+ {t("healthSourceCount", {+ conversations: n(source.imported_conversations),+ messages: n(source.imported_messages),+ })}</dd></div>))}</dl>) : !sourceUnavailable && !imports.loading ? (- <p>还没有已连接的来源。</p>+ <p>{t("healthNoSources")}</p>) : null}</section>- <section className="health-block" aria-label="记忆提炼">- <h2>记忆提炼</h2>+ <section className="health-block" aria-label={t("healthProcessing")}>+ <h2>{t("healthProcessing")}</h2><ReadReceipt {...processingRead} />{processing ? (<><p>- {`${processing.running} 处理中 · ${processing.pending} 排队 · ${processing.completed} 已完成 · ${processing.failed} 失败`}+ {t("healthTaskCounts", {+ running: n(processing.running),+ pending: n(processing.pending),+ completed: n(processing.completed),+ failed: n(processing.failed),+ })}</p>{processing.metrics ? (- <dl aria-label="导入与整理详情">+ <dl aria-label={t("healthImportDetails")}><div>- <dt>原文与完整对话轮次</dt>- <dd>{`${processing.metrics.raw_evidence} 条原文 · ${processing.metrics.complete_turns} 个完整 turn`}</dd>+ <dt>{t("healthRawTurns")}</dt>+ <dd>+ {t("healthRawCounts", {+ raw: n(processing.metrics.raw_evidence),+ turns: n(processing.metrics.complete_turns),+ })}+ </dd></div><div>- <dt>HY 整理</dt>- <dd>{`${processing.metrics.hy_calls} 次调用 · ${processing.metrics.completed} 完成 · ${processing.metrics.unknown} 结果不确定 · ${processing.metrics.failed} 失败 · ${processing.metrics.cancelled} 取消`}</dd>+ <dt>{t("healthHy")}</dt>+ <dd>+ {t("healthHyCounts", {+ calls: n(processing.metrics.hy_calls),+ completed: n(processing.metrics.completed),+ unknown: n(processing.metrics.unknown),+ failed: n(processing.metrics.failed),+ cancelled: n(processing.metrics.cancelled),+ })}+ </dd></div><div>- <dt>产出</dt>- <dd>{`${processing.metrics.governed_memories} 条记忆`}</dd>+ <dt>{t("healthOutput")}</dt>+ <dd>+ {tn("healthMemories", processing.metrics.governed_memories)}+ </dd></div><div>- <dt>WorkBuddy 查记忆</dt>- <dd>{`${processing.metrics.workbuddy.injected} 次注入 · ${processing.metrics.workbuddy.timed_out} 次超时 · ${processing.metrics.workbuddy.unavailable} 次不可用`}</dd>+ <dt>{t("healthWorkbuddy")}</dt>+ <dd>+ {t("healthWorkbuddyCounts", {+ injected: n(processing.metrics.workbuddy.injected),+ timedOut: n(processing.metrics.workbuddy.timed_out),+ unavailable: n(processing.metrics.workbuddy.unavailable),+ })}+ </dd></div></dl>) : null}@@ -378,26 +431,35 @@ export function HealthPanel({ imports }: { imports: ImportState }) {{splitBlockedStages(processing.blocked_stages).named.map((block) => (<li key={`${block.kind}:${block.reason}`}>- {`${taskKindLabel(block.kind)}卡在 ${blockReasonLabel(block.reason)}(${block.count} 条)`}+ {t("healthBlocked", {+ kind: memoryText(locale, taskKindLabel(block.kind)),+ reason: memoryText(+ locale,+ blockReasonLabel(block.reason),+ ),+ count: n(block.count),+ })}</li>),)}- {retrying ? <li>{retryingBlockLabel(retrying)}</li> : null}+ {retrying ? (+ <li>{tnPlain("healthRetrying", retrying)}</li>+ ) : null}</ul>) : !processingRead.failedAt && !processingRead.pending ? (- <p>暂无需要处理的问题。</p>+ <p>{t("healthNoIssues")}</p>) : null}</>) : null}</section>- <section className="health-block" aria-label="AI 接通情况">- <h2>AI 接通情况</h2>+ <section className="health-block" aria-label={t("healthHosts")}>+ <h2>{t("healthHosts")}</h2>{/* Host state lives in the desktop shell. In a browser it is notfalse, it is unavailable, and reporting it as 未接通 would sendthe user to repair links that may well be fine. */}{hosts === "no-bridge" || !window.oneMemory ? (- <p>在浏览器里读不到;请在桌面 App 里查看。</p>+ <p>{t("healthHostsUnavailable")}</p>) : (<><ReadReceipt {...hostsRead} />@@ -408,34 +470,34 @@ export function HealthPanel({ imports }: { imports: ImportState }) {<dt>{host.label}</dt><dd>{hostsRead.failedAt || hostsRead.pending- ? "上次读取:"+ ? t("healthPreviousPrefix"): ""}- {hostVerdict(host)}+ {hostVerdict(host, locale)}</dd></div>))}</dl>) : hosts && !hostsRead.failedAt && !hostsRead.pending ? (- <p>本机没有检测到可接入的 AI 工具。</p>+ <p>{t("healthNoHosts")}</p>) : null}</>)}</section>- <section className="health-block" aria-label="详细日志">+ <section className="health-block" aria-label={t("healthDetailed")}><div className="health-setting-row"><div>- <h2>详细日志(排查用)</h2>- <p>默认关闭。仅在开发人员请你协助排查时开启。</p>+ <h2>{t("healthDetailedTitle")}</h2>+ <p>{t("healthDetailedHint")}</p></div><R6Switch- label="详细日志(排查用)"+ label={t("healthDetailedTitle")}checked={detailedLogging}pending={detailedLoggingPending}onCheckedChange={(enabled) => {setDetailedLoggingPending(true);void setDetailedLogging(enabled).then(setDetailedLoggingState)- .catch(() => setDiagnosticMessage("详细日志设置失败,请重试。"))+ .catch(() => setDiagnosticMessage(t("healthDetailedError"))).finally(() => setDetailedLoggingPending(false));}}/>@@ -448,7 +510,7 @@ export function HealthPanel({ imports }: { imports: ImportState }) {onClick={() => void refresh()}><RefreshCw size={16} aria-hidden="true" />- 重新读取状态+ {t("healthRefresh")}</R6Button><R6Buttonvariant="quiet"@@ -456,7 +518,7 @@ export function HealthPanel({ imports }: { imports: ImportState }) {onClick={() => void markIncident()}><Flag size={16} aria-hidden="true" />- 记录问题时间点+ {t("healthIncident")}</R6Button></div>{diagnosticMessage ? (@@ -470,31 +532,52 @@ export function HealthPanel({ imports }: { imports: ImportState }) {/** A host with no self-check on record has not been shown to work, and the* install flow's own wording for that is 未接通. */-function hostVerdict(host: RecallHostStatus): string {- if (!host.installed) return LINK_WORDING.unreachable;- const state = host.selfCheck?.state;- return (state ? LINK_WORDING[state] : undefined) ?? LINK_WORDING.unreachable;+function hostVerdict(host: RecallHostStatus, locale: GuiLocale): string {+ return translate(+ locale,+ !host.installed+ ? "healthUnreachable"+ : host.selfCheck?.state === "wired"+ ? "healthWired"+ : host.selfCheck?.state === "reachable_but_blind"+ ? "healthBlind"+ : "healthUnreachable",+ );}-function backgroundVerdict(state: BackgroundSnapshot["state"]): string {- return {- healthy: "后台服务可用",- stopped: "后台服务已停止",- degraded: "后台服务部分不可用",- untrusted: "后台服务身份未通过核验",- unknown: "后台状态尚未确认",- }[state];+function backgroundVerdict(+ state: BackgroundSnapshot["state"],+ locale: GuiLocale,+): string {+ return translate(+ locale,+ (+ {+ healthy: "healthBackgroundHealthy",+ stopped: "healthBackgroundStopped",+ degraded: "healthBackgroundDegraded",+ untrusted: "healthBackgroundUntrusted",+ unknown: "healthBackgroundUnknown",+ } as const+ )[state],+ );}function runtimeStateLabel(state: BackgroundSnapshot["core"] | BackgroundSnapshot["broker"],+ locale: GuiLocale,): string {- return {- running: "运行中",- stopped: "已停止",- unhealthy: "无法连接",- untrusted: "身份未通过核验",- unknown: "尚未确认",- not_checked: "未检查",- }[state];+ return translate(+ locale,+ (+ {+ running: "healthRunning",+ stopped: "healthStopped",+ unhealthy: "healthUnhealthy",+ untrusted: "healthUntrusted",+ unknown: "healthUnknown",+ not_checked: "healthNotChecked",+ } as const+ )[state],+ );}diff --git a/memhub/apps/web/src/HomeCardBoundary.tsx b/memhub/apps/web/src/HomeCardBoundary.tsxindex 9d30730..2491c86 100644--- a/memhub/apps/web/src/HomeCardBoundary.tsx+++ b/memhub/apps/web/src/HomeCardBoundary.tsx@@ -1,9 +1,14 @@import { Component, type ReactNode } from "react";+import { useApplicationsLanguage } from "./applications-language";-type Props = { label: string; children: ReactNode };+type Props = { label: string; children: ReactNode; fallback?: ReactNode };type State = { crashed: boolean };const RESET_MS = 15_000;+function CardFallback({ label }: { label: string }) {+ const { a } = useApplicationsLanguage();+ return <p>{a("cardUnavailable", { label })}</p>;+}/*** 2026-10-12: 首页任何一张卡片渲染出错时,只塌这一张卡,不塌整页。@@ -36,9 +41,7 @@ export class HomeCardBoundary extends Component<Props, State> {if (this.state.crashed) {return (<section className="r6-home-auto-failure" role="status">- <p>- {this.props.label}暂时显示不了,其他功能不受影响,稍后会自动恢复。- </p>+ {this.props.fallback ?? <CardFallback label={this.props.label} />}</section>);}diff --git a/memhub/apps/web/src/ImportProgressStrip.test.tsx b/memhub/apps/web/src/ImportProgressStrip.test.tsxindex b978951..355282b 100644--- a/memhub/apps/web/src/ImportProgressStrip.test.tsx+++ b/memhub/apps/web/src/ImportProgressStrip.test.tsx@@ -12,6 +12,11 @@ import userEvent from "@testing-library/user-event";import { useState } from "react";import { afterEach, describe, expect, it, vi } from "vitest";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";import { ImportProgressStrip } from "./ImportProgressStrip";function job(overrides: Partial<ImportJob> = {}): ImportJob {@@ -84,6 +89,57 @@ function deferred() {describe("ImportProgressStrip", () => {afterEach(cleanup);+ it("translates user-facing progress and live settings CTA without invoking actions", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const open = vi.fn();+ function Switch() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ Cambiar idioma+ </button>+ );+ }+ const view = render(+ <LanguageProvider>+ <Switch />+ <ImportProgressStrip+ userFacing+ jobs={[job()]}+ sources={[+ source("cursor", "Cursor", { imported_conversations: 12345 }),+ ]}+ backfilling={false}+ onOpenSources={open}+ />+ </LanguageProvider>,+ );+ expect((await screen.findByRole("status")).textContent).toContain(+ "12.345 conversaciones",+ );+ view.rerender(+ <LanguageProvider>+ <Switch />+ <ImportProgressStrip+ userFacing+ jobs={[job({ status: "failed" })]}+ sources={sources}+ backfilling={false}+ onOpenSources={open}+ onConfigureModel={open}+ />+ </LanguageProvider>,+ );+ await screen.findByRole("button", { name: "Ir a configuración" });+ expect(open).not.toHaveBeenCalled();+ await userEvent.click(+ screen.getByRole("button", { name: "Cambiar idioma" }),+ );+ await screen.findByRole("button", { name: "去设置" });+ expect(open).not.toHaveBeenCalled();+ localStorage.clear();+ });+it("keeps daily sync silent in the user-facing shell", () => {const { container } = render(<ImportProgressStripdiff --git a/memhub/apps/web/src/ImportProgressStrip.tsx b/memhub/apps/web/src/ImportProgressStrip.tsxindex 68560c6..4ba9226 100644--- a/memhub/apps/web/src/ImportProgressStrip.tsx+++ b/memhub/apps/web/src/ImportProgressStrip.tsx@@ -5,6 +5,7 @@ import type {} from "@one-memory/contracts";import { LoaderCircle, Pause, Play, RefreshCw, Settings2 } from "lucide-react";import { useEffect, useRef, useState } from "react";+import { useGuiLanguage } from "./gui-language";import {type MemoryArrival,memoryArrivalTitle,@@ -85,6 +86,7 @@ export function ImportProgressStrip({showProgressDetails = true,userFacing = false,}: ImportProgressStripProps) {+ const { t, tn } = useGuiLanguage();const [refreshing, setRefreshing] = useState(false);const [refreshError, setRefreshError] = useState<{epoch: number;@@ -252,10 +254,10 @@ export function ImportProgressStrip({0,);const message = firstImport- ? `正在导入你的历史对话,已导入 ${imported.toLocaleString("zh-CN")} 个会话。记忆会陆续生成,你可以先正常使用。`+ ? tn("importUserProgress", imported): currentArrival?.phase === "model-required"- ? "模型还没有配置好,新的对话暂时不会整理成记忆。"- : "有些内容没有处理完成,请前往设置查看。";+ ? t("importUserModel")+ : t("importUserIncomplete");return (<divclassName="import-strip"@@ -277,7 +279,7 @@ export function ImportProgressStrip({onClick={onConfigureModel}><Settings2 size={15} aria-hidden="true" />- 去设置+ {t("importUserSettings")}</button>)}</div>diff --git a/memhub/apps/web/src/LanguageSelector.test.tsx b/memhub/apps/web/src/LanguageSelector.test.tsxnew file mode 100644index 0000000..7cd62c8--- /dev/null+++ b/memhub/apps/web/src/LanguageSelector.test.tsx@@ -0,0 +1,98 @@+// @vitest-environment jsdom++import { translate } from "@one-memory/i18n";+import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";+import { LanguageSelector } from "./LanguageSelector";++afterEach(() => {+ cleanup();+ localStorage.clear();+ vi.restoreAllMocks();+});++it.each(["zh-CN", "en", "es"] as const)(+ "hides the compact label while preserving its accessible name in %s",+ (locale) => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, locale);+ render(+ <LanguageProvider>+ <LanguageSelector compact />+ </LanguageProvider>,+ );+ const name = translate(locale, "languageTitle");+ const selector = screen.getByRole("combobox", { name });+ const label = screen.getByText(name) as HTMLLabelElement;+ expect(label.hidden).toBe(true);+ expect(label.htmlFor).toBe(selector.id);+ expect(screen.getByRole("region", { name })).toBeTruthy();+ expect(screen.getByRole("option", { name: "Español" })).toBeTruthy();+ expect(screen.getByRole("option", { name: "English" })).toBeTruthy();+ expect(screen.getByRole("option", { name: "简体中文" })).toBeTruthy();+ },+);++it.each(["zh-CN", "en", "es"] as const)(+ "keeps the normal settings label visible and accessible in %s",+ (locale) => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, locale);+ render(+ <LanguageProvider>+ <LanguageSelector />+ </LanguageProvider>,+ );+ const name = translate(locale, "languageLabel");+ const selector = screen.getByRole("combobox", { name });+ const label = screen.getByText(name) as HTMLLabelElement;+ expect(label.hidden).toBe(false);+ expect(label.htmlFor).toBe(selector.id);+ expect(selector.getAttribute("aria-label")).toBeNull();+ expect(+ screen.getByRole("heading", { name: translate(locale, "languageTitle") }),+ ).toBeTruthy();+ expect(+ screen.getByText(translate(locale, "languageDescription")),+ ).toBeTruthy();+ },+);++it("offers an accessible selector, persists and updates its label", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ render(+ <LanguageProvider>+ <LanguageSelector />+ </LanguageProvider>,+ );+ const selector = screen.getByRole("combobox", {+ name: translate("zh-CN", "languageLabel"),+ });+ expect(screen.getAllByRole("option")).toHaveLength(4);+ expect(selector.getAttribute("aria-describedby")).toBeTruthy();+ await userEvent.selectOptions(selector, "es");+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("es");+ expect(+ screen.getByRole("combobox", { name: translate("es", "languageLabel") }),+ ).toBe(selector);+ expect(document.documentElement.lang).toBe("es");+});++it("announces storage errors without replacing the confirmed choice", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ render(+ <LanguageProvider>+ <LanguageSelector />+ </LanguageProvider>,+ );+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new Error("denied");+ });+ await userEvent.selectOptions(screen.getByRole("combobox"), "es");+ expect(screen.getByRole("alert").textContent).toBe(+ translate("zh-CN", "languageSaveError"),+ );+ expect((screen.getByRole("combobox") as HTMLSelectElement).value).toBe(+ "zh-CN",+ );+});diff --git a/memhub/apps/web/src/LanguageSelector.tsx b/memhub/apps/web/src/LanguageSelector.tsxnew file mode 100644index 0000000..7e524ca--- /dev/null+++ b/memhub/apps/web/src/LanguageSelector.tsx@@ -0,0 +1,58 @@+import { isLanguagePreference } from "@one-memory/i18n";+import { useId, useState } from "react";+import { useGuiLanguage } from "./gui-language";++export function LanguageSelector({ compact = false }: { compact?: boolean }) {+ const id = useId();+ const { preference, setPreference, t, error } = useGuiLanguage();+ const [pending, setPending] = useState(false);+ return (+ <section+ aria-labelledby={compact ? `${id}-label` : `${id}-title`}+ className={+ compact ? "r6-language-selector--compact" : "r6-language-setting"+ }+ >+ {!compact && <h2 id={`${id}-title`}>{t("languageTitle")}</h2>}+ <div className={compact ? "r6-language-selector-row" : "r6-setting-row"}>+ <label id={`${id}-label`} htmlFor={`${id}-select`} hidden={compact}>+ {t(compact ? "languageTitle" : "languageLabel")}+ </label>+ <select+ id={`${id}-select`}+ aria-label={compact ? t("languageTitle") : undefined}+ aria-describedby={compact ? undefined : `${id}-description`}+ value={preference}+ disabled={pending}+ onChange={async (event) => {+ const value = event.currentTarget.value;+ if (!isLanguagePreference(value)) return;+ setPending(true);+ try {+ await setPreference(value);+ } finally {+ setPending(false);+ }+ }}+ >+ <option value="system">{t("languageSystem")}</option>+ <option value="zh-CN" lang={compact ? "zh-CN" : undefined}>+ {compact ? "简体中文" : t("languageChinese")}+ </option>+ <option value="en" lang={compact ? "en" : undefined}>+ {compact ? "English" : t("languageEnglish")}+ </option>+ <option value="es" lang={compact ? "es" : undefined}>+ {compact ? "Español" : t("languageSpanish")}+ </option>+ </select>+ </div>+ {!compact && <p id={`${id}-description`}>{t("languageDescription")}</p>}+ {error && (+ <p role="alert" className="r6-settings-error">+ {t(error)}+ </p>+ )}+ </section>+ );+}diff --git a/memhub/apps/web/src/MemoryEvidencePanel.tsx b/memhub/apps/web/src/MemoryEvidencePanel.tsxindex 9a572a9..a9e395c 100644--- a/memhub/apps/web/src/MemoryEvidencePanel.tsx+++ b/memhub/apps/web/src/MemoryEvidencePanel.tsx@@ -5,6 +5,7 @@ import {useRef,useState,} from "react";+import { useMemoryLanguage } from "./memory-language";import { useMediaPreference } from "./use-media-preference";type Phase = "closed" | "opening" | "open" | "closing";@@ -20,6 +21,7 @@ export function MemoryEvidencePanel({children: ReactNode;suspended?: boolean;}) {+ const { text } = useMemoryLanguage();const compact = useMediaPreference("(max-width: 1100px)");const reduceMotion = useMediaPreference("(prefers-reduced-motion: reduce)");const reduceTransparency = useMediaPreference(@@ -135,7 +137,7 @@ export function MemoryEvidencePanel({className="map-inspector"{...(modal ? { role: "dialog", "aria-modal": !suspended } : {})}inert={suspended}- aria-label="记忆与原文"+ aria-label={text("记忆与原文")}data-tour-id="memory-original-pane"tabIndex={-1}hidden={!present || (compact && suspended)}diff --git a/memhub/apps/web/src/MemoryGraph3D.tsx b/memhub/apps/web/src/MemoryGraph3D.tsxindex 7d92779..62344c4 100644--- a/memhub/apps/web/src/MemoryGraph3D.tsx+++ b/memhub/apps/web/src/MemoryGraph3D.tsx@@ -11,6 +11,7 @@ import {subscribeDisplayPreference,} from "./display-preferences";import { graphEase } from "./graph-motion";+import { useMemoryLanguage } from "./memory-language";/** 力导向迭代总步数。原实现在挂载时一次算完,现改为分帧推进。 */const LAYOUT_ITERATIONS = 90;@@ -35,6 +36,7 @@ export function MemoryGraph3D({selectedNodeId: string | null;onSelectNode(node: MemoryGraphNode): void;}) {+ const { text } = useMemoryLanguage();const host = useRef<HTMLDivElement>(null);const labelHost = useRef<HTMLDivElement>(null);const selectRef = useRef(onSelectNode);@@ -626,7 +628,7 @@ export function MemoryGraph3D({<div className="graph-labels" ref={labelHost} aria-hidden="true" />{!available ? (<div className="memory-graph-fallback">- <p>这台设备打不开 3D 视图,已显示关联列表。</p>+ <p>{text("这台设备打不开 3D 视图,已显示关联列表。")}</p>{graph.nodes.map((node) => (<buttontype="button"@@ -644,13 +646,13 @@ export function MemoryGraph3D({<divclassName="memory-graph-controls"role="toolbar"- aria-label="图谱工具"+ aria-label={text("图谱工具")}><buttontype="button"className="secondary"- title="放大"- aria-label="放大图谱"+ title={text("放大")}+ aria-label={text("放大图谱")}onClick={() => actionsRef.current?.zoom(0.8)}><Plus size={16} />@@ -658,8 +660,8 @@ export function MemoryGraph3D({<buttontype="button"className="secondary"- title="缩小"- aria-label="缩小图谱"+ title={text("缩小")}+ aria-label={text("缩小图谱")}onClick={() => actionsRef.current?.zoom(1.25)}><Minus size={16} />@@ -667,8 +669,8 @@ export function MemoryGraph3D({<buttontype="button"className="secondary"- title="重置视角"- aria-label="重置图谱视角"+ title={text("重置视角")}+ aria-label={text("重置图谱视角")}onClick={() => actionsRef.current?.reset()}><Focus size={16} />diff --git a/memhub/apps/web/src/MemoryMap.test.tsx b/memhub/apps/web/src/MemoryMap.test.tsxindex 02099f3..5a0a87d 100644--- a/memhub/apps/web/src/MemoryMap.test.tsx+++ b/memhub/apps/web/src/MemoryMap.test.tsx@@ -18,6 +18,23 @@ import {within,} from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";++it("traduce los controles del mapa en español sin cambiar etiquetas importadas", () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const { container } = render(+ <LanguageProvider>+ <Host simplified />+ </LanguageProvider>,+ );+ expect(screen.getByLabelText("Filtrar memorias del mapa")).toBeTruthy();+ expect(container.textContent).not.toContain("全部记忆");+ expect(container.textContent).not.toContain("当前已加载");+ expect(container.textContent).not.toContain("来源视角");+ expect(container.textContent).not.toContain("段原文");+ localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});+import { useState } from "react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import {diff --git a/memhub/apps/web/src/MemoryMap.tsx b/memhub/apps/web/src/MemoryMap.tsxindex 613df7c..e41c1d7 100644--- a/memhub/apps/web/src/MemoryMap.tsx+++ b/memhub/apps/web/src/MemoryMap.tsx@@ -5,6 +5,7 @@ import type {MemoryLibraryPage,RecentConversationItem,} from "@one-memory/contracts";+import type { GuiLocale } from "@one-memory/i18n";import {ArrowUp,ChevronLeft,@@ -29,6 +30,7 @@ import {type MemoryArrival,resolveMemoryArrival,} from "./memory-arrival-state";+import { memoryText, useMemoryLanguage } from "./memory-language";import {type MapAxis,mapGroups,@@ -96,8 +98,12 @@ function authorLabel(writtenBy: string) {return "未知";}-function dayStamp(value: string | null | undefined) {- if (!value || !Number.isFinite(Date.parse(value))) return "时间未知";+function dayStamp(+ value: string | null | undefined,+ locale: GuiLocale = "zh-CN",+) {+ if (!value || !Number.isFinite(Date.parse(value)))+ return memoryText(locale, "时间未知");const date = new Date(value);const now = new Date();if (@@ -105,8 +111,8 @@ function dayStamp(value: string | null | undefined) {date.getMonth() === now.getMonth() &&date.getDate() === now.getDate())- return "今天";- return date.toLocaleDateString("zh-CN");+ return memoryText(locale, "今天");+ return date.toLocaleDateString(locale);}/**@@ -116,28 +122,37 @@ function dayStamp(value: string | null | undefined) {*/export const DIALOGUE_PANE_VISIBLE = false;-/** "10月2日", with the year only when it is not this year. */-function monthDay(value: string): string | null {+/** "10月2日" / "2 oct", with the year only when it is not this year. */+function monthDay(value: string, locale: GuiLocale): string | null {if (!Number.isFinite(Date.parse(value))) return null;const date = new Date(value);- const day = `${date.getMonth() + 1}月${date.getDate()}日`;- return date.getFullYear() === new Date().getFullYear()- ? day- : `${date.getFullYear()}年${day}`;+ return new Intl.DateTimeFormat(locale, {+ day: "numeric",+ month: "short",+ ...(date.getFullYear() !== new Date().getFullYear()+ ? { year: "numeric" }+ : {}),+ }).format(date);}/** D96: when the cited conversation happened, not when the memory was generated. */function sourceStamp(time: { at: string; basis: "conversation" | "import" } | undefined,fallback: string | null | undefined,+ locale: GuiLocale = "zh-CN",): string {- const day = time ? monthDay(time.at) : null;+ const day = time ? monthDay(time.at, locale) : null;if (time && day)- return time.basis === "conversation" ? `对话于 ${day}` : `导入于 ${day}`;- return dayStamp(fallback);+ return memoryText(+ locale,+ time.basis === "conversation" ? "对话于 {day}" : "导入于 {day}",+ { day },+ );+ return dayStamp(fallback, locale);}export function MemoryMap(props: Props) {+ const { locale, text, count, plain } = useMemoryLanguage();const {memories,graph: baseGraph,@@ -322,14 +337,16 @@ export function MemoryMap(props: Props) {if (library) {const ids = library.page?.source_ids_by_memory?.[memoryId];return ids?.length- ? ids.map((id) => sourceNameOr(sources, id, "来源待核对")).join("、")- : "来源待核对";+ ? ids+ .map((id) => sourceNameOr(sources, id, text("来源待核对")))+ .join("、")+ : text("来源待核对");}return (sourceGroups.filter((entry) => entry.memoryIds.includes(memoryId)).map((entry) => entry.label)- .join("、") || "来源待核对"+ .join(text("列表分隔符")) || text("来源待核对"));}const filtered = useMemo(@@ -594,7 +611,7 @@ export function MemoryMap(props: Props) {(source) =>source.authorized && groupKey === `source:${source.source_id}`,)?.display_name ??- "全部记忆";+ text("全部记忆");if (props.simplified &&(!library ||@@ -614,28 +631,31 @@ export function MemoryMap(props: Props) {<div><h2>{running- ? "已开始处理所选对话"+ ? text("已开始处理所选对话"): queued- ? "处理请求已受理"- : "还没有已生成的记忆"}+ ? text("处理请求已受理")+ : text("还没有已生成的记忆")}</h2><p>{running || queued- ? "模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。"+ ? text("模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。"): arrival.importedConversations > 0- ? `已导入 ${arrival.importedConversations.toLocaleString()} 段对话,整理成记忆后会出现在这里。`+ ? text("已导入 {count} 段对话,整理成记忆后会出现在这里。", {+ count: count(arrival.importedConversations),+ }): arrival.importedMessages > 0- ? "历史已保存在本机,记忆就绪后会出现在这里。"- : "连接应用并导入历史后,可以开始沉淀记忆。"}+ ? text("历史已保存在本机,记忆就绪后会出现在这里。")+ : text("连接应用并导入历史后,可以开始沉淀记忆。")}{(running || queued) && (<small>- 当前已生成 0- 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。+ {text(+ "当前已生成 0 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。",+ )}</small>)}</p><div>- <R6Button onClick={props.onConnect}>返回应用</R6Button>+ <R6Button onClick={props.onConnect}>{text("返回应用")}</R6Button></div></div>{running && (@@ -648,7 +668,7 @@ export function MemoryMap(props: Props) {<sectionid={id}className="core-memory-map"- aria-label="记忆工作台"+ aria-label={text("记忆工作台")}hidden={hidden}inert={hidden}onKeyDown={(e) => {@@ -663,12 +683,12 @@ export function MemoryMap(props: Props) {clear();}}>- <nav className="map-library" aria-label="来源与主题" ref={pane}>+ <nav className="map-library" aria-label={text("来源与主题")} ref={pane}>{props.simplified && DIALOGUE_PANE_VISIBLE ? (<divclassName="map-library-pane"role="tablist"- aria-label="记忆或原始对话"+ aria-label={text("记忆或原始对话")}onKeyDown={(event) => {const order = ["memories", "dialogues"] as const;const current = order.indexOf(libraryPane);@@ -705,20 +725,20 @@ export function MemoryMap(props: Props) {aria-controls={`memory-pane-${value}`}onClick={() => setLibraryPane(value)}>- {title}+ {text(title)}</button>))}</div>) : null}{props.simplified ? (<div className="selected-source-filter">- <label htmlFor="selected-source-filter">来源</label>+ <label htmlFor="selected-source-filter">{text("来源")}</label><OptionMenuid="selected-source-filter"className="om-option-menu--plain"value={controlledSource}options={[- { value: "", label: "全部应用" },+ { value: "", label: text("全部应用") },...(library?.source &&!sources.some((source) =>@@ -727,7 +747,7 @@ export function MemoryMap(props: Props) {? [{value: `source:${library.source}`,- label: "所选来源待核对",+ label: text("所选来源待核对"),},]: []),@@ -747,7 +767,7 @@ export function MemoryMap(props: Props) {/></div>) : (- <fieldset className="map-axis" aria-label="地图组织方式">+ <fieldset className="map-axis" aria-label={text("地图组织方式")}>{([["source", "来源"],@@ -764,7 +784,7 @@ export function MemoryMap(props: Props) {setGroupKey("");}}>- {title}+ {text(title)}</button>))}</fieldset>@@ -772,15 +792,15 @@ export function MemoryMap(props: Props) {<div className="map-search"><Search size={16} aria-hidden="true" /><input- aria-label="筛选地图记忆"+ aria-label={text("筛选地图记忆")}name="map-memory-search"autoComplete="off"placeholder={libraryPane === "dialogues"- ? "搜索原始对话"+ ? text("搜索原始对话"): props.simplified- ? "搜索记忆"- : "筛选记忆…"+ ? text("搜索记忆")+ : text("筛选记忆…")}value={libraryPane === "dialogues"@@ -815,22 +835,30 @@ export function MemoryMap(props: Props) {<span>{library.stale? library.page && library.page.total > 0- ? `共 ${library.page.total} 条 · 正在核对来源…`- : "正在核对来源…"+ ? text(+ "共 {count} 条 · 正在核对来源…",+ { count: plain(library.page.total) },+ library.page.total,+ )+ : text("正在核对来源…"): library.failed- ? "读取失败"+ ? text("读取失败"): library.loading && library.page?.total === 0- ? "正在读取…"+ ? text("正在读取…"): library.page- ? `共 ${library.page.total} 条${refreshing ? " · 正在核对…" : ""}`- : "正在读取…"}+ ? `${text(+ "共 {count} 条",+ { count: plain(library.page.total) },+ library.page.total,+ )}${refreshing ? text(" · 正在核对…") : ""}`+ : text("正在读取…")}</span>{!library.stale && (<buttontype="button"className="quiet map-tool"- aria-label="刷新地图记忆"- title="刷新地图记忆"+ aria-label={text("刷新地图记忆")}+ title={text("刷新地图记忆")}disabled={library.loading || hidden}onClick={library.onRetry}>@@ -847,7 +875,7 @@ export function MemoryMap(props: Props) {aria-pressed={!groupKey}onClick={() => chooseGroup("")}>- 全部记忆 <span>{active.length}</span>+ {text("全部记忆")} <span>{active.length}</span></button>{groups.map((g) => (<button@@ -867,16 +895,22 @@ export function MemoryMap(props: Props) {{!props.simplified && (<div className="map-list-heading"><span>{label}</span>- <span>{filtered.length} 条</span>+ <span>{text("{count} 条", { count: filtered.length })}</span></div>)}{arrivalCount > 0 && (<div className="map-arrival-notice">- <span role="status">新增 {arrivalCount} 条记忆</span>+ <span role="status">+ {text(+ "新增 {count} 条记忆",+ { count: plain(arrivalCount) },+ arrivalCount,+ )}+ </span><buttontype="button"- title="关闭新增记忆提示"- aria-label="关闭新增记忆提示"+ title={text("关闭新增记忆提示")}+ aria-label={text("关闭新增记忆提示")}onClick={() => setArrivedIds([])}><X size={15} aria-hidden="true" />@@ -885,7 +919,7 @@ export function MemoryMap(props: Props) {)}{filterNotice && (<p className="map-filter-notice" role="status">- {filterNotice}+ {text(filterNotice)}</p>)}{libraryPane === "dialogues" ? (@@ -893,10 +927,10 @@ export function MemoryMap(props: Props) {<div className="map-list-heading" aria-live="polite"><span>{dialogueFailed- ? "读取失败"+ ? text("读取失败"): dialoguePage- ? `最近 ${dialoguePage.length} 条`- : "正在读取…"}+ ? text("最近 {count} 条", { count: dialoguePage.length })+ : text("正在读取…")}</span></div><ul@@ -925,19 +959,23 @@ export function MemoryMap(props: Props) {</li>))}</ul>- {dialogueFailed ? <p role="alert">原始对话暂时无法读取</p> : null}+ {dialogueFailed ? (+ <p role="alert">{text("原始对话暂时无法读取")}</p>+ ) : null}{dialoguePage && !dialoguePage.length ? (<p className="map-empty">- {dialogueFilter.trim()- ? "没有匹配的原始对话"- : "还没有导入的原始对话"}+ {text(+ dialogueFilter.trim()+ ? "没有匹配的原始对话"+ : "还没有导入的原始对话",+ )}</p>) : null}</>) : null}<ulclassName="map-memory-list"- aria-label="地图记忆列表"+ aria-label={text("地图记忆列表")}id="memory-pane-memories"hidden={libraryPane === "dialogues"}>@@ -957,15 +995,19 @@ export function MemoryMap(props: Props) {{`${sourceLabel(m.memory_id)} · ${sourceStamp(library?.page?.source_time_by_memory?.[m.memory_id],m.updated_at,+ locale,)}`}{/* D99: the conversation date alone would hide that thisone was made today, so the generated day stays too. */}<span className="map-memory-made">- 沉淀于 {dayStamp(m.updated_at)}+ {text("沉淀于 ")}+ {dayStamp(m.updated_at, locale)}</span></>) : (- <>已可用 · {m.evidence_ids.length} 段原文</>+ text("已可用 · {count} 段原文", {+ count: m.evidence_ids.length,+ }))}</small></button>@@ -974,8 +1016,10 @@ export function MemoryMap(props: Props) {</ul>{libraryPane === "memories" && library?.failed && (<div role="alert">- <p>记忆读取失败,请重试。</p>- <R6Button onClick={library.onRetry}>重新读取地图记忆</R6Button>+ <p>{text("记忆读取失败,请重试。")}</p>+ <R6Button onClick={library.onRetry}>+ {text("重新读取地图记忆")}+ </R6Button></div>)}{libraryPane === "memories" &&@@ -986,10 +1030,10 @@ export function MemoryMap(props: Props) {!filtered.length && (<p className="map-empty">{library.query || library.source- ? "没有匹配的记忆"+ ? text("没有匹配的记忆"): groupKey- ? "本页没有匹配的主题记忆"- : "还没有已生成的记忆"}+ ? text("本页没有匹配的主题记忆")+ : text("还没有已生成的记忆")}</p>)}{libraryPane === "memories" &&@@ -997,12 +1041,12 @@ export function MemoryMap(props: Props) {!library.loading &&!library.failed &&!library.stale && (- <nav aria-label="地图记忆分页" className="map-list-heading">+ <nav aria-label={text("地图记忆分页")} className="map-list-heading"><buttontype="button"className="quiet map-tool"- aria-label="上一页记忆"- title="上一页记忆"+ aria-label={text("上一页记忆")}+ title={text("上一页记忆")}disabled={library.page.offset === 0}onClick={() => {clear();@@ -1014,18 +1058,25 @@ export function MemoryMap(props: Props) {<ChevronLeft size={16} aria-hidden="true" /></button><span>- 共 {library.page.total.toLocaleString()} 条,第{" "}- {library.page.total === 0- ? 0- : Math.floor(library.page.offset / library.page.limit) +- 1}{" "}- / {Math.ceil(library.page.total / library.page.limit)} 页+ {text(+ "共 {count} 条,第 {page} / {pages} 页",+ {+ count: count(library.page.total),+ page:+ library.page.total === 0+ ? 0+ : Math.floor(library.page.offset / library.page.limit) ++ 1,+ pages: Math.ceil(library.page.total / library.page.limit),+ },+ library.page.total,+ )}</span><buttontype="button"className="quiet map-tool"- aria-label="下一页记忆"- title="下一页记忆"+ aria-label={text("下一页记忆")}+ title={text("下一页记忆")}disabled={library.page.offset + library.page.items.length >=library.page.total@@ -1042,7 +1093,7 @@ export function MemoryMap(props: Props) {</nav>)}{!library && loaded && !filtered.length && (search || groupKey) && (- <p className="map-empty">没有匹配的记忆</p>+ <p className="map-empty">{text("没有匹配的记忆")}</p>)}{(!props.simplified || (!library && !active.length)) && (<MemoryArrivalPanel@@ -1056,26 +1107,26 @@ export function MemoryMap(props: Props) {/>)}</nav>- <section className="map-stage" aria-label="记忆关系图">+ <section className="map-stage" aria-label={text("记忆关系图")}><header className="map-stage-heading"><div><span className="map-kicker" hidden={props.simplified}>- {axis === "topic" ? "主题视角(非事项)" : "来源视角"}+ {text(axis === "topic" ? "主题视角(非事项)" : "来源视角")}</span><h2>{libraryPane === "dialogues"- ? "原始对话"+ ? text("原始对话"): props.simplified- ? "记忆关联"+ ? text("记忆关联"): label}</h2>{props.simplified && (<p className="selected-graph-subtitle">{libraryPane === "dialogues"- ? "刚导入的原话,还不是沉淀后的记忆"+ ? text("刚导入的原话,还不是沉淀后的记忆"): projection.nodes.length- ? "来源归属"- : "可在沉淀记忆后查看视图"}+ ? text("来源归属")+ : text("可在沉淀记忆后查看视图")}</p>)}</div>@@ -1083,10 +1134,10 @@ export function MemoryMap(props: Props) {<buttontype="button"className="quiet map-tool"- aria-label={- selectedSource ? "查看选中来源原文" : "查看选中记忆原文"- }- title="查看原文"+ aria-label={text(+ selectedSource ? "查看选中来源原文" : "查看选中记忆原文",+ )}+ title={text("查看原文")}onClick={() => setInspectorOpen(true)}><FileText size={17} />@@ -1097,7 +1148,7 @@ export function MemoryMap(props: Props) {type="button"className="quiet map-tool"title="整理已有关系"- aria-label="整理已有关系"+ aria-label={text("整理已有关系")}disabled={busy || !graph?.nodes.length}onClick={props.onBuildRelations}>@@ -1120,9 +1171,9 @@ export function MemoryMap(props: Props) {))}</ol>) : selectedDialogueId ? (- <p>正在读取原文…</p>+ <p>{text("正在读取原文…")}</p>) : (- <p>选择一条原始对话</p>+ <p>{text("选择一条原始对话")}</p>)}</div>) : projection.nodes.length && (!props.simplified || !hidden) ? (@@ -1139,19 +1190,19 @@ export function MemoryMap(props: Props) {<Network size={32} strokeWidth={1} /><p>{library?.stale- ? "可在沉淀记忆后查看视图"+ ? text("可在沉淀记忆后查看视图"): library?.failed- ? "记忆暂时无法读取"+ ? text("记忆暂时无法读取"): library?.page &&(library.query || library.source || groupKey)- ? "当前筛选没有可显示的记忆"+ ? text("当前筛选没有可显示的记忆"): !loaded- ? "正在读取记忆…"+ ? text("正在读取记忆…"): active.length- ? "当前筛选没有可显示的记忆"+ ? text("当前筛选没有可显示的记忆"): arrival.importedMessages > 0- ? "已保存的对话还未生成记忆"- : "还没有可显示的记忆"}+ ? text("已保存的对话还未生成记忆")+ : text("还没有可显示的记忆")}</p></div>)}@@ -1161,18 +1212,20 @@ export function MemoryMap(props: Props) {something else left it dangling under a view it cannot describe. */}{!props.simplified && libraryPane === "memories" && (<div className="map-legend">- <span data-kind="memory">记忆</span>- <span data-kind="topic">主题</span>- <span data-kind="source">来源</span>- <span data-kind="schema">归纳</span>+ <span data-kind="memory">{text("记忆")}</span>+ <span data-kind="topic">{text("主题")}</span>+ <span data-kind="source">{text("来源")}</span>+ <span data-kind="schema">{text("归纳")}</span></div>)}{props.simplified ? (projection.nodes.length ? (- <span>连线表示来源归属</span>+ <span>{text("连线表示来源归属")}</span>) : null) : (- <span>{filtered.length} 条记忆 · 当前已加载</span>+ <span>+ {text("{count} 条记忆 · 当前已加载", { count: filtered.length })}+ </span>)}</footer>{!props.simplified && (@@ -1187,10 +1240,10 @@ export function MemoryMap(props: Props) {}}><input- aria-label="向记忆提问"+ aria-label={text("向记忆提问")}name="map-question"autoComplete="off"- placeholder="询问全部已授权可用记忆…"+ placeholder={text("询问全部已授权可用记忆…")}value={question}onCompositionStart={() => {composing.current = true;@@ -1209,8 +1262,8 @@ export function MemoryMap(props: Props) {/><buttontype="submit"- title="发送问题"- aria-label="发送问题"+ title={text("发送问题")}+ aria-label={text("发送问题")}disabled={!question.trim() || !!props.streaming}><ArrowUp size={17} />@@ -1248,19 +1301,19 @@ export function MemoryMap(props: Props) {<header className="map-inspector-heading"><h2>{inspectorDetail- ? "记忆详情"+ ? text("记忆详情"): selectedSource- ? "来源原文"+ ? text("来源原文"): visibleGroupNode- ? "关联节点"- : "记忆详情"}+ ? text("关联节点")+ : text("记忆详情")}</h2>{(activeId || visibleGroupNode) && (<buttontype="button"className="quiet map-tool"- aria-label="关闭记忆详情"- title="关闭详情"+ aria-label={text("关闭记忆详情")}+ title={text("关闭详情")}onClick={closeInspector}><X size={17} />@@ -1311,7 +1364,7 @@ export function MemoryMap(props: Props) {<i /><i /></div>- <p role="status">正在读取这条记忆…</p>+ <p role="status">{text("正在读取这条记忆…")}</p></div>) : (<SelectedMemoryDetail@@ -1366,13 +1419,15 @@ export function MemoryMap(props: Props) {{props.detailLoad?.memoryId === activeId &&props.detailLoad.status === "failed" ? (<>- <p role="alert">这条记忆的原文暂时无法读取,选择已保留。</p>+ <p role="alert">+ {text("这条记忆的原文暂时无法读取,选择已保留。")}+ </p><buttontype="button"className="secondary"onClick={() => activeId && onOpenMemory(activeId)}>- 重试读取原文+ {text("重试读取原文")}</button></>) : props.simplified && !activeId && filtered.length ? (@@ -1382,15 +1437,26 @@ export function MemoryMap(props: Props) {// single-column surface needs it — the three-column one already// lists the same memories in the pane beside this one.<>- <p>{`已沉淀 ${filtered.length} 条记忆`}</p>- <ul className="map-settled-list" aria-label="已沉淀的记忆">+ <p>+ {text(+ "已沉淀 {count} 条记忆",+ { count: plain(filtered.length) },+ filtered.length,+ )}+ </p>+ <ul+ className="map-settled-list"+ aria-label={text("已沉淀的记忆")}+ >{filtered.map((m) => (<li key={m.memory_id}>{m.content}</li>))}</ul></>) : (- <p>{activeId ? "正在读取记忆详情…" : "沉淀记忆后查看详情"}</p>+ <p>+ {text(activeId ? "正在读取记忆详情…" : "沉淀记忆后查看详情")}+ </p>)}</div>)}diff --git a/memhub/apps/web/src/MemoryNoteComposer.test.tsx b/memhub/apps/web/src/MemoryNoteComposer.test.tsxindex 1fbea50..9598070 100644--- a/memhub/apps/web/src/MemoryNoteComposer.test.tsx+++ b/memhub/apps/web/src/MemoryNoteComposer.test.tsx@@ -3,8 +3,40 @@ import type { MemoryNoteReceipt } from "@one-memory/contracts";import { cleanup, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { MemoryNoteComposer } from "./MemoryNoteComposer";+it("opens a Spanish composer without saving, processing or enabling anything", async () => {+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <MemoryNoteComposer+ onSaved={vi.fn()}+ onOpenMemory={vi.fn()}+ onConfigureModel={vi.fn()}+ />+ </LanguageProvider>,+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Añadir memoria" }),+ );+ expect(screen.getByRole("dialog", { name: "Añadir memoria" })).toBeTruthy();+ expect(+ screen.getByRole("textbox", { name: "¿Qué quieres recordar?" }),+ ).toBeTruthy();+ expect(+ (screen.getByRole("button", { name: "Guardar texto" }) as HTMLButtonElement)+ .disabled,+ ).toBe(true);+ await userEvent.click(+ screen.getByRole("button", { name: "Cerrar nueva memoria" }),+ );+ expect(api.saveMemoryNote).not.toHaveBeenCalled();+ expect(api.processMemoryNote).not.toHaveBeenCalled();+ localStorage.clear();+});+const api = vi.hoisted(() => ({getMemoryNotes: vi.fn(),getMemoryNoteOperation: vi.fn(),diff --git a/memhub/apps/web/src/MemoryNoteComposer.tsx b/memhub/apps/web/src/MemoryNoteComposer.tsxindex a04af7f..97f6758 100644--- a/memhub/apps/web/src/MemoryNoteComposer.tsx+++ b/memhub/apps/web/src/MemoryNoteComposer.tsx@@ -8,6 +8,7 @@ import {processMemoryNote,saveMemoryNote,} from "./api";+import { useMemoryLanguage } from "./memory-language";import { memoryWriteErrorText } from "./model-error-text";import { subscribePoll } from "./poll-scheduler";import { traceUiAction } from "./ui-trace";@@ -42,6 +43,7 @@ export function MemoryNoteComposer({onPendingChange?(note: PendingMemoryNote | null): void;suspended?: boolean;}) {+ const { text: copy } = useMemoryLanguage();const [open, setOpen] = useState(false);const [text, setText] = useState("");const [notes, setNotes] = useState<MemoryNoteReceipt[]>([]);@@ -274,11 +276,11 @@ export function MemoryNoteComposer({data-tour-id="memory-note-trigger"onClick={() => setOpen(true)}>- <FilePlus2 size={16} aria-hidden="true" /> 添加记忆+ <FilePlus2 size={16} aria-hidden="true" /> {copy("添加记忆")}</button>{savedToast && (<p className="memory-note-toast" role="status">- {savedToast}+ {copy(savedToast)}</p>)}{open && (@@ -313,12 +315,12 @@ export function MemoryNoteComposer({}}><header className="memory-note-heading">- <h2 id="memory-note-title">添加记忆</h2>+ <h2 id="memory-note-title">{copy("添加记忆")}</h2><buttonclassName="quiet"type="button"- aria-label="关闭新增记忆"- title="关闭"+ aria-label={copy("关闭新增记忆")}+ title={copy("关闭")}disabled={busy}onClick={close}>@@ -332,7 +334,7 @@ export function MemoryNoteComposer({}}><label className="memory-note-label" htmlFor="memory-note-text">- 记下这件事+ {copy("记下这件事")}</label><textareaid="memory-note-text"@@ -340,20 +342,20 @@ export function MemoryNoteComposer({maxLength={12000}value={text}disabled={busy}- placeholder="例如:项目周会不排在周五。"+ placeholder={copy("例如:项目周会不排在周五。")}onChange={(event) => setText(event.target.value)}/><p className="memory-note-model">- 整理模型:+ {copy("整理模型:")}{model?.name ??- (modelRead ? "尚未配置,原话仍可保存" : "正在读取")}+ copy(modelRead ? "尚未配置,原话仍可保存" : "正在读取")}</p>{error && (<p className="error-banner" role="alert">- {error}+ {copy(error)}</p>)}- {notice && <p role="status">{notice}</p>}+ {notice && <p role="status">{copy(notice)}</p>}<div className="consent-actions">{modelRead && !model && (<button@@ -365,30 +367,35 @@ export function MemoryNoteComposer({onConfigureModel();}}>- 配置模型+ {copy("配置模型")}</button>)}<button type="submit" disabled={busy || !text.trim()}>- {busy ? "保存中…" : "保存原话"}+ {copy(busy ? "保存中…" : "保存原话")}</button></div></form>{notes.length > 0 && (- <section className="memory-note-recent" aria-label="最近添加">- <h3>最近添加</h3>+ <section+ className="memory-note-recent"+ aria-label={copy("最近添加")}+ >+ <h3>{copy("最近添加")}</h3><ul>{notes.map((note) => (<li key={note.evidence_id}><p>{note.text}</p>- <small>{states[note.state]}</small>+ <small>{copy(states[note.state])}</small>{memoryWriteErrorText(note.error) && (<p className="error-banner">- {memoryWriteErrorText(note.error)}+ {copy(memoryWriteErrorText(note.error) ?? "")}</p>)}{note.error === "hy_memory_model_payment_required" && (<p className="error-banner">- 模型服务要求检查余额或付款状态,原话仍已保存。+ {copy(+ "模型服务要求检查余额或付款状态,原话仍已保存。",+ )}</p>)}<div className="memory-note-actions">@@ -402,7 +409,7 @@ export function MemoryNoteComposer({onOpenMemory(id);}}>- 查看记忆+ {copy("查看记忆")}{note.memory_ids.length > 1 ? ` ${index + 1}` : ""}</button>))}@@ -416,7 +423,7 @@ export function MemoryNoteComposer({onClick={() => void retry(note)}><RefreshCw size={14} aria-hidden="true" />- 重新整理+ {copy("重新整理")}</button>)}</div>diff --git a/memhub/apps/web/src/MemorySpace.r6.test.tsx b/memhub/apps/web/src/MemorySpace.r6.test.tsxindex af2255b..0edfa74 100644--- a/memhub/apps/web/src/MemorySpace.r6.test.tsx+++ b/memhub/apps/web/src/MemorySpace.r6.test.tsx@@ -8,9 +8,87 @@ import {waitFor,} from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { DIALOGUE_PANE_VISIBLE } from "./MemoryMap";import { MemorySpace } from "./MemorySpace";+it("translates memory filters and detail affordances live without refetching", async () => {+ setup();+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <MemorySpace simplified />+ </LanguageProvider>,+ );+ await screen.findByRole("heading", { name: "Memorias", level: 1 });+ await screen.findByText("已保存的记忆");+ expect(+ screen.getByRole("textbox", { name: "Filtrar memorias del mapa" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Actualizar memorias" }),+ ).toBeTruthy();+ const calls = reads.mapLibrary.mock.calls.length;+ act(() => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ window.dispatchEvent(+ new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }),+ );+ });+ expect(screen.getByRole("heading", { name: "记忆", level: 1 })).toBeTruthy();+ expect(reads.mapLibrary).toHaveBeenCalledTimes(calls);+ localStorage.clear();+});++it("localiza la navegación de gobierno de la biblioteca", async () => {+ setup();+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <MemorySpace simplified />+ </LanguageProvider>,+ );+ await screen.findByRole("heading", { name: "Memorias", level: 1 });+ expect(+ screen.getByRole("navigation", {+ name: "Estado de las memorias",+ hidden: true,+ }),+ ).toBeTruthy();+ localStorage.clear();+});++it("localiza cola y estimación sin alterar las memorias", async () => {+ setup();+ delete window.oneMemory;+ reads.processing.mockResolvedValue({+ running: 1,+ pending: 2,+ fresh_pending: 1,+ backlog_pending: 1,+ in_flight_count: 1,+ active_queue: 1,+ seconds_per_completion: 60,+ completed: 0,+ blocked_stages: [],+ });+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <MemorySpace />+ </LanguageProvider>,+ );+ expect(+ await screen.findByText(+ /1 en procesamiento · 1 recientes pendientes · 1 del historial pendientes/,+ ),+ ).toBeTruthy();+ expect(screen.getByText(/aprox. 2 minutos/)).toBeTruthy();+ localStorage.clear();+});+const { reads } = vi.hoisted(() => ({reads: {memories: vi.fn(),@@ -73,6 +151,36 @@ afterEach(() => {vi.useRealTimers();vi.clearAllMocks();});+it("translates the model-required prompt without configuring a model", async () => {+ setup();+ reads.processing.mockResolvedValue({+ running: 0,+ pending: 0,+ completed: 0,+ blocked_stages: [+ { kind: "extract", reason: "waiting_for_model", count: 4 },+ ],+ });+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const configure = vi.fn();+ render(+ <LanguageProvider>+ <MemorySpace simplified onConfigureModel={configure} />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("status", {+ name: "Generación de memorias detenida",+ }),+ ).toHaveProperty(+ "textContent",+ "Aún no se generan memorias: Esperando un modelo disponible (4 pendientes)Configurar modelo de generación",+ );+ expect(configure).not.toHaveBeenCalled();+ localStorage.clear();+});+function setup() {const items = [{diff --git a/memhub/apps/web/src/MemorySpace.tsx b/memhub/apps/web/src/MemorySpace.tsxindex 9406d62..e3796ed 100644--- a/memhub/apps/web/src/MemorySpace.tsx+++ b/memhub/apps/web/src/MemorySpace.tsx@@ -9,6 +9,7 @@ import type {SdkAskMemory,SourceResponse,} from "@one-memory/contracts";+import { isMessageKey } from "@one-memory/i18n";import {ChevronDown,ChevronLeft,@@ -48,6 +49,7 @@ import {import { ConversationSearch } from "./ConversationSearch";import { clockStamp } from "./clock-stamp";import { GraphWidthPrompt } from "./GraphWidthPrompt";+import { useGuiLanguage } from "./gui-language";import { MemoryDeleteDialog } from "./MemoryDeleteDialog";import { MemoryMap } from "./MemoryMap";import { subscribePoll } from "./poll-scheduler";@@ -64,7 +66,6 @@ import {MemoryNoteComposer,type PendingMemoryNote,} from "./MemoryNoteComposer";-import { memoryProvenanceLabel } from "./MemoryRecallScope";import type { MemoryArrival } from "./memory-arrival-state";import {blockReasonLabel,@@ -72,12 +73,13 @@ import {extractionWindowPresetLabel,memoryHistoryActionLabel,modelBlock,- retryingBlockLabel,splitBlockedStages,taskKindLabel,} from "./memory-processing-labels";type MemoryMode = "map" | "ask" | "library" | "history";+type Translate = ReturnType<typeof useGuiLanguage>["t"];+type TranslateCount = ReturnType<typeof useGuiLanguage>["tn"];type AskMemory = GovernedMemory | SdkAskMemory;type MemoryStatusFilter = "confirmed" | "deleted" | "superseded";type BulkAction = "delete";@@ -123,6 +125,13 @@ export function MemorySpace({focusDialogue?: boolean;onFocusDialogueConsumed?(): void;}) {+ const { locale, t, tn } = useGuiLanguage();+ const translation = useRef(t);+ translation.current = t;+ const memoryText = (text: string) => {+ const key = `memory:${text}`;+ return isMessageKey(key) ? t(key) : text;+ };const [memories, setMemories] = useState<GovernedMemory[]>([]);const [detail, setDetail] = useState<MemoryDetail | null>(null);const [detailFreshness, setDetailFreshness] = useState<{@@ -221,10 +230,12 @@ export function MemorySpace({// filter's, and naming the new one would caption the wrong numbers.const settledFilterLabel = [mapLibrary.settledSource- ? `来源 ${sourceNameOr(sources, mapLibrary.settledSource, mapLibrary.settledSource)}`+ ? `${t("memory:来源")} ${sourceNameOr(sources, mapLibrary.settledSource, mapLibrary.settledSource)}`: "",mapLibrary.settledQuery.trim()- ? `关键词“${mapLibrary.settledQuery.trim()}”`+ ? t("memory:关键词“{query}”", {+ query: mapLibrary.settledQuery.trim(),+ }): "",].filter(Boolean)@@ -512,7 +523,11 @@ export function MemorySpace({(latest.memory.deleted_at && !selected.memory.deleted_at)) {closeDetail();- setError("所选记忆已不可读取,请重新读取记忆库。");+ setError(+ translation.current(+ "memory:所选记忆已不可读取,请重新读取记忆库。",+ ),+ );return;}// Refresh the read-only projection even when the memory revision did@@ -559,7 +574,11 @@ export function MemorySpace({code === "memory_deleted") {closeDetail();- setError("所选记忆已不可读取,请重新读取记忆库。");+ setError(+ translation.current(+ "memory:所选记忆已不可读取,请重新读取记忆库。",+ ),+ );} else setDetailFreshness({ id: selectedDetailId, state: "failed" });} finally {inFlight = false;@@ -764,7 +783,7 @@ export function MemorySpace({// The graph is a view of the library, so the library is what decides// whether this screen has anything to show.if (items.status === "rejected") {- setReadError(message(items.reason));+ setReadError(message(items.reason, translation.current));return false;}setReadError(null);@@ -1008,8 +1027,12 @@ export function MemorySpace({setDraft(result.memory.content);} catch (reason) {if (epoch === detailEpoch.current) {- setError(message(reason));- setDetailLoad({ memoryId, status: "failed", error: message(reason) });+ setError(message(reason, t));+ setDetailLoad({+ memoryId,+ status: "failed",+ error: message(reason, t),+ });}}}@@ -1073,8 +1096,10 @@ export function MemorySpace({});setError(committed- ? "修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。"- : message(reason),+ ? t(+ "memory:修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ )+ : message(reason, t),);} finally {setBusy(false);@@ -1211,8 +1236,8 @@ export function MemorySpace({...target,error:apiErrorCode(reason) === null- ? "未收到操作结果,请重试。"- : message(reason),+ ? t("memory:未收到操作结果,请重试。")+ : message(reason, t),}),);setSelection((current) => new Set(current).add(target.memoryId));@@ -1230,8 +1255,10 @@ export function MemorySpace({} catch {setError(simplified- ? "批量处理结果已保留,但列表刷新失败,请重新读取记忆库。"- : "批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。",+ ? t("memory:批量处理结果已保留,但列表刷新失败,请重新读取记忆库。")+ : t(+ "memory:批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。",+ ),);}} finally {@@ -1273,8 +1300,10 @@ export function MemorySpace({});setError(committed- ? "纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。"- : message(reason),+ ? t(+ "memory:纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ )+ : message(reason, t),);} finally {setBusy(false);@@ -1307,7 +1336,7 @@ export function MemorySpace({? "memory_index_sync_failed": "memory_index_sync_result_unknown",});- setError(message(reason));+ setError(message(reason, t));} finally {setBusy(false);}@@ -1327,7 +1356,7 @@ export function MemorySpace({? "memory_graph_digest_failed": "memory_graph_digest_result_unknown",});- setError(message(reason));+ setError(message(reason, t));} finally {setBusy(false);}@@ -1337,7 +1366,9 @@ export function MemorySpace({if (busy ||!window.confirm(- "重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?",+ t(+ "memory:重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?",+ ),))return;@@ -1354,7 +1385,7 @@ export function MemorySpace({? "memory_unknown_retry_rejected": "memory_unknown_retry_result_unknown",});- setError(message(reason));+ setError(message(reason, t));} finally {setBusy(false);}@@ -1409,26 +1440,44 @@ export function MemorySpace({</div><header className="memory-instrument-header"><div>- <h1 id="memory-title">{simplified ? "记忆" : "记忆空间"}</h1>+ <h1 id="memory-title">+ {simplified ? t("memory:记忆") : t("memory:记忆空间")}+ </h1><span className="memory-loaded-count">{simplified && !management? mapLibrary.failed- ? "记忆读取失败"+ ? t("memory:记忆读取失败"): mapLibrary.stale- ? "正在导入历史会话,记忆将陆续出现"+ ? t("memory:正在导入历史会话,记忆将陆续出现"): mapLibrary.page- ? `已沉淀 ${mapLibrary.page.total} 条${settledFilterLabel ? `(${settledFilterLabel})` : ""} · 当前展示 ${mapLibrary.page.items.length} 条`- : "正在读取…"+ ? tn(+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条",+ mapLibrary.page.total,+ {+ filter: settledFilterLabel+ ? t("memory:({filter})", {+ filter: settledFilterLabel,+ })+ : "",+ shown: new Intl.NumberFormat(locale).format(+ mapLibrary.page.items.length,+ ),+ },+ )+ : t("memory:正在读取…"): loaded- ? `已加载 ${memories.filter((m) => m.status !== "deleted").length} 条记忆`- : "正在读取…"}+ ? tn(+ "memory:已加载 {count} 条记忆",+ memories.filter((m) => m.status !== "deleted").length,+ )+ : t("memory:正在读取…")}</span></div><MemoryNoteComposersuspended={!active}onPendingChange={setPendingNote}onSaved={() => {- void refresh(query).catch((reason) => setError(message(reason)));+ void refresh(query).catch((reason) => setError(message(reason, t)));}}onOpenMemory={(id) => {if (!simplified) setMode("library");@@ -1440,7 +1489,7 @@ export function MemorySpace({<divclassName="memory-mode-tabs"role="tablist"- aria-label="记忆空间模式"+ aria-label={t("memory:记忆空间模式")}onKeyDown={(event) => {// A `role="tablist"` is expected to move selection with the arrow// keys (WAI-ARIA tabs pattern). Without this the four tabs were@@ -1472,10 +1521,10 @@ export function MemorySpace({>{([- ["map", "工作台", Network],- ["library", "记忆库", LayoutList],- ["ask", "问记忆", MessageCircle],- ["history", "历史对话", TextSearch],+ ["map", t("memorySpace.tabs.workbench"), Network],+ ["library", t("memory:记忆库"), LayoutList],+ ["ask", t("memory:问记忆"), MessageCircle],+ ["history", t("memory:历史对话"), TextSearch],] as const).map(([value, label, Icon]) => (<button@@ -1510,10 +1559,10 @@ export function MemorySpace({className={processingNeedsAttention ? "status-attention" : ""}>{processingNeedsAttention- ? "整理需要处理"+ ? t("memory:整理需要处理"): processing.running || processing.pending- ? "正在整理记忆"- : "整理状态"}+ ? t("memory:正在整理记忆")+ : t("memory:整理状态")}</span><ChevronDown size={14} aria-hidden="true" /></summary>@@ -1525,39 +1574,63 @@ export function MemorySpace({}/>{processing.running || processing.pending- ? `${processing.running} 处理中 · ${queueWaiting(processing)}${queueEta(processing)}`- : `${processing.completed} 次整理已完成`}+ ? `${tn("memory:{count} 处理中", processing.running)} · ${queueWaiting(processing, t, tn)}${queueEta(processing, tn)}`+ : tn("memory:{count} 次整理已完成", processing.completed)}{processing.outside_window_pending ? (<span className="pipeline-outside-window">- {` · ${processing.outside_window_pending} 条在窗口外(原文可搜)`}+ {tn(+ "memory: · {count} 条在窗口外(原文可搜)",+ processing.outside_window_pending,+ )}</span>) : null}{processing.manual_extract_batches_planned ? (<span className="pipeline-manual-batches">- {` · 已规划 ${processing.manual_extract_batches_planned} 批,当前第 ${processing.manual_extract_batches_current} 批`}+ {t("memory: · 已规划 {planned} 批,当前第 {current} 批", {+ planned: new Intl.NumberFormat(locale).format(+ processing.manual_extract_batches_planned,+ ),+ current: new Intl.NumberFormat(locale).format(+ processing.manual_extract_batches_current,+ ),+ })}</span>) : null}{blocked.named.length ? (<span className="pipeline-blocked">{blocked.named- .map(- (block) =>- `${taskKindLabel(block.kind)}卡在 ${blockReasonLabel(block.reason)}(${block.count} 条)`,+ .map((block) =>+ tn(+ "memory:{kind}卡在 {reason}({count} 条)",+ block.count,+ {+ kind: memoryText(taskKindLabel(block.kind)),+ reason: memoryText(blockReasonLabel(block.reason)),+ },+ ),).join(" · ")}</span>) : null}{blocked.retrying ? (<span className="pipeline-retrying">- {` · ${retryingBlockLabel(blocked.retrying)}`}+ {` · ${tn(+ "memory:{count} 条这次没能整理成功,正在重试",+ blocked.retrying,+ )}`}</span>) : null}</p>{(processing.unknown ?? 0) > 0 ? (<div className="memory-processing-unknown" role="status">- <span>{`有 ${processing.unknown} 段对话的整理结果不确定`}</span>+ <span>+ {tn(+ "memory:有 {count} 段对话的整理结果不确定",+ processing.unknown ?? 0,+ )}+ </span><R6Button disabled={busy} onClick={() => void retryUnknown()}>- 重新整理+ {t("memory:重新整理")}</R6Button></div>) : null}@@ -1570,7 +1643,7 @@ export function MemorySpace({try {setProcessing(await getMemoryProcessing());} catch (reason) {- setError(message(reason));+ setError(message(reason, t));}}}/>@@ -1589,10 +1662,13 @@ export function MemorySpace({/>{simplified && pendingNote ? (<p className="memory-pending-note" role="status">- <span>原话已保存,正在等待整理:{pendingNote.text}</span>+ <span>+ {t("memory:原话已保存,正在等待整理:")}+ {pendingNote.text}+ </span>{pendingNote.state === "waiting_for_model" ? (<button type="button" onClick={onConfigureModel}>- 配置整理模型+ {t("memory:配置整理模型")}</button>) : null}</p>@@ -1600,13 +1676,13 @@ export function MemorySpace({{readError && (<details className="memory-feedback-details">- <summary>查看读取详情</summary>+ <summary>{t("memory:查看读取详情")}</summary><p>{readError}</p></details>)}{refreshing ? (<p className="memory-refreshing" role="status">- 正在更新…+ {t("memory:正在更新…")}</p>) : null}{error ? (@@ -1630,7 +1706,7 @@ export function MemorySpace({}}/>) : (- <p role="status">正在确认记忆数据来源…</p>+ <p role="status">{t("memory:正在核对来源…")}</p>)}</div>)}@@ -1662,26 +1738,28 @@ export function MemorySpace({await refresh(query);}} catch (reason) {- setError(message(reason));+ setError(message(reason, t));} finally {setBusy(false);}}}><label htmlFor="memory-query">- {displayedMode === "ask" ? "向已确认记忆提问" : "搜索记忆库"}+ {displayedMode === "ask"+ ? t("memory:向已确认记忆提问")+ : t("memory:搜索记忆库")}</label><div>{displayedMode === "ask" ? (<select- aria-label="问答记忆范围"+ aria-label={t("memory:问答记忆范围")}value={askScope}onChange={(event) =>setAskScope(event.target.value as "all-apps" | "*")}>- <option value="all-apps">只问个人画像</option>- <option value="*">问全部记忆(含项目)</option>+ <option value="all-apps">{t("memory:只问个人画像")}</option>+ <option value="*">{t("memory:问全部记忆(含项目)")}</option></select>) : null}<input@@ -1693,8 +1771,8 @@ export function MemorySpace({maxLength={management ? 512 : undefined}placeholder={displayedMode === "ask"- ? "例如:我对真实数据有什么要求?"- : "搜索偏好、决定或经历"+ ? t("memory:例如:我对真实数据有什么要求?")+ : t("memory:搜索偏好、决定或经历")}onChange={(event) => {if (bulkInFlight.current) return;@@ -1707,10 +1785,10 @@ export function MemorySpace({disabled={busy || (!management && !query.trim())}>{busy- ? "处理中…"+ ? t("memory:处理中…"): displayedMode === "ask"- ? "根据记忆回答"- : "搜索"}+ ? t("memory:根据记忆回答")+ : t("memory:搜索")}</button>{management && (query || submittedQuery) ? (<R6Button@@ -1723,7 +1801,7 @@ export function MemorySpace({setSelection(new Set());}}>- 清除搜索+ {t("memory:清除搜索")}</R6Button>) : null}</div>@@ -1757,7 +1835,7 @@ export function MemorySpace({onMutationComplete={(id) => {void refresh(query).then(() => open(id))- .catch((reason) => setError(message(reason)));+ .catch((reason) => setError(message(reason, t)));}}hidden={!active || displayedMode !== "map"}memories={simplified ? (mapLibrary.page?.items ?? []) : memories}@@ -1795,12 +1873,14 @@ export function MemorySpace({onAsk={(fullQuestion) => {setError(null);void ask(fullQuestion, "*").catch((reason) =>- setError(message(reason)),+ setError(message(reason, t)),);}}onSaveAnswer={(saved) => {setError(null);- void saveAnswer(saved).catch((reason) => setError(message(reason)));+ void saveAnswer(saved).catch((reason) =>+ setError(message(reason, t)),+ );}}onConnect={onConnect}onConfigureModel={onConfigureModel}@@ -1816,14 +1896,17 @@ export function MemorySpace({<p className="answer-label">{answer? answer.mode === "generated"- ? "模型综合"+ ? t("memory:模型综合"): answer.mode === "extractive"- ? "原文摘录"- : "没有命中"+ ? t("memory:原文摘录")+ : t("memory:没有命中"): streaming?.text- ? "正在生成"- : "正在检索记忆"}{" "}- · 基于 {(answer ?? streaming)?.memories.length ?? 0} 条已确认记忆+ ? t("memory:正在生成")+ : t("memory:正在检索记忆")}+ {tn(+ "memory: · 基于 {count} 条已确认记忆",+ (answer ?? streaming)?.memories.length ?? 0,+ )}</p><h2 aria-live="polite">{answer ? answer.answer : streaming?.text}@@ -1843,7 +1926,9 @@ export function MemorySpace({</article>) : (<p className="ask-intro">- 回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。+ {t(+ "memory:回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。",+ )}</p>)}<MemoryInspector@@ -1877,13 +1962,13 @@ export function MemorySpace({<navclassName="memory-status-tabs"data-tour-id="memory-status-tabs"- aria-label="记忆治理状态"+ aria-label={t("memory:记忆治理状态")}>{([- ["confirmed", "已可用"],- ["superseded", "已被取代"],- ["deleted", "已删除"],+ ["confirmed", t("memory:已可用")],+ ["superseded", t("memory:已被取代")],+ ["deleted", t("memory:已删除")],] as const).map(([value, label]) => (<button@@ -1900,26 +1985,33 @@ export function MemorySpace({>{label}{" "}{!simplified &&- memories.filter((memory) => memory.status === value)- .length}+ new Intl.NumberFormat(locale).format(+ memories.filter((memory) => memory.status === value)+ .length,+ )}</button>))}</nav>{management && (<>{library.page ? (- <nav aria-label="记忆库分页">- <span aria-live="polite">共 {library.page.total} 条</span>{" "}+ <nav aria-label={t("memory:记忆库分页")}>+ <span aria-live="polite">+ {tn("memory:共 {count} 条", library.page.total)}+ </span>{" "}<span>- 第{" "}- {Math.floor(library.page.offset / library.page.limit) +- 1}{" "}- 页+ {t("memory:第 {page} 页", {+ page: new Intl.NumberFormat(locale).format(+ Math.floor(+ library.page.offset / library.page.limit,+ ) + 1,+ ),+ })}</span><R6Buttonvariant="quiet"- title="上一页"- aria-label="上一页"+ title={t("memory:上一页")}+ aria-label={t("memory:上一页")}disabled={busy || library.page.offset === 0}onClick={() => {if (library.page) {@@ -1934,8 +2026,8 @@ export function MemorySpace({</R6Button><R6Buttonvariant="quiet"- title="下一页"- aria-label="下一页"+ title={t("memory:下一页")}+ aria-label={t("memory:下一页")}disabled={busy ||library.page.offset + library.page.limit >=@@ -1955,30 +2047,41 @@ export function MemorySpace({</nav>) : null}{sourceSnapshotStale ? (- <p role="status">来源状态待核对,记忆库暂不可读取。</p>+ <p role="status">+ {t("memory:来源状态待核对,记忆库暂不可读取。")}+ </p>) : library.stale ? (<p role="status">- 正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。+ {t(+ "memory:正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。",+ )}</p>) : library.failed ? (<div role="alert">- <p>记忆库读取失败,请重试。</p>+ <p>{t("memory:记忆库读取失败,请重试。")}</p><R6ButtononClick={() => {void library.refresh().catch(() => {});}}>- 重新读取记忆库+ {t("memory:重新读取记忆库")}</R6Button></div>) : library.loading ? (- <p role="status">正在读取记忆库…</p>+ <p role="status">{t("memory:正在读取记忆库…")}</p>) : null}</>)}{bulkResult ? (- <p role="status" aria-label="批量操作结果">- {`已${bulkResult.action ? bulkActionLabel(bulkResult.action) : "处理"} ${bulkResult.succeeded} 条${bulkResult.failed ? `,${bulkResult.failed} 条未完成` : ""}`}+ <p role="status" aria-label={t("memory:批量操作结果")}>+ {tn("memory:已{action} {count} 条", bulkResult.succeeded, {+ action: bulkResult.action+ ? bulkActionLabel(bulkResult.action, t)+ : t("memory:处理(操作)"),+ })}+ {bulkResult.failed+ ? tn("memory:,{count} 条未完成", bulkResult.failed)+ : ""}</p>) : null}{visibleFailures.length ? (@@ -1987,19 +2090,22 @@ export function MemorySpace({disabled={busy}onClick={() => void runBulk(visibleFailures)}>- {`重试失败的 ${visibleFailures.length} 条`}+ {tn("memory:重试失败的 {count} 条", visibleFailures.length)}</button>) : null}{selectedCount ? (- <fieldset className="memory-bulk-bar" aria-label="批量操作">- <span>{`已选 ${selectedCount} 条`}</span>+ <fieldset+ className="memory-bulk-bar"+ aria-label={t("memory:批量操作")}+ >+ <span>{tn("memory:已选 {count} 条", selectedCount)}</span><buttontype="button"className="danger"disabled={busy}onClick={() => void bulkAction("delete")}>- {`删除所选 ${selectedCount} 条`}+ {tn("memory:删除所选 {count} 条", selectedCount)}</button><buttontype="button"@@ -2009,7 +2115,7 @@ export function MemorySpace({if (!bulkInFlight.current) setSelection(new Set());}}>- 取消选择+ {t("memory:取消选择")}</button></fieldset>) : null}@@ -2022,7 +2128,9 @@ export function MemorySpace({<inputtype="checkbox"disabled={busy}- aria-label={`选择:${memory.content}`}+ aria-label={t("memory:选择:{content}", {+ content: memory.content,+ })}checked={selection.has(memory.memory_id)}onChange={() => toggleSelection(memory.memory_id)}/>@@ -2038,23 +2146,35 @@ export function MemorySpace({><span>{memory.content}</span><small>- {kindLabel(memory.kind)} ·{" "}- {statusLabel(memory.status)} ·{" "}- {memory.evidence_ids.length} 条原话+ {kindLabel(memory.kind, t)} ·{" "}+ {statusLabel(memory.status, t)} ·{" "}+ {tn(+ "memory:{count} 条原话",+ memory.evidence_ids.length,+ )}</small></button>{failure ? (<fieldsetclassName="memory-bulk-failure"- aria-label={`处理失败:${memory.content}`}+ aria-label={t("memory:处理失败:{content}", {+ content: memory.content,+ })}>- <p>{`未能${bulkActionLabel(failure.action)}:${failure.error}`}</p>+ <p>+ {t("memory:未能{action}:{error}", {+ action: bulkActionLabel(failure.action, t),+ error: failure.error,+ })}+ </p><buttontype="button"disabled={busy}onClick={() => void runBulk([failure])}>- {`重试${bulkActionLabel(failure.action)}`}+ {t("memory:重试{action}", {+ action: bulkActionLabel(failure.action, t),+ })}</button></fieldset>) : null}@@ -2066,10 +2186,14 @@ export function MemorySpace({!management ? (// Not the same as having none, and it used to read as if it// were.- <p className="memory-status-empty">正在读取记忆库…</p>+ <p className="memory-status-empty">+ {t("memory:正在读取记忆库…")}+ </p>) : (<p className="memory-status-empty">- {`没有${statusLabel(statusFilter)}的记忆。`}+ {t("memory:没有{status}的记忆。", {+ status: statusLabel(statusFilter, t),+ })}</p>)}</div>@@ -2115,6 +2239,7 @@ function ModelPrompt({hasMemories: boolean;onConfigureModel(): void;}) {+ const { t, tn } = useGuiLanguage();const blocked = processing ? modelBlock(processing.blocked_stages) : null;if (!blocked) return null;if (@@ -2125,12 +2250,26 @@ function ModelPrompt({)return null;return (- <p className="model-prompt" role="status" aria-label="记忆未在生成">+ <p+ className="model-prompt"+ role="status"+ aria-label={t("memory:记忆未在生成")}+ ><span>- {`还没有开始生成记忆:${blockReasonLabel(blocked.reason)}(${blocked.count} 条待处理)`}+ {tn(+ "memory:还没有开始生成记忆:{reason}({count} 条待处理)",+ blocked.count,+ {+ reason: t(+ `memory:${blockReasonLabel(blocked.reason)}` as Parameters<+ typeof t+ >[0],+ ),+ },+ )}</span><button type="button" onClick={onConfigureModel}>- 去配置生成模型+ {t("memory:去配置生成模型")}</button></p>);@@ -2161,36 +2300,38 @@ function MemoryInspector({onConfigureModel(): void;onOpen(memoryId: string): Promise<void>;}) {+ const { locale, t } = useGuiLanguage();if (!detail) {return (<asideclassName="memory-inspector memory-inspector-empty"data-tour-id="memory-original-pane">- <p>选择一条记忆</p>- <small>查看它的来源、内容和修改历史。</small>+ <p>{t("memory:选择一条记忆")}</p>+ <small>{t("memoryInspector.emptyHint")}</small></aside>);}return (<asideclassName="memory-inspector"- aria-label="记忆详情"+ aria-label={t("memory:记忆详情")}data-tour-id="memory-original-pane"><buttontype="button"className="drawer-close"- aria-label="关闭记忆详情"+ aria-label={t("memory:关闭记忆详情")}onClick={onClose}>×</button><p className="status-label">- {kindLabel(detail.memory.kind)} · {statusLabel(detail.memory.status)} ·- r{detail.memory.revision}+ {kindLabel(detail.memory.kind, t)} ·{" "}+ {statusLabel(detail.memory.status, t)} · r+ {new Intl.NumberFormat(locale).format(detail.memory.revision)}</p>- <p className="map-origin">{memoryProvenanceLabel(detail)}</p>+ <p className="map-origin">{localizedMemoryProvenance(detail, t)}</p>{detail.memory.superseded_by?.length ||detail.memory.supersedes?.length ? (<p className="memory-supersession">@@ -2201,7 +2342,7 @@ function MemoryInspector({className="quiet"onClick={() => void onOpen(memoryId)}>- 查看替代它的记忆+ {t("memory:查看替代它的记忆")}</button>))}{(detail.memory.supersedes ?? []).map((memoryId) => (@@ -2211,7 +2352,7 @@ function MemoryInspector({className="quiet"onClick={() => void onOpen(memoryId)}>- 查看它取代的旧记忆+ {t("memory:查看它取代的旧记忆")}</button>))}</p>@@ -2231,7 +2372,7 @@ function MemoryInspector({{detail.memory.status === "confirmed" ? (<form onSubmit={onSave}><label>- 记忆内容+ {t("memory:记忆内容")}<textareaname="memory-content"autoComplete="off"@@ -2244,7 +2385,7 @@ function MemoryInspector({/></label><button type="submit" disabled={busy}>- 保存纠正+ {t("memory:保存纠正")}</button></form>) : null}@@ -2258,7 +2399,7 @@ function MemoryInspector({disabled={busy}onClick={() => onAction("undo")}>- 撤销上次修改+ {t("memory:撤销上次修改")}</button>) : null}{detail.memory.status !== "deleted" ? (@@ -2268,31 +2409,42 @@ function MemoryInspector({disabled={busy}onClick={() => onAction("delete")}>- 删除+ {t("memory:删除")}</button>) : null}</div>- <h3>来源原话</h3>+ <h3>{t("memory:来源原文")}</h3>{detail.evidence.map((item) => (<blockquote key={item.evidence_id}>{item.available ? (<>{item.extraction_state &&item.extraction_state !== "extracted" ? (- <small>{extractionStateLabel(item.extraction_state)}</small>+ <small>+ {t(+ `memory:${extractionStateLabel(item.extraction_state)}` as Parameters<+ typeof t+ >[0],+ )}+ </small>) : null}{item.verbatim}</>) : (- "来源原话已不可读取"+ t("memory:来源原文已不可读取"))}</blockquote>))}- <h3>修改历史</h3>+ <h3>{t("memory:修改历史")}</h3><ol>{detail.history.map((item) => (<li key={item.revision}>- r{item.revision} · {memoryHistoryActionLabel(item.action)}+ r{new Intl.NumberFormat(locale).format(item.revision)} ·{" "}+ {t(+ `memory:${memoryHistoryActionLabel(item.action)}` as Parameters<+ typeof t+ >[0],+ )}</li>))}</ol>@@ -2300,32 +2452,32 @@ function MemoryInspector({);}-function message(reason: unknown): string {+function message(reason: unknown, t: Translate): string {const code =reason instanceof Error &&reason.message === "memory_answer_context_changed"? reason.message: apiErrorCode(reason);- const labels: Record<string, string> = {+ const labels: Record<string, Parameters<Translate>[0]> = {memory_answer_context_changed:- "记忆内容或使用权限已变化,回答已停止。请重新提问。",- memory_source_revoked: "这条记忆的来源授权已撤回,暂时不能读取。",- memory_revision_conflict: "记忆已被更新,请刷新后重试。",- memory_not_correctable: "已删除的记忆不能修改。",- memory_deleted: "这条记忆已经删除。",- memory_superseded: "这条记忆已被更新的记忆取代,只能查看或删除。",- memory_nothing_to_undo: "没有更早的修改可以撤销。",- memory_evidence_not_found: "来源原话已不存在,无法建立这条记忆。",- memory_request_conflict: "这次操作与已完成的请求不一致。",- request_validation_failed: "输入内容不符合要求。",- local_store_unavailable: "本地记忆库正忙,请稍后重试。",+ "memory:记忆内容或使用权限已变化,回答已停止。请重新提问。",+ memory_source_revoked: "memory:这条记忆的来源授权已撤回,暂时不能读取。",+ memory_revision_conflict: "memory:记忆已被更新,请刷新后重试。",+ memory_not_correctable: "memory:已删除的记忆不能修改。",+ memory_deleted: "memory:这条记忆已经删除。",+ memory_superseded: "memory:这条记忆已被更新的记忆取代,只能查看或删除。",+ memory_nothing_to_undo: "memory:没有更早的修改可以撤销。",+ memory_evidence_not_found: "memory:来源原话已不存在,无法建立这条记忆。",+ memory_request_conflict: "memory:这次操作与已完成的请求不一致。",+ request_validation_failed: "memory:输入内容不符合要求。",+ local_store_unavailable: "memory:本地记忆库正忙,请稍后重试。",};- if (code && labels[code]) return labels[code];+ if (code && labels[code]) return t(labels[code]);// No code at all means the request never reached the core — usually because// it is still starting. Saying only "failed" left the one case that resolves// itself looking like the ones that do not.- if (code === null) return "还没连上本地 Core,正在重试…";- return `记忆操作失败(${code})`;+ if (code === null) return t("memory:还没连上本地 Core,正在重试…");+ return t("memory.operationFailed", { code });}function IndexSyncNotice({@@ -2341,14 +2493,17 @@ function IndexSyncNotice({onConfigureModel(): void;onRefresh(): void;}) {+ const { locale, t } = useGuiLanguage();const { attemptedLine, explanation, action } = indexSyncPresentation(sync,- clockStamp(sync.updated_at),+ clockStamp(sync.updated_at, locale),+ locale,);return (<p className="notice" role="status">- 搜索里还是改之前那句话。{explanation} <small>{attemptedLine}</small>+ {t("memory:搜索里还是改之前那句话。")}+ {explanation} <small>{attemptedLine}</small>{action === "retry" ? (<>{" "}@@ -2358,7 +2513,7 @@ function IndexSyncNotice({disabled={busy}onClick={onRetry}>- 重试同步+ {t("memory:重试同步")}</button></>) : null}@@ -2371,7 +2526,7 @@ function IndexSyncNotice({disabled={busy}onClick={onConfigureModel}>- 配置整理模型+ {t("memory:配置整理模型")}</button></>) : null}@@ -2384,7 +2539,7 @@ function IndexSyncNotice({disabled={busy}onClick={onRefresh}>- 刷新核对+ {t("memory:刷新核对")}</button></>) : null}@@ -2400,32 +2555,64 @@ function requestIdFor(requests: Map<string, string>, intent: string): string {return requestId;}-function kindLabel(kind: string) {- const labels: Record<string, string> = {- chat: "对话",- working: "项目记忆",- coding: "编码偏好",- schema: "长期模式",- intention: "意图",+function kindLabel(kind: string, t: Translate) {+ const labels: Record<string, Parameters<Translate>[0]> = {+ chat: "memory:对话",+ working: "memory:项目记忆",+ coding: "memory:编码偏好",+ schema: "memory:长期模式",+ intention: "memory:意图",};- return labels[kind] ?? kind;+ return labels[kind] ? t(labels[kind]) : kind;}-function bulkActionLabel(action: BulkAction): string {- const labels = { delete: "删除" };- return labels[action];+function bulkActionLabel(action: BulkAction, t: Translate): string {+ const labels = { delete: "memory:删除(操作)" } as const;+ return t(labels[action]);}-function statusLabel(status: string) {- const labels: Record<string, string> = {- confirmed: "已确认",- deleted: "已删除",- superseded: "已被取代",+function statusLabel(status: string, t: Translate) {+ const labels: Record<string, Parameters<Translate>[0]> = {+ confirmed: "memory:已确认",+ deleted: "memory:已删除",+ superseded: "memory:已被取代",};- return labels[status] ?? status;+ return labels[status] ? t(labels[status]) : status;}-function queueWaiting(processing: MemoryProcessingSummary): string {+function localizedMemoryProvenance(detail: MemoryDetail, t: Translate): string {+ const evidence = detail.evidence.filter((item) => item.available);+ if (+ evidence.length &&+ evidence.every((item) => item.source_id === "memory-content-export")+ ) {+ const authors = new Set(+ evidence.map((item) => item.written_by ?? "unknown"),+ );+ const author =+ authors.size !== 1+ ? t("provenance.multiple")+ : authors.has("person")+ ? t("provenance.person")+ : authors.has("agent")+ ? t("provenance.agent")+ : t("provenance.unknown");+ return t("provenance.imported", { author });+ }+ return detail.memory.origin === "manual"+ ? t("provenance.manual")+ : detail.memory.origin === "answered"+ ? t("provenance.answered")+ : detail.memory.origin === "agent"+ ? t("provenance.generated")+ : t("provenance.conversation");+}++function queueWaiting(+ processing: MemoryProcessingSummary,+ t: Translate,+ tn: TranslateCount,+): string {const fresh = processing.fresh_pending ?? 0;const backlog = processing.backlog_pending ?? 0;const active = processing.active_queue ?? 0;@@ -2435,22 +2622,31 @@ function queueWaiting(processing: MemoryProcessingSummary): string {const stranded = processing.stranded_running ?? 0;const activeSuffix =inFlight || active- ? ` · 处理中 ${inFlight} / 待派发 ${active}`+ ? t("memory: · 处理中 {running} / 待派发 {active}", {+ running: inFlight,+ active,+ }): strandedUnknown- ? ` · ${processing.running - inFlight} 条任务状态待核对`+ ? tn(+ "memory: · {count} 条任务状态待核对",+ processing.running - inFlight,+ ): stranded- ? ` · ${stranded} 条任务状态异常,正在恢复`+ ? tn("memory: · {count} 条任务状态异常,正在恢复", stranded): "";if (fresh + backlog === 0) {- return `${processing.pending} 等待${activeSuffix}`;+ return `${tn("memory:{count} 等待", processing.pending)}${activeSuffix}`;}if (backlog === 0) {- return `最新 ${fresh} 条待处理${activeSuffix}`;+ return `${tn("memory:最新 {count} 条待处理", fresh)}${activeSuffix}`;}if (fresh === 0) {- return `历史积压 ${backlog} 条${activeSuffix}`;+ return `${tn("memory:历史积压 {count} 条", backlog)}${activeSuffix}`;}- return `最新 ${fresh} 条待处理 · 历史积压 ${backlog} 条${activeSuffix}`;+ return `${tn("memory:最新 {count} 条待处理", fresh)} · ${tn(+ "memory:历史积压 {count} 条",+ backlog,+ )}${activeSuffix}`;}const EXTRACTION_WINDOW_PRESETS: ExtractionWindowPreset[] = [@@ -2473,6 +2669,7 @@ function ExtractionWindowControls({onError(value: string | null): void;onRefresh(): Promise<void>;}) {+ const { t } = useGuiLanguage();async function changeWindow(preset: ExtractionWindowPreset) {if (preset === processing.extraction_window_preset) return;onBusy(true);@@ -2488,7 +2685,7 @@ function ExtractionWindowControls({? "extraction_window_failed": "extraction_window_result_unknown",});- onError(message(reason));+ onError(message(reason, t));} finally {onBusy(false);}@@ -2508,7 +2705,7 @@ function ExtractionWindowControls({? "manual_extract_failed": "manual_extract_result_unknown",});- onError(message(reason));+ onError(message(reason, t));} finally {onBusy(false);}@@ -2517,7 +2714,7 @@ function ExtractionWindowControls({return (<div className="extraction-window-controls"><label>- 自动提炼范围+ {t("memory:自动提炼范围")}<selectvalue={processing.extraction_window_preset}disabled={busy}@@ -2527,7 +2724,11 @@ function ExtractionWindowControls({>{EXTRACTION_WINDOW_PRESETS.map((preset) => (<option key={preset} value={preset}>- {extractionWindowPresetLabel(preset)}+ {t(+ `memory:${extractionWindowPresetLabel(preset)}` as Parameters<+ typeof t+ >[0],+ )}</option>))}</select>@@ -2538,14 +2739,17 @@ function ExtractionWindowControls({disabled={busy}onClick={() => void extractNextBatch()}>- 手动提炼下一批+ {t("memory:手动提炼下一批")}</button>) : null}</div>);}-function queueEta(processing: MemoryProcessingSummary): string {+function queueEta(+ processing: MemoryProcessingSummary,+ tn: TranslateCount,+): string {// A local model handles one extraction at a time, so a long queue can mean// most of a day. Saying so is kinder than a bare count that looks stuck.const perTask = processing.seconds_per_completion;@@ -2554,10 +2758,13 @@ function queueEta(processing: MemoryProcessingSummary): string {}const hours = (processing.pending * perTask) / 3600;if (hours < 1) {- return `(约 ${Math.max(1, Math.round(hours * 60))} 分钟)`;+ return tn(+ "memory:(约 {count} 分钟)",+ Math.max(1, Math.round(hours * 60)),+ );}if (hours < 24) {- return `(约 ${Math.round(hours)} 小时)`;+ return tn("memory:(约 {count} 小时)", Math.round(hours));}- return `(约 ${Math.round(hours / 24)} 天)`;+ return tn("memory:(约 {count} 天)", Math.round(hours / 24));}diff --git a/memhub/apps/web/src/ModelSettings.test.tsx b/memhub/apps/web/src/ModelSettings.test.tsxindex 90e0254..b972fae 100644--- a/memhub/apps/web/src/ModelSettings.test.tsx+++ b/memhub/apps/web/src/ModelSettings.test.tsx@@ -13,7 +13,7 @@ import {import userEvent from "@testing-library/user-event";import { createRef, useState } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import {ModelSettings,type ModelSettingsActions,@@ -22,6 +22,45 @@ import {import type { PendingModelProbe } from "./pending-model-probe";import { PROVIDER_PRESETS } from "./provider-presets";+it("keeps the edited model draft and does not mutate on live language changes", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ profiles = [profile];+ const user = userEvent.setup();+ render(+ <LanguageProvider>+ <ModelSettings />+ </LanguageProvider>,+ );+ const field = await screen.findByLabelText(+ "Identificador del modelo de generación",+ );+ await user.type(field, "synthetic-model");+ const before = [+ create.mock.calls.length,+ update.mock.calls.length,+ activate.mock.calls.length,+ probeProfile.mock.calls.length,+ ];+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ await act(async () =>+ window.dispatchEvent(+ new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }),+ ),+ );+ expect(await screen.findByLabelText("生成模型名")).toHaveProperty(+ "value",+ "synthetic-model",+ );+ expect([+ create.mock.calls.length,+ update.mock.calls.length,+ activate.mock.calls.length,+ probeProfile.mock.calls.length,+ ]).toEqual(before);+ cleanup();+ localStorage.clear();+});+const create = vi.fn();const probeProfile = vi.fn();const activate = vi.fn();diff --git a/memhub/apps/web/src/ModelSettings.tsx b/memhub/apps/web/src/ModelSettings.tsxindex ac7675e..cd5fb4b 100644--- a/memhub/apps/web/src/ModelSettings.tsx+++ b/memhub/apps/web/src/ModelSettings.tsx@@ -17,6 +17,7 @@ import {useState,} from "react";import { OptionMenu } from "./OptionMenu";+import { useOnboardingTranslation } from "./onboarding-language";import { PROVIDER_PRESETS } from "./provider-presets";import { useModelProfiles } from "./use-model-profiles";import "./model-setup-next.css";@@ -231,6 +232,7 @@ export function ModelSettings({compactSingle?: boolean;onSetupComplete?(): void;} = {}) {+ const { text } = useOnboardingTranslation();const models = useModelProfiles();const [provider, setProvider] = useState<ProviderKind>("openai_compatible");const [providerPreset, setProviderPreset] = useState("custom");@@ -698,25 +700,28 @@ export function ModelSettings({<div className="section-heading"><div><p className="section-index">02</p>- <h2 id="models-title">记忆模型</h2>+ <h2 id="models-title">{text("记忆模型")}</h2></div><p>- 只需配置生成模型。向量嵌入已内置在本机,不为 System 1、System 2- 分开选模型。+ {text(+ "只需配置生成模型。向量嵌入已内置在本机,不为 System 1、System 2 分开选模型。",+ )}</p></div>{models.error ? (<p className="error-banner" role="alert">- {models.error}+ {text(models.error)}</p>) : null}{(models.pendingProbe || models.probeStorageFailed) && (<div role="status" className="model-refresh-notice"><p>- {models.probeStorageFailed- ? "无法读取测试恢复记录,暂不发送新的测试。"- : "上次模型测试结果待核对,暂不修改或启用配置。"}+ {text(+ models.probeStorageFailed+ ? "无法读取测试恢复记录,暂不发送新的测试。"+ : "上次模型测试结果待核对,暂不修改或启用配置。",+ )}</p>{models.pendingProbe && (<button@@ -731,7 +736,7 @@ export function ModelSettings({if (alive.current) onProfilesChanged?.();}}>- 核对测试结果+ {text("核对测试结果")}</button>)}</div>@@ -739,9 +744,11 @@ export function ModelSettings({{(models.pendingCreation || models.creationStorageFailed) && (<div role="status" className="model-refresh-notice"><p>- {models.creationMissing- ? "未找到上次创建记录。确认放弃旧记录后可重新配置;系统不会自动重试。"- : "上次模型创建结果待核对,暂不开始新的操作。"}+ {text(+ models.creationMissing+ ? "未找到上次创建记录。确认放弃旧记录后可重新配置;系统不会自动重试。"+ : "上次模型创建结果待核对,暂不开始新的操作。",+ )}</p><buttontype="button"@@ -757,7 +764,7 @@ export function ModelSettings({onProfilesChanged?.();}}>- 核对创建结果+ {text("核对创建结果")}</button>{models.pendingCreation && (<button@@ -771,26 +778,28 @@ export function ModelSettings({setSaveError(null);}}>- 放弃旧记录,重新配置+ {text("放弃旧记录,重新配置")}</button>)}</div>)}{setupPhase && (<p className="model-test-notice" role="status">- {setupPhase === "testing"- ? "配置已保存,正在测试连接…"- : "连接通过,正在启用模型…"}+ {text(+ setupPhase === "testing"+ ? "配置已保存,正在测试连接…"+ : "连接通过,正在启用模型…",+ )}</p>)}{setupError && (<p className="model-save-error" role="alert">- {setupError}+ {text(setupError)}</p>)}{models.refreshError && (<div className="model-refresh-notice" role="status">- <p>{models.refreshError}</p>+ <p>{text(models.refreshError)}</p><buttontype="button"className="secondary"@@ -798,7 +807,7 @@ export function ModelSettings({onClick={() => void models.refreshProfiles()}><RefreshCw size={16} aria-hidden="true" />- 刷新配置列表+ {text("刷新配置列表")}</button></div>)}@@ -837,7 +846,7 @@ export function ModelSettings({} else newProfile();}}>- 自定义一个模型+ {text("自定义一个模型")}</button></div>) : null}@@ -845,7 +854,7 @@ export function ModelSettings({{!compactSingle && savedProfile && (<articleclassName="model-saved-card"- aria-label="已保存的模型配置"+ aria-label={text("已保存的模型配置")}tabIndex={-1}ref={savedCard}data-tour-id="model-form"@@ -853,34 +862,37 @@ export function ModelSettings({<div className="model-saved-heading"><Check size={18} aria-hidden="true" /><strong>- {isReady(savedProfile) && savedProfile.is_active- ? "已保存,已启用"- : isReady(savedProfile)- ? "已保存,连接通过"- : models.probeFor(savedProfile)- ? "已保存,测试未通过"- : "已保存,待测试"}+ {text(+ isReady(savedProfile) && savedProfile.is_active+ ? "已保存,已启用"+ : isReady(savedProfile)+ ? "已保存,连接通过"+ : models.probeFor(savedProfile)+ ? "已保存,测试未通过"+ : "已保存,待测试",+ )}</strong></div><h3>{savedProfile.name}</h3><p>- {savedProfile.model} · {endpointLabel(savedProfile.base_url)} · 版本{" "}- {savedProfile.revision}+ {savedProfile.model} · {text(endpointLabel(savedProfile.base_url))}{" "}+ · {text("版本")} {savedProfile.revision}</p>{savedProfile.credential_state === "unavailable" && (<p role="status">- 需要允许 MemHub- 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。+ {text(+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。",+ )}</p>)}- <p>测试只向此接口发送测试内容,不发送历史对话。</p>+ <p>{text("测试只向此接口发送测试内容,不发送历史对话。")}</p><div className="source-actions"><buttontype="button"disabled={locked}onClick={() => void resumeSetup(savedProfile)}>- {setupError ? "重试测试并启用" : "测试并启用"}+ {text(setupError ? "重试测试并启用" : "测试并启用")}</button><buttontype="button"@@ -889,7 +901,7 @@ export function ModelSettings({onClick={() => editProfile(savedProfile)}><Pencil size={16} aria-hidden="true" />- 编辑配置+ {text("编辑配置")}</button><buttontype="button"@@ -898,7 +910,7 @@ export function ModelSettings({onClick={newProfile}><Plus size={16} aria-hidden="true" />- 新增配置+ {text("新增配置")}</button></div><ProbeFeedback@@ -920,18 +932,20 @@ export function ModelSettings({>{editing && (<p className="model-test-notice">- 编辑 {editing.name} · 版本 {editing.revision}- 。修改后需重新测试并设为当前模型,内容授权不会自动更新。+ {text("编辑")} {editing.name} · {text("版本")} {editing.revision}+ {text("。修改后需重新测试并设为当前模型,内容授权不会自动更新。")}</p>)}{editChanged && (<p role="alert" className="model-save-error">- 配置已在其他位置变化,草稿已保留。请取消编辑后重新打开核对。+ {text(+ "配置已在其他位置变化,草稿已保留。请取消编辑后重新打开核对。",+ )}</p>)}{saveError && (<p className="model-save-error" role="alert">- {saveError}+ {text(saveError)}</p>)}{unknownCreation && !editing && (@@ -940,13 +954,13 @@ export function ModelSettings({disabled={formLocked}onClick={() => void models.refreshProfiles()}>- 刷新配置列表+ {text("刷新配置列表")}</button>)}<div className="model-form-field">- 服务商预设+ {text("服务商预设")}<OptionMenu- ariaLabel="服务商预设"+ ariaLabel={text("服务商预设")}describedBy="model-preset-help"value={providerPreset}disabled={formLocked}@@ -955,7 +969,7 @@ export function ModelSettings({value: item.id,label: item.label,})),- { value: "custom", label: "自定义兼容服务" },+ { value: "custom", label: text("自定义兼容服务") },]}onChange={(value) => {const next = PROVIDER_PRESETS.find((item) => item.id === value);@@ -977,15 +991,16 @@ export function ModelSettings({}}/><small id="model-preset-help">- 只是帮你填好接口地址和一个模型名,不代表这个模型当前可用。- 请对照服务商的模型列表核对后再保存。+ {text(+ "只是帮你填好接口地址和一个模型名,不代表这个模型当前可用。 请对照服务商的模型列表核对后再保存。",+ )}</small></div><label>- 协议+ {text("协议")}<selectname="provider"- aria-label="协议"+ aria-label={text("协议")}aria-describedby="model-provider-help"value={provider}disabled={formLocked}@@ -1001,19 +1016,19 @@ export function ModelSettings({* the reader parse a parenthesis to find out they were dead. */}{PROVIDERS.filter((item) => item.activatable).map((item) => (<option key={item.kind} value={item.kind}>- {item.label}+ {text(item.label)}</option>))}</select><small id="model-provider-help">- 与模型服务提供的接口协议保持一致。+ {text("与模型服务提供的接口协议保持一致。")}</small></label><label>- 配置名称+ {text("配置名称")}<inputname="name"- aria-label="配置名称"+ aria-label={text("配置名称")}aria-describedby="model-name-help"autoComplete="off"maxLength={128}@@ -1024,13 +1039,15 @@ export function ModelSettings({setName(event.target.value);}}/>- <small id="model-name-help">用于区分配置,不影响模型请求。</small>+ <small id="model-name-help">+ {text("用于区分配置,不影响模型请求。")}+ </small></label><label>- 生成模型名+ {text("生成模型名")}<inputname="model"- aria-label="生成模型名"+ aria-label={text("生成模型名")}aria-describedby={`model-identifier-help${fields.model ? " model-field-error" : ""}`}aria-invalid={!!fields.model}autoComplete="off"@@ -1043,14 +1060,14 @@ export function ModelSettings({setProviderPreset("custom");if (!nameEdited) setName(suggestedName(event.target.value));}}- placeholder="例如:gpt-4o-mini…"+ placeholder={text("例如:gpt-4o-mini…")}/><small id="model-identifier-help">- 填写服务方提供的完整模型标识。+ {text("填写服务方提供的完整模型标识。")}</small>{fields.model && (<small id="model-field-error" className="model-field-error">- {fields.model}+ {text(fields.model)}</small>)}</label>@@ -1063,12 +1080,12 @@ export function ModelSettings({disabled={formLocked}onClick={() => setAdvancedEmbedding(!advancedEmbedding)}>- 高级:自行配置向量模型+ {text("高级:自行配置向量模型")}</button>{advancedEmbedding ? (<><label>- 向量配置模式+ {text("向量配置模式")}<selectname="embedding-mode"value={embeddingMode}@@ -1085,14 +1102,14 @@ export function ModelSettings({}));}}>- <option value="local">本地内置</option>- <option value="custom">自定义向量模型</option>+ <option value="local">{text("本地内置")}</option>+ <option value="custom">{text("自定义向量模型")}</option></select></label>{embeddingMode === "custom" ? (<><label>- 向量模型名+ {text("向量模型名")}<inputname="embedding-model"autoComplete="off"@@ -1109,19 +1126,19 @@ export function ModelSettings({onChange={(event) =>setEmbeddingModel(event.target.value)}- placeholder="例如:text-embedding-3-small…"+ placeholder={text("例如:text-embedding-3-small…")}/>{fields["embedding-model"] && (<smallid="model-embedding-error"className="model-field-error">- {fields["embedding-model"]}+ {text(fields["embedding-model"])}</small>)}</label><label>- 向量模型来源+ {text("向量模型来源")}<selectname="embedding-provider"value={embeddingProvider}@@ -1133,14 +1150,14 @@ export function ModelSettings({setEmbeddingProvider(next);}}>- <option value="ollama">本机 Ollama</option>+ <option value="ollama">{text("本机 Ollama")}</option><option value="openai_compatible">- 同源 OpenAI-compatible(共用 API Key)+ {text("同源 OpenAI-compatible(共用 API Key)")}</option></select></label><label>- 向量模型 Base URL+ {text("向量模型 Base URL")}<inputname="embedding-base-url"type="url"@@ -1169,27 +1186,27 @@ export function ModelSettings({id="model-embedding-url-error"className="model-field-error">- {fields["embedding-base-url"]}+ {text(fields["embedding-base-url"])}</small>)}</label>{embeddingProvider === "openai_compatible" ? (<small>- 为避免凭据外泄,向量地址必须与生成模型同源。+ {text("为避免凭据外泄,向量地址必须与生成模型同源。")}</small>) : null}</>) : (<small>- 使用内置本地向量模型;不会发送内容给远程向量服务。+ {text("使用内置本地向量模型;不会发送内容给远程向量服务。")}</small>)}</>) : null}{!advancedEmbedding && embeddingMode === "custom" ? (<p className="model-help">- 自定义向量:{embeddingModel || "尚未填写模型"} ·{" "}- {embeddingBaseUrl || "尚未填写地址"}+ {text("自定义向量")}: {embeddingModel || text("尚未填写模型")} ·{" "}+ {embeddingBaseUrl || text("尚未填写地址")}</p>) : null}</div>@@ -1212,19 +1229,19 @@ export function ModelSettings({}}/><small id="model-url-help">- 填写服务接口地址,不是聊天网页地址。+ {text("填写服务接口地址,不是聊天网页地址。")}</small>{fields["base-url"] && (<small id="model-url-error" className="model-field-error">- {fields["base-url"]}+ {text(fields["base-url"])}</small>)}</label><label>- API Key{keyRequired ? "" : "(可选)"}+ API Key{keyRequired ? "" : text("(可选)")}<inputname="api-key"- aria-label={`API Key${keyRequired ? "" : "(可选)"}`}+ aria-label={`API Key${keyRequired ? "" : text("(可选)")}`}aria-describedby={`model-key-help${fields["api-key"] ? " model-key-error" : ""}`}aria-invalid={!!fields["api-key"]}type="password"@@ -1233,18 +1250,20 @@ export function ModelSettings({value={apiKey}disabled={formLocked}onChange={(event) => setApiKey(event.target.value)}- placeholder="保存后不会再次显示…"+ placeholder={text("保存后不会再次显示…")}/><small id="model-key-help">- {editing && !endpointMoved- ? "留空保留已保存密钥;填写新密钥后需重新测试和启用。"- : editing && keyRequired- ? "换了服务商后需要填写新的 API Key,已保存的密钥不会带到新地址。"- : "保存在系统安全存储中,不随安装包分发。"}+ {text(+ editing && !endpointMoved+ ? "留空保留已保存密钥;填写新密钥后需重新测试和启用。"+ : editing && keyRequired+ ? "换了服务商后需要填写新的 API Key,已保存的密钥不会带到新地址。"+ : "保存在系统安全存储中,不随安装包分发。",+ )}</small>{fields["api-key"] && (<small id="model-key-error" className="model-field-error">- {fields["api-key"]}+ {text(fields["api-key"])}</small>)}</label>@@ -1256,7 +1275,7 @@ export function ModelSettings({disabled={formLocked}onChange={(event) => setDisableThinking(event.target.checked)}/>- 关闭思考链(向支持的厂商下发 thinking-off 参数)+ {text("关闭思考链(向支持的厂商下发 thinking-off 参数)")}</label><div className="form-submit">{!compactSingle && (@@ -1266,7 +1285,7 @@ export function ModelSettings({locked || editChanged || (!editing && unknownCreation)}>- {editing ? "保存修改" : "保存配置"}+ {text(editing ? "保存修改" : "保存配置")}</button>)}<button@@ -1274,13 +1293,15 @@ export function ModelSettings({disabled={locked || editChanged || (!editing && unknownCreation)}onClick={() => void persist(true)}>- {setupPhase === "testing"- ? "正在测试连接…"- : setupPhase === "activating"- ? "正在启用配置…"- : compactSingle- ? "测试并完成配置"- : "保存并测试启用"}+ {text(+ setupPhase === "testing"+ ? "正在测试连接…"+ : setupPhase === "activating"+ ? "正在启用配置…"+ : compactSingle+ ? "测试并完成配置"+ : "保存并测试启用",+ )}</button>{editing && (<button@@ -1295,10 +1316,12 @@ export function ModelSettings({setFields({});}}>- 取消编辑+ {text("取消编辑")}</button>)}- <small>密钥保存在系统安全存储;测试仅发送测试内容。</small>+ <small>+ {text("密钥保存在系统安全存储;测试仅发送测试内容。")}+ </small></div></form>) : null}@@ -1315,14 +1338,16 @@ export function ModelSettings({<article key={profile.profile_id} className="profile-row">{profile.credential_state === "unavailable" && (<p className="error-banner" role="status">- 需要允许 MemHub- 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。+ {text(+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。",+ )}</p>)}<div><strong>{profile.name}</strong><p>- {providerLabel(profile.provider_kind)} · {profile.model} ·+ {text(providerLabel(profile.provider_kind))} ·{" "}+ {profile.model} ·{/* Core fills in the built-in vector model on every profile,* so printing it unconditionally put a line about* bge-small-zh-v1.5 under a profile whose owner never chose@@ -1331,17 +1356,17 @@ export function ModelSettings({{profile.embedding_model &&profile.embedding_provider_kind &&profile.embedding_provider_kind !== BUILTIN_EMBEDDING_KIND- ? ` 向量: ${profile.embedding_model} (${providerLabel(- profile.embedding_provider_kind,+ ? ` ${text("自定义向量")}: ${profile.embedding_model} (${text(+ providerLabel(profile.embedding_provider_kind),)}) ·`: ""}{" "}revision {profile.revision}</p></div>- <span>{profile.is_active ? "当前使用" : "未启用"}</span>+ <span>{text(profile.is_active ? "当前使用" : "未启用")}</span><p className="model-test-notice">- 测试目标:{endpointLabel(profile.base_url)}- 。仅发送测试内容,不发送历史对话。+ {text("测试目标")}: {text(endpointLabel(profile.base_url))}+ {text("。仅发送测试内容,不发送历史对话。")}</p><div className="source-actions"><button@@ -1349,7 +1374,7 @@ export function ModelSettings({disabled={locked}onClick={() => void resumeSetup(profile)}>- {setupError ? "重试测试并启用" : "测试并启用"}+ {text(setupError ? "重试测试并启用" : "测试并启用")}</button><buttontype="button"@@ -1358,7 +1383,7 @@ export function ModelSettings({onClick={() => editProfile(profile)}><Pencil size={16} aria-hidden="true" />- 编辑配置+ {text("编辑配置")}</button><buttontype="button"@@ -1366,7 +1391,7 @@ export function ModelSettings({disabled={locked}onClick={() => models.probeProfile(profile.profile_id)}>- 测试连接+ {text("测试连接")}</button>{!profile.is_active ? (<>@@ -1375,7 +1400,7 @@ export function ModelSettings({disabled={locked || !isReady(profile)}onClick={() => models.activate(profile.profile_id)}>- 设为当前模型+ {text("设为当前模型")}</button><buttontype="button"@@ -1383,7 +1408,7 @@ export function ModelSettings({disabled={locked}onClick={() => models.remove(profile.profile_id)}>- 删除+ {text("删除")}</button></>) : null}@@ -1435,6 +1460,7 @@ function PresetProfileCard({probe: ModelProbeResult | null;probeError: string | null;}) {+ const { text } = useOnboardingTranslation();const [key, setKey] = useState("");const [error, setError] = useState<string | null>(null);const [saving, setSaving] = useState(false);@@ -1483,21 +1509,25 @@ function PresetProfileCard({<section className="preset-profile" aria-label={profile.name}><div><strong>{profile.name}</strong>- <p>{presetStatus(profile)}</p>+ <p>{text(presetStatus(profile))}</p></div>{discloseRecipients && (<p>- 生成接收方:{endpointLabel(profile.base_url)};向量接收方:+ {text("生成接收方")}: {text(endpointLabel(profile.base_url))};{" "}+ {text("向量接收方")}:{profile.embedding_provider_kind === BUILTIN_EMBEDDING_KIND- ? "本机"- : endpointLabel(profile.embedding_base_url ?? profile.base_url)}- 。启用此配置后按上方选择处理历史及未来允许来源。+ ? text("本机")+ : text(+ endpointLabel(profile.embedding_base_url ?? profile.base_url),+ )}+ {text("。启用此配置后按上方选择处理历史及未来允许来源。")}</p>)}{profile.credential_state === "unavailable" && (<p role="status">- 需要允许 MemHub- 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。+ {text(+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。",+ )}</p>)}{profile.has_api_key ? null : (@@ -1511,7 +1541,7 @@ function PresetProfileCard({noValidate><label>- {keyLabel}+ {text(keyLabel)}<inputname="preset-api-key"type="password"@@ -1524,7 +1554,7 @@ function PresetProfileCard({}value={key}onChange={(event) => setKey(event.target.value)}- placeholder="保存后不会再次显示…"+ placeholder={text("保存后不会再次显示…")}/>{error && (<small@@ -1532,12 +1562,12 @@ function PresetProfileCard({className="model-field-error"role="alert">- {error}+ {text(error)}</small>)}</label><button type="submit" disabled={busy || saving}>- 保存 key+ {text("保存 key")}</button><buttontype="button"@@ -1545,11 +1575,11 @@ function PresetProfileCard({disabled={busy || saving || !canEnable}onClick={() => void save(true)}>- 保存并测试启用+ {text("保存并测试启用")}</button>{applyHref ? (<a href={applyHref} target="_blank" rel="noreferrer">- 还没有 key?去申请+ {text("还没有 key?去申请")}</a>) : null}</form>@@ -1562,21 +1592,21 @@ function PresetProfileCard({disabled={busy || !canEnable}onClick={onContinue}>- 测试并启用+ {text("测试并启用")}</button><p className="model-test-notice">- 测试目标:{endpointLabel(profile.base_url)}- 。仅发送测试内容,不发送历史对话。+ {text("测试目标")}: {text(endpointLabel(profile.base_url))}+ {text("。仅发送测试内容,不发送历史对话。")}</p><button type="button" disabled={busy} onClick={onTest}>- 测试连接+ {text("测试连接")}</button><buttontype="button"disabled={busy || !canEnable || !ready(profile, probe, probeError)}onClick={onActivate}>- 设为当前模型+ {text("设为当前模型")}</button><buttontype="button"@@ -1584,7 +1614,7 @@ function PresetProfileCard({disabled={busy}onClick={onRemove}>- 删除+ {text("删除")}</button></div>) : null}@@ -1601,7 +1631,7 @@ function PresetProfileCard({disabled={busy}onClick={onRemove}>- 删除这张卡+ {text("删除这张卡")}</button></div>)}@@ -1639,6 +1669,7 @@ function ProbeFeedback({result: ModelProbeResult | null;error: string | null;}) {+ const { text } = useOnboardingTranslation();const matching =result?.profile_id === profile.profile_id &&result.profile_revision === profile.revision@@ -1648,20 +1679,22 @@ function ProbeFeedback({return (<sectionclassName="probe-result"- aria-label={`${profile.name} 版本 ${profile.revision} 测试结果`}+ aria-label={`${profile.name} ${text("版本")} ${profile.revision} ${text("测试结果")}`}><strong>- {profile.name} · 版本 {profile.revision} · 连接测试+ {profile.name} · {text("版本")} {profile.revision} · {text("测试连接")}</strong><p>- 测试目标:{endpointLabel(profile.base_url)} · {profile.model}+ {text("测试目标")}: {text(endpointLabel(profile.base_url))} ·{" "}+ {profile.model}</p>- {error && <p role="alert">{error}</p>}+ {error && <p role="alert">{text(error)}</p>}{matching && (<ul>{matching.stages.map((stage) => (<li key={stage.stage}>- {stage.stage}: {probeLabel(stage.code)} · {stage.latency_ms}ms+ {stage.stage}: {text(probeLabel(stage.code))} · {stage.latency_ms}+ ms</li>))}</ul>diff --git a/memhub/apps/web/src/ModelUsageView.tsx b/memhub/apps/web/src/ModelUsageView.tsxindex 469a6ea..c124cb9 100644--- a/memhub/apps/web/src/ModelUsageView.tsx+++ b/memhub/apps/web/src/ModelUsageView.tsx@@ -1,16 +1,18 @@+import type { MessageKey } from "@one-memory/i18n";import { useCallback, useEffect, useMemo, useState } from "react";import {getModelUsage,type ModelUsageMinute,type ModelUsageReport,} from "./api";+import { useGuiLanguage } from "./gui-language";-const RANGES = [- { minutes: 15, label: "最近 15 分钟" },- { minutes: 60, label: "最近 1 小时" },- { minutes: 360, label: "最近 6 小时" },- { minutes: 1_440, label: "最近 24 小时" },- { minutes: 10_080, label: "最近 7 天" },+const RANGES: { minutes: number; label: MessageKey }[] = [+ { minutes: 15, label: "usageRange15m" },+ { minutes: 60, label: "usageRange1h" },+ { minutes: 360, label: "usageRange6h" },+ { minutes: 1_440, label: "usageRange24h" },+ { minutes: 10_080, label: "usageRange7d" },];const STAGE_LABELS: Record<string, string> = {@@ -41,6 +43,7 @@ interface ModelUsageViewProps {}export function ModelUsageView({ live, refreshToken }: ModelUsageViewProps) {+ const { t, tnPlain } = useGuiLanguage();const [rangeMinutes, setRangeMinutes] = useState(60);const [report, setReport] = useState<ModelUsageReport | null>(null);const [state, setState] = useState<"loading" | "ready" | "error">("loading");@@ -76,33 +79,33 @@ export function ModelUsageView({ live, refreshToken }: ModelUsageViewProps) {<div className="model-usage-view"><div className="model-usage-toolbar"><label>- <span>时间范围</span>+ <span>{t("usageRange")}</span><select- aria-label="模型用量时间范围"+ aria-label={t("usageRangeLabel")}value={rangeMinutes}onChange={(event) => setRangeMinutes(Number(event.target.value))}>{RANGES.map((range) => (<option key={range.minutes} value={range.minutes}>- {range.label}+ {t(range.label)}</option>))}</select></label><span className={`model-usage-state state-${state}`}>{state === "loading"- ? "正在读取…"+ ? t("usageLoading"): state === "error"- ? "读取失败"+ ? t("usageReadError"): live- ? "每 5 秒刷新"- : "已暂停"}+ ? t("usageLive")+ : t("debugPaused")}</span></div><div className="model-usage-metrics"><Metric- label="总 Tokens"+ label={t("usageTotalTokens")}value={formatTokens(report?.summary.total_tokens)}/><Metric@@ -114,26 +117,26 @@ export function ModelUsageView({ live, refreshToken }: ModelUsageViewProps) {value={formatTokens(report?.summary.avg_completion_tokens)}/><Metric- label="请求数"+ label={t("usageRequests")}value={String(report?.summary.request_count ?? 0)}/></div><sectionclassName="model-usage-chart-card"- aria-label="各 Prompt 每分钟 Token 曲线"+ aria-label={t("usageChartRegion")}><div className="model-usage-section-title">- <strong>各 Prompt 花费曲线</strong>- <span>每分钟 · Total Tokens</span>+ <strong>{t("usageChartTitle")}</strong>+ <span>{t("usageChartSubtitle")}</span></div><UsageChart rows={report?.by_minute ?? []} /></section><section className="model-usage-stage-card"><div className="model-usage-section-title">- <strong>Prompt 明细</strong>- <span>当前时间范围</span>+ <strong>{t("usageBreakdown")}</strong>+ <span>{t("usageCurrentRange")}</span></div><div className="model-usage-stage-list">{stages.length ? (@@ -141,14 +144,14 @@ export function ModelUsageView({ live, refreshToken }: ModelUsageViewProps) {<div className="model-usage-stage-row" key={stage.name}><i style={{ background: stageColor(stage.name) }} /><strong>{stageLabel(stage.name)}</strong>- <span>{stage.requests} 次</span>+ <span>{tnPlain("usageRequestCount", stage.requests)}</span><span>Prompt {formatTokens(stage.prompt)}</span><span>Completion {formatTokens(stage.completion)}</span><b>{formatTokens(stage.total)}</b></div>))) : (- <p className="debug-log-empty">这个时间范围内没有沉淀模型调用</p>+ <p className="debug-log-empty">{t("usageEmpty")}</p>)}</div></section>@@ -166,6 +169,7 @@ function Metric({ label, value }: { label: string; value: string }) {}function UsageChart({ rows }: { rows: ModelUsageMinute[] }) {+ const { t } = useGuiLanguage();const minutes = [...new Set(rows.map((row) => row.minute))].sort();const stages = [...new Set(rows.map((row) => row.prompt_stage))].sort();const width = 640;@@ -189,7 +193,7 @@ function UsageChart({ rows }: { rows: ModelUsageMinute[] }) {pad.top + plotHeight - (value / max) * plotHeight;if (!rows.length)- return <div className="model-usage-chart-empty">暂无曲线数据</div>;+ return <div className="model-usage-chart-empty">{t("usageNoChart")}</div>;return (<>@@ -197,7 +201,7 @@ function UsageChart({ rows }: { rows: ModelUsageMinute[] }) {className="model-usage-chart"viewBox={`0 0 ${width} ${height}`}role="img"- aria-label="按分钟显示各 Prompt 的 Token 花费"+ aria-label={t("usageChartAria")}>{[0, 0.5, 1].map((ratio) => (<g key={ratio}>diff --git a/memhub/apps/web/src/OnboardingFlow.language.test.tsx b/memhub/apps/web/src/OnboardingFlow.language.test.tsxnew file mode 100644index 0000000..50db9b8--- /dev/null+++ b/memhub/apps/web/src/OnboardingFlow.language.test.tsx@@ -0,0 +1,492 @@+// @vitest-environment jsdom+import type { ImportJob, SourceResponse } from "@one-memory/contracts";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { completeOnboarding } from "./api";+import { FirstImportReview } from "./FirstImportReview";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";+import { OnboardingFlow } from "./OnboardingFlow";+import { OnboardingModelController } from "./OnboardingModelController";+import { R6ImportProgress } from "./R6ImportProgress";+import type { ImportSourcesController } from "./use-import-sources";++vi.mock("./api", () => ({+ completeOnboarding: vi.fn(),+ getModelProfiles: vi.fn(),+}));+const models = {+ pendingProbe: false,+ probeStorageFailed: false,+ pendingCreation: false,+ creationStorageFailed: false,+ error: null,+ create: vi.fn(),+ update: vi.fn(),+ probeProfile: vi.fn(),+ activate: vi.fn(),+};+vi.mock("./use-model-profiles", () => ({ useModelProfiles: () => models }));+const source: SourceResponse = {+ source_id: "cursor",+ display_name: "Cursor",+ available: true,+ authorized: false,+ detected: false,+ storage_kinds: ["jsonl"],+ root_label: null,+ candidate_path: "/fixture/cursor",+ candidate_kind: "default",+ candidate_root_id: "fixture-root",+ location_state: "found",+ imported_messages: 0,+ imported_conversations: 0,+ sync_enabled: false,+ sync_completeness: "additions_only",+ capabilities: {+ historical_import: "implemented",+ incremental_import: "implemented",+ live_sync: "not_implemented",+ recall: "not_implemented",+ installer: "not_implemented",+ verification: "fixture_only",+ },+};+function controller(overrides: Partial<SourceResponse> = {}) {+ const sources = [{ ...source, ...overrides }];+ return {+ sources,+ jobs: [],+ loading: false,+ refresh: vi.fn().mockResolvedValue({ sources, jobs: [], health: null }),+ connectForOnboarding: vi.fn(),+ detect: vi.fn(),+ } as unknown as ImportSourcesController;+}+function SwitchLanguage() {+ const { setPreference } = useGuiLanguage();+ return (+ <button type="button" onClick={() => void setPreference("zh-CN")}>+ 中文+ </button>+ );+}+const state = {+ status: "not_started" as const,+ selected_source_ids: [],+ started_at: null,+ completed_at: null,+};+beforeEach(() => {+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ vi.clearAllMocks();+});+afterEach(() => {+ cleanup();+ localStorage.clear();+ delete window.oneMemory;+});++it("changes the first-screen language without losing source choices or starting an import", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ const imports = controller();+ const finish = vi.fn();+ const user = userEvent.setup();+ render(+ <LanguageProvider>+ <OnboardingFlow state={state} imports={imports} onFinish={finish} />+ </LanguageProvider>,+ );+ const selector = screen.getByRole("combobox", { name: "界面语言" });+ await waitFor(() =>+ expect(screen.getByLabelText("导入 Cursor 历史")).toHaveProperty(+ "checked",+ true,+ ),+ );+ await user.click(screen.getByLabelText("导入 Cursor 历史"));+ await user.selectOptions(selector, "es");+ expect(screen.getByRole("combobox", { name: "Idioma de la interfaz" })).toBe(+ selector,+ );+ expect(+ screen.getByLabelText("Importar el historial de Cursor"),+ ).toHaveProperty("checked", false);+ await user.click(screen.getByLabelText("Importar el historial de Cursor"));+ await user.selectOptions(selector, "zh-CN");+ expect(screen.getByLabelText("导入 Cursor 历史")).toHaveProperty(+ "checked",+ true,+ );+ expect(imports.refresh).toHaveBeenCalledOnce();+ expect(imports.connectForOnboarding).not.toHaveBeenCalled();+ expect(imports.detect).not.toHaveBeenCalled();+ expect(completeOnboarding).not.toHaveBeenCalled();+ expect(finish).not.toHaveBeenCalled();+});++it("translates discovery, progress and privacy without importing or authorizing on language changes", async () => {+ const imports = controller();+ render(+ <LanguageProvider>+ <SwitchLanguage />+ <OnboardingFlow state={state} imports={imports} onFinish={vi.fn()} />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("heading", {+ name: "Trae aquí el contexto que ya tienes",+ }),+ ).toBeTruthy();+ await waitFor(() =>+ expect(+ screen.getByLabelText<HTMLInputElement>("Importar el historial de Cursor")+ .checked,+ ).toBe(true),+ );+ expect(+ screen.getByRole("navigation", {+ name: "Progreso de la configuración inicial",+ }),+ ).toBeTruthy();+ expect(+ screen.getByText(+ "Antes de confirmar, solo se comprueba la información de las aplicaciones. No se leen conversaciones ni se instalan conexiones.",+ ),+ ).toBeTruthy();+ expect(+ screen.getByText("/fixture/cursor · Ubicación predeterminada"),+ ).toBeTruthy();+ fireEvent.click(screen.getByText("中文"));+ await screen.findByRole("heading", { name: "把熟悉的背景,带到这里" });+ expect(+ screen.getByLabelText<HTMLInputElement>("导入 Cursor 历史").checked,+ ).toBe(true);+ expect(imports.refresh).toHaveBeenCalledTimes(1);+ expect(imports.connectForOnboarding).not.toHaveBeenCalled();+ expect(imports.detect).not.toHaveBeenCalled();+});+it("translates stored discovery errors live without repeating discovery", async () => {+ const imports = controller();+ vi.mocked(imports.refresh).mockRejectedValue(new Error("fixture-offline"));+ render(+ <LanguageProvider>+ <SwitchLanguage />+ <OnboardingFlow state={state} imports={imports} onFinish={vi.fn()} />+ </LanguageProvider>,+ );+ await waitFor(() =>+ expect(screen.getByRole("alert").textContent).toContain(+ "No se completó la detección",+ ),+ );+ fireEvent.click(screen.getByText("中文"));+ await waitFor(() =>+ expect(screen.getByRole("alert").textContent).toContain("位置检测未完成"),+ );+ expect(imports.refresh).toHaveBeenCalledTimes(1);+});+it("translates custom-location consent without granting access", async () => {+ const imports = controller({ candidate_kind: "environment_override" });+ render(+ <LanguageProvider>+ <OnboardingFlow state={state} imports={imports} onFinish={vi.fn()} />+ </LanguageProvider>,+ );+ await waitFor(() =>+ expect(+ screen.getByLabelText("Importar el historial de Cursor"),+ ).toHaveProperty("disabled", false),+ );+ fireEvent.click(screen.getByLabelText("Importar el historial de Cursor"));+ expect(+ screen.getByRole("dialog", { name: "Confirmar ubicación personalizada" }),+ ).toBeTruthy();+ expect(+ screen.getByLabelText(+ "Confirmo que esta es la ubicación del historial de Cursor",+ ),+ ).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Cancelar" }));+ expect(imports.connectForOnboarding).not.toHaveBeenCalled();+});+it("translates import review and preserves independent permission disclosure", async () => {+ const change = vi.fn();+ render(+ <LanguageProvider>+ <FirstImportReview+ sources={[{ ...source, authorized: true }]}+ sourceIds={[source.source_id]}+ jobs={[]}+ onContinue={change}+ />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("heading", {+ name: "Tus conversaciones llegan; tus memorias empiezan aquí",+ }),+ ).toBeTruthy();+ expect(+ screen.getByText(+ "Importar no concede automáticamente acceso de lectura a las aplicaciones. Las memorias comenzarán a generarse cuando configures un modelo.",+ ),+ ).toBeTruthy();+ expect(+ screen.getByRole("region", {+ name: "Progreso de importación de las aplicaciones",+ }),+ ).toBeTruthy();+ expect(change).not.toHaveBeenCalled();+});+it("uses compact Spanish actions and preserves Chinese copy and permissions", async () => {+ const next = vi.fn();+ const draft = vi.fn();+ render(+ <LanguageProvider>+ <SwitchLanguage />+ <FirstImportReview+ sources={[{ ...source, authorized: true }]}+ sourceIds={[source.source_id]}+ jobs={[]}+ connectionDraft={{ hostSourceIds: [] }}+ onConnectionDraftChange={draft}+ onContinue={next}+ />+ </LanguageProvider>,+ );+ const navigation = screen.getByRole("navigation");+ expect(navigation.textContent).toContain("Conectar apps");+ expect(+ screen.getByRole("button", {+ name: "Configurar un modelo para crear memorias",+ }),+ ).toBeTruthy();+ expect(screen.getByText(/Importar no concede automáticamente/)).toBeTruthy();+ expect(+ screen.getByText(/Solo para las apps seleccionadas y compatibles/),+ ).toBeTruthy();+ expect(screen.getByText(/Si una falla, las demás siguen/)).toBeTruthy();+ fireEvent.click(screen.getByText("中文"));+ expect(+ screen.getByRole("button", { name: "配置模型,沉淀记忆" }),+ ).toBeTruthy();+ expect(navigation.textContent).toContain("连接应用");+ expect(screen.getByText(/不会自动开放应用读取权限/)).toBeTruthy();+ expect(next).not.toHaveBeenCalled();+ expect(draft).not.toHaveBeenCalled();+});+it.each([+ ["pending", "Importando"],+ ["running", "Importando"],+ ["paused", "En pausa"],+ ["interrupted", "Interrumpida"],+ ["failed", "Problema de importación"],+ ["cancelled", "Cancelada"],+ ["completed", "Importación completada"],+] as const)(+ "translates %s progress receipts without changing counts",+ async (status, label) => {+ const job = {+ job_id: "fixture-job",+ source_id: "cursor",+ status,+ stored: 17,+ errors: 2,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:01:00Z",+ } as ImportJob;+ render(+ <LanguageProvider>+ <R6ImportProgress+ sourceIds={["cursor"]}+ sources={[{ ...source, authorized: true }]}+ jobs={[job]}+ />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("article", {+ name: "Progreso de importación de Cursor",+ }),+ ).toBeTruthy();+ expect(screen.getByText("Mensajes guardados: 17")).toBeTruthy();+ expect(screen.getByRole("status").textContent).toBe(+ `${label} · Errores de lectura: 2`,+ );+ },+);+it.each(["es", "zh-CN"] as const)(+ "preserves three multiline progress cards and receipt statuses in %s",+ (locale) => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, locale);+ const sources = ["cursor", "claude-code", "codex"].map((id, i) => ({+ ...source,+ source_id: id,+ display_name: `${locale === "es" ? "Aplicación con nombre largo" : "名称较长的应用"} ${i + 1}`,+ authorized: true,+ }));+ const jobs = sources.map((item, i) => ({+ job_id: `fixture-${i}`,+ source_id: item.source_id,+ status: ["completed", "failed", "paused"][i],+ stored: 12345,+ errors: i,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:01:00Z",+ })) as ImportJob[];+ render(+ <LanguageProvider>+ <R6ImportProgress+ sourceIds={sources.map((item) => item.source_id)}+ sources={sources}+ jobs={jobs}+ />+ </LanguageProvider>,+ );+ expect(screen.getAllByRole("article")).toHaveLength(3);+ const statuses = screen+ .getAllByRole("status")+ .map((item) => item.textContent);+ expect(statuses).toEqual(+ locale === "es"+ ? [+ "Importación completada",+ "Problema de importación · Errores de lectura: 1",+ "En pausa · Errores de lectura: 2",+ ]+ : ["导入完成", "导入遇到问题 · 1 条读取异常", "已暂停 · 2 条读取异常"],+ );+ },+);+it("translates completion recovery live without repeating completion writes", async () => {+ vi.mocked(completeOnboarding).mockRejectedValueOnce(+ new Error("fixture-offline"),+ );+ const imports = controller();+ const finish = vi.fn();+ render(+ <LanguageProvider>+ <SwitchLanguage />+ <OnboardingFlow state={state} imports={imports} onFinish={finish} />+ </LanguageProvider>,+ );+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: "Entrar y añadir más tarde" }),+ ).toHaveProperty("disabled", false),+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Entrar y añadir más tarde" }),+ );+ expect(+ await screen.findByRole("button", { name: "Reintentar guardar y entrar" }),+ ).toBeTruthy();+ expect(screen.getByRole("alert").textContent).toContain(+ "aún no está confirmada",+ );+ fireEvent.click(screen.getByText("中文"));+ expect(+ await screen.findByRole("button", { name: "重试保存并进入" }),+ ).toBeTruthy();+ expect(completeOnboarding).toHaveBeenCalledTimes(1);+ expect(finish).not.toHaveBeenCalled();+});+it("translates model configuration, validation and advanced fields without activating permissions", async () => {+ render(+ <LanguageProvider>+ <SwitchLanguage />+ <OnboardingModelController sourceNames={["Cursor"]} onBack={vi.fn()} />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("heading", {+ name: "Elige un modelo para crear memorias",+ }),+ ).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Probar conexión" }));+ expect(await screen.findByText("Introduce una API Key.")).toBeTruthy();+ expect(screen.getByLabelText("Tiempo de espera (segundos)")).toBeTruthy();+ expect(models.create).not.toHaveBeenCalled();+ expect(models.activate).not.toHaveBeenCalled();+ await act(async () => fireEvent.click(screen.getByText("中文")));+ expect(screen.getByText("请填写 API Key。")).toBeTruthy();+ expect(screen.getByLabelText("超时(秒)")).toBeTruthy();+});++it.each([+ [+ "completed",+ null,+ "Mensajes examinados: 5; no hay conversaciones para guardar",+ "已扫描 5 条,本次没有可保存的对话",+ ],+ [+ "completed",+ "2026-01-01T00:00:00Z",+ "Mensajes examinados: 5; no hay conversaciones dentro del periodo elegido",+ "已扫描 5 条,本次没有符合时间范围的对话",+ ],+ [+ "running",+ "2026-01-01T00:00:00Z",+ "Mensajes examinados: 5; filtrando los últimos 3 días",+ "已扫描 5 条,正在筛选最近 3 天",+ ],+ [+ "running",+ null,+ "Mensajes examinados: 5; filtrando",+ "已扫描 5 条,正在筛选",+ ],+ [+ "paused",+ null,+ "Mensajes examinados: 5; aún sin guardar",+ "已扫描 5 条,尚未保存",+ ],+] as const)(+ "words a %s scan with history_after=%s in both languages",+ async (status, historyAfter, spanish, chinese) => {+ const job = {+ job_id: "fixture-job",+ source_id: "cursor",+ status,+ stored: 0,+ discovered: 5,+ errors: 0,+ history_after: historyAfter,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:01:00Z",+ } as unknown as ImportJob;+ for (const [locale, expected] of [+ ["es", spanish],+ ["zh-CN", chinese],+ ] as const) {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, locale);+ const view = render(+ <LanguageProvider>+ <R6ImportProgress+ sourceIds={["cursor"]}+ sources={[{ ...source, authorized: true }]}+ jobs={[job]}+ />+ </LanguageProvider>,+ );+ expect(await screen.findByText(expected)).toBeTruthy();+ view.unmount();+ }+ },+);diff --git a/memhub/apps/web/src/OnboardingFlow.multisource-recovery.test.tsx b/memhub/apps/web/src/OnboardingFlow.multisource-recovery.test.tsxindex ee882cc..541261a 100644--- a/memhub/apps/web/src/OnboardingFlow.multisource-recovery.test.tsx+++ b/memhub/apps/web/src/OnboardingFlow.multisource-recovery.test.tsx@@ -261,7 +261,7 @@ it("keeps the single-source submit frozen when another source arrives during finit("empty discovery shows zero and allows explicit entry without a connection request", async () => {await ready();- expect(count()).toBe("0");+ await waitFor(() => expect(count()).toBe("0"));expect(screen.getByRole("button", { name: "开始导入" })).toHaveProperty("disabled",true,diff --git a/memhub/apps/web/src/OnboardingFlow.tsx b/memhub/apps/web/src/OnboardingFlow.tsxindex 7b67009..f1f8e6d 100644--- a/memhub/apps/web/src/OnboardingFlow.tsx+++ b/memhub/apps/web/src/OnboardingFlow.tsx@@ -29,6 +29,7 @@ import {hostWriteReason,} from "./host-state";import { OnboardingModelController } from "./OnboardingModelController";+import { useOnboardingTranslation } from "./onboarding-language";import { R6ColdStartFrame } from "./R6ColdStartFrame";import { R6Button } from "./R6Controls";import { traceUiAction } from "./ui-trace";@@ -63,6 +64,7 @@ export function OnboardingFlow({imports: ImportSourcesController;onFinish(destination: OnboardingDestination): void;}) {+ const { text, t } = useOnboardingTranslation();const [sources, setSources] = useState(imports.sources);const sourceGeneration = useRef({ value: imports.sources, epoch: 0 });if (sourceGeneration.current.value !== imports.sources) {@@ -99,7 +101,21 @@ export function OnboardingFlow({"idle" | "applying" | "applied" | "partial" | "failed">("idle");const [applyTick, setApplyTick] = useState(0);- const [connectionNote, setConnectionNote] = useState("");+ const [connectionNote, setConnectionNote] = useState<+ string | { success: number; failures: [string, string | null][] }+ >("");+ const renderedConnectionNote =+ typeof connectionNote === "string"+ ? text(connectionNote)+ : t("onboardingConnectionPartial", {+ success: connectionNote.success,+ failed: connectionNote.failures.length,+ names: connectionNote.failures+ .map(([name, reason]) =>+ reason ? `${name}(${text(reason)})` : name,+ )+ .join("、"),+ });const flight = useRef(false);const connectionAttempt = useRef<string | null>(null);const connectionQueue = useRef(Promise.resolve());@@ -244,12 +260,10 @@ export function OnboardingFlow({}if (failed.size && alive.current) {connectionQueueFailed.current = true;- const names = [...failed].map(([name, reason]) =>- reason ? `${name}(${reason})` : name,- );- setConnectionNote(- `${apps.size - failed.size} 个应用已接入,${failed.size} 个未完成:${names.join("、")}。可进入应用后单独处理。`,- );+ setConnectionNote({+ success: apps.size - failed.size,+ failures: [...failed],+ });}try {await refreshImports();@@ -637,7 +651,7 @@ export function OnboardingFlow({}}connectionExecutionAvailable={connectionAvailable}hostConnectionAvailable={hostConnectionAvailable}- connectionNote={connectionNote}+ connectionNote={renderedConnectionNote}acceptedJobIds={accepted?.jobs.map((job) => job.job_id)}onChangeJob={imports.changeJob}sourceIds={sourceIds}@@ -646,7 +660,7 @@ export function OnboardingFlow({failedSources={accepted?.failed_sources}sourceSnapshot={imports.sourceSnapshot}busy={busy === "leaving"}- error={error}+ error={error && text(error)}onContinue={(destination) => {if (busy === "leaving") return;const selection = {@@ -710,8 +724,8 @@ export function OnboardingFlow({return (<R6ColdStartFramestep={1}- title="把熟悉的背景,带到这里"- eyebrow="你的记忆,从这里接上"+ title={text("把熟悉的背景,带到这里")}+ eyebrow={text("你的记忆,从这里接上")}footer={<><R6Button@@ -719,20 +733,22 @@ export function OnboardingFlow({disabled={busy !== null}onClick={() => finishOnce(exitDestination)}>- {exitDestination === "sources" ? "仍进入应用页" : "仍进入工作台"}+ {text(+ exitDestination === "sources" ? "仍进入应用页" : "仍进入工作台",+ )}</R6Button><R6Buttonvariant="primary"disabled={busy !== null}onClick={() => void leave(exitDestination)}>- 重试保存并进入+ {text("重试保存并进入")}</R6Button></>}><p className="onboarding-r6-error" role="alert">- {error}+ {error && text(error)}</p></R6ColdStartFrame>);@@ -740,8 +756,8 @@ export function OnboardingFlow({return (<R6ColdStartFramestep={1}- title="把熟悉的背景,带到这里"- eyebrow="你的记忆,从这里接上"+ title={text("把熟悉的背景,带到这里")}+ eyebrow={text("你的记忆,从这里接上")}footer={<><R6Button@@ -749,11 +765,11 @@ export function OnboardingFlow({disabled={locked}onClick={() => void leave("sources")}>- 稍后添加,先进入+ {text("稍后添加,先进入")}</R6Button>{error && (<p className="onboarding-r6-error" role="alert">- {error}+ {error && text(error)}</p>)}<R6Button@@ -762,7 +778,7 @@ export function OnboardingFlow({disabled={locked || count === 0}onClick={() => void startImport()}>- {busy === "submitting" ? "正在开始导入…" : "开始导入"}+ {text(busy === "submitting" ? "正在开始导入…" : "开始导入")}</R6Button></>}@@ -773,33 +789,35 @@ export function OnboardingFlow({aria-labelledby="cold-start-phase"><div className="onboarding-r6-intro">- <p>不用从头介绍自己。从常用的 App 开始,把已有背景带过来。</p>- <p>确认前只检查应用信息,不读取对话,也不安装连接。</p>+ <p>+ {text("不用从头介绍自己。从常用的 App 开始,把已有背景带过来。")}+ </p>+ <p>{text("确认前只检查应用信息,不读取对话,也不安装连接。")}</p></div><div className="onboarding-r6-list-heading"><h2 id="cold-start-phase" ref={heading} tabIndex={-1}>- 本机 AI 应用+ {text("本机 AI 应用")}</h2><buttontype="button"className="onboarding-r6-quiet"- aria-label="重新检测位置"+ aria-label={text("重新检测位置")}disabled={locked}onClick={() => void checkLocations()}>- {busy === "checking" ? "检测中…" : "重新检测"}+ {text(busy === "checking" ? "检测中…" : "重新检测")}</button></div><SourceListclassName="onboarding-r6-list"- aria-label="候选应用"+ aria-label={text("候选应用")}aria-busy={busy === "checking"}count={visibleApps.length}status={locationCheck === "checking"- ? "正在检测其他应用…"+ ? text("正在检测其他应用…"): locationCheck === "failed"- ? "检测未完成"+ ? text("检测未完成"): undefined}selection={@@ -809,7 +827,7 @@ export function OnboardingFlow({disabled={locked || allSelected || readableApps.length === 0}onClick={selectAllSources}>- {allSelected ? "已全选" : "全选"}+ {text(allSelected ? "已全选" : "全选")}</button>}>@@ -818,7 +836,9 @@ export function OnboardingFlow({<label><inputtype="checkbox"- aria-label={`导入 ${visibleApps[0].display_name} 历史`}+ aria-label={t("onboardingImportHistory", {+ name: visibleApps[0].display_name,+ })}checkeddisabledreadOnly@@ -826,11 +846,11 @@ export function OnboardingFlow({<R6SourceIcon id={visibleApps[0].source_id} /><span className="onboarding-r6-row-info"><strong>{visibleApps[0].display_name}</strong>- <small>正在核对本机保存位置</small>+ <small>{text("正在核对本机保存位置")}</small></span><span className="onboarding-r6-badge" data-found="true"><i aria-hidden="true" />- 已发现+ {text("已发现")}</span></label></li>@@ -842,6 +862,7 @@ export function OnboardingFlow({);const note =locationCheck === "ready" ? locationNote(item) : null;+ const translatedNote = note ? text(note) : null;return (<liclassName={`onboarding-r6-row${checked ? " is-selected" : ""}`}@@ -853,7 +874,9 @@ export function OnboardingFlow({<label><inputtype="checkbox"- aria-label={`导入 ${item.display_name} 历史`}+ aria-label={t("onboardingImportHistory", {+ name: item.display_name,+ })}checked={checked}disabled={locked || locationCheck !== "ready" || !canRead(item)@@ -865,13 +888,13 @@ export function OnboardingFlow({<R6SourceIcon id={item.source_id} /><span className="onboarding-r6-row-info"><strong>{item.display_name}</strong>- <small title={note ?? item.candidate_path}>- {item.candidate_path || "位置待核对"} ·{" "}- {pathKind(item)}+ <small title={translatedNote ?? item.candidate_path}>+ {item.candidate_path || text("位置待核对")} ·{" "}+ {text(pathKind(item))}</small>{itemErrors[item.source_id] && (<small className="onboarding-r6-error">- {failureLabel(itemErrors[item.source_id])}+ {failureLabel(itemErrors[item.source_id], text, t)}</small>)}</span>@@ -881,10 +904,10 @@ export function OnboardingFlow({locationCheck === "ready" &&item.location_state === "found"}- title={note ?? undefined}+ title={translatedNote ?? undefined}><i aria-hidden="true" />- {locationLabel(item, locationCheck)}+ {text(locationLabel(item, locationCheck))}</span></label></li>@@ -907,28 +930,30 @@ export function OnboardingFlow({{!visibleApps.length && busy !== "checking" && (<li className="onboarding-r6-empty">{locationCheck === "ready"- ? "当前没有候选来源。可以稍后在应用页添加历史包。"- : "候选来源尚未加载。可以检测位置,或先进入工作台。"}+ ? text("当前没有候选来源。可以稍后在应用页添加历史包。")+ : text("候选来源尚未加载。可以检测位置,或先进入工作台。")}</li>)}</SourceList></section>- <aside className="onboarding-r6-summary" aria-label="本次导入">- <p>本次导入</p>+ <aside className="onboarding-r6-summary" aria-label={text("本次导入")}>+ <p>{text("本次导入")}</p><pclassName="onboarding-r6-count"aria-live="polite"data-unknown={locationCheck !== "ready"}>- {summaryCount}+ {text(summaryCount)}</p>- <p>个 App 的历史对话</p>+ <p>{text("个 App 的历史对话")}</p><h2>- 把零散的会话,+ {text("把零散的会话,")}<br />- 汇成完整的记忆+ {text("汇成完整的记忆")}</h2>- <p className="onboarding-r6-signoff">少一些重复交代,多一些理解。</p>+ <p className="onboarding-r6-signoff">+ {text("少一些重复交代,多一些理解。")}+ </p></aside></div>{custom && (@@ -966,6 +991,7 @@ function SourceList({status?: string;selection: ReactNode;}) {+ const { t, tnPlain } = useOnboardingTranslation();const list = useRef<HTMLUListElement>(null);const [more, setMore] = useState(0);const measure = useCallback(() => {@@ -1014,9 +1040,9 @@ function SourceList({<span data-scroll-hint={!status && more > 0 ? "true" : "false"}>{status ??(more > 0- ? `向下查看更多 · 还有 ${more} 个应用`+ ? tnPlain("onboardingMoreApps", more): count > 3- ? `已显示全部 ${count} 个应用`+ ? t("onboardingAllApps", { count }): "")}</span>{selection}@@ -1114,7 +1140,11 @@ function locationNote(source: SourceResponse) {return null;}-function failureLabel(reason: string) {+function failureLabel(+ reason: string,+ text: (value: string) => string,+ t: ReturnType<typeof useOnboardingTranslation>["t"],+) {const labels: Record<string, string> = {source_unavailable: "来源目录暂时不可读取,请核对位置和权限。",source_not_available: "来源目录暂时不可读取,请核对位置和权限。",@@ -1124,7 +1154,9 @@ function failureLabel(reason: string) {environment_override_confirmation_required: "自定义来源位置需要重新确认。",imports_disabled: "当前 Core 未启用历史导入。",};- return labels[reason] ?? `尚未获准导入(${reason})。请核对来源后重试。`;+ return labels[reason]+ ? text(labels[reason])+ : t("onboardingImportRefused", { reason });}// S1.3 supplied app marks; WorkBuddy keeps the source geometry with flat fills.@@ -1149,6 +1181,7 @@ function CustomLocationDialog({onCancel(): void;onConfirm(): void;}) {+ const { text, t } = useOnboardingTranslation();const [confirmed, setConfirmed] = useState(false);const panel = useRef<HTMLDivElement>(null);useLayoutEffect(() => {@@ -1233,12 +1266,12 @@ function CustomLocationDialog({tabIndex={-1}><header>- <h2 id="cold-start-custom-title">确认自定义位置</h2>+ <h2 id="cold-start-custom-title">{text("确认自定义位置")}</h2><buttontype="button"className="cold-start-icon-button"- aria-label="关闭位置确认"- title="关闭位置确认"+ aria-label={text("关闭位置确认")}+ title={text("关闭位置确认")}onClick={onCancel}><X size={18} aria-hidden="true" />@@ -1246,7 +1279,9 @@ function CustomLocationDialog({</header><div className="cold-start-dialog-body"><p id="cold-start-custom-description">- 此位置来自当前配置,并非应用默认目录。确认位置不会开始读取历史。+ {text(+ "此位置来自当前配置,并非应用默认目录。确认位置不会开始读取历史。",+ )}</p><strong>{source.display_name}</strong><code>{source.candidate_path}</code>@@ -1256,7 +1291,9 @@ function CustomLocationDialog({checked={confirmed}onChange={(event) => setConfirmed(event.target.checked)}/>- <span>确认这是 {source.display_name} 的历史位置</span>+ <span>+ {t("onboardingConfirmHistory", { name: source.display_name })}+ </span></label></div><footer>@@ -1265,7 +1302,7 @@ function CustomLocationDialog({className="cold-start-secondary"onClick={onCancel}>- 取消+ {text("取消")}</button><buttontype="button"@@ -1275,7 +1312,7 @@ function CustomLocationDialog({}}><Check size={16} aria-hidden="true" />- 确认此位置+ {text("确认此位置")}</button></footer></div>diff --git a/memhub/apps/web/src/OnboardingModelController.tsx b/memhub/apps/web/src/OnboardingModelController.tsxindex 9b3f2e7..6abbd29 100644--- a/memhub/apps/web/src/OnboardingModelController.tsx+++ b/memhub/apps/web/src/OnboardingModelController.tsx@@ -9,6 +9,7 @@ import {type OnboardingModelDraft,OnboardingModelStep,} from "./OnboardingModelStep";+import { useOnboardingTranslation } from "./onboarding-language";import { PROVIDER_PRESETS } from "./provider-presets";import { traceUiAction } from "./ui-trace";import { useModelProfiles } from "./use-model-profiles";@@ -65,6 +66,7 @@ export function OnboardingModelController({onEnabled?(): void;connectionAlreadyApplied?: boolean;}) {+ const { text, t } = useOnboardingTranslation();const models = useModelProfiles();const [draft, setDraft] = useState(initial);const [advanced, setAdvanced] = useState(false);@@ -119,7 +121,7 @@ export function OnboardingModelController({value < min ||value > max)- next[key] = `请输入 ${min} 至 ${max} 的整数。`;+ next[key] = "onboardingIntegerRange";return value;};const timeout = integer("timeout_seconds", 1, 600);@@ -269,8 +271,22 @@ export function OnboardingModelController({canTest={!models.pendingProbe && !models.probeStorageFailed}canSaveDraft={!models.pendingCreation && !models.creationStorageFailed}inputsLocked={flight.current}- fieldErrors={fields}- error={error ?? models.error}+ fieldErrors={Object.fromEntries(+ Object.entries(fields).map(([key, value]) => [+ key,+ value === "onboardingIntegerRange"+ ? t(+ "onboardingIntegerRange",+ key === "timeout_seconds"+ ? { min: 1, max: 600 }+ : key === "max_concurrency"+ ? { min: 1, max: 32 }+ : { min: 1024, max: 10_000_000 },+ )+ : text(value),+ ]),+ )}+ error={error ?? (models.error ? text(models.error) : null)}probe={probe}profile={saveddiff --git a/memhub/apps/web/src/OnboardingModelStep.test.tsx b/memhub/apps/web/src/OnboardingModelStep.test.tsxindex 220917b..c158d69 100644--- a/memhub/apps/web/src/OnboardingModelStep.test.tsx+++ b/memhub/apps/web/src/OnboardingModelStep.test.tsx@@ -9,12 +9,93 @@ import {within,} from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import {OnboardingModelStep,type OnboardingModelStepProps,} from "./OnboardingModelStep";-afterEach(cleanup);+afterEach(() => {+ cleanup();+ localStorage.clear();+});++it.each(["es", "zh-CN"] as const)(+ "keeps %s footer actions, pending locks and permission boundaries",+ async (locale) => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, locale);+ const p = props();+ p.onSkip = vi.fn();+ let finish!: () => void;+ p.onTest = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const labels =+ locale === "es"+ ? [+ "Omitir por ahora",+ "Probar conexión",+ "Confirmar y habilitar",+ "Probando el modelo…",+ ]+ : ["跳过,先进入应用", "测试模型连通性", "确认启用", "正在测试模型…"];+ const draw = (probe?: OnboardingModelStepProps["probe"]) => (+ <LanguageProvider>+ <OnboardingModelStep+ {...p}+ capability={{ saveAndEnable: true }}+ probe={probe}+ advancedOpen+ />+ </LanguageProvider>+ );+ const view = render(draw());+ const skip = screen.getByRole("button", { name: labels[0] });+ if (locale === "es") {+ expect(+ document.getElementById(skip.getAttribute("aria-describedby") ?? "")+ ?.textContent,+ ).toContain("Aplicaciones");+ }+ fireEvent.click(skip);+ expect(p.onSkip).toHaveBeenCalledOnce();+ expect(p.onBack).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: labels[2] })).toHaveProperty(+ "disabled",+ true,+ );+ fireEvent.click(screen.getByRole("button", { name: labels[1] }));+ expect(screen.getByRole("button", { name: labels[3] })).toHaveProperty(+ "disabled",+ true,+ );+ expect(skip).toHaveProperty("disabled", true);+ expect(p.onSaveAndEnable).not.toHaveBeenCalled();+ await act(async () => finish());+ view.rerender(draw({ state: "failed", message: "synthetic failure" }));+ expect(screen.getByRole("button", { name: labels[2] })).toHaveProperty(+ "disabled",+ true,+ );+ expect(screen.getByLabelText("API Key")).toHaveProperty("value", "secret");+ expect(p.onDraftChange).not.toHaveBeenCalled();+ view.rerender(draw({ state: "passed", message: "synthetic success" }));+ fireEvent.click(screen.getByRole("button", { name: labels[2] }));+ await act(async () => {});+ expect(p.onSaveAndEnable).toHaveBeenCalledOnce();+ expect(p.onSaveDraft).not.toHaveBeenCalled();+ expect(+ screen.getByText(+ locale === "es"+ ? /La prueba de conexión solo envía/+ : /测试连接只发送测试内容/,+ ),+ ).toBeTruthy();+ },+);function props(): OnboardingModelStepProps {return {draft: {diff --git a/memhub/apps/web/src/OnboardingModelStep.tsx b/memhub/apps/web/src/OnboardingModelStep.tsxindex 55fc0bd..0e3fe25 100644--- a/memhub/apps/web/src/OnboardingModelStep.tsx+++ b/memhub/apps/web/src/OnboardingModelStep.tsx@@ -2,6 +2,7 @@ import type { ProviderKind } from "@one-memory/contracts";import { ChevronDown, ChevronUp } from "lucide-react";import { useEffect, useId, useRef, useState } from "react";import { OptionMenu } from "./OptionMenu";+import { useOnboardingTranslation } from "./onboarding-language";import { R6ColdStartFrame } from "./R6ColdStartFrame";import { R6Button } from "./R6Controls";import "./onboarding-model-r6.css";@@ -71,8 +72,13 @@ export interface OnboardingModelStepProps {}export function OnboardingModelStep(props: OnboardingModelStepProps) {+ const { text, t, locale } = useOnboardingTranslation();const { draft, advancedOpen, onDraftChange, fieldErrors = {}, phase } = props;const id = useId();+ // The Chinese label already names the destination; shorter translated labels+ // need it as a description for assistive technology.+ const skipDestination =+ locale === "zh-CN" ? "" : t("onboardingModelSkipDestination");const fields = useRef<HTMLElement>(null);const advancedToggle = useRef<HTMLButtonElement>(null);const restoreToggleFocus = useRef(false);@@ -113,7 +119,10 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {const sourceSummary =props.sourceNames.length <= 3? props.sourceNames.join(" · ")- : `${props.sourceNames.slice(0, 3).join(" · ")} 等 ${props.sourceNames.length} 个应用`;+ : t("onboardingSourcesSummary", {+ names: props.sourceNames.slice(0, 3).join(" · "),+ count: props.sourceNames.length,+ });async function run(action: Action) {if (flight.current || locked) return;if (action === "save-and-enable" && !canEnable) return;@@ -153,11 +162,11 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {const error = fieldErrors[key];return (<label className="onboarding-model-field" htmlFor={`${id}-${key}`}>- <span>{label}</span>+ <span>{text(label)}</span><inputid={`${id}-${key}`}name={key}- aria-label={label}+ aria-label={text(label)}type={options.type ?? "text"}autoComplete="off"spellCheck={false}@@ -169,7 +178,9 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {max={options.max}maxLength={options.maxLength}required={options.required}- placeholder={options.placeholder}+ placeholder={+ options.placeholder ? text(options.placeholder) : undefined+ }onChange={(event) => {if (!flight.current && !fieldsLocked)onDraftChange({ [key]: event.target.value });@@ -177,7 +188,7 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {/>{error && (<small id={`${id}-${key}-error`} className="onboarding-model-error">- {error}+ {text(error)}</small>)}</label>@@ -215,43 +226,57 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {><R6ColdStartFramestep={3}- eyebrow="沉淀记忆 · 使用你选择的模型"- title={pageTitle}+ eyebrow={text("沉淀记忆 · 使用你选择的模型")}+ title={text(pageTitle)}footer={<><p className="onboarding-model-footer-note">- {!props.capability.saveAndEnable- ? "当前无法启用模型,已填写内容保留。"- : props.probe?.state === "passed"- ? "模型连接测试通过,可以启用并开始沉淀记忆。"- : "先测试模型连通性;测试通过后再启用。"}+ {text(+ !props.capability.saveAndEnable+ ? "当前无法启用模型,已填写内容保留。"+ : props.probe?.state === "passed"+ ? "模型连接测试通过,可以启用并开始沉淀记忆。"+ : "先测试模型连通性;测试通过后再启用。",+ )}</p><div className="onboarding-model-footer-actions">+ {skipDestination && (+ <span id={`${id}-skip-destination`} hidden>+ {skipDestination}+ </span>+ )}<R6Button+ aria-describedby={+ skipDestination ? `${id}-skip-destination` : undefined+ }disabled={locked}onClick={() => {if (!flight.current && !locked)(props.onSkip ?? props.onBack)();}}>- 跳过,先进入应用+ {text("跳过,先进入应用")}</R6Button><R6Buttondisabled={locked || !props.canTest}onClick={() => void run("test")}>- {displayedPhase === "testing"- ? "正在测试模型…"- : (props.testActionLabel ?? "测试模型连通性")}+ {text(+ displayedPhase === "testing"+ ? "正在测试模型…"+ : (props.testActionLabel ?? "测试模型连通性"),+ )}</R6Button><R6Buttonvariant="primary"disabled={locked || !canEnable}onClick={() => void run("save-and-enable")}>- {displayedPhase === "enabling"- ? "正在启用…"- : (props.enableActionLabel ?? "确认启用")}+ {text(+ displayedPhase === "enabling"+ ? "正在启用…"+ : (props.enableActionLabel ?? "确认启用"),+ )}</R6Button></div></>@@ -260,27 +285,29 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {<div className="onboarding-model-layout"><sectionclassName="onboarding-model-form"- aria-label="模型配置"+ aria-label={text("模型配置")}data-advanced={advancedOpen}><sectionref={fields}id={`${id}-fields`}className="onboarding-model-fields"- aria-label="模型参数"+ aria-label={text("模型参数")}// biome-ignore lint/a11y/noNoninteractiveTabindex: The parameter pane needs keyboard scrolling.tabIndex={0}>{!advancedOpen ? (<><p className="onboarding-model-intro">- 选择服务商,填入 API Key。核对已有配置后再继续。+ {text("选择服务商,填入 API Key。核对已有配置后再继续。")}</p><labelclassName="onboarding-model-field onboarding-model-provider"htmlFor={`${id}-provider`}>- <span id={`${id}-provider-label`}>模型服务商</span>+ <span id={`${id}-provider-label`}>+ {text("模型服务商")}+ </span><OptionMenuid={`${id}-provider`}labelledBy={`${id}-provider-label`}@@ -288,11 +315,11 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {disabled={fieldsLocked}options={[...(!provider- ? [{ value: "", label: "选择服务商" }]+ ? [{ value: "", label: text("选择服务商") }]: []),...props.providers.map((item) => ({value: item.id,- label: item.label,+ label: text(item.label),disabled: !item.supported,})),]}@@ -317,13 +344,15 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {className="onboarding-model-key-note"data-state={connectionFailed ? "failed" : "idle"}>- {connectionFailed- ? "连接未通过,请检查 API Key、模型与接口地址后重试。配置已保留。"- : props.profile?.credential_state === "unavailable"- ? "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”。"- : props.profile?.has_configured_api_key- ? "留空保留已保存密钥;填写新密钥后需重新测试。"- : "密钥保存在系统安全存储中,不写入对话或日志。"}+ {text(+ connectionFailed+ ? "连接未通过,请检查 API Key、模型与接口地址后重试。配置已保留。"+ : props.profile?.credential_state === "unavailable"+ ? "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”。"+ : props.profile?.has_configured_api_key+ ? "留空保留已保存密钥;填写新密钥后需重新测试。"+ : "密钥保存在系统安全存储中,不写入对话或日志。",+ )}</p><buttonref={advancedToggle}@@ -334,24 +363,27 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {disabled={fieldsLocked}onClick={() => changeAdvanced(true)}>- 配置详情与高级设置{" "}+ {text("配置详情与高级设置")}{" "}<ChevronDown size={16} aria-hidden="true" /></button><p className="onboarding-model-profile">- {provider?.label ?? "服务商待选择"} ·{" "}- {draft.model || "模型待填写"}+ {provider ? text(provider.label) : text("服务商待选择")} ·{" "}+ {draft.model || text("模型待填写")}<br />- {safeEndpoint(draft.base_url)} ·{" "}+ {text(safeEndpoint(draft.base_url))} ·{" "}{draft.embedding_mode === "local"- ? "本地向量模型"- : draft.embedding_model || "向量模型待填写"}{" "}- · {draft.disable_thinking ? "思考已关闭" : "思考未关闭"}+ ? text("本地向量模型")+ : draft.embedding_model || text("向量模型待填写")}{" "}+ ·{" "}+ {text(draft.disable_thinking ? "思考已关闭" : "思考未关闭")}</p></>) : (<><div className="onboarding-model-advanced-head">- <p>预设已填好,只有自定义服务或特殊需求才需要修改。</p>+ <p>+ {text("预设已填好,只有自定义服务或特殊需求才需要修改。")}+ </p><buttonref={advancedToggle}type="button"@@ -361,7 +393,8 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {disabled={fieldsLocked}onClick={() => changeAdvanced(false)}>- 返回服务商选择 <ChevronUp size={16} aria-hidden="true" />+ {text("返回服务商选择")}{" "}+ <ChevronUp size={16} aria-hidden="true" /></button></div><div className="onboarding-model-advanced-grid">@@ -390,15 +423,17 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {className="onboarding-model-key-note"data-state={connectionFailed ? "failed" : "idle"}>- {props.profile?.has_configured_api_key- ? "留空保留已保存密钥;填写新密钥后需重新测试。"- : "密钥保存在系统安全存储中,不写入对话或日志。"}+ {text(+ props.profile?.has_configured_api_key+ ? "留空保留已保存密钥;填写新密钥后需重新测试。"+ : "密钥保存在系统安全存储中,不写入对话或日志。",+ )}</p></div><label className="onboarding-model-field">- <span>协议</span>+ <span>{text("协议")}</span><select- aria-label="协议"+ aria-label={text("协议")}value={draft.provider_kind}disabled={fieldsLocked}onChange={(e) => {@@ -413,17 +448,17 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {</option><option value="ollama">Ollama</option><option value="anthropic" disabled>- Anthropic(暂不支持)+ {text("Anthropic(暂不支持)")}</option><option value="hy_default" disabled>- HY 托管(当前不可用)+ {text("HY 托管(当前不可用)")}</option></select></label><label className="onboarding-model-field">- <span>向量模型</span>+ <span>{text("向量模型")}</span><select- aria-label="向量模型"+ aria-label={text("向量模型")}value={draft.embedding_mode}disabled={fieldsLocked}onChange={(e) => {@@ -435,8 +470,10 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {});}}>- <option value="local">本地 ONNX · 内置</option>- <option value="custom">自定义向量</option>+ <option value="local">+ {text("本地 ONNX · 内置")}+ </option>+ <option value="custom">{text("自定义向量")}</option></select></label><div className="onboarding-model-numbers">@@ -469,12 +506,14 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {});}}/>- 关闭思考模式+ {text("关闭思考模式")}</label><p className="onboarding-model-vector-note">- 自定义向量配置可展开;远程向量服务须遵守凭据边界。+ {text(+ "自定义向量配置可展开;远程向量服务须遵守凭据边界。",+ )}<br />- 切换服务商或模型后,需要重新测试并启用。+ {text("切换服务商或模型后,需要重新测试并启用。")}</p>{draft.embedding_mode === "custom" && (<>@@ -483,9 +522,9 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {maxLength: 256,})}<label className="onboarding-model-field">- <span>向量协议</span>+ <span>{text("向量协议")}</span><select- aria-label="向量协议"+ aria-label={text("向量协议")}value={draft.embedding_provider_kind}disabled={fieldsLocked}onChange={(e) => {@@ -498,9 +537,11 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {}}><option value="openai_compatible">- 同源 OpenAI-compatible(共用 Key)+ {text("同源 OpenAI-compatible(共用 Key)")}+ </option>+ <option value="ollama">+ {text("本机 Ollama")}</option>- <option value="ollama">本机 Ollama</option></select></label><div className="onboarding-model-wide">@@ -509,7 +550,9 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {required: true,})}<small>- 远程向量地址须与生成服务同源;本机地址仍需校验。+ {text(+ "远程向量地址须与生成服务同源;本机地址仍需校验。",+ )}</small></div></>@@ -524,7 +567,7 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {disabled={locked}onClick={() => void props.onRecoverCreation?.()}>- 核对创建结果+ {text("核对创建结果")}</R6Button>)}{props.onDiscardMissingCreation && (@@ -533,17 +576,19 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {disabled={locked}onClick={() => void props.onDiscardMissingCreation?.()}>- 放弃旧记录,重新配置+ {text("放弃旧记录,重新配置")}</R6Button>)}</div><div className="onboarding-model-feedback" tabIndex={-1}>{(displayedPhase === "testing" ||displayedPhase === "enabling") && (- <p role="status" aria-label="模型提交状态">- {displayedPhase === "testing"- ? "正在测试连接…"- : "正在提交保存与启用,请等待回执…"}+ <p role="status" aria-label={text("模型提交状态")}>+ {text(+ displayedPhase === "testing"+ ? "正在测试连接…"+ : "正在提交保存与启用,请等待回执…",+ )}</p>)}{props.probe && (@@ -552,54 +597,60 @@ export function OnboardingModelStep(props: OnboardingModelStepProps) {data-state={props.probe.state}role="status">- {props.probe.message}+ {text(props.probe.message)}</p>)}{(props.error || callbackFailed) && (<p className="onboarding-model-error" role="alert">- {props.error ||- "操作结果未确认,已填写内容保留,请核对后重试。"}+ {text(+ props.error ||+ "操作结果未确认,已填写内容保留,请核对后重试。",+ )}</p>)}</div></section><asideclassName="onboarding-model-summary"- aria-label="本次沉淀"+ aria-label={text("本次沉淀")}data-full-height={advancedOpen || connectionFailed}// biome-ignore lint/a11y/noNoninteractiveTabindex: Keyboard users must be able to scroll the full permission disclosure.tabIndex={0}><div className="onboarding-model-summary-heading">- <p>本次沉淀</p>- <h2>让记忆从这里开始</h2>+ <p>{text("本次沉淀")}</p>+ <h2>{text("让记忆从这里开始")}</h2></div><div className="onboarding-model-connections">- <p>对话来源</p>- <strong>{sourceSummary || "尚无已选来源"}</strong>+ <p>{text("对话来源")}</p>+ <strong>{sourceSummary || text("尚无已选来源")}</strong><small>- 已导入 {props.importedConversationCount ?? 0}{" "}- 条对话;来源开关继续控制之后同步到本机的内容。+ {t("onboardingImportedConversations", {+ count: props.importedConversationCount ?? 0,+ })}</small></div><div className="onboarding-model-summary-status">{connectionReceipt && (<small className="onboarding-model-connection-receipt">- {connectionReceipt}+ {text(connectionReceipt)}</small>)}<small>- 处理服务:{provider?.label ?? "待选择"}+ {text("处理服务:")}+ {text(provider?.label ?? "待选择")}<br />- 相关对话会发送给所选服务商。+ {text("相关对话会发送给所选服务商。")}</small><small>- 测试连接只发送测试内容。启用后会使用此模型整理已导入和之后同步的会话。+ {text(+ "测试连接只发送测试内容。启用后会使用此模型整理已导入和之后同步的会话。",+ )}</small></div>{!props.capability.saveAndEnable && (<p role="status">- {props.capability.reason || "当前不能在此启用模型。"}+ {text(props.capability.reason || "当前不能在此启用模型。")}</p>)}</aside>diff --git a/memhub/apps/web/src/OptionMenu.tsx b/memhub/apps/web/src/OptionMenu.tsxindex 27b1ebb..11409da 100644--- a/memhub/apps/web/src/OptionMenu.tsx+++ b/memhub/apps/web/src/OptionMenu.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState } from "react";+import { useGuiLanguage } from "./gui-language";export interface OptionMenuItem {value: string;@@ -18,6 +19,7 @@ export function OptionMenu(props: {options: readonly OptionMenuItem[];onChange: (value: string) => void;}) {+ const { t } = useGuiLanguage();const [open, setOpen] = useState(false);const root = useRef<HTMLDivElement>(null);const selected = props.options.find((item) => item.value === props.value);@@ -60,7 +62,7 @@ export function OptionMenu(props: {}}}>- {selected?.label ?? "请选择"}+ {selected?.label ?? t("wb.select")}</button>{open && (<div className="om-option-menu-panel" role="listbox">diff --git a/memhub/apps/web/src/R6ColdStartFrame.test.tsx b/memhub/apps/web/src/R6ColdStartFrame.test.tsxnew file mode 100644index 0000000..7e41c2b--- /dev/null+++ b/memhub/apps/web/src/R6ColdStartFrame.test.tsx@@ -0,0 +1,153 @@+// @vitest-environment jsdom+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, expect, it } from "vitest";+import { LanguageProvider } from "./gui-language";+import { R6ColdStartFrame } from "./R6ColdStartFrame";++afterEach(() => {+ cleanup();+ localStorage.clear();+});++function declaration(file: string, selector: string): string {+ const css = readFileSync(join(process.cwd(), "src", file), "utf8");+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return css.match(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`))?.[1] ?? "";+}++it("lets multiline headings grow above the separator in normal flow", () => {+ const head = declaration("onboarding-r6.css", ".onboarding-r6-head");+ expect(head).toMatch(/flex:\s*0 0 auto/);+ expect(head).toMatch(/display:\s*flex/);+ expect(head).toMatch(/flex-wrap:\s*wrap/);+ expect(+ declaration("onboarding-r6.css", ".onboarding-r6-head .r6-stepper"),+ ).not.toMatch(/position:\s*absolute/);+});++it("allows step labels to wrap in separate flexible tracks", () => {+ const list = declaration("r6-controls.css", ".r6-stepper ol");+ const step = declaration("r6-controls.css", ".r6-stepper li");+ expect(list).toMatch(+ /grid-template-columns:\s*repeat\(3, minmax\(0, 1fr\)\)/,+ );+ expect(step).toMatch(/white-space:\s*normal/);+ expect(step).toMatch(/height:\s*auto/);+ expect(step).not.toMatch(/width:\s*84px/);+});++it("sizes the import action to its label and wraps footer content", () => {+ const submit = declaration("onboarding-r6.css", ".onboarding-r6-submit");+ expect(submit).toMatch(/width:\s*auto/);+ expect(submit).toMatch(/min-width:\s*138px/);+ expect(declaration("onboarding-r6.css", ".onboarding-r6-foot")).toMatch(+ /flex-wrap:\s*wrap/,+ );+});++it("keeps progress cards content-sized and the step-two footer in normal flow", () => {+ const card = declaration(+ "r6-import-progress.css",+ ".r6-import-progress-card",+ );+ expect(card).toMatch(/min-height:\s*218px/);+ expect(card).not.toMatch(/(?:^|;)\s*height:/);+ expect(+ declaration(+ "first-import-r6.css",+ ".first-import-r6-main > .r6-import-progress",+ ),+ ).toMatch(/flex:\s*0 0 auto/);+ expect(declaration("first-import-r6.css", ".first-import-r6-layout")).toMatch(+ /height:\s*auto/,+ );+ expect(+ declaration("first-import-r6.css", ".first-import-r6-footer-note"),+ ).not.toMatch(/max-height|overflow/);+ expect(declaration("onboarding-r6.css", ".onboarding-r6-body")).toMatch(+ /overflow-y:\s*auto/,+ );+});++it("removes the duplicate native drag overlay above the language selector", () => {+ expect(+ declaration(+ "onboarding-r6.css",+ ".desktop-frame:has(.onboarding-r6) > .window-drag-region",+ ),+ ).toMatch(/display:\s*none/);+ expect(+ declaration(+ "onboarding-r6.css",+ ".onboarding-r6-titlebar .r6-language-selector--compact",+ ),+ ).toMatch(/-webkit-app-region:\s*no-drag/);+});++it("keeps selection status outside decorative fades and readable when disabled", () => {+ expect(+ declaration("onboarding-r6.css", ".onboarding-r6-list-area::after"),+ ).toBe("");+ expect(+ declaration(+ "onboarding-r6.css",+ ".onboarding-r6-list-status .onboarding-r6-quiet:disabled",+ ),+ ).toMatch(/opacity:\s*1/);+});++it("keeps the native selector keyboard-focusable and switches both languages", async () => {+ render(+ <LanguageProvider>+ <R6ColdStartFrame+ step={1}+ title="Fixture"+ eyebrow="Fixture"+ footer={null}+ >+ <p>Fixture body</p>+ </R6ColdStartFrame>+ </LanguageProvider>,+ );+ const user = userEvent.setup();+ const selector = screen.getByRole("combobox");+ await user.tab();+ expect(document.activeElement).toBe(selector);+ await user.selectOptions(selector, "es");+ expect(document.documentElement.lang).toBe("es");+ expect(screen.getByRole("combobox").getAttribute("id")).toBe(selector.id);+ await user.selectOptions(selector, "zh-CN");+ expect(document.documentElement.lang).toBe("zh-CN");+ expect(screen.getByRole("combobox", { name: "界面语言" })).toBe(selector);+});++it.each([1, 2, 3] as const)(+ "offers a compact language selector on step %s",+ (step) => {+ render(+ <LanguageProvider>+ <R6ColdStartFrame+ step={step}+ title="Fixture"+ eyebrow="Fixture"+ footer={null}+ >+ <p>Fixture body</p>+ </R6ColdStartFrame>+ </LanguageProvider>,+ );+ const selector = screen.getByRole("combobox", { name: "界面语言" });+ expect(selector.closest(".r6-language-selector--compact")).toBeTruthy();+ expect(+ screen.getByRole("option", { name: "简体中文" }).getAttribute("lang"),+ ).toBe("zh-CN");+ expect(+ screen.getByRole("option", { name: "Español" }).getAttribute("lang"),+ ).toBe("es");+ expect(screen.queryByRole("heading", { name: "界面语言" })).toBeNull();+ expect(selector.getAttribute("aria-describedby")).toBeNull();+ },+);diff --git a/memhub/apps/web/src/R6ColdStartFrame.tsx b/memhub/apps/web/src/R6ColdStartFrame.tsxindex f2eeebf..c9b8e9f 100644--- a/memhub/apps/web/src/R6ColdStartFrame.tsx+++ b/memhub/apps/web/src/R6ColdStartFrame.tsx@@ -1,4 +1,5 @@import type { ReactNode } from "react";+import { LanguageSelector } from "./LanguageSelector";import { R6LocalStorage, R6Stepper } from "./R6Controls";import "./onboarding-r6.css";@@ -21,9 +22,12 @@ export function R6ColdStartFrame({left of this bar and a "第一次见面" caption on the right. The userremoved both deliberately on 2026-09-20 — this is a product decision,not a missing implementation, so do not "restore" them when comparing- against the canvas. The bar itself stays: it is the 58px window drag- region and reserves room for the native traffic lights. */}- <header className="onboarding-r6-titlebar" />+ against the canvas. The bar itself stays: it is the window drag+ region (at least 58px) and reserves room for native traffic lights.+ The language control opts out of dragging. */}+ <header className="onboarding-r6-titlebar">+ <LanguageSelector compact />+ </header><div className="onboarding-r6-stage"><section className="onboarding-r6-shell" data-step={step}><header className="onboarding-r6-head">diff --git a/memhub/apps/web/src/R6Controls.tsx b/memhub/apps/web/src/R6Controls.tsxindex 4a289a3..f61fdbb 100644--- a/memhub/apps/web/src/R6Controls.tsx+++ b/memhub/apps/web/src/R6Controls.tsx@@ -3,6 +3,7 @@ import {type InputHTMLAttributes,useId,} from "react";+import { useOnboardingTranslation } from "./onboarding-language";import "./r6-controls.css";type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {@@ -35,15 +36,16 @@ export function R6Button({}export function R6Stepper({ active }: { active: 1 | 2 | 3 }) {+ const { text } = useOnboardingTranslation();return (- <nav className="r6-stepper" aria-label="首次设置进度">+ <nav className="r6-stepper" aria-label={text("首次设置进度")}><ol>{["导入历史", "连接应用", "沉淀记忆"].map((label, index) => (<likey={label}aria-current={active === index + 1 ? "step" : undefined}>- <span aria-hidden="true">0{index + 1}</span> {label}+ <span aria-hidden="true">0{index + 1}</span> {text(label)}</li>))}</ol>@@ -115,13 +117,16 @@ export function R6Field({}export function R6LocalStorage() {+ const { text } = useOnboardingTranslation();return (<spanclassName="r6-local-storage"- title="对话与记忆保存在本机;使用云模型或已授权的助手时,相关内容会发送给对应服务。"+ title={text(+ "对话与记忆保存在本机;使用云模型或已授权的助手时,相关内容会发送给对应服务。",+ )}><span aria-hidden="true" />- 本地存储+ {text("本地存储")}</span>);}diff --git a/memhub/apps/web/src/R6ImportProgress.tsx b/memhub/apps/web/src/R6ImportProgress.tsxindex 32ec64e..dce8819 100644--- a/memhub/apps/web/src/R6ImportProgress.tsx+++ b/memhub/apps/web/src/R6ImportProgress.tsx@@ -1,21 +1,37 @@import type { ImportJob, SourceResponse } from "@one-memory/contracts";import { useEffect, useLayoutEffect, useRef } from "react";import { AppMark } from "./app-mark";+import { useOnboardingTranslation } from "./onboarding-language";import "./r6-import-progress.css";-function progressText(job: ImportJob): string | null {- if (job.stored > 0) return `已保存 ${job.stored.toLocaleString()} 条消息`;+type Translate = ReturnType<typeof useOnboardingTranslation>["t"];++function progressText(+ job: ImportJob,+ t: Translate,+ locale: string,+): string | null {+ if (job.stored > 0)+ return t("onboardingSavedMessages", {+ count: job.stored.toLocaleString(locale),+ });if (job.discovered <= 0) return null;- const scanned = `已扫描 ${job.discovered.toLocaleString()} 条`;+ const count = job.discovered.toLocaleString(locale);if (job.status === "completed")- return job.history_after- ? `${scanned},本次没有符合时间范围的对话`- : `${scanned},本次没有可保存的对话`;+ return t(+ job.history_after+ ? "onboardingScannedOutsideRange"+ : "onboardingScannedNothingToSave",+ { count },+ );if (job.status === "pending" || job.status === "running")- return job.history_after- ? `${scanned},正在筛选最近 3 天`- : `${scanned},正在筛选`;- return `${scanned},尚未保存`;+ return t(+ job.history_after+ ? "onboardingScannedFilteringRecent"+ : "onboardingScannedFiltering",+ { count },+ );+ return t("onboardingScannedNotSaved", { count });}export function R6ImportProgress({@@ -29,6 +45,7 @@ export function R6ImportProgress({jobs: ImportJob[];stale?: boolean;}) {+ const { text, t, locale } = useOnboardingTranslation();const scroller = useRef<HTMLElement>(null);const userScrollLeft = useRef(0);const userScrollIntent = useRef(false);@@ -56,7 +73,7 @@ export function R6ImportProgress({return (<sectionclassName="r6-import-progress"- aria-label="本次应用导入进度"+ aria-label={text("本次应用导入进度")}data-count={ids.length <= 2 ? String(ids.length) : "many"}ref={scroller}onPointerDown={markUserScrollIntent}@@ -103,12 +120,14 @@ export function R6ImportProgress({cancelled: "已取消",completed: "导入完成",};- const progress = job ? progressText(job) : null;+ const progress = job ? progressText(job, t, locale) : null;return (<articleclassName="r6-import-progress-card"key={id}- aria-label={`${source?.display_name ?? id} 导入进度`}+ aria-label={t("onboardingAppProgress", {+ name: source?.display_name ?? id,+ })}data-running={running ? "true" : "false"}><div className="r6-import-progress-orbit" aria-hidden="true">@@ -121,18 +140,22 @@ export function R6ImportProgress({{progress ? (<p>{progress}</p>) : noImportedHistory ? (- <p>没有可保存的历史对话</p>+ <p>{text("没有可保存的历史对话")}</p>) : null}<small role="status">- {stale- ? "状态待核对"- : source?.authorized !== true- ? "读取授权不可用"- : job- ? names[job.status]- : "正在导入"}+ {text(+ stale+ ? "状态待核对"+ : source?.authorized !== true+ ? "读取授权不可用"+ : job+ ? names[job.status]+ : "正在导入",+ )}{job && job.errors > 0- ? ` · ${job.errors.toLocaleString()} 条读取异常`+ ? t("onboardingReadErrors", {+ count: job.errors.toLocaleString(locale),+ }): ""}</small></article>diff --git a/memhub/apps/web/src/R6Settings.test.tsx b/memhub/apps/web/src/R6Settings.test.tsxindex 77eec8e..6f9dc6c 100644--- a/memhub/apps/web/src/R6Settings.test.tsx+++ b/memhub/apps/web/src/R6Settings.test.tsx@@ -5,9 +5,32 @@ import userEvent from "@testing-library/user-event";import type { Ref } from "react";import { afterEach, expect, it, vi } from "vitest";import { getModelProfiles, getSedimentation, setSedimentation } from "./api";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { queryClient, resetClient } from "./query-client";import { R6Settings } from "./R6Settings";+it("changes settings copy live without rereading profiles or changing permissions", async () => {+ const user = userEvent.setup();+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const { getModelProfiles } = await import("./api");+ render(+ <LanguageProvider>+ <R6Settings onDiagnostics={vi.fn()} />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("heading", { name: "Modelo de memorias" }),+ ).toBeTruthy();+ expect(+ screen.queryByRole("switch", {+ name: "Permitir que el modelo configurado lea las conversaciones locales",+ }),+ ).toBeNull();+ const reads = vi.mocked(getModelProfiles).mock.calls.length;+ await user.selectOptions(screen.getByRole("combobox"), "zh-CN");+ expect(await screen.findByRole("heading", { name: "记忆模型" })).toBeTruthy();+ expect(vi.mocked(getModelProfiles).mock.calls).toHaveLength(reads);+});vi.mock("./api", () => ({getModelProfiles: vi.fn().mockResolvedValue([{@@ -55,6 +78,7 @@ vi.mock("./diagnostics-export", () => ({}));afterEach(() => {cleanup();+ localStorage.clear();resetClient();vi.clearAllMocks();window.oneMemory = undefined;@@ -70,6 +94,8 @@ it("shows the help and diagnostics group by default and hides it when opted out"} as NonNullable<typeof window.oneMemory>;const user = userEvent.setup();const view = render(<R6Settings onDiagnostics={vi.fn()} />);+ expect(screen.getByRole("combobox")).toBeTruthy();+ expect(screen.getAllByRole("option")).toHaveLength(4);await user.click(screen.getByRole("button", { name: "帮助与诊断" }));expect(screen.getByRole("heading", { name: "帮助与诊断" })).toBeTruthy();expect(screen.getByRole("heading", { name: "导出日志" })).toBeTruthy();diff --git a/memhub/apps/web/src/R6Settings.tsx b/memhub/apps/web/src/R6Settings.tsxindex 3c33e51..b96f154 100644--- a/memhub/apps/web/src/R6Settings.tsx+++ b/memhub/apps/web/src/R6Settings.tsx@@ -11,7 +11,9 @@ import {import { getModelProfiles, setSedimentation } from "./api";import { ConnectionFallback } from "./ConnectionFallback";import { exportDiagnosticsFile } from "./diagnostics-export";+import { LanguageSelector } from "./LanguageSelector";import { ModelSettings, type ModelSettingsActions } from "./ModelSettings";+import { useOnboardingTranslation } from "./onboarding-language";import { R6Button, R6Switch } from "./R6Controls";import {refreshLoginPreference,@@ -55,6 +57,7 @@ export function R6Settings({showDiagnostics?: boolean;}) {const id = useId();+ const { t, text, locale } = useOnboardingTranslation();const groups = showDiagnostics? [...primaryGroups, "help" as const]: primaryGroups;@@ -99,7 +102,7 @@ export function R6Settings({setExportingLogs(true);setExportMessage("");try {- const result = await exportDiagnosticsFile();+ const result = await exportDiagnosticsFile(locale);setExportMessage(result.message);} finally {setExportingLogs(false);@@ -263,10 +266,11 @@ export function R6Settings({}return (- <section className="r6-settings" aria-label="设置">- <h1>设置</h1>+ <section className="r6-settings" aria-label={t("settings")}>+ <h1>{t("settings")}</h1>+ <LanguageSelector /><div className="r6-settings-layout">- <nav aria-label="设置分组">+ <nav aria-label={text("设置分组")}>{groups.map((key) => (<buttontype="button"@@ -277,7 +281,7 @@ export function R6Settings({onKeyDown={moveGroupFocus}onClick={() => setGroup(key)}>- {labels[key]}+ {text(labels[key])}</button>))}</nav>@@ -288,20 +292,23 @@ export function R6Settings({hidden={group !== "model"}className="r6-settings-model">- <h2>记忆模型</h2>+ <h2>{text("记忆模型")}</h2><div className="r6-model-overview">- <p className="r6-model-caption">当前模型</p>+ <p className="r6-model-caption">{text("当前模型")}</p><h3 className="r6-current-model">{currentModel?.name ??- (profiles === null- ? "正在读取模型…"- : modelError- ? "模型状态暂不可读"- : "尚未配置模型")}+ text(+ profiles === null+ ? "正在读取模型…"+ : modelError+ ? "模型状态暂不可读"+ : "尚未配置模型",+ )}</h3>{currentModel && (<p className="r6-model-state">- {currentModel.model} · {safeEndpoint(currentModel.base_url)}+ {currentModel.model} ·{" "}+ {text(safeEndpoint(currentModel.base_url))}</p>)}<div className="r6-model-actions">@@ -310,12 +317,12 @@ export function R6Settings({disabled={profiles === null}onClick={openConfiguration}>- {currentModel ? "修改模型" : "配置模型"}+ {text(currentModel ? "修改模型" : "配置模型")}</R6Button><R6Buttonvariant="quiet"- aria-label="刷新模型状态"- title="刷新模型状态"+ aria-label={text("刷新模型状态")}+ title={text("刷新模型状态")}onClick={() => setModelVersion((value) => value + 1)}><RefreshCw size={16} aria-hidden="true" />@@ -323,29 +330,32 @@ export function R6Settings({</div>{modelError && (<p role="alert" className="r6-settings-error">- {profiles === null- ? "模型状态未能读取,请重试。"- : "模型状态刷新未成功,仍显示上次确认的模型状态;请重试。"}+ {text(+ profiles === null+ ? "模型状态未能读取,请重试。"+ : "模型状态刷新未成功,仍显示上次确认的模型状态;请重试。",+ )}</p>)}{configurationRefusal && (<p role="alert" className="r6-settings-error">- 上次模型测试或创建还待核对,配置暂时不能改动。请先在下方模型配置区核对结果;- 现有配置和原文不会被改动。+ {text(+ "上次模型测试或创建还待核对,配置暂时不能改动。请先在下方模型配置区核对结果; 现有配置和原文不会被改动。",+ )}</p>)}{currentModel && (<div className="r6-setting-row"><div>- <h3>用模型沉淀记忆</h3>+ <h3>{text("用模型沉淀记忆")}</h3><p>- 开启后,导入和同步到本机的会话会交给当前模型整理成记忆,会产生模型调用。- 停止后不再调用模型、不再整理记忆,但会话仍会照常导入和保存;已排队的内容会留着,重新开启后继续。- 模型配置始终保留,重新开启不需要重新填写。+ {text(+ "开启后,导入和同步到本机的会话会交给当前模型整理成记忆,会产生模型调用。 停止后不再调用模型、不再整理记忆,但会话仍会照常导入和保存;已排队的内容会留着,重新开启后继续。 模型配置始终保留,重新开启不需要重新填写。",+ )}</p></div><R6Switch- label="用模型沉淀记忆"+ label={text("用模型沉淀记忆")}checked={sedimentation === true}disabled={sedimentation === null ||@@ -360,19 +370,21 @@ export function R6Settings({)}{sedimentationError && (<p role="alert" className="r6-settings-error">- {sedimentationError}+ {text(sedimentationError)}</p>)}{sedimentationUnavailable && (<p role="alert" className="r6-settings-error">- 当前安装还不能读取这个开关,请确认后台服务已启动后重试。+ {text(+ "当前安装还不能读取这个开关,请确认后台服务已启动后重试。",+ )}</p>)}</div><sectionclassName="r6-model-owner"hidden={!configurationOpen}- aria-label="模型配置表单"+ aria-label={text("模型配置表单")}><ModelSettingscompactSingle@@ -388,7 +400,7 @@ export function R6Settings({hidden={group !== "connections"}className="r6-settings-connections">- <h2>连接其他应用</h2>+ <h2>{text("连接其他应用")}</h2><ConnectionFallback /></section>{showDiagnostics && (@@ -398,14 +410,14 @@ export function R6Settings({hidden={group !== "help"}className="r6-settings-help">- <h2>帮助与诊断</h2>+ <h2>{text("帮助与诊断")}</h2><div className="r6-setting-row"><div>- <h3>登录后启动后台服务</h3>- <p>无需打开界面,持续同步、整理和提供记忆。</p>+ <h3>{text("登录后启动后台服务")}</h3>+ <p>{text("无需打开界面,持续同步、整理和提供记忆。")}</p></div><R6Switch- label="登录后启动后台服务"+ label={text("登录后启动后台服务")}checked={login?.enabled === true}disabled={!dataReady ||@@ -418,15 +430,17 @@ export function R6Settings({</div>{(dataError || readError) && (<p role="alert" className="r6-settings-error">- {dataError || readError}+ {text(dataError || readError)}</p>)}<div className="r6-setting-row"><div>- <h3>导出日志</h3>+ <h3>{text("导出日志")}</h3><p>- {exportMessage ||- "把本机运行日志打包成一个文件,发给开发排查。"}+ {text(+ exportMessage ||+ "把本机运行日志打包成一个文件,发给开发排查。",+ )}</p></div><R6Button@@ -435,15 +449,15 @@ export function R6Settings({onClick={() => void handleExportLogs()}><Download size={16} aria-hidden="true" />- 导出日志+ {text("导出日志")}</R6Button></div><div className="r6-setting-row r6-settings-about"><div>- <h3>关于</h3>+ <h3>{text("关于")}</h3><dl><div>- <dt>版本</dt>+ <dt>{text("版本")}</dt><dd>{buildInfo.version}</dd></div><div>@@ -497,23 +511,25 @@ export function R6Settings({}}}>- <h2 id={`${id}-quit-title`}>确定退出 One Memory 界面吗?</h2>- <p>后台服务会继续同步、整理和提供记忆。</p>+ <h2 id={`${id}-quit-title`}>+ {text("确定退出 One Memory 界面吗?")}+ </h2>+ <p>{text("后台服务会继续同步、整理和提供记忆。")}</p>{quitError && (<p role="alert" className="r6-settings-error">- {quitError}+ {text(quitError)}</p>)}<footer><R6Button disabled={quitting} onClick={() => setQuitOpen(false)}>- 取消+ {text("取消")}</R6Button><R6Buttonvariant="primary"pending={quitting}onClick={() => void quitApplication()}>- 退出界面+ {text("退出界面")}</R6Button></footer></section>diff --git a/memhub/apps/web/src/SdkMemoryLibrary.test.tsx b/memhub/apps/web/src/SdkMemoryLibrary.test.tsxindex 7c153eb..c302184 100644--- a/memhub/apps/web/src/SdkMemoryLibrary.test.tsx+++ b/memhub/apps/web/src/SdkMemoryLibrary.test.tsx@@ -18,6 +18,7 @@ vi.mock("./api", () => ({updateSdkMemory,}));+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { SdkMemoryLibrary } from "./SdkMemoryLibrary";const memory = {@@ -52,7 +53,26 @@ describe("SDK memory library", () => {);deleteSdkMemory.mockResolvedValue(undefined);});- afterEach(cleanup);+ afterEach(() => {+ cleanup();+ localStorage.clear();+ });++ it("localizes controls while leaving memory content unchanged", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <SdkMemoryLibrary active />+ </LanguageProvider>,+ );+ expect(+ await screen.findByRole("navigation", {+ name: "Estado de la memoria",+ }),+ ).toBeTruthy();+ expect(screen.getByRole("button", { name: "original" })).toBeTruthy();+ expect(screen.getByText("1 memoria")).toBeTruthy();+ });it("edits the same memory id and physically deletes without revision or undo", async () => {render(<SdkMemoryLibrary active />);diff --git a/memhub/apps/web/src/SdkMemoryLibrary.tsx b/memhub/apps/web/src/SdkMemoryLibrary.tsxindex 1cc5648..e7253e7 100644--- a/memhub/apps/web/src/SdkMemoryLibrary.tsx+++ b/memhub/apps/web/src/SdkMemoryLibrary.tsx@@ -1,11 +1,12 @@import type { SdkMemoryRecord, SdkMemoryStatus } from "@one-memory/contracts";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {deleteSdkMemory,getSdkMemory,getSdkMemoryLibrary,updateSdkMemory,} from "./api";+import { useGuiLanguage } from "./gui-language";import { R6Button } from "./R6Controls";export function SdkMemoryLibrary({@@ -17,6 +18,9 @@ export function SdkMemoryLibrary({onChanged?(): void;focusedMemoryId?: string | null;}) {+ const { t, tn } = useGuiLanguage();+ const translation = useRef(t);+ translation.current = t;const [status, setStatus] = useState<SdkMemoryStatus>("active");const [offset, setOffset] = useState(0);const [rows, setRows] = useState<SdkMemoryRecord[]>([]);@@ -42,7 +46,7 @@ export function SdkMemoryLibrary({if (offset >= page.total && offset > 0)setOffset(Math.max(0, offset - limit));} catch {- setError("记忆库读取失败,请重试。");+ setError(translation.current("sdk.memory.loadFailed"));} finally {setBusy(false);}@@ -60,7 +64,7 @@ export function SdkMemoryLibrary({setSelected(memory);setDraft(memory.content);} catch {- setError("记忆详情读取失败。");+ setError(translation.current("sdk.memory.detailLoadFailed"));} finally {setBusy(false);}@@ -80,7 +84,7 @@ export function SdkMemoryLibrary({await refresh();onChanged?.();} catch {- setError("修改未完成,请重试。");+ setError(t("sdk.memory.updateFailed"));} finally {setBusy(false);}@@ -96,19 +100,19 @@ export function SdkMemoryLibrary({await refresh();onChanged?.();} catch {- setError("删除未完成,请重试。");+ setError(t("sdk.memory.deleteFailed"));} finally {setBusy(false);}}return (- <section className="sdk-memory-library" aria-label="SDK 记忆库">- <nav aria-label="记忆状态">+ <section className="sdk-memory-library" aria-label={t("sdk.memory.title")}>+ <nav aria-label={t("sdk.memory.status")}>{([- ["active", "已可用"],- ["superseded", "已被取代"],+ ["active", t("sdk.memory.status.active")],+ ["superseded", t("sdk.memory.status.superseded")],] as const).map(([value, label]) => (<button@@ -126,9 +130,11 @@ export function SdkMemoryLibrary({</button>))}</nav>- <p aria-live="polite">共 {total} 条</p>+ <p aria-live="polite">{tn("sdk.memory.total", total)}</p>{error && <p role="alert">{error}</p>}- {busy && !rows.length ? <p role="status">正在读取记忆库…</p> : null}+ {busy && !rows.length ? (+ <p role="status">{t("sdk.memory.loading")}</p>+ ) : null}<ul>{rows.map((memory) => (<li key={memory.memory_id}>@@ -138,29 +144,29 @@ export function SdkMemoryLibrary({</li>))}</ul>- <nav aria-label="SDK 记忆库分页">+ <nav aria-label={t("sdk.memory.pagination")}><R6Buttonvariant="quiet"disabled={busy || offset === 0}onClick={() => setOffset(Math.max(0, offset - limit))}>- 上一页+ {t("sdk.memory.previous")}</R6Button><R6Buttonvariant="quiet"disabled={busy || offset + limit >= total}onClick={() => setOffset(offset + limit)}>- 下一页+ {t("sdk.memory.next")}</R6Button></nav>{selected ? (- <aside aria-label="SDK 记忆详情">+ <aside aria-label={t("sdk.memory.detail")}><p>{selected.layer}</p>{selected.status === "active" ? (<><textarea- aria-label="记忆内容"+ aria-label={t("sdk.memory.content")}value={draft}disabled={busy}onChange={(event) => setDraft(event.target.value)}@@ -171,10 +177,10 @@ export function SdkMemoryLibrary({pending={busy}onClick={() => void save()}>- 保存修改+ {t("sdk.memory.save")}</R6Button><R6Button pending={busy} onClick={() => void remove()}>- 删除记忆+ {t("sdk.memory.delete")}</R6Button></>) : (diff --git a/memhub/apps/web/src/SdkRawHistory.test.tsx b/memhub/apps/web/src/SdkRawHistory.test.tsxindex dbe5d4e..229094c 100644--- a/memhub/apps/web/src/SdkRawHistory.test.tsx+++ b/memhub/apps/web/src/SdkRawHistory.test.tsx@@ -9,9 +9,45 @@ const { getSdkRaw, searchSdkRaw } = vi.hoisted(() => ({}));vi.mock("./api", () => ({ getSdkRaw, searchSdkRaw }));+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { SdkRawHistory } from "./SdkRawHistory";-afterEach(cleanup);+afterEach(() => {+ cleanup();+ localStorage.clear();+});++it("localizes controls without translating original conversation fields", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ getSdkRaw.mockResolvedValue({+ items: [+ {+ raw_id: "raw-es",+ content: "原始内容 sin traducir",+ user_id: "local",+ agent_id: "one-memory",+ session_id: "sesión-original",+ source: "cursor",+ memory_at: null,+ gmt_created: null,+ custom: {},+ },+ ],+ total: 1,+ offset: 0,+ limit: 100,+ });+ render(+ <LanguageProvider>+ <SdkRawHistory />+ </LanguageProvider>,+ );+ expect(+ await screen.findByLabelText("Buscar conversaciones originales"),+ ).toBeTruthy();+ expect(screen.getByText("原始内容 sin traducir")).toBeTruthy();+ expect(screen.getByText(/sesión-original/)).toBeTruthy();+});it("lists and searches SDK raw without legacy conversation APIs", async () => {getSdkRaw.mockResolvedValue({diff --git a/memhub/apps/web/src/SdkRawHistory.tsx b/memhub/apps/web/src/SdkRawHistory.tsxindex 5942c2d..e7065b4 100644--- a/memhub/apps/web/src/SdkRawHistory.tsx+++ b/memhub/apps/web/src/SdkRawHistory.tsx@@ -1,8 +1,12 @@import type { SdkRawContextItem, SdkRawRecord } from "@one-memory/contracts";-import { type FormEvent, useEffect, useState } from "react";+import { type FormEvent, useEffect, useRef, useState } from "react";import { getSdkRaw, searchSdkRaw } from "./api";+import { useGuiLanguage } from "./gui-language";export function SdkRawHistory() {+ const { locale, t, tn } = useGuiLanguage();+ const translation = useRef(t);+ translation.current = t;const [recent, setRecent] = useState<SdkRawRecord[]>([]);const [results, setResults] = useState<SdkRawContextItem[] | null>(null);const [query, setQuery] = useState("");@@ -16,7 +20,7 @@ export function SdkRawHistory() {if (current) setRecent(page.items);},() => {- if (current) setError("原始对话暂时无法读取。");+ if (current) setError(translation.current("sdk.raw.loadFailed"));},);return () => {@@ -32,7 +36,7 @@ export function SdkRawHistory() {try {setResults(await searchSdkRaw(query.trim()));} catch {- setError("原始对话搜索失败,请重试。");+ setError(t("sdk.raw.searchFailed"));} finally {setBusy(false);}@@ -40,22 +44,24 @@ export function SdkRawHistory() {const items = results ?? recent.map(asContextItem);return (- <section aria-label="SDK 原始对话">+ <section aria-label={t("sdk.raw.title")}><form onSubmit={(event) => void submit(event)}><label>- 搜索原始对话+ {t("sdk.raw.searchLabel")}<inputvalue={query}onChange={(event) => setQuery(event.target.value)}/></label><button type="submit" disabled={busy || !query.trim()}>- {busy ? "搜索中…" : "搜索"}+ {busy ? t("sdk.raw.searching") : t("sdk.raw.search")}</button></form>{error ? <p role="alert">{error}</p> : null}<p aria-live="polite">- {results === null ? "最近原始对话" : `找到 ${items.length} 条`}+ {results === null+ ? t("sdk.raw.recent")+ : tn("sdk.raw.found", items.length)}</p><ol>{items.map((item) => (@@ -64,7 +70,7 @@ export function SdkRawHistory() {<small>{item.source} · {item.session_id}{item.memory_at- ? ` · ${new Date(item.memory_at).toLocaleString("zh-CN")}`+ ? ` · ${new Date(item.memory_at).toLocaleString(locale)}`: ""}</small></li>diff --git a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx b/memhub/apps/web/src/SelectedMemoryDetail.test.tsxindex bb79bee..a332e18 100644--- a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx+++ b/memhub/apps/web/src/SelectedMemoryDetail.test.tsx@@ -11,8 +11,32 @@ import {} from "@testing-library/react";import { StrictMode } from "react";import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { SelectedMemoryDetail } from "./SelectedMemoryDetail";+it("localizes informational details and dates while preserving evidence and memory", async () => {+ delete window.oneMemory;+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <SelectedMemoryDetail+ detail={detail}+ sources={[]}+ onChanged={vi.fn()}+ hideActions+ />+ </LanguageProvider>,+ );+ expect(await screen.findByText("Guardada · Versión 2")).toBeTruthy();+ expect(+ screen.getByRole("heading", { name: "Evidencia original" }),+ ).toBeTruthy();+ expect(screen.getByText("这次先确认范围。")).toBeTruthy();+ expect(correct).not.toHaveBeenCalled();+ expect(remove).not.toHaveBeenCalled();+ localStorage.clear();+});+const { correct, read, remove, errorCode } = vi.hoisted(() => ({correct: vi.fn(),read: vi.fn(),diff --git a/memhub/apps/web/src/SelectedMemoryDetail.tsx b/memhub/apps/web/src/SelectedMemoryDetail.tsxindex 56ae89a..4621e15 100644--- a/memhub/apps/web/src/SelectedMemoryDetail.tsx+++ b/memhub/apps/web/src/SelectedMemoryDetail.tsx@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import { apiErrorCode, correctMemory, getMemory, mutateMemory } from "./api";import { clockStamp } from "./clock-stamp";+import { useGuiLanguage } from "./gui-language";import { R6Button } from "./R6Controls";import { sourceNameOr } from "./source-label";import { traceUiAction } from "./ui-trace";@@ -27,6 +28,7 @@ export function SelectedMemoryDetail({/** D99: when the cited conversation happened, in the list's own terms. */conversationAt?: { at: string; basis: "conversation" | "import" } | null;}) {+ const { locale, t } = useGuiLanguage();const [page, setPage] = useState<Page>("read");const [draft, setDraft] = useState(detail.memory.content);const [base, setBase] = useState(detail.memory.revision);@@ -50,13 +52,17 @@ export function SelectedMemoryDetail({const evidence = detail.evidence[0];const statusLabel =memory.status === "confirmed"- ? "已沉淀"+ ? t("selectedMemory.status.confirmed"): memory.status === "deleted"- ? "已删除"+ ? t("selectedMemory.status.deleted"): memory.status === "superseded"- ? "已被取代"- : "状态待核对";- const source = sourceNameOr(sources, evidence?.source_id, "来源待核对");+ ? t("selectedMemory.status.superseded")+ : t("selectedMemory.status.unknown");+ const source = sourceNameOr(+ sources,+ evidence?.source_id,+ t("selectedMemory.sourceUnknown"),+ );const dirty = page === "edit" && draft !== memory.content;useEffect(() => {if (page === "edit" && memory.revision > base) setConflictFound(true);@@ -85,7 +91,7 @@ export function SelectedMemoryDetail({}, [dirty]);function close() {if (busy) return;- if (dirty && !window.confirm("放弃尚未保存的修改?")) return;+ if (dirty && !window.confirm(t("selectedMemory.discardDraft"))) return;setPage("read");setError("");setConflictFound(false);@@ -98,7 +104,7 @@ export function SelectedMemoryDetail({const latest = await getMemory(memory.memory_id);if (alive.current) setConflict(latest);} catch {- if (alive.current) setError("暂时无法读取新版本,草稿已保留。");+ if (alive.current) setError(t("selectedMemory.newVersionReadFailed"));} finally {if (alive.current) setBusy(false);}@@ -138,8 +144,8 @@ export function SelectedMemoryDetail({setConflictFound(true);setError("");} else if (isDefiniteRefusal(reason))- setError("修改未提交;草稿已保留。请按提示修正后重试。");- else setError("修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。");+ setError(t("selectedMemory.updateRejected"));+ else setError(t("selectedMemory.updateUnknown"));}} finally {flight.current = false;@@ -175,8 +181,8 @@ export function SelectedMemoryDetail({if (alive.current)setError(refused- ? "删除未提交。请核对这条记忆的状态后重试。"- : "删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。",+ ? t("selectedMemory.deleteRejected")+ : t("selectedMemory.deleteUnknown"),);} finally {flight.current = false;@@ -207,8 +213,8 @@ export function SelectedMemoryDetail({if (alive.current)setError(refused- ? "撤销未提交。请按提示修正后重试。"- : "撤销尚未确认,请先核对当前记忆版本,避免重复撤销。",+ ? t("selectedMemory.undoRejected")+ : t("selectedMemory.undoUnknown"),);} finally {flight.current = false;@@ -217,11 +223,11 @@ export function SelectedMemoryDetail({}const author =evidence?.written_by === "person" || evidence?.written_by === "user"- ? "你说"+ ? t("selectedMemory.author.you"): evidence?.written_by === "agent" || evidence?.written_by === "assistant"- ? "助手原话"- : "作者待核对";- const timestamp = clockStamp(evidence?.created_at);+ ? t("selectedMemory.author.assistant")+ : t("selectedMemory.author.unknown");+ const timestamp = clockStamp(evidence?.created_at, locale);const split = memory.content.search(/[。\n]/);const heading =split > 0 && split < 85@@ -236,17 +242,24 @@ export function SelectedMemoryDetail({data-hide-actions={hideActions ? "true" : "false"}><p className="selected-memory-status">- {statusLabel} · 第 {memory.revision} 版+ {statusLabel} ·{" "}+ {t("selectedMemory.version", {+ revision: new Intl.NumberFormat(locale).format(memory.revision),+ })}</p><h3>{heading}</h3>{body && <p className="selected-memory-body">{body}</p>}<p className="selected-memory-source">- 来源 {source} · {timestamp}+ {t("selectedMemory.sourceLine", { source, time: timestamp })}</p><p className="selected-memory-times">- 对话时间 {clockStamp(conversationAt?.at ?? evidence?.created_at)}- {" · "}- 沉淀时间 {clockStamp(memory.updated_at)}+ {t("selectedMemory.timestamps", {+ conversation: clockStamp(+ conversationAt?.at ?? evidence?.created_at,+ locale,+ ),+ created: clockStamp(memory.updated_at, locale),+ })}</p>{!hideActions && (<R6Button@@ -260,16 +273,18 @@ export function SelectedMemoryDetail({setPage("edit");}}>- 编辑+ {t("selectedMemory.edit")}</R6Button>)}<section className="selected-memory-evidence">- <h4>原始依据</h4>+ <h4>{t("selectedMemory.evidence")}</h4><small>- {author} · 原对话 {timestamp}:+ {t("selectedMemory.evidenceLine", { author, time: timestamp })}</small><blockquote>- {evidence?.available ? evidence.verbatim : "这段原文当前不可查看。"}+ {evidence?.available+ ? evidence.verbatim+ : t("selectedMemory.evidenceUnavailable")}</blockquote>{!hideActions && (<R6Button@@ -278,20 +293,24 @@ export function SelectedMemoryDetail({setPage("original");}}>- 查看原文+ {t("selectedMemory.viewOriginal")}</R6Button>)}</section>{!hideActions && (<R6Button variant="quiet" onClick={() => setShowHistory((v) => !v)}>- 版本记录+ {t("selectedMemory.history")}</R6Button>)}{!hideActions && showHistory && (<ol className="selected-memory-history">{detail.history.map((v) => (<li key={v.revision}>- <small>第 {v.revision} 版</small>+ <small>+ {t("selectedMemory.version", {+ revision: new Intl.NumberFormat(locale).format(v.revision),+ })}+ </small><p>{v.content}</p></li>))}@@ -299,10 +318,10 @@ export function SelectedMemoryDetail({)}{!hideActions && (<details className="selected-memory-more">- <summary>更多管理</summary>+ <summary>{t("selectedMemory.more")}</summary>{detail.history.length > 1 && (<R6Button pending={busy} onClick={() => void govern("undo")}>- 撤销上次修改+ {t("selectedMemory.undo")}</R6Button>)}<R6Button@@ -312,7 +331,7 @@ export function SelectedMemoryDetail({setPage("delete");}}>- 删除记忆+ {t("selectedMemory.delete")}</R6Button></details>)}@@ -325,10 +344,10 @@ export function SelectedMemoryDetail({hidden={suspended}aria-label={page === "edit"- ? "编辑记忆"+ ? t("selectedMemory.editTitle"): page === "original"- ? "原始对话"- : "删除记忆"+ ? t("selectedMemory.originalTitle")+ : t("selectedMemory.delete")}onKeyDown={(event) => {if (event.key === "Tab") {@@ -360,20 +379,20 @@ export function SelectedMemoryDetail({<header><h1 ref={focus} tabIndex={-1}>{page === "edit"- ? "编辑记忆"+ ? t("selectedMemory.editTitle"): page === "original"- ? "原始对话"- : "删除记忆"}+ ? t("selectedMemory.originalTitle")+ : t("selectedMemory.delete")}</h1>{page === "original" && (- <R6Button onClick={close}>返回记忆</R6Button>+ <R6Button onClick={close}>{t("selectedMemory.back")}</R6Button>)}</header>{page === "edit" ? (<div className="selected-editor">- <p>修改这条记忆,原始对话保持不变。</p>+ <p>{t("selectedMemory.editDescription")}</p><textarea- aria-label="记忆内容"+ aria-label={t("selectedMemory.content")}name="memory-content"value={draft}disabled={busy}@@ -383,16 +402,16 @@ export function SelectedMemoryDetail({request.current = null;}}/>- <p>使用范围保持不变</p>+ <p>{t("selectedMemory.scopeUnchanged")}</p>{conflictFound && (<section className="selected-conflict">- <h2>已有新版本</h2>- <p>你的草稿已保留,先查看新版本再决定如何修改。</p>+ <h2>{t("selectedMemory.conflictTitle")}</h2>+ <p>{t("selectedMemory.conflictDescription")}</p><R6Buttonpending={busy}onClick={() => void refreshConflict()}>- 查看新版本+ {t("selectedMemory.viewNewVersion")}</R6Button>{conflict && (<>@@ -404,7 +423,7 @@ export function SelectedMemoryDetail({request.current = null;}}>- 基于此版本继续编辑+ {t("selectedMemory.continueFromVersion")}</R6Button></>)}@@ -412,7 +431,7 @@ export function SelectedMemoryDetail({)}<div className="selected-page-actions"><R6Button disabled={busy} onClick={close}>- 取消+ {t("selectedMemory.cancel")}</R6Button><R6Buttonvariant="primary"@@ -420,7 +439,7 @@ export function SelectedMemoryDetail({disabled={!draft.trim() || conflictFound}onClick={() => void save()}>- 保存修改+ {t("selectedMemory.save")}</R6Button></div></div>@@ -433,43 +452,50 @@ export function SelectedMemoryDetail({{detail.evidence.map((item) => (<section key={item.evidence_id}><small>- {sourceNameOr(sources, item.source_id, "来源待核对")} ·{" "}+ {sourceNameOr(+ sources,+ item.source_id,+ t("selectedMemory.sourceUnknown"),+ )}{" "}+ ·{" "}{item.written_by === "person"- ? "你"+ ? t("selectedMemory.author.user"): item.written_by === "agent"- ? "助手"- : "作者待核对"}+ ? t("selectedMemory.author.agent")+ : t("selectedMemory.author.unknown")}</small><blockquote>{item.available? item.verbatim- : "来源权限已变化或原文不可用。"}+ : t("selectedMemory.sourceUnavailable")}</blockquote></section>))}- <small>对应记忆</small>+ <small>{t("selectedMemory.related")}</small><h2>{heading}</h2>- <R6Button onClick={close}>查看记忆</R6Button>+ <R6Button onClick={close}>+ {t("selectedMemory.viewMemory")}+ </R6Button></div>) : (<div className="selected-delete">- <h2>删除这条记忆?</h2>+ <h2>{t("selectedMemory.deleteTitle")}</h2><p>{heading}</p><p>- 删除后不再用于新的召回,来源 App 中的原始对话不会删除。+ {t("selectedMemory.deleteDescription")}<br />- 已经发送给应用的内容无法远程收回。+ {t("selectedMemory.sentCannotRecall")}</p><div className="selected-page-actions"><R6Button disabled={busy} onClick={close}>- 取消+ {t("selectedMemory.cancel")}</R6Button><R6Buttonvariant="primary"pending={busy}onClick={() => void remove()}>- 删除记忆+ {t("selectedMemory.delete")}</R6Button></div></div>diff --git a/memhub/apps/web/src/SourceImportReceipt.tsx b/memhub/apps/web/src/SourceImportReceipt.tsxindex 84a3f23..dc4e62f 100644--- a/memhub/apps/web/src/SourceImportReceipt.tsx+++ b/memhub/apps/web/src/SourceImportReceipt.tsx@@ -3,9 +3,11 @@ import type {SourceImportReceipt as Receipt,SourceResponse,} from "@one-memory/contracts";+import type { GuiLocale } from "@one-memory/i18n";import { FileText, RefreshCw, X } from "lucide-react";import { useEffect, useRef, useState } from "react";import { getConversation, getSourceImportReceipt } from "./api";+import { memoryText, useMemoryLanguage } from "./memory-language";export function SourceImportReceipt({ source }: { source: SourceResponse }) {return source.authorized ? (@@ -14,6 +16,7 @@ export function SourceImportReceipt({ source }: { source: SourceResponse }) {}function ReceiptBody({ source }: { source: SourceResponse }) {+ const { locale, text, count } = useMemoryLanguage();const [receipt, setReceipt] = useState<Receipt | null>(null);const [error, setError] = useState("");const [loading, setLoading] = useState(false);@@ -97,85 +100,96 @@ function ReceiptBody({ source }: { source: SourceResponse }) {}}}>- <summary>查看已读内容</summary>+ <summary>{text("查看已读内容")}</summary>{opened && (<div className="source-receipt-body"><header>- <span>已保存原文 · {source.display_name}</span>+ <span>+ {text("已保存原文")} · {source.display_name}+ </span><buttontype="button"className="quiet"- title="刷新已读内容"- aria-label="刷新已读内容"+ title={text("刷新已读内容")}+ aria-label={text("刷新已读内容")}disabled={loading}onClick={() => void load()}><RefreshCw size={15} /></button></header>- {loading && <p role="status">正在核对本机已保存记录…</p>}- {error && <p role="alert">{error}</p>}+ {loading && <p role="status">{text("正在核对本机已保存记录…")}</p>}+ {error && <p role="alert">{text(error)}</p>}{receipt && (<><dl className="source-receipt-counts"><div>- <dt>原始消息</dt>- <dd>{receipt.messages.toLocaleString()}</dd>+ <dt>{text("原始消息")}</dt>+ <dd>{receipt.messages.toLocaleString(locale)}</dd></div><div>- <dt>会话</dt>- <dd>{receipt.conversations.toLocaleString()}</dd>+ <dt>{text("会话")}</dt>+ <dd>{receipt.conversations.toLocaleString(locale)}</dd></div><div>- <dt>用户发言</dt>- <dd>{receipt.person_messages.toLocaleString()}</dd>+ <dt>{text("用户发言")}</dt>+ <dd>{receipt.person_messages.toLocaleString(locale)}</dd></div><div>- <dt>Agent 发言</dt>- <dd>{receipt.agent_messages.toLocaleString()}</dd>+ <dt>{text("Agent 发言")}</dt>+ <dd>{receipt.agent_messages.toLocaleString(locale)}</dd></div><div>- <dt>作者未知</dt>- <dd>{receipt.unknown_author_messages.toLocaleString()}</dd>+ <dt>{text("作者未知")}</dt>+ <dd>+ {receipt.unknown_author_messages.toLocaleString(locale)}+ </dd></div><div>- <dt>原始时间未知</dt>- <dd>{receipt.unknown_time_messages.toLocaleString()}</dd>+ <dt>{text("原始时间未知")}</dt>+ <dd>+ {receipt.unknown_time_messages.toLocaleString(locale)}+ </dd></div>{receipt.tool_messages > 0 && (<div>- <dt>工具记录</dt>- <dd>{receipt.tool_messages.toLocaleString()}</dd>+ <dt>{text("工具记录")}</dt>+ <dd>{receipt.tool_messages.toLocaleString(locale)}</dd></div>)}</dl><p className="source-receipt-note">{receipt.unknown_time_messages > 0- ? `${receipt.unknown_time_messages.toLocaleString()} 条记录没有原始时间,未用导入时间代替。`- : "原始时间来自已保存记录。"}{" "}- 作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。+ ? text("{count} 条记录没有原始时间,未用导入时间代替。", {+ count: count(receipt.unknown_time_messages),+ })+ : text("原始时间来自已保存记录。")}{" "}+ {text(+ "作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。",+ )}</p><p className="source-receipt-meta">- 统计于 {time(receipt.measured_at)}+ {text("统计于 ")}+ {time(receipt.measured_at, locale)}{receipt.messages !== source.imported_messages- ? " · 导入数量仍在更新,可刷新核对"+ ? text(" · 导入数量仍在更新,可刷新核对"): ""}</p>{receipt.examples.length > 0 ? (<sectionclassName="source-receipt-examples"- aria-label="已保存的原文样例"+ aria-label={text("已保存的原文样例")}>- <h3>已保存的原文样例</h3>+ <h3>{text("已保存的原文样例")}</h3><p className="source-receipt-meta">- 最多展示 3 段,不代表全部历史或推荐记忆。+ {text("最多展示 3 段,不代表全部历史或推荐记忆。")}</p>{receipt.examples.map((example) => (<article key={example.evidence_id}><header><span>- {author(example.written_by)} ·{" "}- {time(example.created_at)}+ {text(author(example.written_by))} ·{" "}+ {time(example.created_at, locale)}</span><buttontype="button"@@ -183,35 +197,37 @@ function ReceiptBody({ source }: { source: SourceResponse }) {onClick={() => void read(example.evidence_id)}><FileText size={14} aria-hidden="true" />- 查看完整对话+ {text("查看完整对话")}</button></header><p className="source-receipt-quote">{example.excerpt}</p>{example.truncated && (- <small>原文较长,此处仅展示前 600 个字符。</small>+ <small>+ {text("原文较长,此处仅展示前 600 个字符。")}+ </small>)}</article>))}</section>) : (- <p>这个来源还没有保存原文。</p>+ <p>{text("这个来源还没有保存原文。")}</p>)}</>)}- {reading && <p role="status">正在读取完整对话…</p>}- {readError && <p role="alert">{readError}</p>}+ {reading && <p role="status">{text("正在读取完整对话…")}</p>}+ {readError && <p role="alert">{text(readError)}</p>}{transcript && (<sectionclassName="source-receipt-conversation"- aria-label="完整对话"+ aria-label={text("完整对话")}><header>- <h3>完整对话</h3>+ <h3>{text("完整对话")}</h3><buttontype="button"className="quiet"- title="关闭完整对话"- aria-label="关闭完整对话"+ title={text("关闭完整对话")}+ aria-label={text("关闭完整对话")}onClick={() => {conversationGeneration.current++;setTranscript(null);@@ -224,7 +240,8 @@ function ReceiptBody({ source }: { source: SourceResponse }) {{transcript.messages.map((message) => (<li key={message.evidence_id}><small>- {author(message.written_by)} · {time(message.created_at)}+ {text(author(message.written_by))} ·{" "}+ {time(message.created_at, locale)}</small><p>{message.verbatim}</p></li>@@ -247,8 +264,8 @@ function author(value: string) {? "工具": "作者未知";}-function time(value: string | null) {+function time(value: string | null, locale: GuiLocale) {return value && Number.isFinite(Date.parse(value))- ? new Date(value).toLocaleString()- : "时间未知";+ ? new Date(value).toLocaleString(locale)+ : memoryText(locale, "时间未知");}diff --git a/memhub/apps/web/src/Workbench.test.tsx b/memhub/apps/web/src/Workbench.test.tsxindex bc8d0e0..0f55b48 100644--- a/memhub/apps/web/src/Workbench.test.tsx+++ b/memhub/apps/web/src/Workbench.test.tsx@@ -18,8 +18,40 @@ import {} from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";+import { OptionMenu } from "./OptionMenu";+import { Answer, Workbench } from "./Workbench";++it("localiza la selección vacía del menú auxiliar", () => {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <OptionMenu value="" options={[]} onChange={vi.fn()} />+ </LanguageProvider>,+ );+ expect(+ screen.getByRole("button", { name: "Selecciona una opción" }),+ ).toBeTruthy();+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});-import { Workbench } from "./Workbench";+it("traduce la respuesta visible sin traducir la respuesta del modelo", () => {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <Answer+ answer={null}+ streaming={{ text: "Respuesta 中文 opaca", memories: [] }}+ onOpenMemory={vi.fn()}+ onSaveAnswer={vi.fn()}+ asPage={false}+ />+ </LanguageProvider>,+ );+ expect(screen.getByText("Respuesta 中文 opaca")).toBeTruthy();+ expect(screen.getByText("Se recuperaron 0 memorias")).toBeTruthy();+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});const getConversation = vi.fn();@@ -222,6 +254,49 @@ function mount(props: Partial<Parameters<typeof Workbench>[0]> = {}) {return { ...handlers, view };}+it("localiza el espacio vacío y sus controles", () => {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ const props = {+ memories: [],+ graph: null,+ sources: [],+ processing: null,+ loaded: true,+ detail: null,+ draft: "",+ scopes: "",+ busy: false,+ answer: null,+ streaming: null,+ requestIds: { current: new Map() },+ onDraft: vi.fn(),+ onScopes: vi.fn(),+ onOpenMemory: vi.fn(),+ onCloseDetail: vi.fn(),+ onSave: vi.fn(),+ onAction: vi.fn(),+ onSyncIndex: vi.fn(),+ onAsk: vi.fn(),+ onSaveAnswer: vi.fn(),+ onBuildRelations: vi.fn(),+ onConnect: vi.fn(),+ onConfigureModel: vi.fn(),+ };+ render(+ <LanguageProvider>+ <Workbench {...props} />+ </LanguageProvider>,+ );+ expect(screen.getByRole("navigation", { name: "Temas" })).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Autorizar una fuente" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("textbox", { name: "Preguntar sobre este asunto" }),+ ).toBeTruthy();+ window.localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});+it("选中的图节点把记忆库与详情联到一起(图 → 列表 → 原文)", async () => {// The goal requires the graph, the memory list and the original text to be// linked in both directions. The list→graph direction is covered elsewhere@@ -796,4 +871,36 @@ describe("按主题聚类", () => {expect(panel.textContent).toContain("同一个主题");expect(panel.textContent).not.toContain("原话来源");});++ it("Core 送来未知的节点类型或连线来头时,仍然说得出一个词而不是留空", async () => {+ const user = userEvent.setup();+ mount({+ graph: {+ total_memories: 1,+ projected_memories: 1,+ hy_graph_available: false,+ nodes: [+ { node_id: "future:x", node_type: "future_kind", label: "新节点" },+ { node_id: "memory:a", node_type: "memory", label: "统一走 axios" },+ ],+ edges: [+ {+ edge_id: "e1",+ source_node_id: "future:x",+ target_node_id: "memory:a",+ relation: "related_to",+ origin: "future_origin",+ },+ ],+ } as unknown as MemoryGraphResponse,+ });++ await user.click(screen.getByRole("button", { name: "新节点" }));++ const panel = screen.getByLabelText("这个节点");+ expect(panel.querySelector(".wb-status")?.textContent).toBe("记忆");+ expect(panel.querySelector(".wb-trace-origin")?.textContent).toBe(+ "原话来源",+ );+ });});diff --git a/memhub/apps/web/src/Workbench.tsx b/memhub/apps/web/src/Workbench.tsxindex 40a622d..dc858a4 100644--- a/memhub/apps/web/src/Workbench.tsx+++ b/memhub/apps/web/src/Workbench.tsx@@ -11,6 +11,7 @@ import type {SdkAskMemory,SourceResponse,} from "@one-memory/contracts";+import { isMessageKey } from "@one-memory/i18n";import { Check, PencilLine, RotateCcw, Trash2 } from "lucide-react";import {type FormEvent,@@ -20,9 +21,9 @@ import {useState,} from "react";import { getConversation } from "./api";+import { useGuiLanguage } from "./gui-language";import { HandoffBar } from "./HandoffBar";import { MemoryGraph3D } from "./MemoryGraph3D";-import { memoryProvenanceLabel } from "./MemoryRecallScope";import { extractionStateLabel } from "./memory-processing-labels";import {type Finding,@@ -32,6 +33,10 @@ import {} from "./workbench-findings";import { singletonTags, tagCounts } from "./workbench-tags";+type Translate = ReturnType<typeof useGuiLanguage>["t"];+type TranslateCount = ReturnType<typeof useGuiLanguage>["tn"];+type GuiLocale = ReturnType<typeof useGuiLanguage>["locale"];+/** The memory tab: three columns over one graph.** Left is what the memories are about, centre is how they relate and where@@ -97,6 +102,7 @@ export function Workbench({* reuses the request id prepared for text the user has since replaced. */requestIds: RefObject<Map<string, string>>;}) {+ const { locale, t, tn } = useGuiLanguage();const [matter, setMatter] = useState("");const [selectedNode, setSelectedNode] = useState<MemoryGraphNode | null>(null,@@ -122,8 +128,14 @@ export function Workbench({[memories, matter],);const findings = useMemo(- () => findingsOf({ memories: inMatter, processing, now: new Date() }),- [inMatter, processing],+ () =>+ findingsOf({+ memories: inMatter,+ processing,+ now: new Date(),+ locale,+ }),+ [inMatter, processing, locale],);// Counted across the whole library, not this matter. A tag used once here// and once elsewhere is a tag used twice; scoping this to the matter would@@ -137,8 +149,8 @@ export function Workbench({// fails. Keying the skeleton on null meant the one screen it existed for// never saw it.const drawn = graph ? narrow(graph, inMatter, matter) : null;- return drawn?.nodes.length ? drawn : skeleton(sources, graph);- }, [graph, inMatter, matter, sources]);+ return drawn?.nodes.length ? drawn : skeleton(sources, graph, tn);+ }, [graph, inMatter, matter, sources, tn]);const evidence = useMemo(() => orderEvidence(detail, highlighted, memories),[detail, highlighted, memories],@@ -157,14 +169,16 @@ export function Workbench({setTranscript(await getConversation(evidenceId));} catch {setTranscript(null);- setTranscriptError("这段对话的原文已经不在库里了。");+ setTranscriptError(t("wb.transcriptGone"));}}const nameOf = (sourceId: string | null) =>sources.find((item) => item.source_id === sourceId)?.display_name ??sourceId ??- "未知来源";+ t("wb.unknownSource");+ const matterLabel = (scope: string, label: string) =>+ scope ? label : t("wb.all");return (<div className="workbench">@@ -176,16 +190,16 @@ export function Workbench({belongs to — is a workspace scope, and its plaintext name lives onthe evidence rows in Core; nothing here can recover it from thehash, so calling this column 事项 named something it was not. */}- <nav className="wb-matters" aria-label="主题">- <p className="wb-column-label">主题</p>+ <nav className="wb-matters" aria-label={t("wb.topics")}>+ <p className="wb-column-label">{t("wb.topics")}</p>{allTags.length ? (// Says the two numbers the column actually shows: how many// topics took shape, and how many tags did not. Reporting one// total meant reading "22 个主题标签" above six rows.<p className="wb-tag-tally">{onceOnly.size === 0- ? `${allTags.length - onceOnly.size} 个主题成形`- : `${allTags.length - onceOnly.size} 个主题成形,另有 ${onceOnly.size} 个标签只出现过一次`}+ ? tn("wb.topicCount", allTags.length - onceOnly.size)+ : `${tn("wb.topicCount", allTags.length - onceOnly.size)}${tn("wb.singletons", onceOnly.size)}`}</p>) : null}{matters.map((item) => (@@ -201,10 +215,12 @@ export function Workbench({setTranscript(null);}}>- {item.label}+ {matterLabel(item.scope, item.label)}<small>- {item.memoryCount} 条记忆- {item.sourceCount ? ` · ${item.sourceCount} 个来源` : ""}+ {tn("wb.memories", item.memoryCount)}+ {item.sourceCount+ ? ` · ${tn("wb.sources", item.sourceCount)}`+ : ""}</small></button>{/* The graph is a canvas: clicking a circle is a mouse-only@@ -249,9 +265,7 @@ export function Workbench({className="wb-tag"data-once={onceOnly.has(tag) ? "true" : undefined}title={- onceOnly.has(tag)- ? "这个主题只出现在这一条上。可能是它只发生过一次,也可能是同一个主题被拆成了两个名字。"- : undefined+ onceOnly.has(tag) ? t("wb.once") : undefined}>{tag}@@ -270,14 +284,25 @@ export function Workbench({<div className="wb-stage"><div className="wb-graph" data-testid="workbench-graph"><p className="wb-graph-title">- {matters.find((item) => item.scope === matter)?.label ?? "全部"}- {shown.nodes.length ? " 的关系图" : ""}+ {shown.nodes.length+ ? t("wb.graphTitle", {+ label: matterLabel(+ matter,+ matters.find((item) => item.scope === matter)?.label ??+ t("wb.all"),+ ),+ })+ : matterLabel(+ matter,+ matters.find((item) => item.scope === matter)?.label ??+ t("wb.all"),+ )}</p><div className="wb-graph-legend">- <span data-kind="memory">记忆</span>- <span data-kind="schema">HY 归纳</span>- <span data-kind="topic">主题</span>- <span data-kind="source">来源 App</span>+ <span data-kind="memory">{t("wb.type.memory")}</span>+ <span data-kind="schema">{t("wb.type.schema")}</span>+ <span data-kind="topic">{t("wb.type.topic")}</span>+ <span data-kind="source">{t("wb.type.source")}</span></div>{/* Laid out by the row, not by offsets. Both were absolutelypositioned with a right edge each, and measuring them found@@ -292,16 +317,16 @@ export function Workbench({className="quiet"disabled={busy}onClick={() => {- const label =+ const label = matterLabel(+ matter,matters.find((item) => item.scope === matter)?.label ??- "全部";- setPageOf(matter);- onAsk(- `把「${label}」这件事讲清楚:现在到哪一步了、已经定下来的有哪些、还有什么没定。`,+ t("wb.all"),);+ setPageOf(matter);+ onAsk(t("wb.summaryPrompt", { label }));}}>- 读这个事项的综述+ {t("wb.readSummary")}</button>) : null}<button@@ -310,7 +335,7 @@ export function Workbench({disabled={busy || !graph?.nodes.length}onClick={onBuildRelations}>- {busy ? "正在归纳…" : "用 HY Memory 生成关系"}+ {busy ? t("wb.building") : t("wb.build")}</button></div>{shown.nodes.length ? (@@ -338,10 +363,16 @@ export function Workbench({</div>{graph?.nodes.length ? (<p className="wb-receipt">- 画的是{" "}- {shown.nodes.filter((node) => node.node_type === "memory").length}{" "}- / 全部 {graph.total_memories} 条记忆- <span>{graphReceipt(shown)}</span>+ {t("wb.drawn", {+ shown: new Intl.NumberFormat(locale).format(+ shown.nodes.filter((node) => node.node_type === "memory")+ .length,+ ),+ total: new Intl.NumberFormat(locale).format(+ graph.total_memories,+ ),+ })}+ <span>{graphReceipt(shown, t, tn)}</span></p>) : null}@@ -351,9 +382,11 @@ export function Workbench({detail={detail}draft={draft}busy={busy}- matterLabel={- matters.find((item) => item.scope === matter)?.label ?? "全部"- }+ matterLabel={matterLabel(+ matter,+ matters.find((item) => item.scope === matter)?.label ??+ t("wb.all"),+ )}onDraft={onDraft}onSave={onSave}onAction={onAction}@@ -376,7 +409,7 @@ export function Workbench({}}><div className="wb-chips">- {chipsFor(inMatter).map((chip) => (+ {chipsFor(inMatter, t).map((chip) => (<buttonkey={chip}type="button"@@ -392,13 +425,13 @@ export function Workbench({</div><div className="wb-ask-row"><input- aria-label="就着这个事项提问"- placeholder="就着这个事项问,回答只用已确认的记忆"+ aria-label={t("wb.askLabel")}+ placeholder={t("wb.askPlaceholder")}value={question}onChange={(event) => setQuestion(event.target.value)}/><button type="submit" disabled={!question.trim()}>- 问+ {t("wb.ask")}</button></div>{answer || streaming ? (@@ -416,18 +449,20 @@ export function Workbench({memories={inMatter.filter((memory) => memory.memory_id === detail?.memory.memory_id,)}- matterLabel={- matters.find((item) => item.scope === matter)?.label ?? "全部"- }+ matterLabel={matterLabel(+ matter,+ matters.find((item) => item.scope === matter)?.label ??+ t("wb.all"),+ )}/></div>- <aside className="wb-evidence" aria-label="原始对话">- <p className="wb-column-label">原始对话</p>+ <aside className="wb-evidence" aria-label={t("wb.originals")}>+ <p className="wb-column-label">{t("wb.originals")}</p><p className="wb-evidence-note">{detail- ? `这条记忆出自下面 ${evidence.length} 段原话,按时间排`- : "点图上任意一个圈,这里显示它出自哪些原话"}+ ? tn("wb.evidenceNote", evidence.length)+ : t("wb.pickCircle")}</p>{evidence.map((item) => (<article@@ -448,16 +483,19 @@ export function Workbench({><span className="wb-evidence-meta"><b>{nameOf(item.source_id)}</b>- <span>{when(item.created_at)}</span>+ <span>{when(item.created_at, locale, t)}</span></span>{item.extraction_state &&item.extraction_state !== "extracted" ? (<small className="wb-evidence-state">- {extractionStateLabel(item.extraction_state)}+ {localizedMemoryText(+ extractionStateLabel(item.extraction_state),+ t,+ )}</small>) : null}<span className="wb-evidence-excerpt">- {item.available ? item.verbatim : "来源原话已不可读取"}+ {item.available ? item.verbatim : t("wb.unavailable")}</span></button>{openEvidence === item.evidence_id ? (@@ -467,7 +505,7 @@ export function Workbench({className="secondary"onClick={() => void openTranscript(item.evidence_id)}>- 看完整对话+ {t("wb.fullConversation")}</button>{transcriptError ? (<p className="wb-transcript-error">{transcriptError}</p>@@ -477,7 +515,9 @@ export function Workbench({{transcript.messages.map((message) => (<li key={message.evidence_id}><span className="wb-transcript-role">- {message.written_by === "user" ? "你" : "助手"}+ {message.written_by === "user"+ ? t("wb.you")+ : t("wb.assistant")}</span>{message.verbatim}</li>@@ -489,18 +529,16 @@ export function Workbench({</article>))}{!detail && !memories.length && loaded ? (- <p className="wb-evidence-note">- 还没有记忆。已经导入的原话可以在「历史对话」里直接搜。- </p>+ <p className="wb-evidence-note">{t("wb.noMemories")}</p>) : null}</aside></div>{processing?.blocked_stages.length ? (<p className="wb-floor">- 有对话排在队里等一个条件。原文已经在库里,随时搜得到。+ {t("wb.waiting")}<button type="button" className="quiet" onClick={onConfigureModel}>- 去看看缺什么+ {t("wb.conditions")}</button></p>) : null}@@ -515,12 +553,13 @@ function Findings({findings: Finding[];onPick(finding: Finding): void;}) {+ const { t } = useGuiLanguage();if (!findings.length) return null;return (- <section className="wb-findings" aria-label="我替你看出这几件事">+ <section className="wb-findings" aria-label={t("wb.findings")}><div className="wb-findings-head">- <b>我替你看出这几件事</b>- <span>都是本机记录算出来的,点一条会在图上标出它依据的记忆</span>+ <b>{t("wb.findings")}</b>+ <span>{t("wb.findingsNote")}</span></div>{findings.map((finding) => (<div key={finding.id} className="wb-finding">@@ -534,7 +573,7 @@ function Findings({className="quiet wb-finding-link"onClick={() => onPick(finding)}>- 在图上看+ {t("wb.showGraph")}</button>) : null}</div>@@ -575,19 +614,24 @@ export function NodeDetail({onClose(): void;compact?: boolean;}) {+ const { locale, t } = useGuiLanguage();const [editing, setEditing] = useState(!compact);const formId = useId();if (detail) {const memory = detail.memory;return (- <article className="wb-detail" aria-label="这条记忆">+ <article className="wb-detail" aria-label={t("wb.memory")}><div className="wb-detail-head"><span className={`wb-status s-${memory.status}`}>- {statusLabel(memory.status)}+ {statusLabel(memory.status, t)}+ </span>+ <span className="wb-detail-rev">+ {t("wb.revision", {+ revision: new Intl.NumberFormat(locale).format(memory.revision),+ })}</span>- <span className="wb-detail-rev">第 {memory.revision} 版</span><button type="button" className="quiet" onClick={onClose}>- 收起+ {t("wb.collapse")}</button></div>{detail.index_sync?.status === "pending" ? (@@ -595,13 +639,13 @@ export function NodeDetail({// the memory here reads correctly and search does not, and nobody// would guess that from a sync badge.<p className="notice" role="status">- 搜索里还是改之前那句话。+ {t("wb.oldSearch")}{detail.index_sync.last_error_code ==="hy_memory_update_rejected" ? (// HY has no such memory to re-embed, so retrying cannot end// differently. Offering the button anyway would have the user// pressing it until they gave up.- "HY Memory 里没有这条记忆,重试也补不上。"+ t("wb.missingIndex")) : (<buttontype="button"@@ -609,7 +653,7 @@ export function NodeDetail({disabled={busy}onClick={onSyncIndex}>- 重试同步+ {t("wb.retrySync")}</button>)}</p>@@ -618,15 +662,15 @@ export function NodeDetail({<p className="map-memory-reading">{memory.content}</p>)}{compact && !editing && (- <p className="map-origin">{memoryProvenanceLabel(detail)}</p>+ <p className="map-origin">{localizedProvenance(detail, t)}</p>)}{editing && memory.status === "confirmed" ? (- <form id={formId} onSubmit={onSave} aria-label="纠正记忆内容">+ <form id={formId} onSubmit={onSave} aria-label={t("wb.correctForm")}><label>- 记忆内容+ {t("wb.content")}<textareaname="memory-content"- aria-label="记忆内容"+ aria-label={t("wb.content")}autoComplete="off"requiredrows={3}@@ -647,13 +691,13 @@ export function NodeDetail({onClick={() => setEditing(true)}><PencilLine size={14} aria-hidden="true" />- 纠正+ {t("wb.correct")}</button>)}{editing && memory.status === "confirmed" ? (<button type="submit" form={formId} disabled={busy}><Check size={14} aria-hidden="true" />- 保存纠正+ {t("wb.saveCorrection")}</button>) : null}{compact && editing && (@@ -667,7 +711,7 @@ export function NodeDetail({setEditing(false);}}>- 取消编辑+ {t("wb.cancelEdit")}</button>)}{detail.history.length > 1 && memory.status !== "deleted" ? (@@ -676,8 +720,8 @@ export function NodeDetail({className="secondary"disabled={busy}onClick={() => onAction("undo")}- title="撤销上次修改"- aria-label="撤销上次修改"+ title={t("wb.undo")}+ aria-label={t("wb.undo")}><RotateCcw size={15} aria-hidden="true" /></button>@@ -690,7 +734,7 @@ export function NodeDetail({onClick={() => onAction("delete")}><Trash2 size={14} aria-hidden="true" />- 删除+ {t("wb.delete")}</button>) : null}</div>@@ -702,24 +746,28 @@ export function NodeDetail({const trace = graph ? traceFrom(graph, node.node_id, 2) : [];const direct = trace.filter((step) => step.hop === 1);return (- <article className="wb-detail" aria-label="这个节点">+ <article className="wb-detail" aria-label={t("wb.node")}><div className="wb-detail-head">- <span className="wb-status">{nodeTypeLabel(node.node_type)}</span>+ <span className="wb-status">{nodeTypeLabel(node.node_type, t)}</span><strong>{node.label}</strong></div><p className="wb-detail-note">- 这不是一条记忆,是记忆挂靠的东西。直接关系 {direct.length} 条,- 两跳可达 {trace.length - direct.length} 条。+ {t("wb.nodeNote", {+ direct: new Intl.NumberFormat(locale).format(direct.length),+ indirect: new Intl.NumberFormat(locale).format(+ trace.length - direct.length,+ ),+ })}</p><ul className="wb-trace">{trace.slice(0, 8).map((step) => (<li key={`${step.edge.edge_id}:${step.hop}`}><span className="wb-trace-hop">- {step.hop === 1 ? "直接" : "两跳"}+ {step.hop === 1 ? t("wb.direct") : t("wb.twoHops")}</span>- {relationLabel(step.edge.relation)} · {step.node.label}+ {relationLabel(step.edge.relation, t)} · {step.node.label}<span className="wb-trace-origin">- {edgeOriginLabel(step.edge.origin)}+ {edgeOriginLabel(step.edge.origin, t)}</span></li>))}@@ -729,13 +777,11 @@ export function NodeDetail({}return (- <article className="wb-detail wb-detail-idle" aria-label="这个事项">+ <article className="wb-detail wb-detail-idle" aria-label={t("wb.matter")}><div className="wb-detail-head"><strong>{matterLabel}</strong></div>- <p className="wb-detail-note">- 图上的圈是记忆,线是它们被同一段对话提到过。选中一个,这里会变成它的来历和改法。左边换一个事项,图跟着换。- </p>+ <p className="wb-detail-note">{t("wb.idle")}</p></article>);}@@ -771,6 +817,7 @@ export function Answer({asPage: boolean;suspended?: boolean;}) {+ const { t, tn } = useGuiLanguage();const shownMemories = (answer ?? streaming)?.memories ?? [];// Only a finished answer, and only one that stands on something. Filing// back what a stream is halfway through writing would keep a sentence that@@ -785,11 +832,18 @@ export function Answer({groundedAnswer.answer.length > ANSWER_AS_MEMORY_LIMIT;return (<div className="wb-answer" aria-live="polite">- <p>{answer ? answer.answer : streaming?.text || "正在检索记忆…"}</p>+ <p>{answer ? answer.answer : streaming?.text || t("wb.searching")}</p><p className="wb-answer-source">{answer- ? `${answer.mode === "generated" ? "模型综合" : answer.mode === "extractive" ? "原文摘录" : "没有命中"} · 依据 ${shownMemories.length} 条已确认记忆`- : `已召回 ${shownMemories.length} 条`}+ ? tn("wb.answerSource", shownMemories.length, {+ mode:+ answer.mode === "generated"+ ? t("wb.generated")+ : answer.mode === "extractive"+ ? t("wb.extractive")+ : t("wb.noHit"),+ })+ : tn("wb.recalled", shownMemories.length)}</p>{groundedAnswer && !tooLong ? (<button@@ -808,23 +862,17 @@ export function Answer({})}>- 存为记忆+ {t("wb.saveMemory")}</button>) : null}- {tooLong ? (- <p className="wb-answer-source">- 这个回答太长,超过当前保存上限,暂不能存为记忆。- </p>- ) : null}+ {tooLong ? <p className="wb-answer-source">{t("wb.tooLong")}</p> : null}{asPage ? (// Not offered as a memory, and said out loud why. A synthesis is// rebuilt from the memories under it every time it is read, which is// the only reason it is safe to let a model write it: a stored// summary drifts from what it summarised and nothing notices, and a// rebuilt one cannot.- <p className="wb-answer-source">- 这是综述,不是记忆。每次都会重新生成,所以它不会和下面这些记忆走散。- </p>+ <p className="wb-answer-source">{t("wb.summary")}</p>) : null}<ol>{shownMemories.map((memory) => (@@ -843,7 +891,7 @@ export function Answer({<HandoffBarmemories={shownMemories}suspended={suspended}- matterLabel="这次回答"+ matterLabel={t("wb.thisAnswer")}answerText={answer.answer}/>)}@@ -858,22 +906,21 @@ function EmptyStage({loaded: boolean;onConnect(): void;}) {+ const { t } = useGuiLanguage();if (!loaded) {return (<div className="wb-graph-empty">- <p>正在读取记忆…</p>- <small>本地 Core 启动后会自动出现,不用刷新。</small>+ <p>{t("wb.loading")}</p>+ <small>{t("wb.coreStarting")}</small></div>);}return (<div className="wb-graph-empty">- <p>这里还没有东西可以连起来。</p>- <small>- 授权一个来源之后,先出现的是来源和主题的骨架,记忆会陆续挂上去。- </small>+ <p>{t("wb.nothingToConnect")}</p>+ <small>{t("wb.skeletonNote")}</small><button type="button" onClick={onConnect}>- 去授权一个来源+ {t("wb.authorize")}</button></div>);@@ -912,6 +959,7 @@ function narrow(function skeleton(sources: SourceResponse[],graph: MemoryGraphResponse | null,+ tn: TranslateCount,): MemoryGraphResponse {const withHistory = sources.filter((item) => item.authorized && item.imported_conversations > 0,@@ -923,7 +971,10 @@ function skeleton(nodes: withHistory.map((item) => ({node_id: `source:${item.source_id}`,node_type: "source" as const,- label: `${item.display_name} · ${item.imported_conversations} 段`,+ label: `${item.display_name} · ${tn(+ "wb.conversations",+ item.imported_conversations,+ )}`,memory_id: null,source_id: item.source_id,kind: null,@@ -971,34 +1022,46 @@ function evidenceOf(/** Questions built from what is actually in this matter, so a chip never* offers to answer something there is no record of. */-function chipsFor(memories: GovernedMemory[]): string[] {+function chipsFor(memories: GovernedMemory[], t: Translate): string[] {if (!memories.length) return [];- const chips = ["这里最近有什么变化"];- if (memories.length >= 3) chips.push("把这些归纳成几条");+ const chips = [t("wb.chipChanges")];+ if (memories.length >= 3) chips.push(t("wb.chipSummarize"));return chips;}-function when(iso: string | null): string {- if (!iso) return "时间不明";+function when(iso: string | null, locale: GuiLocale, t: Translate): string {+ if (!iso) return t("wb.unknownTime");const at = new Date(iso);- if (Number.isNaN(at.getTime())) return "时间不明";- return `${at.getMonth() + 1}/${at.getDate()} ${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`;+ if (Number.isNaN(at.getTime())) return t("wb.unknownTime");+ return new Intl.DateTimeFormat(locale, {+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ }).format(at);}-function statusLabel(status: GovernedMemory["status"]): string {- if (status === "confirmed") return "已可用";- if (status === "superseded") return "已被取代";- return "已删除";+function statusLabel(status: GovernedMemory["status"], t: Translate): string {+ if (status === "confirmed") return t("wb.available");+ if (status === "superseded") return t("wb.superseded");+ return t("wb.deleted");}-function nodeTypeLabel(type: MemoryGraphNode["node_type"]): string {- if (type === "source") return "来源 App";- if (type === "topic") return "主题";- if (type === "schema") return "HY 归纳";- return "记忆";+function nodeTypeLabel(+ type: MemoryGraphNode["node_type"],+ t: Translate,+): string {+ if (type === "source") return t("wb.type.source");+ if (type === "topic") return t("wb.type.topic");+ if (type === "schema") return t("wb.type.schema");+ return t("wb.type.memory");}-function graphReceipt(graph: MemoryGraphResponse): string {+function graphReceipt(+ graph: MemoryGraphResponse,+ t: Translate,+ tn: TranslateCount,+): string {const counts = {provenance: 0,same_conversation: 0,@@ -1007,43 +1070,91 @@ function graphReceipt(graph: MemoryGraphResponse): string {};for (const edge of graph.edges) counts[edge.origin] += 1;const parts = [- `原话来源 ${counts.provenance} 条`,- `同一次对话 ${counts.same_conversation} 条`,+ tn("wb.edgeCount", counts.provenance, {+ label: t("wb.origin.provenance"),+ }),+ tn("wb.edgeCount", counts.same_conversation, {+ label: t("wb.origin.same_conversation"),+ }),];// Only mentioned once there is one. A young library has no shared tag yet,// and a line reading 0 would be one more thing to read past.- if (counts.shared_tag > 0) parts.push(`同一个主题 ${counts.shared_tag} 条`);+ if (counts.shared_tag > 0)+ parts.push(+ tn("wb.edgeCount", counts.shared_tag, {+ label: t("wb.origin.shared_tag"),+ }),+ );if (counts.hy_relation > 0) {- parts.push(`HY Memory 归纳 ${counts.hy_relation} 条`);+ parts.push(+ tn("wb.edgeCount", counts.hy_relation, {+ label: t("wb.origin.hy_relation"),+ }),+ );return parts.join(" · ");}parts.push(- graph.hy_graph_available- ? "HY Memory 还没归纳出关系,点击上方按钮运行 System 2"- : "还没配置可用模型,无法读取 HY Memory 的归纳关系",+ graph.hy_graph_available ? t("wb.noRelations") : t("wb.noModelRelations"),);return parts.join(" · ");}-function edgeOriginLabel(origin: MemoryGraphEdge["origin"]): string {- if (origin === "hy_relation") return "HY Memory 归纳";- if (origin === "same_conversation") return "同一次对话";+function edgeOriginLabel(+ origin: MemoryGraphEdge["origin"],+ t: Translate,+): string {+ if (origin === "hy_relation") return t("wb.origin.hy_relation");+ if (origin === "same_conversation") return t("wb.origin.same_conversation");// Named before the fallthrough. The chain ends in 原话来源, so a missing// case here is not an error — it is a line that says the wrong thing.- if (origin === "shared_tag") return "同一个主题";- return "原话来源";+ if (origin === "shared_tag") return t("wb.origin.shared_tag");+ return t("wb.origin.provenance");}/** Walk out from one node so each drawn line can be checked by hand. */-function relationLabel(relation: string): string {- const labels: Record<string, string> = {- evidence_source: "来源于",- same_conversation: "同一次对话",- shared_tag: "同一个主题",- derived_from: "归纳自",- tagged_with: "属于主题",- related_to: "相关",+function relationLabel(relation: string, t: Translate): string {+ const labels: Record<string, Parameters<Translate>[0]> = {+ evidence_source: "wb.relation.evidence_source",+ same_conversation: "wb.relation.same_conversation",+ shared_tag: "wb.relation.shared_tag",+ derived_from: "wb.relation.derived_from",+ tagged_with: "wb.relation.tagged_with",+ related_to: "wb.relation.related_to",};- return labels[relation] ?? relation.replaceAll("_", " ");+ const key = labels[relation];+ return key ? t(key) : relation.replaceAll("_", " ");+}++function localizedProvenance(detail: MemoryDetail, t: Translate): string {+ const evidence = detail.evidence.filter((item) => item.available);+ if (+ evidence.length &&+ evidence.every((item) => item.source_id === "memory-content-export")+ ) {+ const authors = new Set(+ evidence.map((item) => item.written_by ?? "unknown"),+ );+ const author =+ authors.size !== 1+ ? t("provenance.multiple")+ : authors.has("person")+ ? t("provenance.person")+ : authors.has("agent")+ ? t("provenance.agent")+ : t("provenance.unknown");+ return t("provenance.imported", { author });+ }+ return detail.memory.origin === "manual"+ ? t("provenance.manual")+ : detail.memory.origin === "answered"+ ? t("provenance.answered")+ : detail.memory.origin === "agent"+ ? t("provenance.generated")+ : t("provenance.conversation");+}++function localizedMemoryText(text: string, t: Translate): string {+ const key = `memory:${text}`;+ return isMessageKey(key) ? t(key) : text;}/** Two numbers rather than one total.diff --git a/memhub/apps/web/src/application-detail.css b/memhub/apps/web/src/application-detail.cssindex cab1e9f..44c047b 100644--- a/memhub/apps/web/src/application-detail.css+++ b/memhub/apps/web/src/application-detail.css@@ -139,7 +139,9 @@display: inline-flex;align-items: center;gap: 8px;- white-space: nowrap;+ white-space: normal;+ overflow-wrap: anywhere;+ text-align: end;cursor: pointer;}.r6-app-detail-status .r6-button-spinner {@@ -213,7 +215,20 @@padding: 20px 16px;}.r6-app-settings {- padding: 0 18px;+ padding: 0;+ margin: 0;+ }+ .r6-app-detail > .r6-button:first-of-type {+ position: static;+ width: auto;+ max-width: 100%;+ }+ .r6-app-detail > header {+ margin: 24px 0;+ min-width: 0;+ }+ .r6-app-detail > header h2 {+ overflow-wrap: anywhere;}}@media (prefers-reduced-transparency: reduce) {diff --git a/memhub/apps/web/src/applications-home.css b/memhub/apps/web/src/applications-home.cssindex c239100..399a3b3 100644--- a/memhub/apps/web/src/applications-home.css+++ b/memhub/apps/web/src/applications-home.css@@ -339,7 +339,9 @@min-width: 0;}.r6-home-apps > header {- height: 56px;+ min-height: 56px;+ flex-wrap: wrap;+ padding-block: 8px;}button.r6-home-expand {padding: 8px;@@ -411,18 +413,19 @@ button.r6-home-expand:active:not(:disabled) {flex: 0 0 auto;}.r6-home-app-row {- height: 96px;+ min-height: 96px;box-sizing: border-box;border-bottom: 1px solid #d0dde5;}.r6-home[data-expanded="true"] .r6-home-app-row {- height: 112px;+ min-height: 112px;}.r6-home-row-content {display: flex;align-items: center;gap: 20px;- height: 100%;+ min-height: inherit;+ padding-block: 12px;}.r6-home-app-row img,.r6-home-row-content > svg {@@ -447,6 +450,8 @@ button.r6-home-expand:active:not(:disabled) {}.r6-home-app-row .r6-home-app-meta {width: 220px;+ max-width: 30%;+ overflow-wrap: anywhere;flex-shrink: 0;margin: 0;text-align: right;@@ -456,8 +461,9 @@ button.r6-home-expand:active:not(:disabled) {}.r6-home-app-row .r6-button {min-width: 78px;- min-height: 26px;- height: 26px;+ flex-shrink: 0;+ min-height: 32px;+ height: auto;padding: 0;font-size: 12px;}@@ -510,7 +516,20 @@ button.r6-home-expand:focus-visible,padding: 0 18px 12px;}.r6-home-row-content {- gap: 12px;+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;+ gap: 8px 12px;+ }+ .r6-home-app-row .r6-home-app-meta {+ grid-column: 2;+ grid-row: 2;+ width: auto;+ max-width: none;+ text-align: left;+ }+ .r6-home-row-content > .r6-button {+ grid-column: 3;+ grid-row: 1 / 3;}.r6-home-heading {flex-wrap: wrap;diff --git a/memhub/apps/web/src/applications-language.ts b/memhub/apps/web/src/applications-language.tsnew file mode 100644index 0000000..c82655a--- /dev/null+++ b/memhub/apps/web/src/applications-language.ts@@ -0,0 +1,37 @@+import {+ type GuiLocale,+ isMessageKey,+ type MessageKey,+ translate,+ translateCount,+} from "@one-memory/i18n";+import { useGuiLanguage } from "./gui-language";++// Presentation-only adapter over the shared "apps." catalog: never translate+// imported content, names or error codes.+type Namespaced = Extract<MessageKey, `apps.${string}`>;+export type ApplicationsMessage = Namespaced extends `apps.${infer Key}`+ ? Key extends `${string}.one`+ ? never+ : Key+ : never;++export function applicationsText(+ locale: GuiLocale,+ key: ApplicationsMessage,+ params?: Record<string, string | number>,+): string {+ const full = `apps.${key}` as const;+ if (!isMessageKey(full)) return key;+ return typeof params?.count === "number"+ ? translateCount(locale, full, params.count, params)+ : translate(locale, full, params);+}+export function useApplicationsLanguage() {+ const { locale } = useGuiLanguage();+ return {+ locale,+ a: (key: ApplicationsMessage, params?: Record<string, string | number>) =>+ applicationsText(locale, key, params),+ };+}diff --git a/memhub/apps/web/src/call-history-client.test.ts b/memhub/apps/web/src/call-history-client.test.tsindex ebaa98c..e4711c3 100644--- a/memhub/apps/web/src/call-history-client.test.ts+++ b/memhub/apps/web/src/call-history-client.test.ts@@ -16,8 +16,11 @@ vi.mock("./api", () => ({import {type CallEvent,+ callDeliveryLabel,callDetailHeadline,callEventHeadline,+ callHostName,+ callReturnDeliveryLabel,callRowDetail,callRowHeadline,clearAllCallEvents,@@ -59,6 +62,32 @@ beforeEach(() => {vi.resetAllMocks();fake.list.mockResolvedValue(structuredClone(page));});+it("traduce entrega y límites sin atribuir adopción ni alterar anfitriones desconocidos", () => {+ const delivered = {+ ...event,+ host_id: "Aplicación 中文",+ delivery: "delivered" as const,+ };+ expect(callDeliveryLabel(delivered, "es")).toBe(+ "Entregado a Aplicación 中文",+ );+ expect(callDeliveryLabel(delivered)).toBe("已提供给 Aplicación 中文");+ expect(callDeliveryLabel(event, "es")).toBe("");+ expect(callReturnDeliveryLabel(event, "es")).toBe("");+ expect(+ callReturnDeliveryLabel({ ...delivered, state: "timed_out" }, "es"),+ ).toContain("Aplicación 中文 respondió sin memorias");+ expect(+ callReturnDeliveryLabel({ ...event, state: "denied" }, "es"),+ ).toContain("No se entregaron memorias");+ expect(callReturnDeliveryLabel({ ...event, state: "partial" }, "es")).toBe(+ "Parte del contenido sigue procesándose.",+ );+ expect(callReturnDeliveryLabel({ ...event, state: "unavailable" })).toBe(+ "MemHub 暂时不可用,这次回答没有带上记忆。",+ );+});+it("reads exact bounded history and current reference metadata", async () => {expect(await getCallHistory()).toEqual(page);expect(fake.list).toHaveBeenCalledExactlyOnceWith({ limit: 20, offset: 0 });@@ -199,3 +228,29 @@ it.each(fake.references.mockResolvedValue(refs);await expect(getCallReferences(event)).rejects.toThrow();});+it("names a direct (host_id null) call in the locale it receives", () => {+ const direct: CallEvent = { ...event, host_id: null, state: "empty" };+ expect(callHostName(null, "es")).toBe("Consulta directa (diagnóstico)");+ expect(callHostName(null)).toBe("直接调用(诊断)");+ expect(callEventHeadline(direct, undefined, "es")).toBe(+ "Consulta directa (diagnóstico) no encontró memorias relacionadas",+ );+ expect(callDetailHeadline(direct, undefined, "es")).toBe(+ "Consulta directa (diagnóstico) no encontró memorias relacionadas",+ );+ const delivered: CallEvent = {+ ...direct,+ state: "grounded",+ delivery: "delivered",+ };+ expect(callRowDetail(delivered, "es")).toBe(+ "Entregado a Consulta directa (diagnóstico)",+ );+ for (const text of [+ callEventHeadline(direct, undefined, "es"),+ callRowDetail(delivered, "es"),+ ])+ expect(text).not.toMatch(/[\u4e00-\u9fff。()]/);+ // Unknown host ids are names, never catalog keys.+ expect(callHostName("toString", "es")).toBe("toString");+});diff --git a/memhub/apps/web/src/call-history-client.ts b/memhub/apps/web/src/call-history-client.tsindex 2415cd4..595d3b9 100644--- a/memhub/apps/web/src/call-history-client.ts+++ b/memhub/apps/web/src/call-history-client.ts@@ -1,3 +1,10 @@+import {+ type GuiLocale,+ type MessageKey,+ plainCount,+ translate,+ translateCount,+} from "@one-memory/i18n";import {clearAllCallEventsRequest,clearCallEventsRequest,@@ -47,12 +54,6 @@ export interface CallHistoryPage {retention_days: number | null;max_events: number | null;}-export const CALL_TOOLS: Record<CallEvent["tool"], string> = {- om_recall: "查记忆",- om_conversations: "查记忆",- om_ask: "查记忆",- om_matters: "查记忆",-};export const CALL_HOSTS: Record<string, string> = {cursor: "Cursor",codex: "Codex",@@ -64,60 +65,91 @@ export const CALL_HOSTS: Record<string, string> = {pi: "Pi","deepseek-harness": "DeepSeek Harness",};-export function callHostName(id: string | null) {- return id === null ? "直接调用(诊断)" : (CALL_HOSTS[id] ?? id);+export function callHostName(id: string | null, locale: GuiLocale = "zh-CN") {+ return id === null+ ? translate(locale, "calls.directHost")+ : Object.hasOwn(CALL_HOSTS, id)+ ? CALL_HOSTS[id]+ : id;}+const HEADLINES = {+ timed_out: "calls.headline.timedOut",+ unavailable: "calls.headline.unavailable",+ denied: "calls.headline.denied",+ empty: "calls.headline.empty",+} as const satisfies Partial<Record<CallEvent["state"], MessageKey>>;+/** The host defaults to its name in the same locale as the sentence. */export function callEventHeadline(item: CallEvent,- host = callHostName(item.host_id),+ host?: string,+ locale: GuiLocale = "zh-CN",) {+ const name = host ?? callHostName(item.host_id, locale);+ const fixed = HEADLINES[item.state as keyof typeof HEADLINES];+ if (fixed) return translate(locale, fixed, { host: name });const count = item.raw_count + item.memory_count;- if (item.state === "timed_out") return `${host} 这次没来得及查到记忆`;- if (item.state === "unavailable") return `${host} 暂时无法查记忆`;- if (item.state === "denied") return `${host} 未获准查记忆`;- if (item.state === "empty") return `${host} 没有查到相关记忆`;- return `${host} 查到 ${count} 条相关内容`;+ return translateCount(locale, "calls.headline.found", count, {+ host: name,+ count: plainCount(locale, count),+ });}-export function callRowHeadline(item: CallEvent) {- return callEventHeadline(item);+export function callRowHeadline(item: CallEvent, locale: GuiLocale = "zh-CN") {+ return callEventHeadline(item, undefined, locale);}-export function callRowDetail(item: CallEvent) {- const host = callHostName(item.host_id);- if (item.state === "timed_out")- return "后台正在整理记忆,查询超时,这次回答没有带上记忆";- if (item.state === "unavailable")- return "One Memory 暂时不可用,这次回答没有带上记忆";- if (item.state === "denied") return "当前授权不允许这次查询";- if (item.state === "partial") {- return item.delivery === "delivered"- ? `已提供给 ${host} · 部分内容还在整理中`- : "部分内容还在整理中";- }- if (item.delivery === "delivered") return `已提供给 ${host}`;- if (item.delivery === "not_delivered") return "没有提供给应用";- return item.state === "empty" ? "这次没有找到相关记忆" : "查询成功";+export function callRowDetail(item: CallEvent, locale: GuiLocale = "zh-CN") {+ const host = callHostName(item.host_id, locale);+ const key: MessageKey =+ item.state === "timed_out"+ ? "calls.detail.timedOut"+ : item.state === "unavailable"+ ? "calls.detail.unavailable"+ : item.state === "denied"+ ? "calls.detail.denied"+ : item.state === "partial"+ ? item.delivery === "delivered"+ ? "calls.detail.partialDelivered"+ : "calls.detail.partial"+ : item.delivery === "delivered"+ ? "calls.detail.delivered"+ : item.delivery === "not_delivered"+ ? "calls.detail.notDelivered"+ : item.state === "empty"+ ? "calls.detail.empty"+ : "calls.detail.success";+ return translate(locale, key, { host });}export function callDetailHeadline(item: CallEvent,- host = callHostName(item.host_id),+ host?: string,+ locale: GuiLocale = "zh-CN",) {- return callEventHeadline(item, host);+ return callEventHeadline(item, host, locale);}-export function callDeliveryLabel(item: CallEvent) {+export function callDeliveryLabel(+ item: CallEvent,+ locale: GuiLocale = "zh-CN",+) {if (item.delivery === "delivered")- return `已提供给 ${callHostName(item.host_id)}`;- if (item.delivery === "not_delivered") return "没有提供给应用";+ return translate(locale, "calls.detail.delivered", {+ host: callHostName(item.host_id, locale),+ });+ if (item.delivery === "not_delivered")+ return translate(locale, "calls.detail.notDelivered");return "";}-export function callReturnDeliveryLabel(item: CallEvent) {- const host = callHostName(item.host_id);- if (item.state === "timed_out")- return `One Memory 正在导入和整理你的记忆,这次没能及时查完,所以 ${host} 这次是在没有记忆的情况下回答的。整理完成后会恢复正常。`;- if (item.state === "unavailable")- return "One Memory 暂时不可用,这次回答没有带上记忆。";- if (item.state === "denied")- return "当前授权不允许这次查询,没有向应用提供记忆。";- if (item.state === "partial") return "部分内容还在整理中。";+export function callReturnDeliveryLabel(+ item: CallEvent,+ locale: GuiLocale = "zh-CN",+) {+ if (+ item.state === "timed_out" ||+ item.state === "unavailable" ||+ item.state === "denied" ||+ item.state === "partial"+ )+ return translate(locale, `calls.return.${item.state}`, {+ host: callHostName(item.host_id, locale),+ });return "";}const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;diff --git a/memhub/apps/web/src/call-history.css b/memhub/apps/web/src/call-history.cssindex d85ddf6..b75ef86 100644--- a/memhub/apps/web/src/call-history.css+++ b/memhub/apps/web/src/call-history.css@@ -25,7 +25,8 @@line-height: 45px;}.call-history-back.r6-button {- width: 132px;+ width: auto;+ min-width: 132px;}.call-history .r6-button-label {display: inline-flex;@@ -65,6 +66,7 @@}.call-history-actions {display: flex;+ flex-wrap: wrap;align-items: center;justify-content: flex-end;gap: 12px;diff --git a/memhub/apps/web/src/clock-stamp.test.ts b/memhub/apps/web/src/clock-stamp.test.tsnew file mode 100644index 0000000..7835bf9--- /dev/null+++ b/memhub/apps/web/src/clock-stamp.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { clockStamp } from "./clock-stamp";++// Controlled clock and zone: "now" is 2026-09-20 14:30 in Buenos Aires.+const NOW = "2026-09-20T17:30:00Z";+const previousTz = process.env.TZ;++beforeEach(() => {+ process.env.TZ = "America/Argentina/Buenos_Aires";+ vi.useFakeTimers();+ vi.setSystemTime(new Date(NOW));+});+afterEach(() => {+ vi.useRealTimers();+ if (previousTz === undefined) delete process.env.TZ;+ else process.env.TZ = previousTz;+});++describe("clockStamp", () => {+ it.each([null, undefined, "", "not a date"])(+ "reports an unknown time for %j",+ (value) => {+ expect(clockStamp(value)).toBe("时间未知");+ expect(clockStamp(value, "zh-CN")).toBe("时间未知");+ expect(clockStamp(value, "es")).toBe("Hora desconocida");+ },+ );++ it("says today in the requested language, in the local zone", () => {+ // 12:05 UTC is 09:05 local on the same day.+ const value = "2026-09-20T12:05:00Z";+ expect(clockStamp(value, "es")).toBe("Hoy 09:05");+ expect(clockStamp(value, "zh-CN")).toBe("今天 09:05");+ });++ it("defaults to Chinese", () => {+ expect(clockStamp("2026-09-20T12:05:00Z")).toBe("今天 09:05");+ });++ it("uses the local day, not the UTC day", () => {+ // 02:00 UTC on the 20th is still the 19th in Buenos Aires.+ const value = "2026-09-20T02:00:00Z";+ expect(clockStamp(value, "es")).not.toMatch(/^Hoy/);+ expect(clockStamp(value, "zh-CN")).not.toMatch(/^今天/);+ expect(clockStamp(value, "es")).toBe(+ new Intl.DateTimeFormat("es", {+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ }).format(new Date(value)),+ );+ expect(clockStamp(value, "es")).toContain("19");+ });++ it("formats another date with month and day, without a today word", () => {+ const value = "2026-08-03T15:07:00Z";+ const es = clockStamp(value, "es");+ const zh = clockStamp(value, "zh-CN");+ // Spanish short date is day/month: 3 August. Padding varies across ICU+ // versions, so only the order is pinned.+ expect(es).toMatch(/^0?3\/0?8\b/);+ expect(es).toContain("12:07");+ expect(es).not.toMatch(/Hoy|今天/);+ expect(zh).toContain("12:07");+ expect(zh).not.toMatch(/Hoy|今天/);+ expect(clockStamp(value)).toBe(zh);+ });+});diff --git a/memhub/apps/web/src/clock-stamp.ts b/memhub/apps/web/src/clock-stamp.tsindex 08361c2..98cfa05 100644--- a/memhub/apps/web/src/clock-stamp.ts+++ b/memhub/apps/web/src/clock-stamp.ts@@ -1,3 +1,5 @@+import { type GuiLocale, translate } from "@one-memory/i18n";+/*** One clock format for every user-facing timestamp.*@@ -14,11 +16,15 @@* Unparseable input returns 时间未知 rather than a fabricated date. That string* is already asserted across several suites, so it stays exactly as-is.*/-export function clockStamp(value: string | null | undefined): string {- if (!value || !Number.isFinite(Date.parse(value))) return "时间未知";+export function clockStamp(+ value: string | null | undefined,+ locale: GuiLocale = "zh-CN",+): string {+ if (!value || !Number.isFinite(Date.parse(value)))+ return translate(locale, "clock.unknown");const date = new Date(value);const now = new Date();- const clock = new Intl.DateTimeFormat("zh-CN", {+ const clock = new Intl.DateTimeFormat(locale, {hour: "2-digit",minute: "2-digit",}).format(date);@@ -27,8 +33,8 @@ export function clockStamp(value: string | null | undefined): string {date.getMonth() === now.getMonth() &&date.getDate() === now.getDate())- return `今天 ${clock}`;- return new Intl.DateTimeFormat("zh-CN", {+ return translate(locale, "clock.today", { clock });+ return new Intl.DateTimeFormat(locale, {month: "2-digit",day: "2-digit",hour: "2-digit",diff --git a/memhub/apps/web/src/diagnostics-export.ts b/memhub/apps/web/src/diagnostics-export.tsindex 9f3d703..bfb0fe9 100644--- a/memhub/apps/web/src/diagnostics-export.ts+++ b/memhub/apps/web/src/diagnostics-export.ts@@ -1,3 +1,5 @@+import { type GuiLocale, translate } from "@one-memory/i18n";+// Log export is offered from two places (the health view and the settings// help card). Both must report the same outcome wording, so the desktop// bridge call and the message live here instead of being copied.@@ -6,17 +8,21 @@ export type DiagnosticsExportResult = {message: string;};-export async function exportDiagnosticsFile(): Promise<DiagnosticsExportResult> {+export async function exportDiagnosticsFile(+ locale: GuiLocale = "zh-CN",+): Promise<DiagnosticsExportResult> {if (!window.oneMemory?.exportDiagnostics) {- return { ok: false, message: "请在桌面 App 中导出诊断信息。" };+ return { ok: false, message: translate(locale, "diagnosticExportDesktop") };}try {const receipt = await window.oneMemory.exportDiagnostics();return {ok: true,- message: `日志已导出:${receipt.filename ?? "诊断文件"}`,+ message: translate(locale, "diagnosticExported", {+ filename: receipt.filename ?? translate(locale, "diagnosticFile"),+ }),};} catch {- return { ok: false, message: "诊断信息未能导出,请重试。" };+ return { ok: false, message: translate(locale, "diagnosticExportFailed") };}}diff --git a/memhub/apps/web/src/first-import-r6.css b/memhub/apps/web/src/first-import-r6.cssindex d30d346..770cc4f 100644--- a/memhub/apps/web/src/first-import-r6.css+++ b/memhub/apps/web/src/first-import-r6.css@@ -3,8 +3,8 @@display: grid;grid-template-columns: minmax(0, 738px) 278px;gap: 30px;- height: 560.2px;- min-height: 0;+ min-height: 100%;+ height: auto;}.first-import-r6-main {min-width: 0;@@ -35,13 +35,12 @@line-height: 20px;}.first-import-r6-main > .r6-import-progress {- flex: 0 0 218px;+ flex: 0 0 auto;}.first-import-r6-feed {- min-height: 0;- flex: 1;+ flex: 0 0 auto;margin-top: 26px;- overflow: auto;+ overflow: visible;scrollbar-width: thin;overscroll-behavior: contain;}@@ -225,10 +224,8 @@margin: 6px 0;}.first-import-r6-footer-note {- flex: 1;+ flex: 1 1 240px;min-width: 0;- max-height: 64px;- overflow: auto;}.first-import-r6-footer-note p {margin: 0;@@ -245,12 +242,15 @@}.first-import-r6-footer-actions {display: flex;+ flex: 0 1 auto;+ min-width: 0;+ max-width: 100%;flex-wrap: wrap;- gap: 16px;+ gap: 12px;align-items: center;}.first-import-r6-footer-actions > [data-variant="primary"] {- min-width: 210px;+ min-width: min(160px, 100%);}.first-import-r6-footer-actions .r6-button-label {display: inline-flex;@@ -403,18 +403,18 @@ dialog.first-import-r6-original[open] {}@media (min-width: 761px) and (max-height: 959px) {.onboarding-r6-body:has(> .first-import-r6-layout) {- overflow: hidden;+ overflow-y: auto;padding-top: 16px;padding-bottom: 16px;}.first-import-r6-layout {- height: 100%;+ height: auto;}}@media (min-width: 761px) and (max-height: 859px) {.first-import-r6-options {padding: 14px;- overflow: hidden;+ overflow: visible;}.first-import-r6-eyebrow {margin-bottom: 4px;diff --git a/memhub/apps/web/src/global.d.ts b/memhub/apps/web/src/global.d.tsindex ab2bd0d..5f3ea05 100644--- a/memhub/apps/web/src/global.d.ts+++ b/memhub/apps/web/src/global.d.ts@@ -6,6 +6,7 @@ import type {ConnectionSetupResult,ConnectionSetupSelection,} from "@one-memory/contracts";+import type { LanguagePreference, LanguageSnapshot } from "@one-memory/i18n";import type { DebugLogSnapshot } from "./debug-log-types.js";export type RecallPermissionTool =@@ -219,6 +220,13 @@ declare global {buildNumber: string;commit: string;};+ getLanguagePreference?(): Promise<LanguageSnapshot>;+ setLanguagePreference?(+ preference: LanguagePreference,+ ): Promise<LanguageSnapshot>;+ onLanguagePreferenceChanged?(+ listener: (snapshot: LanguageSnapshot) => void,+ ): () => void;getDebugLogs?(): Promise<DebugLogSnapshot>;/** Renderer end of the four-step UI/kernel trace. */logUiTrace?(input: {diff --git a/memhub/apps/web/src/gui-language-lifecycle.test.tsx b/memhub/apps/web/src/gui-language-lifecycle.test.tsxnew file mode 100644index 0000000..15b60dc--- /dev/null+++ b/memhub/apps/web/src/gui-language-lifecycle.test.tsx@@ -0,0 +1,140 @@+// @vitest-environment jsdom++import type { LanguageSnapshot } from "@one-memory/i18n";+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { StrictMode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";++function Probe() {+ const { locale, preference, error, setPreference } = useGuiLanguage();+ return (+ <>+ <output>+ {locale}:{preference}+ </output>+ <button type="button" onClick={() => void setPreference("es")}>+ Spanish+ </button>+ {error && <p role="alert">{error}</p>}+ </>+ );+}+function mount() {+ return render(+ <StrictMode>+ <LanguageProvider>+ <Probe />+ </LanguageProvider>+ </StrictMode>,+ );+}+beforeEach(() => {+ localStorage.clear();+ delete window.oneMemory;+});+afterEach(() => {+ cleanup();+ delete window.oneMemory;+ vi.restoreAllMocks();+ localStorage.clear();+});++it("removes browser listeners on StrictMode cleanup and final unmount", () => {+ const add = vi.spyOn(window, "addEventListener");+ const remove = vi.spyOn(window, "removeEventListener");+ const view = mount();+ view.unmount();+ for (const type of ["storage", "languagechange"]) {+ const callbacks = add.mock.calls+ .filter(([name]) => name === type)+ .map(([, callback]) => callback);+ expect(callbacks).toHaveLength(2);+ for (const callback of callbacks)+ expect(remove).toHaveBeenCalledWith(type, callback);+ }+});+it("ignores unrelated storage and language changes for explicit preferences", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");+ mount();+ vi.spyOn(navigator, "language", "get").mockReturnValue("es");+ act(() => {+ window.dispatchEvent(new Event("languagechange"));+ window.dispatchEvent(+ new StorageEvent("storage", { key: "unrelated", newValue: "es" }),+ );+ window.dispatchEvent(+ new StorageEvent("storage", {+ key: LANGUAGE_STORAGE_KEY,+ storageArea: sessionStorage,+ }),+ );+ });+ expect(screen.getByText("zh-CN:zh-CN")).toBeTruthy();+});+it("shows errors for unavailable desktop bridges without using browser fallback", async () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ window.oneMemory = {} as NonNullable<Window["oneMemory"]>;+ const read = vi.spyOn(Storage.prototype, "getItem");+ const write = vi.spyOn(Storage.prototype, "setItem");+ mount();+ expect(screen.getByRole("alert").textContent).toBe("languageLoadError");+ await userEvent.click(screen.getByRole("button"));+ expect(screen.getByRole("alert").textContent).toBe("languageSaveError");+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+ expect(read).not.toHaveBeenCalled();+ expect(write).not.toHaveBeenCalled();+});+it("does not surface a stale read rejection after an authoritative event", async () => {+ let rejectRead!: (reason?: unknown) => void;+ let listener!: (value: LanguageSnapshot) => void;+ const pending = new Promise<LanguageSnapshot>((_, reject) => {+ rejectRead = reject;+ });+ window.oneMemory = {+ getLanguagePreference: () => pending,+ onLanguagePreferenceChanged: (next: typeof listener) => {+ listener = next;+ return () => {};+ },+ } as NonNullable<Window["oneMemory"]>;+ mount();+ await act(async () => {+ listener({ preference: "es", locale: "es", revision: 3 });+ rejectRead(new Error("late failure"));+ });+ expect(screen.getByText("es:es")).toBeTruthy();+ expect(screen.queryByRole("alert")).toBeNull();+});+it("validates native replies and keeps the last confirmed snapshot when saving fails", async () => {+ const set = vi.fn().mockRejectedValue(new Error("denied"));+ let listener!: (value: LanguageSnapshot) => void;+ window.oneMemory = {+ getLanguagePreference: async () => ({+ preference: "bad",+ locale: "es",+ revision: 0,+ }),+ setLanguagePreference: set,+ onLanguagePreferenceChanged: (next: typeof listener) => {+ listener = next;+ return () => {};+ },+ } as unknown as NonNullable<Window["oneMemory"]>;+ mount();+ await waitFor(() =>+ expect(screen.getByRole("alert").textContent).toBe("languageLoadError"),+ );+ act(() => listener({ preference: "system", locale: "zh-CN", revision: 2 }));+ await userEvent.click(screen.getByRole("button"));+ expect(set).toHaveBeenCalledWith("es");+ expect(screen.getByRole("alert").textContent).toBe("languageSaveError");+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+ act(() => listener({ preference: "system", locale: "zh-CN", revision: 2 }));+ expect(screen.queryByRole("alert")).toBeNull();+});diff --git a/memhub/apps/web/src/gui-language.test.tsx b/memhub/apps/web/src/gui-language.test.tsxnew file mode 100644index 0000000..0da5fc9--- /dev/null+++ b/memhub/apps/web/src/gui-language.test.tsx@@ -0,0 +1,261 @@+// @vitest-environment jsdom++import type { LanguageSnapshot } from "@one-memory/i18n";+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { StrictMode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ LANGUAGE_STORAGE_KEY,+ LanguageProvider,+ useGuiLanguage,+} from "./gui-language";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+function Probe() {+ const language = useGuiLanguage();+ return (+ <>+ <output>+ {language.locale}:{language.preference}+ </output>+ <input aria-label="draft" defaultValue="draft" />+ <button onClick={() => void language.setPreference("es")} type="button">+ Spanish+ </button>+ {language.error && <p role="alert">{language.error}</p>}+ </>+ );+}+function mount() {+ return render(+ <StrictMode>+ <LanguageProvider>+ <Probe />+ </LanguageProvider>+ </StrictMode>,+ );+}+function desktop(get: () => Promise<LanguageSnapshot>) {+ const listeners = new Set<(value: LanguageSnapshot) => void>();+ const unsubscribe = vi.fn();+ const bridge = {+ getLanguagePreference: vi.fn(() => {+ expect(listeners.size).toBe(1);+ return get();+ }),+ setLanguagePreference: vi+ .fn()+ .mockResolvedValue({ preference: "es", locale: "es", revision: 2 }),+ onLanguagePreferenceChanged: vi.fn(+ (listener: (value: LanguageSnapshot) => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ unsubscribe();+ };+ },+ ),+ };+ window.oneMemory = bridge as unknown as NonNullable<Window["oneMemory"]>;+ return { bridge, listeners, unsubscribe };+}+beforeEach(() => {+ localStorage.clear();+ delete window.oneMemory;+ vi.spyOn(navigator, "language", "get").mockReturnValue("zh-CN");+});+afterEach(() => {+ cleanup();+ delete window.oneMemory;+ vi.restoreAllMocks();+ localStorage.clear();+});++it("persists before publishing and retains form state without remounting", async () => {+ const user = userEvent.setup();+ mount();+ await user.type(screen.getByRole("textbox"), " preserved");+ await user.click(screen.getByRole("button"));+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("es");+ expect(screen.getByText("es:es")).toBeTruthy();+ expect(document.documentElement.lang).toBe("es");+ expect((screen.getByRole("textbox") as HTMLInputElement).value).toBe(+ "draft preserved",+ );+ cleanup();+ mount();+ expect(screen.getByText("es:es")).toBeTruthy();+});+it("keeps confirmed language and exposes storage write errors", async () => {+ mount();+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new Error("private storage");+ });+ await userEvent.click(screen.getByRole("button"));+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+ expect(screen.getByRole("alert").textContent).toBe("languageSaveError");+});+it("exposes browser read errors without crashing", () => {+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {+ throw new Error("denied");+ });+ mount();+ expect(screen.getByRole("alert").textContent).toBe("languageLoadError");+});+it("validates browser storage and synchronizes tabs and principal navigator language", () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "invalid");+ mount();+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+ act(() => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ window.dispatchEvent(+ new StorageEvent("storage", {+ key: LANGUAGE_STORAGE_KEY,+ storageArea: localStorage,+ }),+ );+ });+ expect(screen.getByText("es:es")).toBeTruthy();+ act(() => {+ localStorage.removeItem(LANGUAGE_STORAGE_KEY);+ window.dispatchEvent(+ new StorageEvent("storage", { key: null, storageArea: localStorage }),+ );+ });+ vi.spyOn(navigator, "language", "get").mockReturnValue("es-MX");+ act(() => window.dispatchEvent(new Event("languagechange")));+ expect(screen.getByText("es:system")).toBeTruthy();+});+it("subscribes before reads, rejects stale snapshots and cleans StrictMode subscriptions", async () => {+ const reads = [deferred<LanguageSnapshot>(), deferred<LanguageSnapshot>()];+ let index = 0;+ const { listeners, unsubscribe } = desktop(() => reads[index++].promise);+ const view = mount();+ expect(listeners.size).toBe(1);+ act(() => {+ for (const listener of listeners)+ listener({ preference: "es", locale: "es", revision: 5 });+ });+ await act(async () => {+ for (const read of reads)+ read.resolve({ preference: "zh-CN", locale: "zh-CN", revision: 1 });+ });+ expect(screen.getByText("es:es")).toBeTruthy();+ view.unmount();+ expect(listeners.size).toBe(0);+ expect(unsubscribe).toHaveBeenCalledTimes(2);+});+it("never accesses browser persistence or browser locale in desktop mode and exposes read failures", async () => {+ const { listeners } = desktop(() => Promise.reject(new Error("unavailable")));+ const read = vi.spyOn(Storage.prototype, "getItem");+ const write = vi.spyOn(Storage.prototype, "setItem");+ mount();+ await waitFor(() =>+ expect(screen.getByRole("alert").textContent).toBe("languageLoadError"),+ );+ vi.spyOn(navigator, "language", "get").mockReturnValue("es");+ act(() => window.dispatchEvent(new Event("languagechange")));+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+ act(() => {+ for (const listener of listeners)+ listener({ preference: "system", locale: "es", revision: 3 });+ });+ expect(screen.queryByRole("alert")).toBeNull();+ expect(screen.getByText("es:system")).toBeTruthy();+ expect(read).not.toHaveBeenCalled();+ expect(write).not.toHaveBeenCalled();+});+it("does not surface an obsolete write failure after a newer save succeeds", async () => {+ const { bridge } = desktop(async () => ({+ preference: "system",+ locale: "zh-CN",+ revision: 0,+ }));+ const first = deferred<LanguageSnapshot>();+ bridge.setLanguagePreference+ .mockReturnValueOnce(first.promise)+ .mockResolvedValueOnce({ preference: "es", locale: "es", revision: 2 });+ mount();+ await act(async () => {});+ await userEvent.click(screen.getByRole("button"));+ await userEvent.click(screen.getByRole("button"));+ expect(screen.getByText("es:es")).toBeTruthy();+ await act(async () => first.reject(new Error("obsolete failure")));+ expect(screen.queryByRole("alert")).toBeNull();+});++it("rejects conflicting native locale and explicit preference pairs", async () => {+ desktop(async () => ({ preference: "es", locale: "zh-CN", revision: 1 }));+ mount();+ await waitFor(() =>+ expect(screen.getByRole("alert").textContent).toBe("languageLoadError"),+ );+ expect(screen.getByText("zh-CN:system")).toBeTruthy();+});++it("does not allow a late write reply to overwrite a newer native event", async () => {+ const { bridge, listeners } = desktop(async () => ({+ preference: "system",+ locale: "zh-CN",+ revision: 0,+ }));+ const write = deferred<LanguageSnapshot>();+ bridge.setLanguagePreference.mockReturnValue(write.promise);+ mount();+ await act(async () => {});+ await userEvent.click(screen.getByRole("button"));+ act(() => {+ for (const listener of listeners)+ listener({ preference: "zh-CN", locale: "zh-CN", revision: 8 });+ });+ await act(async () =>+ write.resolve({ preference: "es", locale: "es", revision: 7 }),+ );+ expect(screen.getByText("zh-CN:zh-CN")).toBeTruthy();+});++it("groups counts in Chinese only where tn asks for it, never with tnPlain", () => {+ function Counts() {+ const { tn, tnPlain } = useGuiLanguage();+ return (+ <>+ <p>{tn("healthMemories", 12345)}</p>+ <p>{tnPlain("healthRetrying", 12345)}</p>+ <p>{tnPlain("healthRetrying", 1)}</p>+ </>+ );+ }+ const view = (stored: string | null) => {+ if (stored) localStorage.setItem(LANGUAGE_STORAGE_KEY, stored);+ const { container, unmount } = render(+ <LanguageProvider>+ <Counts />+ </LanguageProvider>,+ );+ const lines = [...container.querySelectorAll("p")].map(+ (p) => p.textContent,+ );+ unmount();+ localStorage.clear();+ return lines;+ };+ expect(view(null)).toEqual([+ "12,345 条记忆",+ "12345 条这次没能整理成功,正在重试",+ "1 条这次没能整理成功,正在重试",+ ]);+ expect(view("es")).toEqual([+ "12.345 memorias",+ "12.345 no se pudieron procesar esta vez; reintentando",+ "1 no se pudo procesar esta vez; reintentando",+ ]);+});diff --git a/memhub/apps/web/src/gui-language.tsx b/memhub/apps/web/src/gui-language.tsxnew file mode 100644index 0000000..20ffbfc--- /dev/null+++ b/memhub/apps/web/src/gui-language.tsx@@ -0,0 +1,228 @@+import {+ isLanguagePreference,+ isLanguageSnapshot,+ type LanguagePreference,+ type LanguageSnapshot,+ plainCount,+ resolveGuiLocale,+ translate,+ translateCount,+} from "@one-memory/i18n";+import {+ createContext,+ type ReactNode,+ useContext,+ useEffect,+ useState,+ useSyncExternalStore,+} from "react";++export const LANGUAGE_STORAGE_KEY = "memhub.ui-language";+type LanguageError = "languageLoadError" | "languageSaveError" | null;+type State = LanguageSnapshot & { error: LanguageError };+const initial: State = {+ preference: "system",+ locale: "zh-CN",+ revision: 0,+ error: null,+};++function createLanguageStore() {+ let state = initial;+ let revision = -1;+ let generation = 0;+ let writeRequest = 0;+ let bridge: Window["oneMemory"];+ const listeners = new Set<() => void>();+ const publish = (next: State) => {+ state = next;+ for (const listener of listeners) listener();+ };+ const accept = (snapshot: unknown) => {+ if (!isLanguageSnapshot(snapshot))+ throw new Error("Invalid language snapshot");+ if (snapshot.revision < revision) return;+ if (+ snapshot.revision === revision &&+ (snapshot.preference !== state.preference ||+ snapshot.locale !== state.locale)+ )+ return;+ revision = snapshot.revision;+ publish({ ...snapshot, error: null });+ };+ const readBrowser = () => {+ try {+ const stored = window.localStorage.getItem(LANGUAGE_STORAGE_KEY);+ const preference = isLanguagePreference(stored) ? stored : "system";+ publish({+ preference,+ locale: resolveGuiLocale(preference, navigator.language),+ revision: state.revision + 1,+ error: null,+ });+ } catch {+ publish({ ...state, error: "languageLoadError" });+ }+ };+ return {+ getSnapshot: () => state,+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ start() {+ const current = ++generation;+ bridge = window.oneMemory;+ if (bridge) {+ let unsubscribe: (() => void) | undefined;+ const beforeRead = revision;+ try {+ if (+ !bridge.onLanguagePreferenceChanged ||+ !bridge.getLanguagePreference+ )+ throw new Error("Language bridge unavailable");+ unsubscribe = bridge.onLanguagePreferenceChanged((snapshot) => {+ if (generation !== current) return;+ try {+ accept(snapshot);+ } catch {+ publish({ ...state, error: "languageLoadError" });+ }+ });+ void bridge+ .getLanguagePreference()+ .then((snapshot) => {+ if (generation === current) accept(snapshot);+ })+ .catch(() => {+ if (generation === current && revision === beforeRead)+ publish({ ...state, error: "languageLoadError" });+ });+ } catch {+ publish({ ...state, error: "languageLoadError" });+ }+ return () => {+ generation++;+ unsubscribe?.();+ };+ }+ const storage = (event: StorageEvent) => {+ if (event.key !== null && event.key !== LANGUAGE_STORAGE_KEY) return;+ try {+ if (+ event.storageArea !== null &&+ event.storageArea !== window.localStorage+ )+ return;+ readBrowser();+ } catch {+ publish({ ...state, error: "languageLoadError" });+ }+ };+ const languageChange = () => {+ if (state.preference === "system")+ publish({+ ...state,+ locale: resolveGuiLocale("system", navigator.language),+ });+ };+ window.addEventListener("storage", storage);+ window.addEventListener("languagechange", languageChange);+ readBrowser();+ return () => {+ generation++;+ window.removeEventListener("storage", storage);+ window.removeEventListener("languagechange", languageChange);+ };+ },+ async setPreference(preference: LanguagePreference) {+ const current = generation;+ const request = ++writeRequest;+ try {+ if (!isLanguagePreference(preference))+ throw new Error("Invalid language preference");+ if (bridge) {+ if (!bridge.setLanguagePreference)+ throw new Error("Language bridge unavailable");+ const snapshot = await bridge.setLanguagePreference(preference);+ if (generation === current) accept(snapshot);+ } else {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, preference);+ publish({+ preference,+ locale: resolveGuiLocale(preference, navigator.language),+ revision: state.revision + 1,+ error: null,+ });+ }+ } catch {+ if (generation === current && request === writeRequest)+ publish({ ...state, error: "languageSaveError" });+ }+ },+ };+}++type LanguageContextValue = State & {+ setPreference(preference: LanguagePreference): Promise<void>;+};+// Standalone components retain the historical Chinese UI without a provider.+const LanguageContext = createContext<LanguageContextValue>({+ ...initial,+ setPreference: async () => {},+});++export function LanguageProvider({ children }: { children: ReactNode }) {+ const [store] = useState(createLanguageStore);+ const state = useSyncExternalStore(+ store.subscribe,+ store.getSnapshot,+ store.getSnapshot,+ );+ useEffect(() => store.start(), [store]);+ useEffect(() => {+ document.documentElement.lang = state.locale;+ }, [state.locale]);+ return (+ <LanguageContext.Provider+ value={{ ...state, setPreference: store.setPreference }}+ >+ {children}+ </LanguageContext.Provider>+ );+}++export function useGuiLanguage() {+ const language = useContext(LanguageContext);+ return {+ ...language,+ t: (+ key: Parameters<typeof translate>[1],+ params?: Parameters<typeof translate>[2],+ ) => translate(language.locale, key, params),+ /** Count-aware `t`: picks the Spanish `.one` variant and groups digits. */+ tn: (+ key: Parameters<typeof translate>[1],+ count: number,+ params?: Parameters<typeof translate>[2],+ ) =>+ translateCount(language.locale, key, count, {+ ...params,+ count: new Intl.NumberFormat(language.locale).format(count),+ }),+ /** `tn` for copy whose Chinese has always shown the bare number. */+ tnPlain: (+ key: Parameters<typeof translate>[1],+ count: number,+ params?: Parameters<typeof translate>[2],+ ) =>+ translateCount(language.locale, key, count, {+ ...params,+ count: plainCount(language.locale, count),+ }),+ };+}diff --git a/memhub/apps/web/src/host-state.ts b/memhub/apps/web/src/host-state.tsindex 01fbadb..8ddb362 100644--- a/memhub/apps/web/src/host-state.ts+++ b/memhub/apps/web/src/host-state.ts@@ -257,14 +257,6 @@ export function hostRereadFailed(error: unknown) {return typeof error === "object" && error !== null && unverified.has(error);}-/** What to add after a failure message: the reason, and whether what is on- * screen could be re-read afterwards. */-export function hostFailureNote(reason: string | null, rereadFailed: boolean) {- return `${reason ? `原因:${reason}。` : ""}${- rereadFailed ? "当前接入状态也未能重新读取,显示的可能不是最新状态。" : ""- }`;-}-type HostPatch = Partial<Pick<RecallHostStatus, "installed" | "permission" | "selfCheck">>;diff --git a/memhub/apps/web/src/index-sync-notice.test.ts b/memhub/apps/web/src/index-sync-notice.test.tsindex e40d5d8..dac846b 100644--- a/memhub/apps/web/src/index-sync-notice.test.ts+++ b/memhub/apps/web/src/index-sync-notice.test.ts@@ -13,6 +13,31 @@ const sync = (});describe("indexSyncPresentation", () => {+ it("localiza tipos y ventanas visibles sin traducir valores desconocidos", async () => {+ const { memoryText } = await import("./memory-language");+ expect(memoryText("es", "近 3 个月")).toBe("Últimos 3 meses");+ expect(memoryText("es", "已确认")).toBe("Confirmada");+ expect(memoryText("es", "记忆库")).toBe("Biblioteca de memorias");+ expect(memoryText("es", "问记忆")).toBe("Preguntar a las memorias");+ expect(memoryText("es", "历史对话")).toBe("Historial de conversaciones");+ expect(memoryText("es", "项目记忆")).toBe("Memoria del proyecto");+ expect(memoryText("es", "contenido opaco")).toBe("contenido opaco");+ });+ it("traduce sincronización sin cambiar la acción ni la fecha opaca", () => {+ expect(+ indexSyncPresentation(+ sync({ attempts: 2, last_error_code: "model_profile_not_active" }),+ "fecha sintética",+ "es",+ ),+ ).toEqual({+ action: "configure",+ attemptedLine:+ "2 intentos de sincronización · Estado actualizado: fecha sintética",+ explanation:+ "La sincronización necesita un modelo local disponible o autorización para embeddings locales.",+ });+ });it("offers retry after an unknown transient failure", () => {expect(indexSyncPresentation(diff --git a/memhub/apps/web/src/index-sync-notice.ts b/memhub/apps/web/src/index-sync-notice.tsindex f1bea4c..da178b0 100644--- a/memhub/apps/web/src/index-sync-notice.ts+++ b/memhub/apps/web/src/index-sync-notice.ts@@ -1,4 +1,6 @@import type { MemoryIndexSync } from "@one-memory/contracts";+import type { GuiLocale } from "@one-memory/i18n";+import { memoryText } from "./memory-language";export type IndexSyncAction = "retry" | "configure" | "refresh" | "none";@@ -16,15 +18,18 @@ export interface IndexSyncPresentation {export function indexSyncPresentation(sync: MemoryIndexSync,updatedAt: string,+ locale: GuiLocale = "zh-CN",): IndexSyncPresentation {+ const text = (message: string, params?: Record<string, string | number>) =>+ memoryText(locale, message, params);const attempted = sync.attempts > 0;- const attemptedLine = `${attempted ? `同步尝试 ${sync.attempts} 次` : "尚未尝试同步"} · 状态更新于 ${updatedAt}`;+ const attemptedLine = `${attempted ? text("同步尝试 {count} 次", { count: sync.attempts }) : text("尚未尝试同步")}${text(" · 状态更新于 {date}", { date: updatedAt })}`;const reason = sync.last_error_code;if (reason === "hy_memory_update_rejected") {return {attemptedLine,- explanation: "HY Memory 当前没有这条记忆,仅重试同步不能补齐。",+ explanation: text("HY Memory 当前没有这条记忆,仅重试同步不能补齐。"),action: "none",};}@@ -36,7 +41,7 @@ export function indexSyncPresentation() {return {attemptedLine,- explanation: "同步需要可用的本机整理模型或本地嵌入授权。",+ explanation: text("同步需要可用的本机整理模型或本地嵌入授权。"),action: "configure",};}@@ -47,27 +52,29 @@ export function indexSyncPresentation() {return {attemptedLine,- explanation: "这条记忆或模型版本已经变化,先刷新核对再决定下一步。",+ explanation: text("这条记忆或模型版本已经变化,先刷新核对再决定下一步。"),action: "refresh",};}if (!attempted) {return {attemptedLine,- explanation: "这条记忆已改,搜索索引还没开始同步。",+ explanation: text("这条记忆已改,搜索索引还没开始同步。"),action: "retry",};}if (reason) {return {attemptedLine,- explanation: "最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。",+ explanation: text(+ "最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。",+ ),action: "retry",};}return {attemptedLine,- explanation: "这条记忆已改,搜索索引还没跟上。",+ explanation: text("这条记忆已改,搜索索引还没跟上。"),action: "retry",};}diff --git a/memhub/apps/web/src/main.tsx b/memhub/apps/web/src/main.tsxindex 9ddb540..ecf4fe3 100644--- a/memhub/apps/web/src/main.tsx+++ b/memhub/apps/web/src/main.tsx@@ -2,6 +2,7 @@ import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { App } from "./App";+import { LanguageProvider } from "./gui-language";import { installNativeDisplayStyles } from "./native-display-styles";import { installRendererDebugLogCapture } from "./renderer-debug-log";import "./native-display-styles.css";@@ -20,6 +21,8 @@ import.meta.hot?.dispose(stopRendererDebugLogs);createRoot(root).render(<StrictMode>- <App />+ <LanguageProvider>+ <App />+ </LanguageProvider></StrictMode>,);diff --git a/memhub/apps/web/src/memory-arrival-state.ts b/memhub/apps/web/src/memory-arrival-state.tsindex 082d492..ee0ef92 100644--- a/memhub/apps/web/src/memory-arrival-state.ts+++ b/memhub/apps/web/src/memory-arrival-state.ts@@ -3,6 +3,7 @@ import type {MemoryProcessingSummary,SourceResponse,} from "@one-memory/contracts";+import { type GuiLocale, translate } from "@one-memory/i18n";import { modelBlock, splitBlockedStages } from "./memory-processing-labels";export type MemoryArrivalPhase =@@ -110,23 +111,39 @@ function onlyRetries(blocks: readonly MemoryProcessingBlock[]): boolean {return blocks.length > 0 && splitBlockedStages(blocks).named.length === 0;}-export function memoryArrivalTitle(arrival: MemoryArrival): string {+export function memoryArrivalTitle(+ arrival: MemoryArrival,+ locale: GuiLocale = "zh-CN",+): string {switch (arrival.phase) {case "checking":case "unavailable":- return arrival.refreshing ? "已保存内容保留,正在核对进度" : "进度待更新";+ return translate(+ locale,+ arrival.refreshing+ ? "arrival.title.refreshing"+ : "arrival.title.checking",+ );case "importing":- return "正在导入对话";+ return translate(locale, "arrival.title.importing");case "processing":- return "正在沉淀记忆";+ return translate(locale, "arrival.title.processing");case "model-required":- return modelBlock(arrival.blockedStages ?? [])- ? "待继续"- : "尚未设置整理模型";+ return translate(+ locale,+ modelBlock(arrival.blockedStages ?? [])+ ? "arrival.title.continue"+ : "arrival.title.model",+ );case "failed":case "stopped":- return "待继续";+ return translate(locale, "arrival.title.continue");default:- return arrival.importedMessages > 0 ? "待继续" : "还没有保存的对话";+ return translate(+ locale,+ arrival.importedMessages > 0+ ? "arrival.title.continue"+ : "arrival.title.empty",+ );}}diff --git a/memhub/apps/web/src/memory-arrival.test.tsx b/memhub/apps/web/src/memory-arrival.test.tsxindex dd968d6..e2f51a8 100644--- a/memhub/apps/web/src/memory-arrival.test.tsx+++ b/memhub/apps/web/src/memory-arrival.test.tsx@@ -2,7 +2,33 @@import { cleanup, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, expect, it, vi } from "vitest";+import { LANGUAGE_STORAGE_KEY, LanguageProvider } from "./gui-language";import { MemoryArrivalPanel } from "./memory-arrival";++it("traduce el progreso conservando mensajes y conversaciones como medidas distintas", () => {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "es");+ render(+ <LanguageProvider>+ <MemoryArrivalPanel+ arrival={{+ importing: true,+ importedMessages: 1,+ importedConversations: 1,+ phase: "importing",+ }}+ onConfigureModel={() => {}}+ onConnect={() => {}}+ />+ </LanguageProvider>,+ );+ expect(screen.getByRole("status").textContent).toBe(+ "Importando conversaciones",+ );+ expect(screen.getByText("Se guardó 1 mensaje")).toBeTruthy();+ expect(screen.getByText("1 conversación")).toBeTruthy();+ localStorage.removeItem(LANGUAGE_STORAGE_KEY);+});+import type { MemoryArrivalPhase } from "./memory-arrival-state";afterEach(() => {diff --git a/memhub/apps/web/src/memory-arrival.tsx b/memhub/apps/web/src/memory-arrival.tsxindex e0a4497..68633ce 100644--- a/memhub/apps/web/src/memory-arrival.tsx+++ b/memhub/apps/web/src/memory-arrival.tsx@@ -1,9 +1,12 @@+import { type GuiLocale, translate } from "@one-memory/i18n";import { FileText, Link2, LoaderCircle, Settings2 } from "lucide-react";+import { useGuiLanguage } from "./gui-language";import {type MemoryArrival,memoryArrivalTitle,resolveMemoryArrival,} from "./memory-arrival-state";+import { useMemoryLanguage } from "./memory-language";import { blockReasonLabel, taskKindLabel } from "./memory-processing-labels";import { useMediaPreference } from "./use-media-preference";import "./memory-arrival.css";@@ -28,6 +31,8 @@ export function MemoryArrivalPanel({onConnect(): void;showDetails?: boolean;}) {+ const { t, tn, locale } = useGuiLanguage();+ const { text } = useMemoryLanguage();const reduceMotion = useMediaPreference("(prefers-reduced-motion: reduce)");const arrival = resolveMemoryArrival({arrival: providedArrival,@@ -42,15 +47,15 @@ export function MemoryArrivalPanel({const hasOriginals = arrival.importedMessages > 0;const title =hasMemories && arrival.phase === "idle"- ? "原文仍在导入"- : memoryArrivalTitle(arrival);- const description = arrivalDescription(arrival);+ ? t("arrival.importing")+ : memoryArrivalTitle(arrival, locale);+ const description = arrivalDescription(arrival, locale);return (<sectionclassName="memory-arrival memory-arrival-neutral"data-phase={arrival.phase}data-compact={String(hasMemories)}- aria-label="记忆整理状态"+ aria-label={t("arrival.region")}><div className="memory-arrival-heading" role="status" aria-live="polite">{active && (@@ -65,15 +70,17 @@ export function MemoryArrivalPanel({</div>{(hasOriginals || arrival.importing) && (<p className="memory-arrival-counts">- 已保存 {arrival.importedMessages.toLocaleString("zh-CN")} 条消息+ <span>{tn("arrival.messages", arrival.importedMessages)}</span>{" · "}- {arrival.importedConversations.toLocaleString("zh-CN")} 个会话+ <span>+ {tn("arrival.conversations", arrival.importedConversations)}+ </span></p>)}{arrival.importing &&arrival.phase !== "importing" &&arrival.phase !== "idle" && (- <p className="memory-arrival-secondary">原文仍在导入</p>+ <p className="memory-arrival-secondary">{t("arrival.importing")}</p>)}{(!hasMemories ||active ||@@ -85,16 +92,17 @@ export function MemoryArrivalPanel({(arrival.phase === "processing" &&(arrival.backlogPending ?? 0) > 0)) && (<details className="memory-feedback-details">- <summary>查看进度与详情</summary>+ <summary>{t("arrival.details")}</summary>{arrival.phase === "processing" &&(arrival.backlogPending ?? 0) > 0 && (- <p>存量数据较大,为保证质量,正在后台分批整理</p>+ <p>{t("arrival.backlog")}</p>)}<ul>{arrival.blockedStages?.map((block) => (<li key={`${block.kind}:${block.reason}`}>- {taskKindLabel(block.kind)} · {blockReasonLabel(block.reason)}{" "}- · {block.count.toLocaleString("zh-CN")} 项+ {text(taskKindLabel(block.kind))} ·{" "}+ {text(blockReasonLabel(block.reason))} ·{" "}+ {tn("arrival.items", block.count)}</li>))}</ul>@@ -104,7 +112,7 @@ export function MemoryArrivalPanel({{arrival.phase === "model-required" && (<button type="button" onClick={onConfigureModel}><Settings2 size={15} aria-hidden="true" />- 设置记忆整理+ {t("arrival.configure")}</button>)}{["failed", "unavailable", "stopped"].includes(arrival.phase) && (@@ -114,19 +122,19 @@ export function MemoryArrivalPanel({onClick={onConfigureModel}><Settings2 size={15} aria-hidden="true" />- 查看整理状态+ {t("arrival.status")}</button>)}{hasOriginals && onViewHistory && (<button type="button" className="secondary" onClick={onViewHistory}><FileText size={15} aria-hidden="true" />- 查看已保存的对话+ {t("arrival.history")}</button>)}{!hasOriginals && !arrival.importing && arrival.phase === "idle" && (<button type="button" onClick={onConnect}><Link2 size={15} aria-hidden="true" />- 关联应用+ {t("arrival.connect")}</button>)}</div>@@ -134,29 +142,29 @@ export function MemoryArrivalPanel({);}-function arrivalDescription(arrival: MemoryArrival): string {- const retained =- arrival.importedMessages > 0 ? "已保存的原文保留在本机。" : "";+function arrivalDescription(arrival: MemoryArrival, locale: GuiLocale): string {+ const t = (key: Parameters<typeof translate>[1]) => translate(locale, key);+ const retained = arrival.importedMessages > 0 ? t("arrival.retained") : "";switch (arrival.phase) {case "model-required":- return `${retained}请核对整理模型后继续。`;+ return `${retained}${t("arrival.description.model-required")}`;case "processing":- return "先整理近期对话,更多记忆会陆续出现";+ return t("arrival.description.processing");case "importing":- return "正在保存原文;导入进度不代表记忆生成进度。";+ return t("arrival.description.importing");case "failed":- return `${retained}请先核对失败原因,再决定是否重试。`;+ return `${retained}${t("arrival.description.failed")}`;case "unavailable":- return "最近确认的信息已保留,当前进度需要重新核对。";+ return t("arrival.description.unavailable");case "checking":return arrival.refreshing- ? "正在核对本机记录,尚未确认的进度不会计入。"- : "已保存内容保留,进度待更新。";+ ? t("arrival.description.refreshing")+ : t("arrival.description.checking");case "stopped":- return `${retained}当前整理已停止,可查看状态后继续。`;+ return `${retained}${t("arrival.description.stopped")}`;default:return arrival.importedMessages > 0- ? "当前没有正在运行的整理任务。"- : "关联应用或导入对话文件后,原文会先保存到本机。";+ ? t("arrival.description.idle")+ : t("arrival.description.empty");}}diff --git a/memhub/apps/web/src/memory-language.ts b/memhub/apps/web/src/memory-language.tsnew file mode 100644index 0000000..2c9296f--- /dev/null+++ b/memhub/apps/web/src/memory-language.ts@@ -0,0 +1,38 @@+import {+ type GuiLocale,+ isMessageKey,+ plainCount,+ translate,+ translateCount,+} from "@one-memory/i18n";+import { useGuiLanguage } from "./gui-language";++type Params = Record<string, string | number>;++/**+ * Adapter over the shared "memory:" catalog. Only explicit interface copy is+ * passed in; unknown text (imported content, names, codes) returns unchanged.+ * `plural` selects the Spanish `.one` variant; callers format shown numbers.+ */+export function memoryText(+ locale: GuiLocale,+ message: string,+ params?: Params,+ plural?: number,+): string {+ const key = `memory:${message}`;+ if (!isMessageKey(key)) return message;+ return plural === undefined+ ? translate(locale, key, params)+ : translateCount(locale, key, plural, params);+}+export function useMemoryLanguage() {+ const { locale } = useGuiLanguage();+ return {+ locale,+ text: (message: string, params?: Params, plural?: number) =>+ memoryText(locale, message, params, plural),+ count: (value: number) => new Intl.NumberFormat(locale).format(value),+ plain: (value: number) => plainCount(locale, value),+ };+}diff --git a/memhub/apps/web/src/onboarding-language.ts b/memhub/apps/web/src/onboarding-language.tsnew file mode 100644index 0000000..7af255b--- /dev/null+++ b/memhub/apps/web/src/onboarding-language.ts@@ -0,0 +1,21 @@+import { isMessageKey, type MessageKey, translate } from "@one-memory/i18n";+import { useGuiLanguage } from "./gui-language";++/** Translate presentation copy at render time, retaining external names and unknown errors. */+export function useOnboardingTranslation() {+ const { t, tn, tnPlain, locale } = useGuiLanguage();+ return {+ locale,+ text: (message: string) => {+ if (message.startsWith("操作没成功:"))+ return translate(locale, "onboardingModelOperationFailed", {+ code: message.slice("操作没成功:".length),+ });+ return isMessageKey(message) ? t(message) : message;+ },+ t: (key: MessageKey, params?: Record<string, string | number>) =>+ translate(locale, key, params),+ tn,+ tnPlain,+ };+}diff --git a/memhub/apps/web/src/onboarding-model-r6.css b/memhub/apps/web/src/onboarding-model-r6.cssindex a70364b..ac525ec 100644--- a/memhub/apps/web/src/onboarding-model-r6.css+++ b/memhub/apps/web/src/onboarding-model-r6.css@@ -1,7 +1,7 @@/* P3 source 143:2786 / 2854 / 2936; shared shell stays in R6ColdStartFrame. */.onboarding-model-r6 .onboarding-r6-head > div {width: 620px;- max-width: calc(100% - 320px);+ max-width: 100%;}.onboarding-model-layout {display: grid;@@ -234,7 +234,7 @@font-size: 12px;}.onboarding-model-footer-note {- flex: 1;+ flex: 1 1 260px;min-width: 0;font-size: 12px;line-height: 24px;@@ -243,13 +243,24 @@}.onboarding-model-footer-actions {display: flex;- gap: 16px;- width: 398px;+ flex: 0 1 auto;+ flex-wrap: wrap;+ min-width: 0;+ max-width: 100%;+ gap: 12px;+ margin-left: auto;justify-content: flex-end;+ align-items: stretch;}.onboarding-model-footer-actions .r6-button {- width: 150px;- height: 44px;+ flex: 1 1 auto;+ min-width: 0;+ max-width: 100%;+ width: auto;+ height: auto;+ padding: 10px 20px;+ white-space: normal;+ overflow-wrap: anywhere;min-height: 44px;border-radius: 8px;font-size: 14px;@@ -257,7 +268,7 @@background: rgb(255 255 255 / 34%);}.onboarding-model-footer-actions .r6-button[data-variant="primary"] {- width: 210px;+ width: auto;background: var(--r6-action);color: white;border-color: #5b6f7e;@@ -268,12 +279,24 @@border-color: var(--r6-control-edge);}.onboarding-model-advanced-head {- display: block;- height: 28px;+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 16px;font-size: 13px;line-height: 21px;color: #63707b;}+.onboarding-model-advanced-head .onboarding-model-toggle {+ margin-top: 0;+ padding: 6px 0;+ gap: 12px;+ text-align: left;+ white-space: normal;+}+.onboarding-model-advanced-head .onboarding-model-toggle svg {+ flex-shrink: 0;+}.onboarding-model-advanced-grid {display: grid;grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);@@ -362,11 +385,10 @@gap: 24px;}}-@media (min-width: 761px) and (max-height: 959px) {+/* One scroll owner for the editable pane; the disclosure scrolls independently. */+@media (min-width: 761px) {.onboarding-model-r6 .onboarding-r6-body {overflow: hidden;- padding-top: 16px;- padding-bottom: 16px;}.onboarding-model-layout {height: 100%;@@ -382,11 +404,21 @@overscroll-behavior: contain;scrollbar-width: thin;scrollbar-gutter: stable;- scroll-padding: 4px;+ scroll-padding: 12px;+ padding-inline: 4px 16px;}.onboarding-model-recovery-actions {flex-shrink: 0;}+}+.onboarding-model-field select {+ padding-inline-end: 32px;+}+@media (min-width: 761px) and (max-height: 959px) {+ .onboarding-model-r6 .onboarding-r6-body {+ padding-top: 16px;+ padding-bottom: 16px;+ }.onboarding-model-feedback {flex: 0 1 auto;min-height: 0;@@ -473,9 +505,14 @@width: 100%;gap: 12px;}+ .onboarding-model-footer-actions .r6-button,.onboarding-model-footer-actions .r6-button[data-variant="primary"] {- width: auto;- flex: 1;+ flex: 1 1 160px;+ }+}+@media (max-width: 480px) {+ .onboarding-model-advanced-grid {+ grid-template-columns: minmax(0, 1fr);}}@media (prefers-reduced-transparency: reduce) {diff --git a/memhub/apps/web/src/onboarding-r6.css b/memhub/apps/web/src/onboarding-r6.cssindex 5accf4f..4770b5a 100644--- a/memhub/apps/web/src/onboarding-r6.css+++ b/memhub/apps/web/src/onboarding-r6.css@@ -24,15 +24,68 @@.onboarding-r6 [hidden] {display: none;}+/* Onboarding owns its drag strip; the global overlay would intercept the select. */+.desktop-frame:has(.onboarding-r6) > .window-drag-region {+ display: none;+}.onboarding-r6-titlebar {position: relative;- flex: 0 0 58px;+ flex: 0 0 auto;+ min-height: 58px;+ display: flex;+ justify-content: flex-end;+ align-items: center;+ padding: 8px 24px 8px 88px;border-bottom: 1px solid #ffffffa8;background: #ffffff30;backdrop-filter: blur(40px);user-select: none;-webkit-app-region: drag;}+.onboarding-r6-titlebar .r6-language-selector--compact {+ min-width: 0;+ max-width: 100%;+ -webkit-app-region: no-drag;+}+.onboarding-r6-titlebar .r6-language-selector-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: flex-end;+ gap: 6px 10px;+ font-size: 12px;+}+.onboarding-r6-titlebar select {+ min-width: 0;+ max-width: 100%;+ min-height: 32px;+ padding: 4px 8px;+ border: 1px solid #9badbd;+ border-radius: 8px;+ color: inherit;+ background: #f7fafc;+ font: inherit;+}+.onboarding-r6-titlebar select:focus-visible {+ outline: 2px solid #356d99;+ outline-offset: 2px;+}+.onboarding-r6-titlebar [role="alert"] {+ margin: 6px 0 0;+ max-width: 320px;+ color: #9f3333;+ font-size: 12px;+ overflow-wrap: anywhere;+}+@media (max-width: 480px) {+ .onboarding-r6-titlebar {+ padding-right: 12px;+ }+ .onboarding-r6-titlebar .r6-language-selector-row {+ flex-direction: column;+ align-items: flex-end;+ }+}.onboarding-r6:is(button,@@ -52,6 +105,7 @@padding: 32px 24px 2px;}.onboarding-r6-shell {+ min-height: 0;width: 1120px;max-width: 100%;height: 820px;@@ -69,8 +123,13 @@inset 0 -1px 0 #adc0d22e;}.onboarding-r6-head {- min-height: 0;- flex: 0 0 123.7px;+ min-height: 123.7px;+ flex: 0 0 auto;+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ justify-content: space-between;+ gap: 22px 32px;position: relative;border-bottom: 1px solid #ffffffc4;background: linear-gradient(115deg, #ffffff57, #ffffff0a);@@ -78,8 +137,11 @@border-radius: 25px 25px 0 0;}.onboarding-r6-head > div {+ flex: 1 1 360px;+ min-width: 0;width: 450px;- max-width: calc(100% - 320px);+ max-width: 100%;+ overflow-wrap: anywhere;}.onboarding-r6-head p {margin: 0 0 10px;@@ -94,12 +156,10 @@line-height: 43px;}.onboarding-r6-head .r6-stepper {- position: absolute;- top: 42px;- right: 36px;+ margin-top: 14px;}.onboarding-r6-head .r6-stepper li {- height: 36px;+ min-height: 36px;padding: 0 0 12px;align-items: flex-start;line-height: 18px;@@ -107,11 +167,15 @@.onboarding-r6-body {flex: 1;min-height: 0;+ overflow-y: auto;+ overscroll-behavior: contain;+ scrollbar-width: thin;padding: 26px 36px;}.onboarding-r6-foot {- min-height: 0;- flex: 0 0 82.1px;+ min-height: 82.1px;+ flex: 0 0 auto;+ flex-wrap: wrap;padding: 20px 36px 18px;border-top: 1px solid #ffffffc4;background: #ffffff38;@@ -202,13 +266,9 @@position: absolute;inset: 142px 0 auto;}-.onboarding-r6-list-area::after {- content: "";- position: absolute;- inset: auto 0 0;- height: 40px;- pointer-events: none;- background: linear-gradient(180deg, transparent, #f7fafc 92%);+.onboarding-r6-list-status .onboarding-r6-quiet:disabled {+ color: #4e6478;+ opacity: 1;}.onboarding-r6-list {padding: 0;@@ -464,9 +524,17 @@color: #4e6478;}.onboarding-r6-submit {- width: 138px;+ width: auto;+ min-width: 138px;margin-left: auto;}+.onboarding-r6-foot .r6-button {+ max-width: 100%;+ height: auto;+ padding-block: 10px;+ white-space: normal;+ overflow-wrap: anywhere;+}.onboarding-r6 .r6-button[data-variant="primary"]:not(:disabled) {background: #4f6373;border-color: #5b6f7e;@@ -605,12 +673,12 @@flex-basis: auto;}.onboarding-r6-head > div {+ flex-basis: 100%;max-width: 100%;width: auto;}.onboarding-r6-head .r6-stepper {- position: static;- margin-top: 22px;+ margin-top: 0;}.onboarding-r6-body {padding: 24px 20px;diff --git a/memhub/apps/web/src/query-client.test-setup.ts b/memhub/apps/web/src/query-client.test-setup.tsindex d08595f..54c4d7b 100644--- a/memhub/apps/web/src/query-client.test-setup.ts+++ b/memhub/apps/web/src/query-client.test-setup.ts@@ -1,6 +1,12 @@-import { afterEach } from "vitest";+import { afterEach, beforeEach, vi } from "vitest";import { resetClient } from "./query-client";+beforeEach(() => {+ if (typeof navigator !== "undefined") {+ vi.spyOn(navigator, "language", "get").mockReturnValue("zh-CN");+ }+});+afterEach(() => {resetClient();});diff --git a/memhub/apps/web/src/r6-controls.css b/memhub/apps/web/src/r6-controls.cssindex cc6cf0a..58c5bce 100644--- a/memhub/apps/web/src/r6-controls.css+++ b/memhub/apps/web/src/r6-controls.css@@ -118,11 +118,13 @@ button.r6-button[data-variant="quiet"]:disabled {.r6-stepper {width: 288px;- height: 40px;+ max-width: 100%;+ min-height: 40px;flex-shrink: 0;}.r6-stepper ol {- display: flex;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));gap: 18px;list-style: none;padding: 0;@@ -134,8 +136,9 @@ button.r6-button[data-variant="quiet"]:disabled {align-items: center;gap: 7px;box-sizing: border-box;- width: 84px;- height: 40px;+ min-width: 0;+ min-height: 40px;+ height: auto;padding-bottom: 12px;border-bottom: 2px solid #cbd6de;color: var(--r6-muted);@@ -144,7 +147,8 @@ button.r6-button[data-variant="quiet"]:disabled {"PingFang SC",sans-serif;letter-spacing: 0;- white-space: nowrap;+ white-space: normal;+ overflow-wrap: normal;transition: color 220ms ease;}/* The active rail is drawn as an overlay that wipes in, rather than by@@ -171,6 +175,7 @@ button.r6-button[data-variant="quiet"]:disabled {transform: scaleX(1);}.r6-stepper li > span {+ flex-shrink: 0;font-size: 10px;font-variant-numeric: tabular-nums;}diff --git a/memhub/apps/web/src/r6-import-progress.css b/memhub/apps/web/src/r6-import-progress.cssindex 0824d0c..a8571de 100644--- a/memhub/apps/web/src/r6-import-progress.css+++ b/memhub/apps/web/src/r6-import-progress.css@@ -2,7 +2,7 @@.r6-import-progress {display: grid;grid-auto-flow: column;- grid-auto-columns: calc((100% - 32px) / 3);+ grid-auto-columns: max(140px, calc((100% - 32px) / 3));gap: 16px;width: 100%;overflow-x: auto;@@ -22,7 +22,7 @@.r6-import-progress-card {box-sizing: border-box;position: relative;- height: 218px;+ min-height: 218px;min-width: 0;padding: 16px 12px 12px;background:diff --git a/memhub/apps/web/src/r6-memory.css b/memhub/apps/web/src/r6-memory.cssindex 97538b9..19bfd91 100644--- a/memhub/apps/web/src/r6-memory.css+++ b/memhub/apps/web/src/r6-memory.css@@ -204,6 +204,19 @@.r6-memory .memory-processing-details {margin: 0 0 16px;}+.r6-memory .memory-library-pagination {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px 12px;+ min-width: 0;+ height: auto;+ overflow: visible;+}+.r6-memory .memory-library-pagination span {+ white-space: normal;+ overflow-wrap: anywhere;+}.r6-memory .memory-library-layout {min-height: 0;overflow: auto;diff --git a/memhub/apps/web/src/r6-settings.css b/memhub/apps/web/src/r6-settings.cssindex e8fe461..2eaaa6f 100644--- a/memhub/apps/web/src/r6-settings.css+++ b/memhub/apps/web/src/r6-settings.css@@ -17,6 +17,35 @@sans-serif;margin: 0 0 28px;}+.r6-settings .r6-language-setting {+ margin-bottom: 24px;+ padding: 20px 24px;+ border: 1px solid #dce4eb;+ border-radius: 16px;+ background: #fff;+}+.r6-settings .r6-language-setting h2 {+ margin: 0 0 12px;+ font-size: 18px;+}+.r6-settings .r6-language-setting select {+ max-width: 100%;+ min-height: 36px;+ padding: 6px 10px;+ border: 1px solid #dce4eb;+ border-radius: 8px;+ color: inherit;+ background: #fff;+ font: inherit;+}+.r6-settings .r6-language-setting select:focus-visible {+ outline: 2px solid #225f9d;+ outline-offset: 2px;+}+.r6-settings .r6-language-setting > p {+ margin: 12px 0 0;+ overflow-wrap: anywhere;+}.r6-settings .r6-settings-layout {display: grid;grid-template-columns: 220px minmax(0, 1fr);@@ -40,7 +69,7 @@.r6-settings .r6-settings-layout > nav > button {box-sizing: border-box;padding: 8px 16px;- height: 46px;+ height: auto;min-height: 46px;text-align: left;border: 0;diff --git a/memhub/apps/web/src/r6-shell.css b/memhub/apps/web/src/r6-shell.cssindex 4e086d4..7847864 100644--- a/memhub/apps/web/src/r6-shell.css+++ b/memhub/apps/web/src/r6-shell.css@@ -1,6 +1,6 @@.app-shell.r6-shell {display: grid;- grid-template-columns: 78px minmax(0, 1fr);+ grid-template-columns: max-content minmax(0, 1fr);grid-template-rows: 58px minmax(0, 1fr) 48px;height: 100dvh;min-height: 0;@@ -26,6 +26,9 @@user-select: none;}.r6-shell > .app-rail {+ /* Keep the R6 sidebar vertical when legacy mobile navigation becomes a grid. */+ display: flex;+ flex-direction: column;grid-column: 1;grid-row: 2;padding: 34px 9px 18px;@@ -43,7 +46,10 @@}.r6-shell button.rail-button {border-radius: 8px;- width: 60px;+ width: 100%;+ min-width: 60px;+ padding-inline: 9px;+ white-space: nowrap;min-height: 70px;height: 70px;}@@ -108,7 +114,7 @@}@media (max-width: 600px) {.app-shell.r6-shell {- grid-template-columns: 64px minmax(0, 1fr);+ grid-template-columns: max-content minmax(0, 1fr);}.r6-shell > .app-rail {padding: 12px 4px;diff --git a/memhub/apps/web/src/ui-text-adapters.test.ts b/memhub/apps/web/src/ui-text-adapters.test.tsnew file mode 100644index 0000000..b4b48d7--- /dev/null+++ b/memhub/apps/web/src/ui-text-adapters.test.ts@@ -0,0 +1,151 @@+import type { SourceResponse } from "@one-memory/contracts";+import { isMessageKey, translate } from "@one-memory/i18n";+import { describe, expect, it } from "vitest";++import { applicationsText } from "./applications-language";+import { memoryText } from "./memory-language";+import {+ blockReasonLabel,+ extractionStateLabel,+ memoryHistoryActionLabel,+} from "./memory-processing-labels";+import { sourceAuthorizationNote } from "./source-state";++const unknown = [+ "一段导入的对话内容",+ "/Users/synthetic/.cursor/projects",+ "E_SYNTHETIC_CODE",+ "toString",+ "__proto__",+ "",+];++describe("presentation adapters", () => {+ it.each(unknown)("memoryText returns unknown text %j untouched", (value) => {+ expect(memoryText("es", value)).toBe(value);+ expect(memoryText("en", value)).toBe(value);+ expect(memoryText("zh-CN", value)).toBe(value);+ });++ it.each(unknown)(+ "applicationsText returns an unknown key %j untouched",+ (value) => {+ // Simulates a key that drifted out of the catalog at runtime.+ const key = value as Parameters<typeof applicationsText>[1];+ expect(applicationsText("es", key)).toBe(value);+ expect(applicationsText("en", key)).toBe(value);+ expect(applicationsText("zh-CN", key)).toBe(value);+ },+ );++ it("still translates known interface copy", () => {+ expect(applicationsText("es", "viewAll", { count: 3 })).toBe(+ "Ver las 3 aplicaciones",+ );+ expect(applicationsText("es", "viewAll", { count: 1 })).toBe(+ "Ver la aplicación",+ );+ expect(applicationsText("zh-CN", "viewAll", { count: 1 })).toBe(+ "查看全部 1 个应用",+ );+ expect(applicationsText("en", "viewAll", { count: 3 })).not.toMatch(+ /[一-鿿]/,+ );+ });++ // Labels and literals that screens now route through `text()`: a missing+ // catalog entry would silently stay Chinese in the Spanish interface.+ it.each([+ ...[+ "waiting_for_model",+ "failed",+ "model_profile_superseded",+ "ingest_policy_superseded",+ "unrecognised_reason",+ ].map(blockReasonLabel),+ ...["extracted", "outside_window", "queued"].map(extractionStateLabel),+ ...[+ "legacy",+ "create",+ "correct",+ "set_scopes",+ "undo",+ "hy_reconcile",+ "hy_supersede",+ "delete",+ "unrecognised_action",+ ].map(memoryHistoryActionLabel),+ "向记忆提问",+ "询问全部已授权可用记忆…",+ "发送问题",+ "保存",+ "重试",+ "删除",+ "对话",+ "修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ "纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ "未收到操作结果,请重试。",+ "批量处理结果已保留,但列表刷新失败,请重新读取记忆库。",+ "批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。",+ "召回范围已保存,但列表刷新失败。请稍后重新打开记忆页。",+ "重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?",+ "原始对话暂时无法读取",+ "没有匹配的原始对话",+ "还没有导入的原始对话",+ ])("memoryText translates %j and keeps the Chinese as is", (label) => {+ expect(memoryText("zh-CN", label)).toBe(label);+ const spanish = memoryText("es", label);+ const english = memoryText("en", label);+ expect(spanish).not.toBe(label);+ expect(spanish).not.toMatch(/[一-鿿]/);+ expect(english).not.toBe(label);+ expect(english).not.toMatch(/[一-鿿]/);+ });++ it("words an action as a verb inside sentences and as a noun in history", () => {+ const action = (locale: "zh-CN" | "en" | "es") =>+ memoryText(locale, "删除(操作)");+ expect(action("zh-CN")).toBe("删除");+ expect(+ memoryText("zh-CN", "重试{action}", { action: action("zh-CN") }),+ ).toBe("重试删除");+ expect(memoryText("es", "重试{action}", { action: action("es") })).toBe(+ "Volver a eliminar",+ );+ expect(+ memoryText("es", "未能{action}:{error}", {+ action: action("es"),+ error: "E",+ }),+ ).toBe("No se pudo eliminar: E");+ expect(memoryText("zh-CN", "删除(记录)")).toBe("删除");+ expect(memoryText("es", "删除(记录)")).toBe("Eliminación");+ expect(memoryText("es", "删除")).toBe("Eliminar");+ expect(memoryText("en", "删除(记录)")).toBe("Deletion");+ expect(memoryText("en", "删除")).toBe("Delete");+ });+});++describe("source authorization notes", () => {+ const states = [+ "missing_grant",+ "revoked_grant",+ "source_identity_changed",+ "source_root_unavailable",+ "candidate_changed",+ ];+ it.each(states)("translates the %s note and its sync follow-up", (state) => {+ const note = sourceAuthorizationNote({+ authorization_state: state,+ } as unknown as SourceResponse);+ expect(note).not.toBeNull();+ // The sync rejection appends this follow-up to the same note.+ for (const message of [note as string, `${note}完成后再开启持续同步。`]) {+ expect(isMessageKey(message), message).toBe(true);+ if (!isMessageKey(message)) continue;+ expect(translate("zh-CN", message)).toBe(message);+ expect(translate("es", message)).not.toMatch(/[一-鿿]/);+ expect(translate("en", message)).not.toMatch(/[一-鿿]/);+ }+ });+});diff --git a/memhub/apps/web/src/workbench-findings.test.ts b/memhub/apps/web/src/workbench-findings.test.tsindex 5603eaf..54c1e37 100644--- a/memhub/apps/web/src/workbench-findings.test.ts+++ b/memhub/apps/web/src/workbench-findings.test.ts@@ -9,6 +9,27 @@ import { findingsOf, mattersOf, memoriesInMatter } from "./workbench-findings";const NOW = new Date("2026-09-10T00:00:00Z");+it("localiza hallazgos conservando contenidos y nombres de ámbitos opacos", () => {+ const findings = findingsOf({+ now: NOW,+ processing: null,+ locale: "es",+ memories: [+ memory("a", { content: "原文甲", evidence_ids: ["shared"] }),+ memory("b", {+ content: "原文乙",+ evidence_ids: ["shared"],+ scopes: ["custom:范围原文"],+ }),+ ],+ });+ expect(findings[0].label).toBe("Proceden del mismo texto");+ expect(findings[0].text).toContain("原文甲");+ expect(findings[0].text).toContain("原文乙");+ expect(findings[0].text).toContain("范围原文");+ expect(findings[0].text).toContain("Perfil personal");+});+function memory(id: string,overrides: Partial<GovernedMemory> = {},diff --git a/memhub/apps/web/src/workbench-findings.ts b/memhub/apps/web/src/workbench-findings.tsindex e9a7163..79e427c 100644--- a/memhub/apps/web/src/workbench-findings.ts+++ b/memhub/apps/web/src/workbench-findings.ts@@ -4,6 +4,8 @@ import type {SourceResponse,} from "@one-memory/contracts";+import { type GuiLocale, translate, translateCount } from "@one-memory/i18n";+/** One row of the left column: a topic, with what is actually under it. */export interface Matter {/** `topic:<tag>`, or `""` for the everything row. */@@ -118,10 +120,12 @@ export function findingsOf({memories,processing,now,+ locale = "zh-CN",}: {memories: GovernedMemory[];processing: MemoryProcessingSummary | null;now: Date;+ locale?: GuiLocale;}): Finding[] {const findings: Finding[] = [];@@ -129,8 +133,13 @@ export function findingsOf({findings.push({id: `duplicate:${pair[0].memory_id}:${pair[1].memory_id}`,kind: "duplicate",- label: "出自同一句话",- text: `「${clip(pair[0].content)}」和「${clip(pair[1].content)}」是从同一句原话里抽出来的,分别挂在 ${scopesText(pair[0])} 和 ${scopesText(pair[1])} 下。看看是不是一回事。`,+ label: translate(locale, "wb.finding.duplicate"),+ text: translate(locale, "wb.finding.duplicateText", {+ first: clip(pair[0].content),+ second: clip(pair[1].content),+ firstScope: scopesText(pair[0], locale),+ secondScope: scopesText(pair[1], locale),+ }),memoryIds: [pair[0].memory_id, pair[1].memory_id],});}@@ -143,8 +152,10 @@ export function findingsOf({findings.push({id: "dormant",kind: "dormant",- label: "很久没动过",- text: `${dormant.length} 条记忆两个月没再被改过也没再被提起。可能已经过时,值得回头看一眼。`,+ label: translate(locale, "wb.finding.dormant"),+ text: translate(locale, "wb.finding.dormantText", {+ count: dormant.length,+ }),memoryIds: dormant.map((item) => item.memory_id),});}@@ -155,8 +166,10 @@ export function findingsOf({findings.push({id: "blocked",kind: "blocked",- label: "卡住了",- text: `${blockedCount} 段对话排在队里,等的不是时间而是一个条件。原文已经在库里,随时搜得到。`,+ label: translate(locale, "wb.finding.blocked"),+ text: translateCount(locale, "wb.finding.blockedText", blockedCount, {+ count: blockedCount,+ }),memoryIds: [],});}@@ -214,10 +227,12 @@ function clip(text: string, limit = 18): string {return text.length > limit ? `${text.slice(0, limit)}…` : text;}-function scopesText(memory: GovernedMemory): string {+function scopesText(memory: GovernedMemory, locale: GuiLocale): string {return memory.scopes.length- ? memory.scopes.map(scopeLabel).join("、")- : "未归类";+ ? memory.scopes+ .map((scope) => scopeLabel(scope, locale))+ .join(locale === "zh-CN" ? "、" : ", ")+ : translate(locale, "wb.unclassified");}/** Say where a memory is authorised, in words.@@ -228,10 +243,12 @@ function scopesText(memory: GovernedMemory): string {* project, but it does tell two projects apart, which is what this sentence* is for. Printing `v1:0027abad1745330f1b57671635e0e9b3bd0cc3d2…` told the* reader nothing and filled the line. */-function scopeLabel(scope: string): string {- if (scope === "all-apps") return "个人画像";+function scopeLabel(scope: string, locale: GuiLocale): string {+ if (scope === "all-apps") return translate(locale, "wb.profile");if (scope.startsWith("workspace:v1:")) {- return `某个项目 ${scope.slice("workspace:v1:".length, "workspace:v1:".length + 8)}`;+ return translate(locale, "wb.project", {+ id: scope.slice("workspace:v1:".length, "workspace:v1:".length + 8),+ });}const [head, ...rest] = scope.split(":");if (rest.length) return rest.join(":");diff --git a/memhub/docs/ARCHITECTURE.md b/memhub/docs/ARCHITECTURE.mdindex dd36712..7487112 100644--- a/memhub/docs/ARCHITECTURE.md+++ b/memhub/docs/ARCHITECTURE.md@@ -69,6 +69,7 @@ files or SDK private stores directly.| `packages/runtime-control` | Runtime discovery/lifecycle, install transactions, service management. || `packages/host-bridge` | Loopback recall broker and host-facing MCP/Skill/Hook/plugin assets. Not a second memory engine. || `packages/contracts` | Shared TypeScript API contracts. |+| `packages/i18n` | Shared interface locales and catalogs for Web and Electron-native surfaces. || `packages/operations` | Shared typed operation flows. || `scripts` | Dev/privacy/test/packaging gates; not runtime product code. |diff --git a/memhub/docs/LOCALIZATION.md b/memhub/docs/LOCALIZATION.mdnew file mode 100644index 0000000..8e9643c--- /dev/null+++ b/memhub/docs/LOCALIZATION.md@@ -0,0 +1,69 @@+# MemHub Localization++MemHub ships Simplified Chinese (`zh-CN`), English (`en`), and Spanish (`es`).+Interface language is independent from conversation, memory, extraction, and+search language.++## Architecture++- `@one-memory/i18n` owns supported locales, catalogs, locale resolution,+ interpolation, plural rules, and formatting helpers.+- Web owns the active UI preference and reacts immediately without remounting+ product state.+- Electron persists the preference before Web starts so startup screens,+ dialogs, menus, and tray items use the same locale.+- `system` is a preference, not a locale. It resolves a supported system+ language and falls back to English.+- User-authored text, memory content, raw conversations, paths, source names,+ model names, endpoints, identifiers, and external error bodies are never+ translated.++The runtime uses `i18next` for CLDR plural selection, fallback, and+interpolation. Date, number, list, and relative-time formatting use the+platform `Intl` APIs.++## Catalog rules++1. Use stable, domain-qualified keys such as `settings.language.title` and+ `sdk.memory.delete.confirm`.+2. Keep the same key and placeholders in every locale.+3. Do not use Chinese or English source text as a new key.+4. Do not concatenate translated fragments when one message with parameters+ can express the sentence.+5. Keep technical identifiers outside translated messages unless they are+ explicit interpolation parameters.+6. Use the language's own name in selectors: `简体中文`, `English`, `Español`.+7. Do not use national flags to represent languages.++Existing compatibility keys are retained while screens move to semantic keys;+new code must not add another source-text key.++## Adding a language++1. Add its BCP 47 locale to `SUPPORTED_LOCALES`.+2. Add a complete catalog with placeholder parity.+3. Add locale resolution and fallback tests.+4. Add the self-name to the language selector.+5. Verify Web and Electron-native surfaces.+6. Test long text with a pseudo-locale or deliberately expanded translations.+7. For right-to-left languages, set `dir` and use logical CSS properties.++A locale contribution should primarily change catalog and locale metadata.+Large unrelated component or product-behavior changes belong in separate PRs.++## Verification++Run focused tests while developing:++```bash+bash scripts/run-tests-isolated.sh pnpm \+ --filter @one-memory/i18n exec vitest run+bash scripts/run-tests-isolated.sh pnpm \+ --filter @one-memory/web exec vitest run <affected tests>+bash scripts/run-tests-isolated.sh pnpm \+ --filter @one-memory/desktop exec vitest run <affected tests>+```++Catalog tests enforce key coverage, placeholder parity, plural behavior, and+safe fallback. Component tests must verify that changing locale does not repeat+network requests, lose form state, broaden authorization, or modify user data.diff --git a/memhub/packages/i18n/package.json b/memhub/packages/i18n/package.jsonnew file mode 100644index 0000000..62183ee--- /dev/null+++ b/memhub/packages/i18n/package.json@@ -0,0 +1,25 @@+{+ "name": "@one-memory/i18n",+ "version": "1.0.4",+ "private": true,+ "type": "module",+ "types": "./src/index.ts",+ "exports": {+ ".": {+ "types": "./src/index.ts",+ "default": "./src/index.ts"+ }+ },+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "typecheck": "tsc --noEmit --pretty false",+ "test": "node ../../scripts/assert-test-isolation.mjs && vitest run"+ },+ "dependencies": {+ "i18next": "^25.8.13"+ },+ "devDependencies": {+ "typescript": "^7.0.2",+ "vitest": "^4.1.11"+ }+}diff --git a/memhub/packages/i18n/src/gui-i18n-applications.ts b/memhub/packages/i18n/src/gui-i18n-applications.tsnew file mode 100644index 0000000..703e557--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-applications.ts@@ -0,0 +1,235 @@+// Applications home and shell copy. Keys are namespaced with "apps." so they+// cannot collide with other catalogs; ".one" variants carry Spanish singulars.+export const applicationsChineseMessages = {+ "apps.apps": "应用",+ "apps.allApps": "全部应用",+ "apps.home": "应用首页",+ "apps.back": "返回首页",+ "apps.overview": "记忆概览",+ "apps.memories": "已沉淀记忆",+ "apps.readingCount": "正在读取已沉淀记忆数量…",+ "apps.unreadable": "暂无法读取",+ "apps.unit": "条",+ "apps.scope": "按应用授权范围使用",+ "apps.processing": "沉淀状态",+ "apps.running": "整理中",+ "apps.paused": "已暂停",+ "apps.stoppedNew": "已停止生成新记忆",+ "apps.checkingProcessing": "正在核对整理状态",+ "apps.unchecked": "待核对",+ "apps.organizingNew": "新的对话正在整理",+ "apps.recentUpdate": "最近更新",+ "apps.notGenerated": "尚未生成",+ "apps.saved": "记忆已保存",+ "apps.separate": "历史与记忆分别处理",+ "apps.recentCall": "最近调用",+ "apps.activityUnavailable": "动态暂不可用",+ "apps.firstBatch": "首批沉淀",+ "apps.callsUnavailable": "暂时无法读取调用记录",+ "apps.memoryUnavailable": "暂时无法读取记忆状态",+ "apps.importing": "对话持续导入中,即将沉淀你的记忆",+ "apps.firstRunning": "正在沉淀第一批记忆",+ "apps.firstQueued": "准备沉淀第一批记忆",+ "apps.readingActivity": "正在读取动态",+ "apps.emptyMemories": "还没有已生成的记忆",+ "apps.callReadFailure": "已有记忆仍可查看;重试不会发起新的调用。",+ "apps.memoryReadFailure": "读取失败不会当作没有记忆。",+ "apps.savingConversations": "对话正在后台持续保存。",+ "apps.waitingMemories": "历史已保存,记忆生成后会显示在这里。",+ "apps.reread": "重新读取",+ "apps.viewCalls": "查看记录",+ "apps.viewMemory": "查看记忆",+ "apps.backgroundDown": "后台服务没有运行,应用暂时查不到记忆",+ "apps.restart": "重新启动",+ "apps.runtime": "运行状态",+ "apps.backgroundRunning": "后台运行中",+ "apps.connectionUnchecked": "连接状态待核对",+ "apps.disconnected": "服务未连接",+ "apps.authorizedOnly": "仅处理已授权范围",+ "apps.sync": "对话同步",+ "apps.organizing": "记忆整理",+ "apps.access": "应用访问",+ "apps.checkingAccess": "应用接入核对",+ "apps.checking": "核对中…",+ "apps.recheck": "重新核对",+ "apps.accessState": "应用接入状态",+ "apps.staleAccess": "应用接入状态暂时读取失败,当前为上次状态。",+ "apps.reconnect": "重新接入",+ "apps.myApps": "我的应用",+ "apps.list": "应用列表",+ "apps.syncEnabled": "持续同步已开启",+ "apps.recallAllowed": "允许请求已授权记忆",+ "apps.historyAllowed": "历史读取已授权",+ "apps.connectionPending": "连接待完成",+ "apps.details": "查看详情",+ "apps.listUnavailable": "应用列表暂时不可读取",+ "apps.emptyApps": "还没有可显示的应用",+ "apps.checkingNow": "正在核对中",+ "apps.checkingState": "正在检查状态",+ "apps.notEnabled": "尚未开启",+ "apps.enableFailed": "未能开启",+ "apps.unknownTime": "时间未知",+ "apps.today": "今天 ",+ "apps.newMemory": "新增记忆",+ "apps.updatedMemory": "更新记忆",+ "apps.unlinked": "尚未关联",+ "apps.lastRead": "上次读取:",+ "apps.recentSync": "最近同步 {time}",+ "apps.connectedCount": "{count} 个应用已接入",+ "apps.connectedCount.one": "{count} 个应用已接入",+ "apps.pendingCount": "{count} 个应用待核对",+ "apps.pendingCount.one": "{count} 个应用待核对",+ "apps.mixedCount": "{count} 个应用已接入,{pending} 个待核对",+ "apps.mixedCount.one": "{count} 个应用已接入,{pending} 个待核对",+ "apps.unknownAccess": "应用接入状态暂时没有读到,无法确认有几个应用已接入。",+ "apps.unknownPermissions":+ "{names} 的记忆权限暂时没有读到,无法确认是否已接入。",+ "apps.enabledCount": "{count} 个应用已开启",+ "apps.enabledCount.one": "{count} 个应用已开启",+ "apps.appCount": "{count} 个应用",+ "apps.appCount.one": "{count} 个应用",+ "apps.viewAll": "查看全部 {count} 个应用",+ "apps.viewAll.one": "查看全部 {count} 个应用",+ "apps.checkedAt": "上次核对:{time}",+ "apps.revision": "版本 {count}",+ "apps.conversationTime": "对话时间",+ "apps.importTime": "导入时间",+ "apps.incompleteCalls": " · 有几次调用没被记下来,列表可能不全",+ "apps.timeoutWarning":+ "{host} 最近几次没查到记忆,后台可能正忙,稍后会自动恢复",+ "apps.autoHostFailed": "{name} 未能自动接入{reason}。",+ "apps.failureReason": ":{reason}",+ "apps.autoSyncFailed": "{name} 的持续同步未能自动开启。{reason}",+ "apps.noAutoRetry": "不会自动重试。",+ "apps.cardUnavailable":+ "{label}暂时显示不了,其他功能不受影响,稍后会自动恢复。",+ "apps.navMemories": "记忆",+ "apps.navigation": "主要导航",+ "apps.skip": "跳到主要内容",+ "apps.local": "本地存储",+ "apps.localHint":+ "记忆保存在本机;使用云模型整理或交给已授权的助手时,相关内容会发送给对应服务。",+} as const;++export const applicationsSpanishMessages: Record<+ keyof typeof applicationsChineseMessages,+ string+> = {+ "apps.apps": "Aplicaciones",+ "apps.allApps": "Todas las aplicaciones",+ "apps.home": "Inicio de aplicaciones",+ "apps.back": "Volver al inicio",+ "apps.overview": "Resumen de memorias",+ "apps.memories": "Memorias guardadas",+ "apps.readingCount": "Leyendo el total de memorias…",+ "apps.unreadable": "No disponible",+ "apps.unit": "",+ "apps.scope": "Según los permisos de cada aplicación",+ "apps.processing": "Procesamiento",+ "apps.running": "Organizando",+ "apps.paused": "En pausa",+ "apps.stoppedNew": "Se dejó de generar memorias nuevas",+ "apps.checkingProcessing": "Comprobando el estado del procesamiento",+ "apps.unchecked": "Sin verificar",+ "apps.organizingNew": "Organizando nuevas conversaciones",+ "apps.recentUpdate": "Última actualización",+ "apps.notGenerated": "Sin generar",+ "apps.saved": "Memoria guardada",+ "apps.separate": "Historial y memorias se procesan por separado",+ "apps.recentCall": "Última consulta",+ "apps.activityUnavailable": "Actividad no disponible",+ "apps.firstBatch": "Primeras memorias",+ "apps.callsUnavailable": "No se pueden leer las consultas",+ "apps.memoryUnavailable": "No se puede leer el estado de las memorias",+ "apps.importing": "Importando conversaciones para generar memorias",+ "apps.firstRunning": "Generando las primeras memorias",+ "apps.firstQueued": "Preparando las primeras memorias",+ "apps.readingActivity": "Leyendo actividad",+ "apps.emptyMemories": "Aún no hay memorias generadas",+ "apps.callReadFailure":+ "Puedes ver las memorias guardadas. Reintentar no inicia otra consulta.",+ "apps.memoryReadFailure":+ "Un error de lectura no significa que no haya memorias.",+ "apps.savingConversations": "Las conversaciones se guardan en segundo plano.",+ "apps.waitingMemories":+ "El historial está guardado. Las memorias aparecerán cuando se generen.",+ "apps.reread": "Reintentar lectura",+ "apps.viewCalls": "Ver consultas",+ "apps.viewMemory": "Ver memoria",+ "apps.backgroundDown":+ "El servicio está detenido; las aplicaciones no pueden consultar memorias",+ "apps.restart": "Reiniciar",+ "apps.runtime": "Estado del servicio",+ "apps.backgroundRunning": "Servicio activo",+ "apps.connectionUnchecked": "Conexión sin verificar",+ "apps.disconnected": "Servicio desconectado",+ "apps.authorizedOnly": "Solo procesa contenido autorizado",+ "apps.sync": "Sincronización",+ "apps.organizing": "Organización de memorias",+ "apps.access": "Acceso de aplicaciones",+ "apps.checkingAccess": "Verificación de acceso",+ "apps.checking": "Verificando…",+ "apps.recheck": "Volver a verificar",+ "apps.accessState": "Estado del acceso",+ "apps.staleAccess":+ "No se pudo actualizar el acceso. Se muestra el último estado conocido.",+ "apps.reconnect": "Volver a conectar",+ "apps.myApps": "Mis aplicaciones",+ "apps.list": "Lista de aplicaciones",+ "apps.syncEnabled": "Sincronización continua activada",+ "apps.recallAllowed": "Puede consultar memorias autorizadas",+ "apps.historyAllowed": "Lectura del historial autorizada",+ "apps.connectionPending": "Conexión pendiente",+ "apps.details": "Ver detalles",+ "apps.listUnavailable": "No se puede leer la lista de aplicaciones",+ "apps.emptyApps": "Aún no hay aplicaciones para mostrar",+ "apps.checkingNow": "Verificando",+ "apps.checkingState": "Comprobando estado",+ "apps.notEnabled": "Desactivada",+ "apps.enableFailed": "No se pudo activar",+ "apps.unknownTime": "Hora desconocida",+ "apps.today": "Hoy ",+ "apps.newMemory": "Nueva memoria",+ "apps.updatedMemory": "Memoria actualizada",+ "apps.unlinked": "Sin vincular",+ "apps.lastRead": "Última lectura: ",+ "apps.recentSync": "Última sincronización: {time}",+ "apps.connectedCount": "{count} aplicaciones conectadas",+ "apps.connectedCount.one": "{count} aplicación conectada",+ "apps.pendingCount": "{count} aplicaciones sin verificar",+ "apps.pendingCount.one": "{count} aplicación sin verificar",+ "apps.mixedCount": "{count} aplicaciones conectadas; {pending} sin verificar",+ "apps.mixedCount.one":+ "{count} aplicación conectada; {pending} sin verificar",+ "apps.unknownAccess":+ "No se pudo leer el acceso; no se puede confirmar cuántas aplicaciones están conectadas.",+ "apps.unknownPermissions":+ "No se pudieron leer los permisos de {names}; su conexión no está confirmada.",+ "apps.enabledCount": "{count} aplicaciones activadas",+ "apps.enabledCount.one": "{count} aplicación activada",+ "apps.appCount": "{count} aplicaciones",+ "apps.appCount.one": "{count} aplicación",+ "apps.viewAll": "Ver las {count} aplicaciones",+ "apps.viewAll.one": "Ver la aplicación",+ "apps.checkedAt": "Última verificación: {time}",+ "apps.revision": "Versión {count}",+ "apps.conversationTime": "Hora de conversación",+ "apps.importTime": "Hora de importación",+ "apps.incompleteCalls":+ " · Algunas consultas no se registraron; la lista puede estar incompleta",+ "apps.timeoutWarning":+ "Las últimas consultas de {host} no se completaron. El servicio puede estar ocupado; se recuperará automáticamente.",+ "apps.autoHostFailed": "No se pudo conectar {name} automáticamente{reason}. ",+ "apps.failureReason": ": {reason}",+ "apps.autoSyncFailed":+ "No se pudo activar la sincronización continua de {name}. {reason}",+ "apps.noAutoRetry": "No se reintentará automáticamente.",+ "apps.cardUnavailable":+ "{label} no está disponible. Las demás funciones siguen activas; se recuperará automáticamente.",+ "apps.navMemories": "Memorias",+ "apps.navigation": "Navegación principal",+ "apps.skip": "Saltar al contenido principal",+ "apps.local": "Almacenamiento local",+ "apps.localHint":+ "Las memorias se guardan en este equipo. Al usar modelos en la nube o asistentes autorizados, el contenido pertinente se envía al servicio correspondiente.",+};diff --git a/memhub/packages/i18n/src/gui-i18n-calls.ts b/memhub/packages/i18n/src/gui-i18n-calls.tsnew file mode 100644index 0000000..27683fe--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-calls.ts@@ -0,0 +1,214 @@+// Call history and timestamp copy. {host} is an app name and {count} is+// formatted by the caller with Intl; ".one" variants carry Spanish singulars.+export const callsChineseMessages = {+ "calls.directHost": "直接调用(诊断)",+ "calls.headline.timedOut": "{host} 这次没来得及查到记忆",+ "calls.headline.unavailable": "{host} 暂时无法查记忆",+ "calls.headline.denied": "{host} 未获准查记忆",+ "calls.headline.empty": "{host} 没有查到相关记忆",+ "calls.headline.found": "{host} 查到 {count} 条相关内容",+ "calls.headline.found.one": "{host} 查到 {count} 条相关内容",+ "calls.detail.timedOut": "后台正在整理记忆,查询超时,这次回答没有带上记忆",+ "calls.detail.unavailable": "MemHub 暂时不可用,这次回答没有带上记忆",+ "calls.detail.denied": "当前授权不允许这次查询",+ "calls.detail.partialDelivered": "已提供给 {host} · 部分内容还在整理中",+ "calls.detail.partial": "部分内容还在整理中",+ "calls.detail.delivered": "已提供给 {host}",+ "calls.detail.notDelivered": "没有提供给应用",+ "calls.detail.empty": "这次没有找到相关记忆",+ "calls.detail.success": "查询成功",+ "calls.title": "使用记录",+ "calls.query": "这次查记忆",+ "calls.backApps": "返回应用",+ "calls.backHistory": "返回记录",+ "calls.filter": "按应用筛选",+ "calls.allApps": "全部应用",+ "calls.recent": "最近记录",+ "calls.refresh": "刷新记录",+ "calls.clearPage": "清除本页记录",+ "calls.clearAll": "清空全部记录",+ "calls.clearAllShort": "清空全部",+ "calls.loading": "正在读取使用记录",+ "calls.clearing": "正在清除所选记录",+ "calls.readFailed": "记录读取失败,请刷新重试。",+ "calls.unavailable": "使用记录暂不可用,请稍后刷新。",+ "calls.incomplete": "有几次调用没被记下来,列表可能不全。",+ "calls.callDetail": "调用详情",+ "calls.source": " · 来源 {source}",+ "calls.stats": "找到原文 {raw} 段 · 记忆 {memories} 条 · 用时 {seconds} 秒",+ "calls.metadata": "记录详情",+ "calls.privacy":+ "为保护隐私,这里不保存你问的原话和回答,只保存时间、来源和结果。",+ "calls.exactTime": "准确时间",+ "calls.app": "应用",+ "calls.type": "类型",+ "calls.result": "结果状态",+ "calls.tool": "查记忆",+ "calls.notRecorded": "未记录",+ "calls.missingRow": "这条记录已不在当前页,请返回记录查看。",+ "calls.list": "调用记录",+ "calls.emptyPage": "本页暂无记录",+ "calls.empty": "暂无使用记录",+ "calls.pagination": "记录分页",+ "calls.previous": "上一页",+ "calls.next": "下一页",+ "calls.policy": "保留 {days} 天,最多 {count} 条记录",+ "calls.confirmAllTitle": "清空全部使用记录?",+ "calls.confirmPageTitle": "清除本页 {count} 条记录?",+ "calls.confirmPageTitle.one": "清除本页 {count} 条记录?",+ "calls.confirmAllDescription":+ "将删除当前保留的全部调用记录,不限于本页或当前筛选。不删除原文或记忆,不更改授权与留存规则。此操作无法撤销。",+ "calls.confirmPageDescription":+ "仅清除这批调用记录,不删除原文或记忆,不更改授权与留存规则。此操作无法撤销。",+ "calls.confirmAll": "确认清空全部",+ "calls.confirmPage": "确认清除",+ "calls.cancel": "取消",+ "calls.clearedAll": "已清空全部记录。",+ "calls.clearedPage": "已清除所选记录。",+ "calls.clearAllFailed": "未能清空使用记录,当前记录保持不变。请核对后重试。",+ "calls.clearPageFailed": "未能清除所选记录,当前记录保持不变。请核对后重试。",+ "calls.clearUnknown":+ "清除结果未确认,请核对重新读取的记录。未自动重试清除。",+ "calls.references": "相关内容",+ "calls.referencesLoading": "正在读取相关内容",+ "calls.referencesFailed": "相关内容暂时无法读取,请刷新重试。",+ "calls.raw": "原文",+ "calls.memory": "记忆",+ "calls.changed": "版本已变更",+ "calls.pending": "待核对",+ "calls.notAvailable": "不可用",+ "calls.openRaw": "查看原文",+ "calls.openMemory": "查看记忆",+ "calls.noReferences": "没有找到相关内容",+ "calls.rawBody": "原文正文",+ "calls.rawLoading": "正在读取原文",+ "calls.rawFailed": "原文已不可用或版本已变更。",+ "calls.state.grounded": "查询成功",+ "calls.state.empty": "查询成功,没有找到相关记忆",+ "calls.state.partial": "查询成功,部分内容还在整理中",+ "calls.state.timed_out": "查询超时,没有提供记忆",+ "calls.state.unavailable": "MemHub 暂时不可用",+ "calls.state.denied": "当前未授权查询",+ "calls.return.timed_out":+ "MemHub 正在导入和整理你的记忆,这次没能及时查完,所以 {host} 这次是在没有记忆的情况下回答的。整理完成后会恢复正常。",+ "calls.return.unavailable": "MemHub 暂时不可用,这次回答没有带上记忆。",+ "calls.return.denied": "当前授权不允许这次查询,没有向应用提供记忆。",+ "calls.return.partial": "部分内容还在整理中。",+ "clock.unknown": "时间未知",+ "clock.today": "今天 {clock}",+} as const;++export const callsSpanishMessages: Record<+ keyof typeof callsChineseMessages,+ string+> = {+ "calls.directHost": "Consulta directa (diagnóstico)",+ "calls.headline.timedOut": "{host} no pudo consultar las memorias a tiempo",+ "calls.headline.unavailable": "{host} no puede consultar memorias ahora",+ "calls.headline.denied": "{host} no tiene permiso para consultar memorias",+ "calls.headline.empty": "{host} no encontró memorias relacionadas",+ "calls.headline.found": "{host} encontró {count} contenidos relacionados",+ "calls.headline.found.one": "{host} encontró {count} contenido relacionado",+ "calls.detail.timedOut":+ "La consulta agotó el tiempo mientras se organizaban las memorias; la respuesta no incluyó memorias",+ "calls.detail.unavailable":+ "MemHub no está disponible; la respuesta no incluyó memorias",+ "calls.detail.denied": "Los permisos actuales no permiten esta consulta",+ "calls.detail.partialDelivered":+ "Entregado a {host} · Parte del contenido sigue procesándose",+ "calls.detail.partial": "Parte del contenido sigue procesándose",+ "calls.detail.delivered": "Entregado a {host}",+ "calls.detail.notDelivered": "No se entregó a la aplicación",+ "calls.detail.empty": "No se encontraron memorias relacionadas",+ "calls.detail.success": "Consulta completada",+ "calls.title": "Historial de uso",+ "calls.query": "Esta consulta de memorias",+ "calls.backApps": "Volver a aplicaciones",+ "calls.backHistory": "Volver al historial",+ "calls.filter": "Filtrar por aplicación",+ "calls.allApps": "Todas las aplicaciones",+ "calls.recent": "Registros recientes",+ "calls.refresh": "Actualizar registros",+ "calls.clearPage": "Borrar registros de esta página",+ "calls.clearAll": "Borrar todos los registros",+ "calls.clearAllShort": "Borrar todo",+ "calls.loading": "Leyendo el historial de uso",+ "calls.clearing": "Borrando los registros seleccionados",+ "calls.readFailed":+ "No se pudo leer el historial. Actualiza e inténtalo de nuevo.",+ "calls.unavailable":+ "El historial no está disponible. Actualízalo más tarde.",+ "calls.incomplete":+ "Algunas consultas no se registraron; la lista puede estar incompleta.",+ "calls.callDetail": "Detalle de la consulta",+ "calls.source": " · Fuente: {source}",+ "calls.stats":+ "Originales: {raw} · Memorias: {memories} · Tiempo: {seconds} s",+ "calls.metadata": "Detalles del registro",+ "calls.privacy":+ "Por privacidad, no se guardan tu pregunta ni la respuesta, solo la fecha, la fuente y el resultado.",+ "calls.exactTime": "Fecha exacta",+ "calls.app": "Aplicación",+ "calls.type": "Tipo",+ "calls.result": "Estado del resultado",+ "calls.tool": "Consulta de memorias",+ "calls.notRecorded": "Sin registrar",+ "calls.missingRow":+ "Este registro ya no está en esta página. Vuelve al historial para buscarlo.",+ "calls.list": "Registros de consultas",+ "calls.emptyPage": "Esta página no tiene registros",+ "calls.empty": "Todavía no hay registros de uso",+ "calls.pagination": "Páginas del historial",+ "calls.previous": "Página anterior",+ "calls.next": "Página siguiente",+ "calls.policy": "Se conservan {days} días, hasta {count} registros",+ "calls.confirmAllTitle": "¿Borrar todo el historial de uso?",+ "calls.confirmPageTitle": "¿Borrar los {count} registros de esta página?",+ "calls.confirmPageTitle.one": "¿Borrar el {count} registro de esta página?",+ "calls.confirmAllDescription":+ "Se borrarán todos los registros conservados, no solo esta página o filtro. No se borran originales ni memorias, ni se cambian los permisos o las reglas de conservación. No se puede deshacer.",+ "calls.confirmPageDescription":+ "Solo se borrarán estos registros de consultas. No se borran originales ni memorias, ni se cambian los permisos o las reglas de conservación. No se puede deshacer.",+ "calls.confirmAll": "Confirmar borrado total",+ "calls.confirmPage": "Confirmar borrado",+ "calls.cancel": "Cancelar",+ "calls.clearedAll": "Se borraron todos los registros.",+ "calls.clearedPage": "Se borraron los registros seleccionados.",+ "calls.clearAllFailed":+ "No se pudo borrar el historial. Los registros no cambiaron. Compruébalos antes de reintentar.",+ "calls.clearPageFailed":+ "No se pudieron borrar los registros seleccionados. No cambiaron. Compruébalos antes de reintentar.",+ "calls.clearUnknown":+ "No se confirmó el borrado. Comprueba los registros recién leídos. No se reintentó automáticamente.",+ "calls.references": "Contenido relacionado",+ "calls.referencesLoading": "Leyendo el contenido relacionado",+ "calls.referencesFailed":+ "No se pudo leer el contenido relacionado. Actualiza e inténtalo de nuevo.",+ "calls.raw": "Original",+ "calls.memory": "Memoria",+ "calls.changed": "La versión cambió",+ "calls.pending": "Pendiente de comprobar",+ "calls.notAvailable": "No disponible",+ "calls.openRaw": "Ver original",+ "calls.openMemory": "Ver memoria",+ "calls.noReferences": "No se encontró contenido relacionado",+ "calls.rawBody": "Texto original",+ "calls.rawLoading": "Leyendo el original",+ "calls.rawFailed": "El original ya no está disponible o su versión cambió.",+ "calls.state.grounded": "Consulta completada",+ "calls.state.empty": "Consulta completada, sin memorias relacionadas",+ "calls.state.partial":+ "Consulta completada; parte del contenido sigue procesándose",+ "calls.state.timed_out": "Consulta agotada; no se entregaron memorias",+ "calls.state.unavailable": "MemHub no está disponible",+ "calls.state.denied": "La consulta no está autorizada",+ "calls.return.timed_out":+ "MemHub está importando y organizando tus memorias y no terminó la consulta a tiempo. Por eso, {host} respondió sin memorias. Volverá a funcionar normalmente al terminar el procesamiento.",+ "calls.return.unavailable":+ "MemHub no está disponible; la respuesta no incluyó memorias.",+ "calls.return.denied":+ "Los permisos actuales no permiten esta consulta. No se entregaron memorias a la aplicación.",+ "calls.return.partial": "Parte del contenido sigue procesándose.",+ "clock.unknown": "Hora desconocida",+ "clock.today": "Hoy {clock}",+};diff --git a/memhub/packages/i18n/src/gui-i18n-catalogs.test.ts b/memhub/packages/i18n/src/gui-i18n-catalogs.test.tsnew file mode 100644index 0000000..82c4a40--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-catalogs.test.ts@@ -0,0 +1,254 @@+import { describe, expect, it } from "vitest";+import {+ isMessageKey,+ type MessageKey,+ translate,+ translateCount,+} from "./gui-i18n.js";+import {+ applicationsChineseMessages,+ applicationsSpanishMessages,+} from "./gui-i18n-applications.js";+import {+ callsChineseMessages,+ callsSpanishMessages,+} from "./gui-i18n-calls.js";+import {+ currentChineseMessages,+ currentEnglishMessages,+ currentSpanishMessages,+} from "./gui-i18n-current.js";+import { englishMessages } from "./gui-i18n-english.js";+import {+ memoryChineseMessages,+ memorySpanishMessages,+} from "./gui-i18n-memory.js";+import {+ chineseMessages,+ guiCatalogs,+ mergeCatalogs,+ spanishMessages,+} from "./gui-i18n-messages.js";++const placeholders = (text: string) =>+ [...text.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1]).sort();++import {+ workbenchChineseMessages,+ workbenchSpanishMessages,+} from "./gui-i18n-workbench.js";++const migrated = [+ ["current", currentChineseMessages, currentSpanishMessages],+ ["workbench", workbenchChineseMessages, workbenchSpanishMessages],+ ["applications", applicationsChineseMessages, applicationsSpanishMessages],+ ["memory", memoryChineseMessages, memorySpanishMessages],+ ["calls", callsChineseMessages, callsSpanishMessages],+] as const;++// The parent integration merges this shard into gui-i18n-english.ts. Keep the+// shard independently type-safe without mutating that shared file here.+const completeEnglishMessages = {+ ...englishMessages,+ ...currentEnglishMessages,+};++describe("mergeCatalogs", () => {+ it("throws when two catalogs give one key divergent texts", () => {+ expect(() =>+ mergeCatalogs([+ { name: "a", chinese: { k: "甲" }, spanish: { k: "A" } },+ { name: "b", chinese: { k: "甲" }, spanish: { k: "B" } },+ ]),+ ).toThrow(/"k" differs between a and b/);+ expect(() =>+ mergeCatalogs([+ { name: "a", chinese: { k: "甲" }, spanish: {} },+ { name: "b", chinese: { k: "乙" }, spanish: {} },+ ]),+ ).toThrow(/differs/);+ });++ it("accepts an identical key repeated across catalogs", () => {+ const merged = mergeCatalogs([+ { name: "a", chinese: { k: "甲", x: "一" }, spanish: { k: "A" } },+ { name: "b", chinese: { k: "甲" }, spanish: { k: "A" } },+ ]);+ expect(merged).toEqual({+ chinese: { k: "甲", x: "一" },+ spanish: { k: "A" },+ });+ });++ it("merges the shipped catalogs without collisions", () => {+ expect(() => mergeCatalogs(guiCatalogs)).not.toThrow();+ });+});++describe.each(migrated)("%s catalog", (_name, chinese, spanish) => {+ it("translates every key with the same parameters", () => {+ expect(Object.keys(spanish).sort()).toEqual(Object.keys(chinese).sort());+ for (const [key, text] of Object.entries(chinese)) {+ const translated = placeholders(spanish[key as keyof typeof spanish]);+ const expected = placeholders(text);+ if (key.endsWith(".one")) {+ // A Spanish singular may drop {count} ("Ver la aplicación"), never invent one.+ for (const name of translated) expect(expected, key).toContain(name);+ } else {+ expect(translated, key).toEqual(expected);+ }+ }+ });++ it("is merged verbatim into the global catalog", () => {+ for (const [key, text] of Object.entries(chinese)) {+ expect(chineseMessages[key as MessageKey]).toBe(text);+ expect(spanishMessages[key as MessageKey]).toBe(+ spanish[key as keyof typeof spanish],+ );+ }+ });++ it("has no Chinese punctuation in Spanish", () => {+ for (const [key, text] of Object.entries(spanish))+ expect(text, key).not.toMatch(/[。,、;:!?()【】“”]/);+ });+});++describe("isMessageKey", () => {+ it("accepts real keys", () => {+ expect(isMessageKey("settings")).toBe(true);+ expect(isMessageKey("calls.directHost")).toBe(true);+ });++ it.each([+ "toString",+ "__proto__",+ "constructor",+ "hasOwnProperty",+ "",+ "apps.",+ "memory:",+ "/Users/synthetic/.cursor",+ "E_SYNTHETIC_CODE",+ "一段导入的对话",+ ])("rejects %j", (value) => {+ expect(isMessageKey(value)).toBe(false);+ });+});++describe("translateCount", () => {+ it("uses the Spanish singular only for exactly one", () => {+ const key = "calls.headline.found";+ const at = (count: number) =>+ translateCount("es", key, count, { host: "Cursor", count });+ expect(at(0)).toBe("Cursor encontró 0 contenidos relacionados");+ expect(at(1)).toBe("Cursor encontró 1 contenido relacionado");+ expect(at(2)).toBe("Cursor encontró 2 contenidos relacionados");+ expect(at(25)).toBe("Cursor encontró 25 contenidos relacionados");+ });++ it("keeps the Chinese wording for every count", () => {+ for (const count of [0, 1, 3])+ expect(+ translateCount("zh-CN", "calls.headline.found", count, {+ host: "Cursor",+ count,+ }),+ ).toBe(`Cursor 查到 ${count} 条相关内容`);+ });++ it("gives every singular a Chinese twin identical to its plural", () => {+ for (const [key, text] of Object.entries(chineseMessages)) {+ if (!key.endsWith(".one")) continue;+ expect(text, key).toBe(chineseMessages[key.slice(0, -4) as MessageKey]);+ }+ expect(translateCount("es", "debugCount", 1, { count: 1 })).toBe(+ "1 registro en este inicio",+ );+ expect(+ translateCount("es", "importUserProgress", 1, { count: 1 }),+ ).toContain("1 conversación importada");+ });++ it("falls back to the plain key when no singular exists", () => {+ expect(translateCount("es", "clock.today", 1, { clock: "09:05" })).toBe(+ "Hoy 09:05",+ );+ });+});++describe("translate interpolation", () => {+ it("replaces once and never re-reads substituted values", () => {+ expect(+ translate("es", "calls.detail.delivered", { host: "{host} $& $1" }),+ ).toBe("Entregado a {host} $& $1");+ });++ it("leaves missing and inherited parameters untouched", () => {+ expect(translate("es", "calls.detail.delivered", {})).toBe(+ "Entregado a {host}",+ );+ const inherited = Object.create({ host: "Inherited" }) as Record<+ string,+ string+ >;+ expect(translate("es", "calls.detail.delivered", inherited)).toBe(+ "Entregado a {host}",+ );+ });+});++describe("English catalog", () => {+ it("covers every shipped key with matching placeholders", () => {+ expect(Object.keys(completeEnglishMessages).sort()).toEqual(+ Object.keys(chineseMessages).sort(),+ );+ for (const [key, text] of Object.entries(chineseMessages)) {+ expect(+ placeholders(completeEnglishMessages[key as MessageKey]),+ key,+ ).toEqual(placeholders(text));+ expect(completeEnglishMessages[key as MessageKey], key).not.toMatch(+ /[一-鿿]/,+ );+ }+ });++ it("uses CLDR English singular and plural forms", () => {+ expect(+ translateCount("en", "calls.headline.found", 1, {+ host: "Cursor",+ count: 1,+ }),+ ).toContain("1");+ expect(+ translateCount("en", "calls.headline.found", 2, {+ host: "Cursor",+ count: 2,+ }),+ ).toContain("2");+ });+});++describe("Spanish catalog", () => {+ it("covers every shipped key with matching placeholders", () => {+ expect(Object.keys(spanishMessages).sort()).toEqual(+ Object.keys(chineseMessages).sort(),+ );+ for (const [key, text] of Object.entries(chineseMessages)) {+ const spanish = spanishMessages[key as MessageKey];+ expect(spanish, key).toBeDefined();+ if (spanish === undefined) continue;+ const translated = placeholders(spanish);+ const expected = placeholders(text);+ if (key !== "connectionFallback.promptTemplate")+ expect(spanish, key).not.toMatch(/[一-鿿]/);+ if (key.endsWith(".one")) {+ for (const name of translated) expect(expected, key).toContain(name);+ } else {+ expect(translated, key).toEqual(expected);+ }+ }+ });+});diff --git a/memhub/packages/i18n/src/gui-i18n-current.ts b/memhub/packages/i18n/src/gui-i18n-current.tsnew file mode 100644index 0000000..e509f01--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-current.ts@@ -0,0 +1,420 @@+/**+ * Semantic messages for the current main-page surfaces that are not owned by+ * the established applications, workbench or memory catalogs.+ */+export const currentChineseMessages = {+ "connectionFallback.title": "连接其他工具",+ "connectionFallback.desktopOnly": "本机配对仅在桌面 App 中可用。",+ "connectionFallback.description":+ "为未列出的本机 Harness 生成一次性配对 Skill。纯网页聊天、远端容器或另一台机器不能直接连接本机。",+ "connectionFallback.name": "Harness 名称",+ "connectionFallback.namePlaceholder": "例如 Kimi Code",+ "connectionFallback.generating": "正在生成…",+ "connectionFallback.generate": "生成配对 Skill",+ "connectionFallback.generateFailed": "未能生成配对 Skill。",+ "connectionFallback.retry": "重试",+ "connectionFallback.generated":+ "已为 {name} 生成一次性配对 Skill,有效期至 {time}。",+ "connectionFallback.skillLabel": "配对 Skill",+ "connectionFallback.copy": "复制 Skill",+ "connectionFallback.copied":+ "已复制配对 Skill。请粘贴到对应 Harness 中执行。",+ "connectionFallback.copyFailed": "复制失败,可在上方选中文本复制。",+ "connectionFallback.localDescription":+ "仅限本机 MCP 或命令工具。纯网页聊天不能直接连接本机。",+ "connectionFallback.loading": "正在读取本机连接配置…",+ "connectionFallback.loadFailed": "未能读取连接配置。",+ "connectionFallback.format": "连接材料格式",+ "connectionFallback.promptTab": "连接提示词",+ "connectionFallback.mcpTab": "MCP 配置",+ "connectionFallback.commandTab": "命令",+ "connectionFallback.materialLabel": "本机连接材料",+ "connectionFallback.materialBoundary":+ "包含本机路径,不含记忆和密钥。粘贴前请核对,并保持 MemHub 运行。",+ "connectionFallback.materialCopied": "已复制,尚未建立连接。",+ "connectionFallback.copyPrompt": "复制提示词",+ "connectionFallback.copyConfig": "复制配置",+ "connectionFallback.copyCommand": "复制命令",+ "connectionFallback.promptTemplate":+ "请按以下 MCP 配置连接本机 MemHub:\n```json\n{mcp}```\n{shellBlock}\n连接后先执行一次真实记忆查询,并如实报告结果。",+ "connectionFallback.promptShell":+ "\n如果只支持本机 shell,请使用:\n```bash\n{shell}```\n",++ "sdk.memory.title": "SDK 记忆库",+ "sdk.memory.status": "记忆状态",+ "sdk.memory.status.active": "已可用",+ "sdk.memory.status.superseded": "已被取代",+ "sdk.memory.total": "共 {count} 条",+ "sdk.memory.total.one": "共 {count} 条",+ "sdk.memory.loadFailed": "记忆库读取失败,请重试。",+ "sdk.memory.detailLoadFailed": "记忆详情读取失败。",+ "sdk.memory.updateFailed": "修改未完成,请重试。",+ "sdk.memory.deleteFailed": "删除未完成,请重试。",+ "sdk.memory.loading": "正在读取记忆库…",+ "sdk.memory.pagination": "SDK 记忆库分页",+ "sdk.memory.previous": "上一页",+ "sdk.memory.next": "下一页",+ "sdk.memory.detail": "SDK 记忆详情",+ "sdk.memory.content": "记忆内容",+ "sdk.memory.save": "保存修改",+ "sdk.memory.delete": "删除记忆",++ "sdk.raw.title": "SDK 原始对话",+ "sdk.raw.searchLabel": "搜索原始对话",+ "sdk.raw.searching": "搜索中…",+ "sdk.raw.search": "搜索",+ "sdk.raw.loadFailed": "原始对话暂时无法读取。",+ "sdk.raw.searchFailed": "原始对话搜索失败,请重试。",+ "sdk.raw.recent": "最近原始对话",+ "sdk.raw.found": "找到 {count} 条",+ "sdk.raw.found.one": "找到 {count} 条",++ "memoryInspector.emptyHint": "查看它的来源、内容和修改历史。",+ "memory.operationFailed": "记忆操作失败({code})",+ "memorySpace.tabs.workbench": "工作台",++ "selectedMemory.status.confirmed": "已沉淀",+ "selectedMemory.status.deleted": "已删除",+ "selectedMemory.status.superseded": "已被取代",+ "selectedMemory.status.unknown": "状态待核对",+ "selectedMemory.sourceUnknown": "来源待核对",+ "selectedMemory.discardDraft": "放弃尚未保存的修改?",+ "selectedMemory.newVersionReadFailed": "暂时无法读取新版本,草稿已保留。",+ "selectedMemory.updateRejected":+ "修改未提交;草稿已保留。请按提示修正后重试。",+ "selectedMemory.updateUnknown":+ "修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。",+ "selectedMemory.deleteRejected": "删除未提交。请核对这条记忆的状态后重试。",+ "selectedMemory.deleteUnknown":+ "删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。",+ "selectedMemory.undoRejected": "撤销未提交。请按提示修正后重试。",+ "selectedMemory.undoUnknown":+ "撤销尚未确认,请先核对当前记忆版本,避免重复撤销。",+ "selectedMemory.author.you": "你说",+ "selectedMemory.author.assistant": "助手原话",+ "selectedMemory.author.unknown": "作者待核对",+ "selectedMemory.version": "第 {revision} 版",+ "selectedMemory.sourceLine": "来源 {source} · {time}",+ "selectedMemory.timestamps": "对话时间 {conversation} · 沉淀时间 {created}",+ "selectedMemory.edit": "编辑",+ "selectedMemory.evidence": "原始依据",+ "selectedMemory.evidenceLine": "{author} · 原对话 {time}:",+ "selectedMemory.evidenceUnavailable": "这段原文当前不可查看。",+ "selectedMemory.viewOriginal": "查看原文",+ "selectedMemory.history": "版本记录",+ "selectedMemory.more": "更多管理",+ "selectedMemory.undo": "撤销上次修改",+ "selectedMemory.delete": "删除记忆",+ "selectedMemory.editTitle": "编辑记忆",+ "selectedMemory.originalTitle": "原始对话",+ "selectedMemory.back": "返回记忆",+ "selectedMemory.editDescription": "修改这条记忆,原始对话保持不变。",+ "selectedMemory.content": "记忆内容",+ "selectedMemory.scopeUnchanged": "使用范围保持不变",+ "selectedMemory.conflictTitle": "已有新版本",+ "selectedMemory.conflictDescription":+ "你的草稿已保留,先查看新版本再决定如何修改。",+ "selectedMemory.viewNewVersion": "查看新版本",+ "selectedMemory.continueFromVersion": "基于此版本继续编辑",+ "selectedMemory.cancel": "取消",+ "selectedMemory.save": "保存修改",+ "selectedMemory.author.user": "你",+ "selectedMemory.author.agent": "助手",+ "selectedMemory.sourceUnavailable": "来源权限已变化或原文不可用。",+ "selectedMemory.related": "对应记忆",+ "selectedMemory.viewMemory": "查看记忆",+ "selectedMemory.deleteTitle": "删除这条记忆?",+ "selectedMemory.deleteDescription":+ "删除后不再用于新的召回,来源 App 中的原始对话不会删除。",+ "selectedMemory.sentCannotRecall": "已经发送给应用的内容无法远程收回。",+} as const;++export const currentEnglishMessages: Record<+ keyof typeof currentChineseMessages,+ string+> = {+ "connectionFallback.title": "Connect other tools",+ "connectionFallback.desktopOnly":+ "Local pairing is available only in the desktop app.",+ "connectionFallback.description":+ "Generate a one-time pairing Skill for a local Harness that is not listed. Browser chats, remote containers and other computers cannot connect directly to this device.",+ "connectionFallback.name": "Harness name",+ "connectionFallback.namePlaceholder": "For example, Kimi Code",+ "connectionFallback.generating": "Generating…",+ "connectionFallback.generate": "Generate pairing Skill",+ "connectionFallback.generateFailed": "Could not generate the pairing Skill.",+ "connectionFallback.retry": "Retry",+ "connectionFallback.generated":+ "Generated a one-time pairing Skill for {name}. It expires at {time}.",+ "connectionFallback.skillLabel": "Pairing Skill",+ "connectionFallback.copy": "Copy Skill",+ "connectionFallback.copied":+ "Pairing Skill copied. Paste and run it in the matching Harness.",+ "connectionFallback.copyFailed":+ "Copy failed. Select and copy the text above instead.",+ "connectionFallback.localDescription":+ "For local MCP or command-line tools only. Browser chats cannot connect directly to this device.",+ "connectionFallback.loading": "Loading local connection details…",+ "connectionFallback.loadFailed": "Could not load connection details.",+ "connectionFallback.format": "Connection details format",+ "connectionFallback.promptTab": "Connection prompt",+ "connectionFallback.mcpTab": "MCP configuration",+ "connectionFallback.commandTab": "Command",+ "connectionFallback.materialLabel": "Local connection details",+ "connectionFallback.materialBoundary":+ "Contains local paths, but no memories or keys. Review it before pasting and keep MemHub running.",+ "connectionFallback.materialCopied":+ "Copied. No connection has been made yet.",+ "connectionFallback.copyPrompt": "Copy prompt",+ "connectionFallback.copyConfig": "Copy configuration",+ "connectionFallback.copyCommand": "Copy command",+ "connectionFallback.promptTemplate":+ "Connect this local Harness to MemHub with the following MCP configuration:\n```json\n{mcp}```\n{shellBlock}\nAfter connecting, run a real memory query and report the result accurately.",+ "connectionFallback.promptShell":+ "\nIf only local shell commands are supported, use:\n```bash\n{shell}```\n",++ "sdk.memory.title": "SDK memory library",+ "sdk.memory.status": "Memory status",+ "sdk.memory.status.active": "Available",+ "sdk.memory.status.superseded": "Superseded",+ "sdk.memory.total": "{count} memories",+ "sdk.memory.total.one": "{count} memory",+ "sdk.memory.loadFailed": "Could not load the memory library. Please retry.",+ "sdk.memory.detailLoadFailed": "Could not load the memory details.",+ "sdk.memory.updateFailed": "Could not save the change. Please retry.",+ "sdk.memory.deleteFailed": "Could not delete the memory. Please retry.",+ "sdk.memory.loading": "Loading memory library…",+ "sdk.memory.pagination": "SDK memory library pages",+ "sdk.memory.previous": "Previous page",+ "sdk.memory.next": "Next page",+ "sdk.memory.detail": "SDK memory details",+ "sdk.memory.content": "Memory content",+ "sdk.memory.save": "Save changes",+ "sdk.memory.delete": "Delete memory",++ "sdk.raw.title": "SDK original conversations",+ "sdk.raw.searchLabel": "Search original conversations",+ "sdk.raw.searching": "Searching…",+ "sdk.raw.search": "Search",+ "sdk.raw.loadFailed": "Original conversations are temporarily unavailable.",+ "sdk.raw.searchFailed":+ "Could not search original conversations. Please retry.",+ "sdk.raw.recent": "Recent original conversations",+ "sdk.raw.found": "{count} results",+ "sdk.raw.found.one": "{count} result",++ "memoryInspector.emptyHint": "See its sources, content and change history.",+ "memory.operationFailed": "Memory operation failed ({code})",+ "memorySpace.tabs.workbench": "Workbench",++ "selectedMemory.status.confirmed": "Created",+ "selectedMemory.status.deleted": "Deleted",+ "selectedMemory.status.superseded": "Superseded",+ "selectedMemory.status.unknown": "Status needs review",+ "selectedMemory.sourceUnknown": "Source needs review",+ "selectedMemory.discardDraft": "Discard unsaved changes?",+ "selectedMemory.newVersionReadFailed":+ "Could not load the new version. Your draft is retained.",+ "selectedMemory.updateRejected":+ "Changes were not submitted. Your draft is retained; fix the issue and retry.",+ "selectedMemory.updateUnknown":+ "Changes are unconfirmed. Your draft is retained; refresh before retrying.",+ "selectedMemory.deleteRejected":+ "Deletion was not submitted. Review this memory and retry.",+ "selectedMemory.deleteUnknown":+ "Deletion is unconfirmed. Review the memory; the deletion scope will not expand.",+ "selectedMemory.undoRejected":+ "Undo was not submitted. Fix the issue and retry.",+ "selectedMemory.undoUnknown":+ "Undo is unconfirmed. Review the current version before retrying.",+ "selectedMemory.author.you": "You said",+ "selectedMemory.author.assistant": "Original assistant message",+ "selectedMemory.author.unknown": "Author needs review",+ "selectedMemory.version": "Version {revision}",+ "selectedMemory.sourceLine": "Source {source} · {time}",+ "selectedMemory.timestamps":+ "Conversation time {conversation} · Created {created}",+ "selectedMemory.edit": "Edit",+ "selectedMemory.evidence": "Original evidence",+ "selectedMemory.evidenceLine": "{author} · Original conversation {time}:",+ "selectedMemory.evidenceUnavailable":+ "This original text is currently unavailable.",+ "selectedMemory.viewOriginal": "View original",+ "selectedMemory.history": "Version history",+ "selectedMemory.more": "More actions",+ "selectedMemory.undo": "Undo last change",+ "selectedMemory.delete": "Delete memory",+ "selectedMemory.editTitle": "Edit memory",+ "selectedMemory.originalTitle": "Original conversation",+ "selectedMemory.back": "Back to memory",+ "selectedMemory.editDescription":+ "Edit this memory; the original conversation stays unchanged.",+ "selectedMemory.content": "Memory content",+ "selectedMemory.scopeUnchanged": "Access scope stays unchanged",+ "selectedMemory.conflictTitle": "A newer version exists",+ "selectedMemory.conflictDescription":+ "Your draft is retained. Review the new version before editing.",+ "selectedMemory.viewNewVersion": "View new version",+ "selectedMemory.continueFromVersion": "Continue editing from this version",+ "selectedMemory.cancel": "Cancel",+ "selectedMemory.save": "Save changes",+ "selectedMemory.author.user": "You",+ "selectedMemory.author.agent": "Assistant",+ "selectedMemory.sourceUnavailable":+ "Source permissions changed or the original text is unavailable.",+ "selectedMemory.related": "Related memory",+ "selectedMemory.viewMemory": "View memory",+ "selectedMemory.deleteTitle": "Delete this memory?",+ "selectedMemory.deleteDescription":+ "It will no longer be used for new lookups. The source app conversation will not be deleted.",+ "selectedMemory.sentCannotRecall":+ "Content already sent to apps cannot be recalled remotely.",+};++export const currentSpanishMessages: Record<+ keyof typeof currentChineseMessages,+ string+> = {+ "connectionFallback.title": "Conectar otras herramientas",+ "connectionFallback.desktopOnly":+ "El emparejamiento local solo está disponible en la aplicación de escritorio.",+ "connectionFallback.description":+ "Genera una Skill de emparejamiento de un solo uso para un Harness local que no aparece en la lista. Los chats web, contenedores remotos y otros equipos no pueden conectarse directamente a este dispositivo.",+ "connectionFallback.name": "Nombre del Harness",+ "connectionFallback.namePlaceholder": "Por ejemplo, Kimi Code",+ "connectionFallback.generating": "Generando…",+ "connectionFallback.generate": "Generar Skill de emparejamiento",+ "connectionFallback.generateFailed":+ "No se pudo generar la Skill de emparejamiento.",+ "connectionFallback.retry": "Reintentar",+ "connectionFallback.generated":+ "Se generó una Skill de emparejamiento de un solo uso para {name}. Caduca a las {time}.",+ "connectionFallback.skillLabel": "Skill de emparejamiento",+ "connectionFallback.copy": "Copiar Skill",+ "connectionFallback.copied":+ "Skill copiada. Pégala y ejecútala en el Harness correspondiente.",+ "connectionFallback.copyFailed":+ "No se pudo copiar. Selecciona y copia el texto de arriba.",+ "connectionFallback.localDescription":+ "Solo para herramientas MCP o comandos locales. Los chats web no pueden conectarse directamente a este dispositivo.",+ "connectionFallback.loading": "Leyendo la configuración de conexión local…",+ "connectionFallback.loadFailed":+ "No se pudo leer la configuración de conexión.",+ "connectionFallback.format": "Formato del material de conexión",+ "connectionFallback.promptTab": "Instrucciones de conexión",+ "connectionFallback.mcpTab": "Configuración MCP",+ "connectionFallback.commandTab": "Comando",+ "connectionFallback.materialLabel": "Material de conexión local",+ "connectionFallback.materialBoundary":+ "Incluye rutas locales, pero no memorias ni claves. Revísalo antes de pegarlo y mantén MemHub en ejecución.",+ "connectionFallback.materialCopied":+ "Copiado. La conexión todavía no se ha establecido.",+ "connectionFallback.copyPrompt": "Copiar instrucciones",+ "connectionFallback.copyConfig": "Copiar configuración",+ "connectionFallback.copyCommand": "Copiar comando",+ "connectionFallback.promptTemplate":+ "Conecta este Harness local con MemHub mediante la siguiente configuración MCP. No crees un proxy público:\n```json\n{mcp}```\n{shellBlock}\nTras conectar, realiza una consulta real de memoria.\n\nVer una herramienta no equivale a tener autorización. Ante una denegación, no reintentes ni amplíes permisos. No cambies de herramienta, transporte, configuración o alcance para eludir una denegación.\n\nSi MemHub está desconectado o falla, indica que no está disponible, sin afirmar éxito ni inventar citas; si la cobertura es parcial, dilo y conserva la limitación. No presentes una cobertura parcial sin resultados como recuperación exitosa.\n\nSi ambas rutas están vacías, indica únicamente «He completado la consulta de memorias de MemHub». Un resultado vacío no demuestra que se haya buscado en todo el historial.\n\nCita solo fuentes devueltas y realmente usadas, atribuyendo fuente, autor, fecha e identificadores. Recuperar resultados no demuestra que la respuesta los haya utilizado.\n\nEn chino, usa «正在使用 MemHub 查询记忆».",+ "connectionFallback.promptShell":+ "\nSi solo admites shell local, usa este comando:\n```bash\n{shell}```\n",++ "sdk.memory.title": "Biblioteca de memorias del SDK",+ "sdk.memory.status": "Estado de la memoria",+ "sdk.memory.status.active": "Disponible",+ "sdk.memory.status.superseded": "Sustituida",+ "sdk.memory.total": "{count} memorias",+ "sdk.memory.total.one": "{count} memoria",+ "sdk.memory.loadFailed":+ "No se pudo cargar la biblioteca de memorias. Reinténtalo.",+ "sdk.memory.detailLoadFailed":+ "No se pudieron cargar los detalles de la memoria.",+ "sdk.memory.updateFailed": "No se pudo guardar el cambio. Reinténtalo.",+ "sdk.memory.deleteFailed": "No se pudo eliminar la memoria. Reinténtalo.",+ "sdk.memory.loading": "Cargando la biblioteca de memorias…",+ "sdk.memory.pagination": "Páginas de la biblioteca de memorias del SDK",+ "sdk.memory.previous": "Página anterior",+ "sdk.memory.next": "Página siguiente",+ "sdk.memory.detail": "Detalles de la memoria del SDK",+ "sdk.memory.content": "Contenido de la memoria",+ "sdk.memory.save": "Guardar cambios",+ "sdk.memory.delete": "Eliminar memoria",++ "sdk.raw.title": "Conversaciones originales del SDK",+ "sdk.raw.searchLabel": "Buscar conversaciones originales",+ "sdk.raw.searching": "Buscando…",+ "sdk.raw.search": "Buscar",+ "sdk.raw.loadFailed":+ "Las conversaciones originales no están disponibles por ahora.",+ "sdk.raw.searchFailed":+ "No se pudieron buscar las conversaciones originales. Reinténtalo.",+ "sdk.raw.recent": "Conversaciones originales recientes",+ "sdk.raw.found": "{count} resultados",+ "sdk.raw.found.one": "{count} resultado",++ "memoryInspector.emptyHint":+ "Consulta su origen, contenido e historial de cambios.",+ "memory.operationFailed": "Falló la operación de memoria ({code})",+ "memorySpace.tabs.workbench": "Espacio de trabajo",++ "selectedMemory.status.confirmed": "Guardada",+ "selectedMemory.status.deleted": "Eliminada",+ "selectedMemory.status.superseded": "Sustituida",+ "selectedMemory.status.unknown": "Estado pendiente de comprobar",+ "selectedMemory.sourceUnknown": "Origen sin verificar",+ "selectedMemory.discardDraft": "¿Descartar los cambios sin guardar?",+ "selectedMemory.newVersionReadFailed":+ "No se pudo leer la nueva versión. Tu borrador se conserva.",+ "selectedMemory.updateRejected":+ "Los cambios no se enviaron. Tu borrador se conserva; corrige el problema y reintenta.",+ "selectedMemory.updateUnknown":+ "Los cambios no están confirmados. Tu borrador se conserva; actualiza antes de reintentar.",+ "selectedMemory.deleteRejected":+ "La eliminación no se envió. Revisa esta memoria y reintenta.",+ "selectedMemory.deleteUnknown":+ "La eliminación no está confirmada. Revisa la memoria; el alcance no se ampliará.",+ "selectedMemory.undoRejected":+ "No se envió la acción de deshacer. Corrige el problema y reintenta.",+ "selectedMemory.undoUnknown":+ "La acción de deshacer no está confirmada. Revisa la versión actual antes de reintentar.",+ "selectedMemory.author.you": "Tus palabras",+ "selectedMemory.author.assistant": "Palabras originales del asistente",+ "selectedMemory.author.unknown": "Autor sin verificar",+ "selectedMemory.version": "Versión {revision}",+ "selectedMemory.sourceLine": "Origen {source} · {time}",+ "selectedMemory.timestamps":+ "Conversación {conversation} · Guardada {created}",+ "selectedMemory.edit": "Editar",+ "selectedMemory.evidence": "Evidencia original",+ "selectedMemory.evidenceLine": "{author} · Conversación original {time}:",+ "selectedMemory.evidenceUnavailable":+ "Este texto original no está disponible.",+ "selectedMemory.viewOriginal": "Ver texto original",+ "selectedMemory.history": "Historial de versiones",+ "selectedMemory.more": "Más opciones",+ "selectedMemory.undo": "Deshacer último cambio",+ "selectedMemory.delete": "Eliminar memoria",+ "selectedMemory.editTitle": "Editar memoria",+ "selectedMemory.originalTitle": "Conversación original",+ "selectedMemory.back": "Volver a la memoria",+ "selectedMemory.editDescription":+ "Edita esta memoria sin modificar la conversación original.",+ "selectedMemory.content": "Contenido de la memoria",+ "selectedMemory.scopeUnchanged": "El ámbito de uso no cambia",+ "selectedMemory.conflictTitle": "Hay una nueva versión",+ "selectedMemory.conflictDescription":+ "Tu borrador se conserva. Revisa la nueva versión antes de editar.",+ "selectedMemory.viewNewVersion": "Ver nueva versión",+ "selectedMemory.continueFromVersion": "Continuar editando desde esta versión",+ "selectedMemory.cancel": "Cancelar",+ "selectedMemory.save": "Guardar cambios",+ "selectedMemory.author.user": "Tú",+ "selectedMemory.author.agent": "Asistente",+ "selectedMemory.sourceUnavailable":+ "Los permisos del origen cambiaron o el texto no está disponible.",+ "selectedMemory.related": "Memoria correspondiente",+ "selectedMemory.viewMemory": "Ver memoria",+ "selectedMemory.deleteTitle": "¿Eliminar esta memoria?",+ "selectedMemory.deleteDescription":+ "Dejará de usarse en nuevas consultas. La conversación de la aplicación de origen no se eliminará.",+ "selectedMemory.sentCannotRecall":+ "No es posible retirar el contenido ya enviado a las aplicaciones.",+};diff --git a/memhub/packages/i18n/src/gui-i18n-english.ts b/memhub/packages/i18n/src/gui-i18n-english.tsnew file mode 100644index 0000000..b20bf91--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-english.ts@@ -0,0 +1,1941 @@+import { currentEnglishMessages } from "./gui-i18n-current.js";++// English translations integrated from PR #114.+const baseEnglishMessages = {+ "memory:{count} 条": "{count} items",+ "memory:已可用 · {count} 段原文": "Available · {count} original excerpts",+ "memory:主题视角(非事项)": "Topic view (not matters)",+ "memory:来源视角": "Source view",+ "memory:{count} 条记忆 · 当前已加载": "{count} memories · Loaded",+ "memory:最近 {count} 条": "{count} recent conversations",+ "memory:已确认": "Confirmed",+ "memory:记忆库": "Memory library",+ "memory:问记忆": "Ask memories",+ "memory:历史对话": "Conversation history",+ "memory:项目记忆": "Project memory",+ "memory:编码偏好": "Coding preference",+ "memory:长期模式": "Long-term pattern",+ "memory:意图": "Intent",+ "memory:近 3 个月": "Past 3 months",+ "memory:近 6 个月": "Past 6 months",+ "memory:近 1 年": "Past year",+ "memory:全部历史": "All history",+ "memory:{count} 条这次没能整理成功,正在重试": "Processing retry · {count}",+ "memory:{count} 处理中": "Processing: {count}",+ "memory: · 处理中 {running} / 待派发 {active}":+ " · {running} processing / {active} queued",+ "memory: · {count} 条任务状态待核对": " · {count} tasks need status review",+ "memory: · {count} 条任务状态异常,正在恢复":+ " · {count} tasks have status issues; recovering",+ "memory:{count} 等待": "{count} waiting",+ "memory:最新 {count} 条待处理": "Latest {count} pending",+ "memory:历史积压 {count} 条": "{count} in backlog",+ "memory:(约 {count} 分钟)": " (about {count} minutes)",+ "memory:(约 {count} 小时)": " (about {count} hours)",+ "memory:(约 {count} 天)": " (about {count} days)",+ "memory:同步尝试 {count} 次": "{count} sync attempts",+ "memory:尚未尝试同步": "Sync not attempted",+ "memory: · 状态更新于 {date}": " · Updated {date}",+ "memory:HY Memory 当前没有这条记忆,仅重试同步不能补齐。":+ "HY Memory does not contain this memory; retrying sync cannot restore it.",+ "memory:同步需要可用的本机整理模型或本地嵌入授权。":+ "Sync requires an available local processing model or permission to use local embeddings.",+ "memory:这条记忆或模型版本已经变化,先刷新核对再决定下一步。":+ "This memory or model version has changed. Refresh and review it before deciding what to do.",+ "memory:这条记忆已改,搜索索引还没开始同步。":+ "This memory changed, but search index sync has not started.",+ "memory:最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。":+ "The last sync failed. Retry first; if the result is still uncertain, refresh and review it.",+ "memory:这条记忆已改,搜索索引还没跟上。":+ "This memory changed, but the search index has not caught up.",+ "memory:搜索里还是改之前那句话。":+ "Search still shows the text from before the correction.",+ "memory:重试同步": "Retry sync",+ "memory:配置整理模型": "Configure processing model",+ "memory:未提炼 · 在窗口外": "Not extracted · Outside the window",+ "memory:未提炼 · 排队中": "Not extracted · Queued",+ "wb.select": "Select",+ "memory:模型综合": "Model synthesis",+ "memory:原文摘录": "Original excerpt",+ "memory:没有命中": "No match",+ "memory:正在生成": "Generating",+ "memory:正在检索记忆": "Looking up memories",+ "memory: · 基于 {count} 条已确认记忆":+ " · Based on {count} confirmed memories",+ "memory: · 基于 {count} 条已确认记忆.one":+ " · Based on {count} confirmed memory",+ "memory:整理需要处理": "Processing needs attention",+ "memory:正在整理记忆": "Processing memories",+ "memory:整理状态": "Processing status",+ "memory:重新整理": "Process again",+ "memory:自动提炼范围": "Automatic extraction window",+ "memory:手动提炼下一批": "Extract next batch manually",+ "memory:刷新核对": "Refresh and check",+ "memory:正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。":+ "Importing conversation history. Only some memories are visible; the list will fill in automatically after import.",+ "memory:选择:{content}": "Select: {content}",+ "memory:处理失败:{content}": "Failed to process: {content}",+ "memory:已选 {count} 条": "{count} selected",+ "memory:已选 {count} 条.one": "{count} selected",+ "memory:删除所选 {count} 条": "Delete {count} selected",+ "memory:删除所选 {count} 条.one": "Delete {count} selected",+ "memory:重试失败的 {count} 条": "Retry {count} failed items",+ "memory:重试失败的 {count} 条.one": "Retry {count} failed items",+ "memory:没有{status}的记忆。": "No {status} memories.",+ "memory:已{action} {count} 条": "Action completed ({action}): {count} items",+ "memory:已{action} {count} 条.one":+ "Action completed ({action}): {count} item",+ "memory:,{count} 条未完成": ", {count} incomplete",+ "memory:,{count} 条未完成.one": ", {count} incomplete",+ "memory:未能{action}:{error}": "Could not {action}: {error}",+ "memory:重试{action}": "Retry {action}",+ "memory:删除(操作)": "Delete",+ "memory:处理(操作)": "process",+ "memory:{count} 条原话": "{count} original excerpts",+ "memory:{count} 条原话.one": "{count} original excerpts",+ "memory:有 {count} 段对话的整理结果不确定":+ "Processing results for {count} conversations are uncertain",+ "memory:有 {count} 段对话的整理结果不确定.one":+ "Processing results for {count} conversations are uncertain",+ "memory:{count} 次整理已完成": "{count} processing runs completed",+ "memory:{count} 次整理已完成.one": "{count} processing runs completed",+ "memory: · {count} 条在窗口外(原文可搜)":+ " · {count} outside the window (original text searchable)",+ "memory: · {count} 条在窗口外(原文可搜).one":+ " · {count} outside the window (original text searchable)",+ "memory: · 已规划 {planned} 批,当前第 {current} 批":+ " · {planned} batches planned, now on batch {current}",+ "memory:{kind}卡在 {reason}({count} 条)":+ "{kind} blocked by {reason} ({count})",+ "memory:已加载 {count} 条记忆": "Loaded {count} memories",+ "memory:已加载 {count} 条记忆.one": "Loaded {count} memories",+ "memory:回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。":+ "Answers use only confirmed memories. Each answer links back to the memory and original text.",+ "memory:选择一条记忆": "Select a memory",+ "memory:查看它的来源、使用范围和修改历史。":+ "See its sources, access scope and change history.",+ "memory:查看替代它的记忆": "View the memory that replaced it",+ "memory:查看它取代的旧记忆": "View the memory it replaced",+ "memory:保存纠正": "Save correction",+ "memory:修改历史": "Change history",+ "memory:已可用": "Available",+ "memory:处理中…": "Processing…",+ "memory:搜索": "Search",+ "memory:记忆治理状态": "Memory status",+ "memory:记忆空间模式": "Memory space modes",+ "memory:来源状态待核对,记忆库暂不可读取。":+ "Source status needs review; the memory library cannot be read yet.",+ "memory:记忆库读取失败,请重试。":+ "Could not load the memory library. Please retry.",+ "memory:重新读取记忆库": "Reload memory library",+ "memory:正在读取记忆库…": "Loading memory library…",+ "memory:批量操作结果": "Bulk action result",+ "memory:批量操作": "Bulk actions",+ "memory:取消选择": "Clear selection",+ "memory:向已确认记忆提问": "Ask confirmed memories",+ "memory:搜索记忆库": "Search memory library",+ "memory:问答记忆范围": "Memory question scope",+ "memory:只问个人画像": "Ask about personal profile only",+ "memory:问全部记忆(含项目)": "Ask all memories (including projects)",+ "memory:例如:我对真实数据有什么要求?":+ "For example: what are my requirements for real data?",+ "memory:搜索偏好、决定或经历": "Search preferences, decisions or experiences",+ "memory:根据记忆回答": "Answer from memories",+ "memory:清除搜索": "Clear search",+ "wb.finding.duplicate": "From the same original message",+ "wb.finding.duplicateText":+ "“{first}” and “{second}” came from the same original message and were assigned to {firstScope} and {secondScope}. Check whether they refer to the same thing.",+ "wb.finding.dormant": "Not updated recently",+ "wb.finding.dormantText":+ "{count} memories have not been changed or mentioned in two months. They may need review.",+ "wb.finding.blocked": "Waiting on a requirement",+ "wb.finding.blockedText":+ "{count} conversations are queued pending a requirement. Their original text is already saved and searchable.",+ "wb.finding.blockedText.one":+ "{count} conversations are queued pending a requirement. Their original text is already saved and searchable.",+ "wb.unclassified": "Uncategorized",+ "wb.profile": "Personal profile",+ "wb.project": "Project {id}",+ "wb.topics": "Topic",+ "wb.all": "All",+ "wb.topicCount": "{count} topics formed",+ "wb.topicCount.one": "{count} topics formed",+ "wb.singletons": "; {count} other tags appear only once",+ "wb.singletons.one": "; {count} other tag appears only once",+ "wb.memories": "{count} memories",+ "wb.memories.one": "{count} memories",+ "wb.sources": "{count} sources",+ "wb.sources.one": "{count} source",+ "wb.once":+ "This topic only appears here. It may be a one-off, or the same topic may have been split under different names.",+ "wb.graphTitle": "{label} relationship graph",+ "wb.readSummary": "Read a summary of this matter",+ "wb.summaryPrompt":+ "Explain “{label}” clearly: where things stand, what has been decided, and what remains open.",+ "wb.building": "Synthesizing…",+ "wb.build": "Build relationships with HY Memory",+ "wb.drawn": "Showing {shown} / {total} memories",+ "wb.askLabel": "Ask about this matter",+ "wb.askPlaceholder":+ "Ask about this matter; answers use only confirmed memories",+ "wb.ask": "Ask",+ "wb.originals": "Original conversations",+ "wb.evidenceNote":+ "This memory comes from {count} original excerpts below, ordered by time",+ "wb.evidenceNote.one":+ "This memory comes from {count} original excerpts below, ordered by time",+ "wb.pickCircle": "Select a circle on the graph to see its original text here",+ "wb.unavailable": "Source original text is unavailable",+ "wb.fullConversation": "View full conversation",+ "wb.you": "You",+ "wb.assistant": "Assistant",+ "wb.noMemories":+ "No memories yet. Search imported original conversations in Conversation history.",+ "wb.waiting":+ "Some conversations are queued pending a requirement. Their original text is saved and searchable.",+ "wb.conditions": "See what is missing",+ "wb.findings": "What your records reveal",+ "wb.findingsNote":+ "Computed from local records. Select one to highlight its supporting memories on the graph.",+ "wb.showGraph": "View on graph",+ "wb.loading": "Loading memories…",+ "wb.coreStarting":+ "It will appear automatically after local Core starts; no refresh needed.",+ "wb.nothingToConnect": "There is nothing to connect yet.",+ "wb.skeletonNote":+ "Authorize a source to see the source and topic structure; memories will appear as they are created.",+ "wb.authorize": "Authorize a source",+ "wb.conversations": "{count} conversations",+ "wb.conversations.one": "{count} conversation",+ "wb.chipChanges": "What has changed recently here?",+ "wb.chipSummarize": "Summarize these in a few points",+ "wb.unknownTime": "Time unknown",+ "wb.unknownSource": "Unknown source",+ "wb.transcriptGone": "This conversation is no longer in the library.",+ "wb.edgeCount": "{label}: {count} connections",+ "wb.edgeCount.one": "{label}: {count} connection",+ "wb.noRelations":+ "HY Memory has not found relationships yet. Use the button above to run System 2.",+ "wb.noModelRelations":+ "No usable model is configured; HY Memory relationships are unavailable.",+ "provenance.multiple": "Multiple authors",+ "provenance.person": "Original user message",+ "provenance.agent": "Original agent message",+ "provenance.unknown": "Unknown author",+ "provenance.imported": "Imported memory · {author}",+ "provenance.manual": "Added manually",+ "provenance.answered": "Created from an answer",+ "provenance.generated": "Created from an AI reply",+ "provenance.conversation": "Created from original conversations",+ "arrival.region": "Memory processing status",+ "arrival.importing": "Originals are still importing",+ "arrival.messages": "{count} messages saved",+ "arrival.messages.one": "{count} messages saved",+ "arrival.conversations": "{count} conversations",+ "arrival.conversations.one": "{count} conversation",+ "arrival.details": "View progress and details",+ "arrival.backlog":+ "Large amount of existing data; processing in batches in the background for quality",+ "arrival.items": "{count} items",+ "arrival.items.one": "{count} item",+ "arrival.configure": "Configure memory processing",+ "arrival.status": "View processing status",+ "arrival.history": "View saved conversations",+ "arrival.connect": "Connect an app",+ "arrival.retained": "Saved originals remain on this device.",+ "arrival.description.model-required":+ "Review the processing model before continuing.",+ "arrival.description.processing":+ "Processing recent conversations first; more memories will appear gradually",+ "arrival.description.importing":+ "Saving originals; import progress does not reflect memory creation progress.",+ "arrival.description.failed":+ "Check why it failed before deciding whether to retry.",+ "arrival.description.unavailable":+ "The last confirmed information is retained; check current progress again.",+ "arrival.description.refreshing":+ "Checking local records; unconfirmed progress is not counted.",+ "arrival.description.checking":+ "Saved content is retained; progress needs updating.",+ "arrival.description.stopped":+ "Processing has stopped; review its status before continuing.",+ "arrival.description.idle": "No processing task is running now.",+ "arrival.description.empty":+ "Connect an app or import a conversation file; originals will be saved on this device first.",+ "arrival.title.refreshing": "Saved content is retained; checking progress",+ "arrival.title.checking": "Progress needs updating",+ "arrival.title.importing": "Importing conversations",+ "arrival.title.processing": "Creating memories",+ "arrival.title.continue": "Needs attention",+ "arrival.title.model": "Processing model not configured",+ "arrival.title.empty": "No conversations saved yet",+ "handoff.region": "Take memories to another app",+ "handoff.answer": "Take answer and references to another app",+ "handoff.selected": "Take selected memories to another app",+ "handoff.title": "Take to another app",+ "handoff.closeTitle": "Close preview",+ "handoff.close": "Close handoff preview",+ "handoff.stats": "{count} memories · {characters} characters · Not truncated",+ "handoff.stats.one":+ "{count} memory · {characters} characters · Not truncated",+ "handoff.content": "Full content to take to another app",+ "handoff.target": "Destination app",+ "handoff.other": "Other app · Copy only",+ "handoff.copyOnly": " · Copy only",+ "handoff.boundary":+ "Only the content above is included, not the original conversations. Copying does not authorize a connection; copies in other apps cannot be recalled.",+ "handoff.copy": "Copy content",+ "handoff.open": "Copy and open {host}",+ "handoff.copyFailed":+ "Copy failed; no app was opened. Select and copy the text in the preview instead.",+ "handoff.opened":+ "Copied and requested to open {host}. Nothing was sent; check the destination input.",+ "handoff.notPrefilled":+ "Copied in full. {host} could not be prefilled; paste it in the destination app. Nothing was sent.",+ "handoff.openFailed":+ "Copied in full, but could not open {host}. Nothing was sent.",+ "handoff.copied": "{target} copied in full. Nothing was sent.",+ "handoff.pasteTarget": ", ready to paste into {host}",+ "wb.memory": "This memory",+ "wb.node": "This node",+ "wb.matter": "This matter",+ "wb.available": "Available",+ "wb.superseded": "Superseded",+ "wb.deleted": "Deleted",+ "wb.revision": "Version {revision}",+ "wb.collapse": "Collapse",+ "wb.oldSearch": "Search still shows the text from before the correction.",+ "wb.missingIndex":+ "HY Memory does not contain this memory; retrying cannot restore it.",+ "wb.retrySync": "Retry sync",+ "wb.correctForm": "Correct memory content",+ "wb.content": "Memory content",+ "wb.correct": "Correct",+ "wb.saveCorrection": "Save correction",+ "wb.cancelEdit": "Cancel editing",+ "wb.undo": "Undo last change",+ "wb.delete": "Delete",+ "wb.nodeNote":+ "This is not a memory; memories connect to it. {direct} direct links; {indirect} reachable in two hops.",+ "wb.direct": "Direct",+ "wb.twoHops": "Two hops",+ "wb.idle":+ "Circles represent memories; lines show those mentioned in the same conversation. Select one to see its origins and edit it. Choosing another matter on the left updates the graph.",+ "wb.searching": "Searching memories…",+ "wb.generated": "Model synthesis",+ "wb.extractive": "Original excerpt",+ "wb.noHit": "No match",+ "wb.answerSource": "{mode} · Based on {count} confirmed memories",+ "wb.answerSource.one": "{mode} · Based on {count} confirmed memories",+ "wb.recalled": "{count} memories retrieved",+ "wb.recalled.one": "{count} memories retrieved",+ "wb.saveMemory": "Save as memory",+ "wb.tooLong":+ "This answer exceeds the current save limit and cannot be saved as a memory.",+ "wb.summary":+ "This is a summary, not a memory. It is rebuilt each time so it stays consistent with the memories below.",+ "wb.thisAnswer": "This answer",+ "wb.type.source": "Source app",+ "wb.type.topic": "Topic",+ "wb.type.schema": "HY synthesis",+ "wb.type.memory": "Memories",+ "wb.origin.hy_relation": "HY Memory synthesis",+ "wb.origin.same_conversation": "Same conversation",+ "wb.origin.shared_tag": "Same topic",+ "wb.origin.provenance": "Original-text source",+ "wb.relation.evidence_source": "From",+ "wb.relation.same_conversation": "Same conversation",+ "wb.relation.shared_tag": "Same topic",+ "wb.relation.derived_from": "Synthesized from",+ "wb.relation.tagged_with": "Tagged with",+ "wb.relation.related_to": "Related",+ guideEyebrow: "Try it out",+ guideTitle: "Pick up where your last conversation left off",+ guideBack: "Back to memory",+ guideChooseScene: "Choose a scenario",+ guideSame: "Continue in a new conversation",+ guideSameDescription:+ "Find earlier decisions in a new conversation with the same app.",+ guideSwitch: "Continue in another app",+ guideSwitchDescription:+ "Same work, different AI. Bring over the relevant context first.",+ guideNew: "Help a new tool understand me",+ guideNewDescription:+ "Start with one detail you choose to share instead of introducing yourself again.",+ guideReadError: "Could not read memories right now. Try again later.",+ guideDetailError:+ "This memory cannot be read right now. Choose another or refresh.",+ guideChanged:+ "The memory or its permissions changed. Refresh and review it again.",+ guideConnectionChanged:+ "Connection status changed; nothing was copied. Choose a method again.",+ guideCopiedOpened:+ "Copied and requested to open {host}. Nothing was sent; check the input field.",+ guideCopiedNotFilled:+ "Copied in full, but could not prefill. Paste it in the destination app; nothing was sent.",+ guideCopiedNotOpened:+ "Copied in full, but could not open the destination app. Nothing was sent.",+ guideCopied: "Copied in full. Nothing was sent or granted new read access.",+ guideValidationError:+ "Could not verify the current memory or permissions. The old preview was hidden; refresh and retry.",+ guideCopyError:+ "Could not verify the latest content or finish copying. Retry; the destination app was not opened.",+ guideManual: "Added in the app",+ guideOriginalApp: "Source app",+ guideListSeparator: ", ",+ guideSaved: "{count} original messages saved on this device · ",+ "guideSaved.one": "{count} original messages saved on this device · ",+ guideReadingMemories: "Loading processed memories",+ guideLoaded: "{count} usable memories loaded on this page",+ "guideLoaded.one": "{count} usable memories loaded on this page",+ guideSeparate: ". These stages are counted separately.",+ guideChooseBackground: "Choose context",+ guideCheckSources: "Review sources",+ guideTry: "Try in a new conversation",+ guideLoading: "Loading existing memories on this device…",+ guideEmptyTitle: "Add one useful piece of context first",+ guideEmptyDescription:+ "No memories are available for this trial. Imported originals are not processed memories, and suggestions are not shared automatically.",+ guideAdd: "Add a memory",+ guideConnections: "View imports and connections",+ guideRefresh: "Refresh",+ guideBackgroundTitle: "Context for this trial",+ guideRefreshExample: "Refresh example",+ guideChooseMemory: "Select a memory",+ guideLoadedScope:+ "Choose from {count} usable memories loaded here; this is not your entire history.",+ "guideLoadedScope.one":+ "Choose from {count} usable memories loaded here; this is not your entire history.",+ guideCheckingEvidence: "Checking original evidence…",+ guideRevision:+ "{source} · Version {revision} · System-generated, needs your review",+ guideScope: "Scope: ",+ guideAllApps: "Available across apps; not necessarily a personal preference",+ guidePrivate:+ "External recall is off; sharing manually requires a separate decision",+ guideLimited: "Limited scope; external recall has not been expanded",+ guideEvidence: "Original evidence · {count} excerpts",+ "guideEvidence.one": "Original evidence · {count} excerpts",+ guideUnknownSource: "Unknown source",+ guideYou: "You",+ guideUnknownAuthor: "Author unknown",+ guideUnknownTime: "Time unknown",+ guideUnavailable:+ "The original text or current permission is unavailable. Choose another memory or refresh; this content will not be shared.",+ guideDraftTitle: "Opening for the next conversation",+ guideChooseApp: "Choose an app to try",+ guideCopyOnly: "Choose an app yourself · Copy only",+ guideHostsError:+ "Could not read connection status. Retry or copy the context only.",+ guideNoApp:+ "No connected app selected. Sharing manually does not install a connection.",+ guideWired: "Last self-check succeeded; verify it works for this use.",+ guideInstalled: "Connection installed; read access has not been verified.",+ guideNotInstalled: "Read connection not installed.",+ guideManage: "Manage app connections",+ guideChooseRoute: "Choose how to bring context in",+ guideContext: "Bring in context",+ guideQuery: "Let the app search",+ guideTopic: "Topic to continue",+ guideQueryHint:+ "Only send a query; do not place the expected answer above into the new conversation.",+ guideNewHint:+ "Only share the memory you chose; no personal profile is created automatically.",+ guideContextHint:+ "Include this context and its citations; this is not an automatic recall test.",+ guidePreview: "Full opening preview",+ guidePreviewPlaceholder:+ "The opening will appear when original evidence is available",+ guideChecking: "Checking…",+ guideCopy: "Copy opening",+ guideCopyOpen: "Copy and open {host}",+ guideNoReceipt:+ "No receipt from an external call this time. Did the new conversation cite the right context?",+ guideVerified: "I reviewed the result",+ guideMissing: "Could not find it",+ guideFeedbackOk:+ "Your feedback: reviewed. This is not an automated verification record.",+ guideFeedbackMissing:+ "Your feedback: not found. Check source imports, memory scope and app connections first.",+ guideInvitation: "Invitation to try it out",+ guideInvitationHint:+ "Try continuing a new conversation with one of your own memories.",+ guideTryOnce: "Try it",+ guideLater: "Maybe later",+ guideDismiss: "Dismiss invitation",+ healthTitle: "Health diagnostics",+ healthLocal: "Local service",+ healthBackground: "Background service",+ healthSources: "Totals by source",+ healthProcessing: "Memory processing",+ healthHosts: "AI connections",+ healthDetailed: "Detailed logging",+ healthDetailedTitle: "Detailed logging (for troubleshooting)",+ healthDetailedHint:+ "Off by default. Turn this on only when support asks you to troubleshoot.",+ healthDetailedError: "Could not change detailed logging. Please retry.",+ healthRefresh: "Refresh status",+ healthIncident: "Mark issue time",+ healthIncidentDesktop: "Mark the issue time in the desktop app.",+ healthIncidentPrompt: "Briefly describe the issue (optional)",+ healthIncidentCopied: "Issue ID copied: {id}",+ healthIncidentError: "Could not mark the issue time. Please retry.",+ healthReadFailed: "Temporarily unavailable",+ healthStale: " · Data is outdated; showing the last result.",+ healthReading: "Reading status…",+ healthRereading: "Refreshing; showing the last successful reading…",+ healthReadSuccessTime: "Last successful reading",+ healthReadFailedTime: "Read failed at",+ healthReadingSources: "Reading local service and source status…",+ healthPrevious: "Last read",+ healthPreviousPrefix: "Last read: ",+ healthRunning: "Running",+ healthCoreVersion: "{state} · Version {version} · Instance {instance}",+ healthCoreDisconnected: "Local Core is not connected yet.",+ healthBackgroundUnavailable:+ "Cannot check the background service here. Use a supported desktop app.",+ healthRuntime: "Core: {core} · Host bridge: {broker}",+ healthSourceCount: "{conversations} conversations · {messages} messages",+ healthNoSources: "No connected sources yet.",+ healthTaskCounts:+ "{running} processing · {pending} queued · {completed} completed · {failed} failed",+ healthImportDetails: "Import and processing details",+ healthRawTurns: "Original text and complete turns",+ healthRawCounts: "{raw} originals · {turns} complete turns",+ healthHy: "HY processing",+ healthHyCounts:+ "{calls} calls · {completed} completed · {unknown} uncertain · {failed} failed · {cancelled} cancelled",+ healthOutput: "Output",+ healthMemories: "{count} memories",+ "healthMemories.one": "{count} memories",+ healthWorkbuddy: "WorkBuddy memory lookups",+ healthWorkbuddyCounts:+ "{injected} injections · {timedOut} timeouts · {unavailable} unavailable",+ healthBlocked: "{kind} blocked by {reason} ({count})",+ healthRetrying: "Processing retry · {count}",+ "healthRetrying.one": "Processing retry · {count}",+ healthNoIssues: "No issues need attention.",+ healthHostsUnavailable:+ "Cannot read this in a browser; check the desktop app.",+ healthNoHosts: "No supported AI tools detected on this device.",+ healthBackgroundHealthy: "Background service available",+ healthBackgroundStopped: "Background service stopped",+ healthBackgroundDegraded: "Background service partially unavailable",+ healthBackgroundUntrusted:+ "Background service identity could not be verified",+ healthBackgroundUnknown: "Background status not confirmed",+ healthStopped: "Stopped",+ healthUnhealthy: "Cannot connect",+ healthUntrusted: "Identity not verified",+ healthUnknown: "Not confirmed",+ healthNotChecked: "Not checked",+ healthWired: "Connected",+ healthBlind: "Installed, but cannot retrieve memories",+ healthUnreachable: "Not connected",+ startupReadError: "Could not read startup status. Please retry.",+ startupRetry: "Retry",+ startupOpening: "Opening MemHub…",+ nativeHelp: "Help",+ nativeExportLogs: "Export logs for support",+ nativeExportError: "Could not export logs. Please retry later.",+ nativeLogin: "Launch {product} at login",+ nativeTrialUnavailable: " (unavailable in this build)",+ nativeCliManaged: " (managed by CLI)",+ nativeStatusUnavailable: " (status unavailable)",+ nativeDevelopmentUnavailable: " (unavailable in development)",+ nativeOpen: "Open {product}",+ nativeQuit: "Quit {product} (background service keeps running)",+ nativeLoginError: "Could not change the login startup setting. Please retry.",+ nativeMoveTitle: "Move MemHub to Applications first",+ nativeMoveDetail:+ "Reopen MemHub from Applications to connect other apps and install the command-line tool.",+ nativeAcknowledge: "OK",+ graphWidthTitle: "Existing memory library does not match the built-in model",+ graphWidthDescription:+ "Your memory library uses {stored} dimensions, but the built-in model produces {expected}. They cannot work together; extraction will keep failing until you choose an option.",+ graphWidthKeep:+ "Keep existing library (default): Continue using the previous embedding configuration; all {count} memories and the graph stay unchanged",+ graphWidthRebuild:+ "Use the built-in model: Archive (do not delete) the existing graph; relationships for {count} memories will need rebuilding",+ graphWidthExport:+ "Export first, then decide: Leave everything unchanged for now and choose again after exporting",+ graphWidthExported:+ "Exported to {path}. The existing library was unchanged; you can choose again.",+ graphWidthUnknown:+ "The dimension choice is unconfirmed. The existing memory library was unchanged; please retry.",+ graphWidthConfirm: "Confirm choice",+ importUserProgress:+ "Importing your conversation history. {count} conversations imported. Memories will appear gradually; you can keep using the app.",+ "importUserProgress.one":+ "Importing your conversation history. {count} conversations imported. Memories will appear gradually; you can keep using the app.",+ importUserModel:+ "The model is not configured yet. New conversations will not be processed into memories for now.",+ importUserIncomplete: "Some content was not fully processed. Check Settings.",+ importUserSettings: "Go to Settings",+ diagnosticExportDesktop: "Export diagnostics from the desktop app.",+ diagnosticExported: "Logs exported: {filename}",+ diagnosticFile: "diagnostics file",+ diagnosticExportFailed: "Could not export diagnostics. Please retry.",+ debugTitle: "Debug logs",+ debugCount: "{count} logs from this session",+ "debugCount.one": "{count} logs from this session",+ debugDiagnostics: "Diagnostics",+ debugUsageSubtitle: "Memory processing model usage",+ debugTabs: "Diagnostics tabs",+ debugLogsTab: "Logs",+ debugUsageTab: "Model usage",+ debugFullscreen: "Fullscreen",+ debugExitFullscreen: "Exit fullscreen",+ debugFullscreenLabel: "Show logs fullscreen",+ debugExitFullscreenLabel: "Exit fullscreen logs",+ usageRange15m: "Last 15 minutes",+ usageRange1h: "Last hour",+ usageRange6h: "Last 6 hours",+ usageRange24h: "Last 24 hours",+ usageRange7d: "Last 7 days",+ usageRange: "Time range",+ usageRangeLabel: "Model usage time range",+ usageLoading: "Loading…",+ usageReadError: "Could not load",+ usageLive: "Refresh every 5 seconds",+ usageTotalTokens: "Total tokens",+ usageRequests: "Requests",+ usageChartRegion: "Tokens per minute by prompt",+ usageChartTitle: "Token usage by prompt",+ usageChartSubtitle: "Per minute · Total tokens",+ usageBreakdown: "Prompt details",+ usageCurrentRange: "Current time range",+ usageRequestCount: "{count} requests",+ "usageRequestCount.one": "{count} requests",+ usageEmpty: "No memory processing model calls in this time range",+ usageNoChart: "No chart data yet",+ usageChartAria: "Token usage per minute by prompt",+ debugPause: "Pause live refresh",+ debugResume: "Resume live refresh",+ debugRefresh: "Refresh now",+ debugClose: "Close Debug logs",+ debugSearchPlaceholder: "Search events, components, error codes or content",+ debugSearch: "Search logs",+ debugSource: "Log source",+ debugAllSources: "All sources",+ debugCapture: "Capture level",+ debugDisplay: "Display level",+ debugAll: "All",+ debugMatches: "{count} matches",+ "debugMatches.one": "{count} matches",+ debugLive: "Refreshing live",+ debugPaused: "Paused",+ debugTruncated: "Too many logs; truncated",+ debugReadError: "Could not load",+ debugLoading: "Loading logs…",+ debugEmpty: "No matching logs",+ debugOpened: "Debug logs are open",+ debugOpen: "Open Debug logs",+ "这里需要 API Key,不是网址。请填写服务方提供的密钥。":+ "Enter the API key provided by the service, not a URL.",+ "服务商拒绝了这个 API Key(401)。请确认密钥属于当前填写的服务地址。":+ "The provider rejected this API key (401). Make sure the key belongs to the endpoint entered.",+ "服务商没有这个模型名,请对照服务商的模型列表核对。":+ "The provider does not recognize this model name. Check the provider's model list.",+ "连不上接口地址,请检查网络和服务地址是否正确。":+ "Could not connect to the endpoint. Check the network and service address.",+ 未提供接口地址: "No endpoint provided",+ "请填写生成模型名。": "Enter the generation model name.",+ "请填写完整的 http:// 或 https:// 接口地址。":+ "Enter a complete http:// or https:// endpoint URL.",+ "请填写向量模型名。": "Enter the embedding model name.",+ "请填写完整的向量模型接口地址。":+ "Enter the complete embedding model endpoint URL.",+ "这份配置在测试期间被改过,刚才测的是改动后的版本。配置已保存但未启用,请重新测试并启用。":+ "This configuration changed during testing; the newer version was tested. It was saved but not enabled. Test and enable it again.",+ "测试结果来自这份配置更早的版本。配置已保存但未启用,请重新测试并启用。":+ "The test result belongs to an earlier version of this configuration. It was saved but not enabled. Test and enable it again.",+ "配置已保存,连接测试未通过。请核对配置后重试,历史对话尚未发送。":+ "Configuration saved, but the connection test failed. Review it and retry. Conversation history was not sent.",+ "配置已保存,尚未确认启用成功。请核对配置后重试。":+ "Configuration saved, but enabling is unconfirmed. Review it and retry.",+ "配置尚未完成测试和启用,请核对后重试。":+ "Testing and enabling are incomplete. Review the configuration and retry.",+ "配置尚未保存成功,已填写内容保留,可核对后重试。":+ "Could not confirm saving the configuration. Your entries are retained; review and retry.",+ "只需配置生成模型。向量嵌入已内置在本机,不为 System 1、System 2 分开选模型。":+ "Only the generation model needs configuring. Vector embeddings are built in locally; System 1 and System 2 do not need separate models.",+ "无法读取测试恢复记录,暂不发送新的测试。":+ "Could not read the test recovery record; no new test will be sent.",+ "上次模型测试结果待核对,暂不修改或启用配置。":+ "The previous model test needs review; configuration will not be edited or enabled yet.",+ 核对测试结果: "Review test result",+ "上次模型创建结果待核对,暂不开始新的操作。":+ "The previous model creation needs review; no new operation will start yet.",+ 核对创建结果: "Review creation result",+ "配置已保存,正在测试连接…": "Configuration saved; testing connection…",+ "连接通过,正在启用模型…": "Connection passed; enabling model…",+ 刷新配置列表: "Refresh configurations",+ 自定义一个模型: "Configure a custom model",+ 已保存的模型配置: "Saved model configuration",+ "已保存,已启用": "Saved and enabled",+ "已保存,连接通过": "Saved; connection passed",+ "已保存,测试未通过": "Saved; test failed",+ "已保存,待测试": "Saved; awaiting test",+ 版本: "Version",+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。":+ "Allow MemHub to access Keychain. Choose ‘Always Allow’ when prompted; saved configurations will not be lost.",+ "测试只向此接口发送测试内容,不发送历史对话。":+ "Tests send only test content to this endpoint, not conversation history.",+ 重试测试并启用: "Retry test and enable",+ 测试并启用: "Test and enable",+ 编辑配置: "Edit configuration",+ 新增配置: "Add configuration",+ 编辑: "Edit",+ "。修改后需重新测试并设为当前模型,内容授权不会自动更新。":+ ". After making changes, test again and set it as the current model. Content permissions will not update automatically.",+ "配置已在其他位置变化,草稿已保留。请取消编辑后重新打开核对。":+ "Configuration changed elsewhere; your draft is retained. Cancel editing and reopen to review.",+ 服务商预设: "Provider preset",+ 自定义兼容服务: "Custom compatible service",+ "只是帮你填好接口地址和一个模型名,不代表这个模型当前可用。 请对照服务商的模型列表核对后再保存。":+ "This fills in an endpoint and model name, but does not guarantee availability. Check the provider's model list before saving.",+ 协议: "Protocol",+ "与模型服务提供的接口协议保持一致。":+ "Match the protocol provided by the model service.",+ 配置名称: "Configuration name",+ "用于区分配置,不影响模型请求。":+ "Identifies the configuration; does not affect model requests.",+ 生成模型名: "Generation model name",+ "例如:gpt-4o-mini…": "For example: gpt-4o-mini…",+ "填写服务方提供的完整模型标识。":+ "Enter the full model ID provided by the service.",+ "高级:自行配置向量模型": "Advanced: configure your own embedding model",+ 向量配置模式: "Embedding configuration mode",+ 本地内置: "Built-in local model",+ 自定义向量模型: "Custom embedding model",+ 向量模型名: "Embedding model name",+ "例如:text-embedding-3-small…": "For example: text-embedding-3-small…",+ 向量模型来源: "Embedding model provider",+ "本机 Ollama": "Local Ollama",+ "同源 OpenAI-compatible(共用 API Key)":+ "Same-origin OpenAI-compatible (shared API key)",+ "向量模型 Base URL": "Embedding model Base URL",+ "为避免凭据外泄,向量地址必须与生成模型同源。":+ "To protect credentials, the embedding endpoint must share the generation model's origin.",+ "使用内置本地向量模型;不会发送内容给远程向量服务。":+ "Uses the built-in local embedding model; no content is sent to a remote embedding service.",+ 自定义向量: "Custom embedding",+ 尚未填写模型: "No model entered",+ 尚未填写地址: "No address entered",+ "填写服务接口地址,不是聊天网页地址。":+ "Enter the API endpoint, not the chat website URL.",+ "(可选)": " (optional)",+ "保存后不会再次显示…": "Will not be shown again after saving…",+ "留空保留已保存密钥;填写新密钥后需重新测试和启用。":+ "Leave blank to keep the saved key; test and enable again after entering a new key.",+ "换了服务商后需要填写新的 API Key,已保存的密钥不会带到新地址。":+ "Enter a new API key after changing providers; the saved key is not sent to the new endpoint.",+ "保存在系统安全存储中,不随安装包分发。":+ "Stored in the system's secure storage; not distributed with the app.",+ "关闭思考链(向支持的厂商下发 thinking-off 参数)":+ "Disable chain of thought (send thinking-off to supported providers)",+ 保存修改: "Save changes",+ 保存配置: "Save configuration",+ "正在启用配置…": "Enabling configuration…",+ 测试并完成配置: "Test and complete setup",+ 保存并测试启用: "Save, test and enable",+ 取消编辑: "Cancel editing",+ "密钥保存在系统安全存储;测试仅发送测试内容。":+ "The key is stored securely; tests send only test content.",+ 当前使用: "In use",+ 未启用: "Not enabled",+ 测试目标: "Test target",+ "。仅发送测试内容,不发送历史对话。":+ ". Only test content is sent, not conversation history.",+ 测试连接: "Test connection",+ 设为当前模型: "Set as current model",+ 删除: "Delete",+ "粘贴 API Key": "Paste API Key",+ "密钥尚未保存成功,已填写内容保留,可重试。":+ "Could not save the key. Your input is retained; you can retry.",+ 生成接收方: "Generation recipient",+ 向量接收方: "Embedding recipient",+ 本机: "On this device",+ "。启用此配置后按上方选择处理历史及未来允许来源。":+ ". After enabling this configuration, the selections above determine which past and future authorized sources are processed.",+ "保存 key": "Save key",+ "还没有 key?去申请": "No key yet? Apply for one",+ 删除这张卡: "Remove this card",+ "密钥已配置,当前读取状态待确认。":+ "Key configured; access status needs confirmation.",+ "等待 key:其余都已经填好了,贴上 key 就能用。":+ "Waiting for a key. The other settings are ready; paste your key to continue.",+ "key 已保存,还没测过这个模型能不能用。":+ "Key saved; this model has not been tested yet.",+ "Ollama(本机)": "Ollama (local)",+ "内置 bge-small-zh-v1.5": "Built-in bge-small-zh-v1.5",+ 通过: "Passed",+ "HY 托管模型尚不可用": "HY hosted model unavailable",+ "缺少 API Key": "API Key missing",+ 服务不可达: "Service unreachable",+ "认证失败;更新 key 后再检测,会自动接着处理":+ "Authentication failed; update the key and test again to resume processing.",+ 请求频率受限: "Rate limited",+ "模型账户余额不足;充值或换 key 后再检测,会自动接着处理":+ "Model account balance is insufficient; top up or change the key and test again to resume.",+ 没有找到模型: "Model not found",+ "该网关不提供模型列表,已改由生成调用验证":+ "The gateway has no model list; verified through a generation request instead.",+ 服务返回不符合协议: "Service response does not match the protocol",+ 结构化输出未通过: "Structured output test failed",+ "需要填写 Embedding 模型": "Enter an embedding model",+ "Embedding 模型不可用": "Embedding model unavailable",+ "请先核对上次模型测试结果,暂不修改或启用配置。":+ "Review the previous model test first; configuration will not be changed or enabled yet.",+ "本地恢复记录已变化,仍保持锁定。请重新打开后核对。":+ "The local recovery record has changed. Configuration remains locked; reopen and review it.",+ 测试结果: "Test results",+ "暂不支持一键插入:它没有 MCP 通道,无法发放可撤销的记忆凭证。":+ "One-click connection is unavailable: this app has no MCP channel for a revocable memory credential.",+ 应用控制通道暂不可用: "The app control channel is unavailable",+ appFailureReason: " Reason: {reason}. ",+ appFailureReread:+ "The connection status could not be reloaded either; the displayed state may be outdated.",+ 模型: "Model",+ 连接其他应用: "Connect other apps",+ 帮助与诊断: "Help and diagnostics",+ 设置分组: "Settings sections",+ 记忆模型: "Memory model",+ 当前模型: "Current model",+ "正在读取模型…": "Loading model…",+ 模型状态暂不可读: "Model status is unavailable",+ 尚未配置模型: "No model configured",+ 修改模型: "Edit model",+ 配置模型: "Configure model",+ 刷新模型状态: "Refresh model status",+ "本机 / 受管端点": "Local / managed endpoint",+ 接口地址待核对: "Endpoint needs review",+ "模型状态未能读取,请重试。":+ "Could not read the model status. Please retry.",+ "模型状态刷新未成功,仍显示上次确认的模型状态;请重试。":+ "Could not refresh the model status. Showing the last confirmed state; please retry.",+ "上次模型测试或创建还待核对,配置暂时不能改动。请先在下方模型配置区核对结果; 现有配置和原文不会被改动。":+ "A previous model test or creation needs review. Check the result below before editing. Your configuration and original text are unchanged.",+ 用模型沉淀记忆: "Create memories with a model",+ "开启后,导入和同步到本机的会话会交给当前模型整理成记忆,会产生模型调用。 停止后不再调用模型、不再整理记忆,但会话仍会照常导入和保存;已排队的内容会留着,重新开启后继续。 模型配置始终保留,重新开启不需要重新填写。":+ "When on, imported and synced conversations are processed into memories by the current model, using model calls. When off, conversations are still imported and saved; queued work resumes when you turn it on again. Your model configuration stays in place.",+ "启用未能确认,仍显示上次确认的状态;请重试。":+ "Could not confirm enabling. Showing the last confirmed state; please retry.",+ "停止未能确认,模型可能仍在整理记忆,请重试。":+ "Could not confirm stopping. The model may still be processing memories; please retry.",+ "当前安装还不能读取这个开关,请确认后台服务已启动后重试。":+ "This installation cannot read the switch. Check that the background service is running and retry.",+ 关于: "About",+ "此应用还没有读取授权,请先授权它的对话目录。":+ "This app has no read permission yet. Authorize its conversation directory first.",+ "此应用的读取授权已撤销,请重新授权。":+ "This app's read permission was revoked. Authorize it again.",+ "此应用的对话目录已被重建,请重新授权。":+ "This app's conversation directory was rebuilt. Authorize it again.",+ "此应用的对话目录现在读不到,请确认应用已安装并产生过对话。":+ "This app's conversation directory cannot be read. Check that the app is installed and has conversations.",+ "此应用的对话目录已变更,请按最新目录重新授权。":+ "This app's conversation directory changed. Authorize the new directory.",+ "此应用还没有读取授权,请先授权它的对话目录。完成后再开启持续同步。":+ "This app does not have read access yet. Authorize its conversation directory, then enable continuous sync.",+ "此应用的读取授权已撤销,请重新授权。完成后再开启持续同步。":+ "This app's read access was revoked. Authorize it again, then enable continuous sync.",+ "此应用的对话目录已被重建,请重新授权。完成后再开启持续同步。":+ "This app's conversation directory was rebuilt. Authorize it again, then enable continuous sync.",+ "此应用的对话目录现在读不到,请确认应用已安装并产生过对话。完成后再开启持续同步。":+ "This app's conversation directory cannot be read. Make sure the app is installed and has conversations, then enable continuous sync.",+ "此应用的对话目录已变更,请按最新目录重新授权。完成后再开启持续同步。":+ "This app's conversation directory changed. Authorize the new directory, then enable continuous sync.",+ "此应用的读取授权已失效,请重新授权后再开启持续同步。":+ "This app's read access expired. Authorize it again before enabling continuous sync.",+ "此应用的授权或目录已变化,已按最新状态显示,请确认后再试。":+ "This app's permissions or directory changed. Review the updated status and try again.",+ 模型配置表单: "Model configuration form",+ "部分运行状态暂时无法读取,当前显示最后读到的状态,请重试。":+ "Some status information is unavailable. Showing the last known state; please retry.",+ "当前安装还不能设置登录后后台启动。":+ "This installation cannot configure startup at login.",+ "登录后后台启动设置未能确认,请重试。":+ "Could not confirm the login startup setting. Please retry.",+ "当前安装还不能退出界面,请从菜单栏退出。":+ "This installation cannot quit the window. Use the menu bar instead.",+ "退出界面未能确认,请重试。": "Could not confirm quitting. Please retry.",+ 登录后启动后台服务: "Start background service at login",+ "无需打开界面,持续同步、整理和提供记忆。":+ "Keep syncing, processing and providing memories without opening the app.",+ 导出日志: "Export logs",+ "把本机运行日志打包成一个文件,发给开发排查。":+ "Package local diagnostic logs into a file to share with support.",+ "确定退出 One Memory 界面吗?": "Quit the MemHub window?",+ "后台服务会继续同步、整理和提供记忆。":+ "The background service will continue syncing, processing and providing memories.",+ 取消: "Cancel",+ 退出界面: "Quit window",+ 应用详情: "App details",+ 返回应用: "Back to apps",+ 同步开关: "Sync switch",+ "开启后处理历史待办,并持续接收此应用的新会话。":+ "Process pending history and keep receiving new conversations from this app when on.",+ "正在读取已有对话,首次开启可能需要一两分钟,请不要重复点击。":+ "Reading existing conversations. The first run may take a minute or two; please do not click again.",+ "将补充冻结期间的新对话;原有 pending Job 继续处理。":+ "Conversations received while frozen will be backfilled; existing pending jobs keep processing.",+ 一键插入应用: "One-click app connection",+ "安装记忆连接,并默认允许此应用使用已授权记忆。":+ "Install the memory connection and allow this app to use authorized memories by default.",+ 允许使用记忆: "Allow memory access",+ 连接状态: "Connection status",+ 已接通: "Connected",+ "已安装,但取不到记忆": "Installed, but cannot retrieve memories",+ 未接通: "Not connected",+ 状态待核对: "Status needs review",+ 检测中: "Checking",+ 未开启关联: "Connection off",+ "正在开启处理…": "Starting processing…",+ "正在冻结处理…": "Freezing processing…",+ 处理中: "Processing",+ 已冻结: "Frozen",+ "此应用的处理开关结果未能确认,其他应用不受影响。":+ "Could not confirm the processing switch for this app. Other apps are unaffected.",+ "暂时无法刷新来源状态,请重试;未更改同步或读取权限。":+ "Could not refresh source status. Retry; sync and read permissions were not changed.",+ "暂时无法读取连接状态,当前状态待核对;请重试。":+ "Could not read connection status. The current state needs review; please retry.",+ "已接通。已经打开的对话不会中途出现这个工具,请新开一轮。":+ "Connected. The tool will not appear in a conversation already open; start a new one.",+ "本次连接探测失败,当前状态待核对;未把上次读取当作本次成功。":+ "This connection check failed. The current state needs review; the previous result was not treated as a new success.",+ 上次读取: "Last read",+ appSettingsTitle: "{name} app settings",+ appMemoryScope:+ "Allow {name} to look up memories within its authorized scope.",+ appRestart:+ "The memory tool is not in {name}'s current conversation. Fully quit and reopen {name}; it will appear in a new conversation.",+ appConnectFailed:+ "One-click connection for this app did not complete. Other apps are unaffected. {reason}",+ appDisconnectFailed:+ "The connection could not be removed, and memory access could not be revoked. {name} can still use memories; please retry. {reason}",+ appPermissionFailed:+ "Memory access for this app could not be confirmed. Please retry. {reason}",+ appRevokedModified:+ "Memory access was revoked, so {name} can no longer look up memories. The configuration file was modified, so MemHub did not delete it automatically; remove the MemHub connection manually.",+ appRevokedRetained:+ "Memory access was revoked, so {name} can no longer look up memories. The connection file was not removed; review it again.",+ appRevokedReview:+ "Memory access was revoked, so {name} can no longer look up memories. Full removal could not be confirmed; review these paths manually: {paths}.",+ appRemovalReview:+ "Full connection removal could not be confirmed. Review these paths manually: {paths}.",+ "Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":+ "Cursor's connection credential changed. Fully quit and reopen Cursor before starting a new conversation.",+ 连接其他工具: "Connect other tools",+ "本机连接材料仅在桌面 App 中可用。":+ "Local connection details are only available in the desktop app.",+ "仅本机 MCP / 命令工具。纯网页聊天不支持直接连接本机。":+ "For local MCP or command-line tools only. Browser chat cannot connect directly to this device.",+ "列表内工具请用上方一键安装,此处仅供未列出的工具。":+ "Use one-click setup above for listed tools. This is for tools that are not listed.",+ "正在读取本机连接配置…": "Loading local connection details…",+ "未能读取连接配置。": "Could not load connection details.",+ 重试: "Retry",+ 连接材料格式: "Connection details format",+ 连接提示词: "Connection prompt",+ "MCP 配置": "MCP configuration",+ 命令: "Command",+ 本机连接材料: "Local connection details",+ "包含本机路径,不含记忆和密钥。片段会运行本机 MemHub 连接程序;粘贴前请确认,MemHub 需保持运行。":+ "Contains local paths, but no memories or keys. The snippet runs the local MemHub connector; review it before pasting and keep MemHub running.",+ "已复制,尚未建立连接。": "Copied; no connection has been made yet.",+ "复制失败,可在上方选中文本复制。":+ "Copy failed. Select and copy the text above instead.",+ 复制提示词: "Copy prompt",+ 复制配置: "Copy configuration",+ 复制命令: "Copy command",+ 记忆库分页: "Memory library pages",+ 上一页: "Previous page",+ 下一页: "Next page",+ "把熟悉的背景,带到这里": "Bring your context here",+ "你的记忆,从这里接上": "Bring your memories together",+ "这张卡还没测过。点一次「设为当前模型」会先自动测,如果还是不行,说明端点、key 或模型名有一处不对。":+ "This configuration has not been tested. Setting it as the current model runs a test first; if it still fails, check the endpoint, key, and model name.",+ "这类模型接口暂时用不了,换一张卡。":+ "This type of model endpoint is not supported yet. Use another configuration.",+ "这张卡缺了向量化模型,补上才能启用。":+ "This configuration needs an embedding model before it can be enabled.",+ "这张卡已经不在了,可能刚被删掉。刷新一下。":+ "This configuration is no longer available. It may have been deleted; refresh the list.",+ "这张卡刚被改过。刷新一下再试,免得覆盖掉别处的改动。":+ "This configuration was just changed. Refresh before retrying to avoid overwriting another change.",+ onboardingModelOperationFailed: "Operation failed: {code}",+ onboardingModelSkipDestination: "Skip and go to Apps",+ 首次设置进度: "First-time setup progress",+ 导入历史: "Import history",+ 连接应用: "Connect apps",+ 沉淀记忆: "Create memories",+ 本地存储: "Stored locally",+ "对话与记忆保存在本机;使用云模型或已授权的助手时,相关内容会发送给对应服务。":+ "Conversations and memories are stored on this device. Relevant content is sent to cloud models or authorized assistants when you use them.",+ "来源位置、身份或状态已变化,请重新选择并核对。尚未提交本次授权。":+ "The source location, identity or status changed. Select and review it again. This authorization was not submitted.",+ "来源位置、身份或状态已变化,正在等待本次提交回执。不会自动扩大已提交范围。":+ "The source location, identity or status changed. Waiting for confirmation of this submission; the submitted scope will not expand automatically.",+ 测试实例不接入应用: "Test instances do not connect to apps",+ "请先把 MemHub 拖到“应用程序”并从那里重新打开,才能接入应用。":+ "Move MemHub to Applications and reopen it from there before connecting apps.",+ "部分应用未能完成接入,已成功的设置会保留,可进入应用后单独处理。":+ "Some apps could not be connected. Successful settings are retained; handle the rest individually in Apps.",+ onboardingConnectionPartial:+ "{success} apps connected; {failed} incomplete: {names}. You can handle them individually in Apps.",+ "首次设置的完成状态未能保存。已确认的导入回执不受影响;下次启动可能再次出现此页。":+ "Could not save first-time setup completion. Confirmed import receipts are unaffected; this page may appear again next time.",+ "首次设置的完成状态尚未确认。已确认的导入回执不受影响;下次启动可能再次出现此页。":+ "First-time setup completion is unconfirmed. Confirmed import receipts are unaffected; this page may appear again next time.",+ "位置检测未完成,尚未读取历史。可以重新检测,或先进入工作台。":+ "Location detection is incomplete, and history has not been read. Check again or continue to the workspace.",+ "暂时无法核对来源,尚未提交授权。选择已保留,可以重试。":+ "Sources cannot be reviewed right now, so authorization was not submitted. Your selections are retained; you can retry.",+ "本次没有来源获准导入。请核对下方原因后重试,或到应用页查看状态。":+ "No sources were authorized for this import. Review the reasons below and retry, or check their status in Apps.",+ "开始导入的结果尚未确认,选择已保留。可以重试,或进入应用页核对。":+ "The import start is unconfirmed. Your selections are retained; retry or check in Apps.",+ 未完成: "Incomplete",+ 核对中: "Checking",+ 仍进入应用页: "Continue to Apps",+ 仍进入工作台: "Continue to workspace",+ 仍进入设置: "Continue to Settings",+ 重试保存并进入: "Retry saving and continue",+ "稍后添加,先进入": "Add later and continue",+ "正在开始导入…": "Starting import…",+ 开始导入: "Start importing",+ "不用从头介绍自己。从常用的 App 开始,把已有背景带过来。":+ "You do not have to start over. Bring context from your frequently used apps.",+ "确认前只检查应用信息,不读取对话,也不安装连接。":+ "Before confirmation, only app information is checked. Conversations are not read and no connection is installed.",+ "本机 AI 应用": "AI apps on this device",+ 重新检测位置: "Check locations again",+ "检测中…": "Checking…",+ 重新检测: "Check again",+ 候选应用: "Available apps",+ "正在检测其他应用…": "Looking for other apps…",+ 检测未完成: "Check incomplete",+ 已全选: "All selected",+ 全选: "Select all",+ onboardingImportHistory: "Import history from {name}",+ 正在核对本机保存位置: "Checking local storage location",+ 已发现: "Found",+ 位置待核对: "Location needs review",+ "当前没有候选来源。可以稍后在应用页添加历史包。":+ "No sources found. You can add a history archive later from Apps.",+ "候选来源尚未加载。可以检测位置,或先进入工作台。":+ "Sources have not loaded. Check locations or continue to the workspace.",+ 本次导入: "This import",+ "个 App 的历史对话": "app histories",+ "把零散的会话,": "Bring conversations",+ 汇成完整的记忆: "together as memories",+ "少一些重复交代,多一些理解。": "Less repetition. More understanding.",+ onboardingMoreApps: "Scroll for more · {count} apps remaining",+ "onboardingMoreApps.one": "Scroll for more · {count} app remaining",+ onboardingAllApps: "All {count} apps shown",+ 默认位置: "Default location",+ 自定义位置: "Custom location",+ 尚未检测: "Not checked",+ 未发现: "Not found",+ 无法访问: "Cannot access",+ 位置无效: "Invalid location",+ "需要更新 Core": "Core update required",+ "候选位置不存在,可能尚无历史或路径不同。":+ "This location does not exist. There may be no history yet, or the path may be different.",+ "无法检查此位置,请核对目录访问权限后重试。":+ "Could not check this location. Review directory access and retry.",+ "此位置未通过安全检查,不能读取。":+ "This location failed the security check and cannot be read.",+ "当前 Core 未提供可确认的位置身份,需更新后再选择。":+ "The current Core does not provide a verifiable location identity. Update it before selecting.",+ 暂不支持历史导入: "History import is not supported yet",+ "当前来源不可读取,请重新检测。":+ "The current source cannot be read. Check again.",+ "来源目录暂时不可读取,请核对位置和权限。":+ "The source directory is temporarily unreadable. Check its location and permissions.",+ "来源目录身份已变化,请返回重新检测。":+ "The source directory identity changed. Go back and check again.",+ "来源权限已变化,请返回重新确认。":+ "Source permissions changed. Go back and confirm again.",+ "此来源尚未获得读取授权。": "This source does not have read access yet.",+ "自定义来源位置需要重新确认。":+ "The custom source location needs confirmation again.",+ "当前 Core 未启用历史导入。":+ "History import is not enabled in the current Core.",+ onboardingImportRefused:+ "Import not authorized ({reason}). Review the source and retry.",+ 确认自定义位置: "Confirm custom location",+ 关闭位置确认: "Close location confirmation",+ "此位置来自当前配置,并非应用默认目录。确认位置不会开始读取历史。":+ "This location comes from your current configuration, not the app's default directory. Confirming the location does not start reading history.",+ onboardingConfirmHistory: "Confirm this is {name}'s history location",+ 确认此位置: "Confirm this location",+ "对话正在汇入,记忆从这里开始":+ "Conversations are coming in. Memories start here",+ "导入进行中 · 顺手连接应用": "Importing · Connect your apps",+ "对话已保存,记忆尚待生成。":+ "Conversations saved; memories are yet to be created.",+ "导入在后台继续,无需等待。":+ "Import continues in the background. No need to wait.",+ "正在重新核对来源;已保存数量仍按任务回执显示。":+ "Rechecking sources; saved counts still reflect job receipts.",+ "本次历史导入已暂停,已保存的对话还在。":+ "This history import is paused. Saved conversations remain available.",+ "导入等待处理,已保存的对话还在。":+ "Import is awaiting processing. Saved conversations remain available.",+ 停止后续操作: "Stop remaining actions",+ 暂停导入: "Pause import",+ 继续导入: "Resume import",+ "配置模型,沉淀记忆": "Configure a model to create memories",+ 导入与原文: "Import and original text",+ "本次导入已结束。已保存的对话无需重复导入。":+ "This import is complete. Saved conversations do not need reimporting.",+ "对话先保存在本机。你可以同时设置后续连接。":+ "Conversations are saved locally first. You can set up connections in the meantime.",+ "导入不会自动开放应用读取权限。配置模型后,才会开始生成记忆。":+ "Importing does not automatically grant apps read access. Memories are created only after you configure a model.",+ onboardingHistoryWindow:+ "A large amount of conversation data was found. To limit usage and keep app timelines aligned, this import includes only the last 3 days for all apps.",+ 导入说明: "Import information",+ 正在导入你的会话: "Importing your conversations",+ "后台将持续为你导入,可以放心进入下一步":+ "Import will continue in the background. You can move on.",+ 未开始的导入: "Imports that could not start",+ "未能开始导入,其他已接受任务不受影响。":+ "Import could not start. Other accepted jobs are unaffected.",+ 查看未导入的应用: "View apps not imported",+ 让记忆继续生长: "Keep your memories growing",+ 连接你的应用: "Connect your apps",+ "适用于本次选择且支持的应用。":+ "For selected apps that support this connection.",+ 一键接入应用: "Connect apps in one step",+ "安装记忆连接,让所选应用用上 MemHub 中的相关记忆。":+ "Install memory connections so selected apps can use relevant memories in MemHub.",+ "当前使用独立测试数据目录,不会修改本机应用的连接配置。":+ "This instance uses an isolated test data directory and will not change local app connections.",+ "点击底部按钮后,后台分别接入各应用;某个应用失败不影响其他应用。":+ "After you click the button below, apps are connected individually in the background; one failure will not affect others.",+ "暂时无法连接应用,当前不会安装连接。":+ "Apps cannot be connected right now. No connection will be installed.",+ onboardingBatchStopped:+ "Stopped remaining actions; check receipts for actions already sent. ",+ onboardingBatchResult: "{confirmed} confirmed, {failed} unconfirmed.",+ "已确认项保留,请核对未确认任务后重试。":+ " Confirmed actions are retained. Check unconfirmed jobs before retrying.",+ 本次应用导入进度: "Import progress for selected apps",+ 正在导入: "Importing",+ 已暂停: "Paused",+ 已中断: "Interrupted",+ 导入遇到问题: "Import encountered a problem",+ 导入完成: "Import complete",+ 已取消: "Cancelled",+ 已保存: "Saved",+ onboardingAppProgress: "Import progress for {name}",+ onboardingSavedMessages: "{count} messages saved",+ onboardingScannedOutsideRange:+ "Scanned {count} items; no conversations matched the time range",+ onboardingScannedNothingToSave:+ "Scanned {count} items; no conversations to save",+ onboardingScannedFilteringRecent:+ "Scanned {count} items; filtering the last 3 days",+ onboardingScannedFiltering: "Scanned {count} items; filtering",+ onboardingScannedNotSaved: "Scanned {count} items; not saved yet",+ 没有可保存的历史对话: "No history conversations to save",+ 读取授权不可用: "Read access unavailable",+ onboardingReadErrors: " · {count} read errors",+ "配置详情,按需要调整": "Configuration details, if needed",+ "连接未通过,配置已保留": "Connection failed; configuration retained",+ "选好模型,让记忆开始沉淀": "Choose a model to start creating memories",+ "连接设置已保存\n成功项保留,不重复执行。":+ "Connection settings saved.\nSuccessful steps are retained and will not be repeated.",+ "已选择:持续同步 · 一键接入":+ "Selected: continuous sync · one-step connection",+ "沉淀记忆 · 使用你选择的模型": "Create memories · With your chosen model",+ "当前无法启用模型,已填写内容保留。":+ "Cannot enable the model right now. Your entries are retained.",+ "模型连接测试通过,可以启用并开始沉淀记忆。":+ "Model connection passed. You can enable it to create memories.",+ "先测试模型连通性;测试通过后再启用。":+ "Test the model connection first; enable it after the test passes.",+ "跳过,先进入应用": "Skip and go to Apps",+ "正在测试模型…": "Testing model…",+ 测试模型连通性: "Test model connection",+ "正在启用…": "Enabling…",+ 确认启用: "Confirm and enable",+ 核对提交状态: "Check submission status",+ 模型配置: "Model configuration",+ 模型参数: "Model parameters",+ "选择服务商,填入 API Key。核对已有配置后再继续。":+ "Choose a provider and enter an API key. Review existing configuration before continuing.",+ 模型服务商: "Model provider",+ 选择服务商: "Select a provider",+ "已安全保存,留空保留": "Saved securely; leave blank to keep",+ "输入服务商提供的 API Key": "Enter the API key from your provider",+ "连接未通过,请检查 API Key、模型与接口地址后重试。配置已保留。":+ "Connection failed. Check the API key, model and endpoint, then retry. Your configuration is retained.",+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”。":+ "Allow MemHub to access Keychain. Choose ‘Always Allow’ when prompted.",+ "留空保留已保存密钥;填写新密钥后需重新测试。":+ "Leave blank to keep the saved key; test again after entering a new key.",+ "密钥保存在系统安全存储中,不写入对话或日志。":+ "The key is kept in secure system storage, not conversations or logs.",+ 配置详情与高级设置: "Configuration details and advanced settings",+ 服务商待选择: "Provider not selected",+ 模型待填写: "Model not entered",+ 本地向量模型: "Local embedding model",+ 向量模型待填写: "Embedding model not entered",+ 思考已关闭: "Thinking disabled",+ 思考未关闭: "Thinking not disabled",+ "预设已填好,只有自定义服务或特殊需求才需要修改。":+ "Presets are filled in. Change them only for custom services or special requirements.",+ 返回服务商选择: "Back to provider selection",+ 模型名称: "Model name",+ "Anthropic(暂不支持)": "Anthropic (not supported yet)",+ "HY 托管(当前不可用)": "HY managed (currently unavailable)",+ 向量模型: "Embedding model",+ "本地 ONNX · 内置": "Local ONNX · Built in",+ "超时(秒)": "Timeout (seconds)",+ 最大并发: "Maximum concurrency",+ 上下文窗口: "Context window",+ "自动 / 可选": "Automatic / optional",+ 关闭思考模式: "Disable thinking mode",+ "自定义向量配置可展开;远程向量服务须遵守凭据边界。":+ "You can expand custom embedding settings. Remote embedding services must respect credential boundaries.",+ "切换服务商或模型后,需要重新测试并启用。":+ "After changing providers or models, test and enable again.",+ 向量模型名称: "Embedding model name",+ 向量协议: "Embedding protocol",+ "同源 OpenAI-compatible(共用 Key)":+ "Same-origin OpenAI-compatible (shared key)",+ "向量 Base URL": "Embedding Base URL",+ "远程向量地址须与生成服务同源;本机地址仍需校验。":+ "Remote embedding endpoints must match the generation service origin; local endpoints still need validation.",+ "放弃旧记录,重新配置": "Discard old record and reconfigure",+ 模型提交状态: "Model submission status",+ "正在测试连接…": "Testing connection…",+ "正在提交保存与启用,请等待回执…":+ "Saving and enabling; waiting for confirmation…",+ "操作结果未确认,已填写内容保留,请核对后重试。":+ "Outcome unconfirmed. Your entries are retained; check before retrying.",+ 本次沉淀: "This memory setup",+ 让记忆从这里开始: "Start creating memories here",+ 对话来源: "Conversation sources",+ 尚无已选来源: "No sources selected",+ onboardingSourcesSummary: "{names} and {count} apps in total",+ onboardingImportedConversations:+ "{count} conversations imported; source switches still control what syncs to this device later.",+ "处理服务:": "Processing service:",+ 待选择: "Not selected",+ "相关对话会发送给所选服务商。":+ "Relevant conversations will be sent to the chosen provider.",+ "测试连接只发送测试内容。启用后会使用此模型整理已导入和之后同步的会话。":+ "Connection tests send only test content. After enabling, this model processes imported and subsequently synced conversations.",+ "当前不能在此启用模型。": "Cannot enable the model here right now.",+ "配置已修改,需要重新测试。": "Configuration changed. Test again.",+ onboardingIntegerRange: "Enter a whole number from {min} to {max}.",+ "请填写配置名称。": "Enter a configuration name.",+ "请填写实际可用的模型 ID。": "Enter an available model ID.",+ "请填写有效的模型接口地址。": "Enter a valid model endpoint URL.",+ "请填写 API Key。": "Enter an API key.",+ "请填写向量模型 ID。": "Enter an embedding model ID.",+ "配置结果尚未确认,请在模型设置中核对后重试。":+ "The configuration result is unconfirmed. Check it in Model settings before retrying.",+ "模型连接测试通过,可以启用。":+ "Model connection test passed. You can enable it.",+ "连接未通过,请核对模型、密钥和接收方。":+ "Connection failed. Check the model, key, and recipient.",+ "配置或测试结果暂未确认,请核对后重试。":+ "Could not confirm the configuration or test result. Check before retrying.",+ 所选连接已启用: "Selected app connections are enabled",+ 本次未选择应用连接: "No app connection selected this time",+ 尚未填写接收方: "No recipient entered",+ 本机内置向量模型: "Built-in local embedding model",+ "操作未确认,草稿已保留。":+ "Could not confirm the action. Your draft is retained.",+ "操作已完成,但配置列表暂未刷新。已保留操作回执,请刷新核对,不要重复保存。":+ "The operation completed, but the configuration list has not refreshed. The receipt is retained; refresh to review it. Do not save again.",+ "暂时无法刷新模型配置,已确认的配置仍保留。请重试刷新。":+ "Could not refresh model configurations. Confirmed configurations are retained; try refreshing again.",+ "未找到上次创建记录。确认放弃旧记录后可重新配置;系统不会自动重试。":+ "The previous creation record was not found. Discard it to reconfigure; no automatic retry will occur.",+ "创建结果仍待核对,不会重复创建。请稍后再次核对。":+ "The creation result still needs review. No duplicate will be created; check again later.",+ "已发现模型配置,旧创建记录仍保留。请先核对已有配置。":+ "A model configuration was found. The old creation record is retained; review the existing configuration first.",+ "旧创建记录尚未安全解除,配置仍保持锁定。请重新核对。":+ "The old creation record has not been safely cleared. Configuration remains locked; review it again.",+ "配置未保存,请检查模型地址和参数后重试;已填写内容保留。":+ "Configuration was not saved. Check the model endpoint and settings before retrying; your input is retained.",+ "创建结果尚未确认,请核对已保存结果,不要重复提交。":+ "The creation result is unconfirmed. Review saved results; do not submit again.",+ "模型配置已变化,旧测试结果不会用于启用,请重新核对配置。":+ "The model configuration changed. The old test result will not be used to enable it; review the configuration again.",+ "暂时无法核对测试服务,本次未发送测试,请恢复连接后重试。":+ "Could not verify the test service. No test was sent; restore the connection and try again.",+ "另一个模型的测试结果尚未确认,请先在该模型上核对测试结果。":+ "Another model's test result is unconfirmed. Review that model's result first.",+ "测试结果尚未确认。再次点击测试连接将核对原操作,不会重复发送测试。":+ "The test result is unconfirmed. Clicking Test connection again will review the original operation without sending another test.",+ "请先点击测试连接,通过后再设为当前模型。":+ "Test the connection first; set it as the current model only after it passes.",+ "这是当前正在使用的模型,请先切换到别的模型再删除。":+ "This model is currently in use. Switch to another model before deleting it.",+ "模型配置操作未成功,请核对输入后重试。":+ "The model configuration operation did not succeed. Check your input and try again.",+ "它没有 MCP 通道,无法发放可撤销的记忆凭证":+ "This app has no MCP channel for a revocable memory credential",+ 当前安装不支持一键插入:+ "One-click connection is unsupported in this installation",+ 桌面端的连接组件不可用: "The desktop connection component is unavailable",+ 安装后没有拿到安装回执: "No installation receipt was returned",+ 记忆使用权限没有获批: "Memory access was not approved",+ 配置文件被改过: "The configuration file was edited",+ "有无法确认的残留,需要人工核对": "Some remnants need manual review",+ 权限存储暂不可用: "Permission storage is unavailable",+ "请先把 MemHub 拖到“应用程序”文件夹,再接入应用":+ "Move MemHub to Applications before connecting apps",+ 本机运行时暂不可用: "The local runtime is unavailable",+ 桌面端读取接入状态超时: "Reading the desktop connection status timed out",+ "apps.apps": "Apps",+ "apps.allApps": "All apps",+ "apps.home": "Apps home",+ "apps.back": "Back to home",+ "apps.overview": "Memory overview",+ "apps.memories": "Saved memories",+ "apps.readingCount": "Loading memory count…",+ "apps.unreadable": "Unavailable",+ "apps.unit": "items",+ "apps.scope": "Used within app permissions",+ "apps.processing": "Processing status",+ "apps.running": "Processing",+ "apps.paused": "Paused",+ "apps.stoppedNew": "No new memories are being created",+ "apps.checkingProcessing": "Checking processing status",+ "apps.unchecked": "Needs review",+ "apps.organizingNew": "Processing new conversations",+ "apps.recentUpdate": "Recent update",+ "apps.notGenerated": "Not created yet",+ "apps.saved": "Memory saved",+ "apps.separate": "History and memories are processed separately",+ "apps.recentCall": "Recent call",+ "apps.activityUnavailable": "Activity unavailable",+ "apps.firstBatch": "First memories",+ "apps.callsUnavailable": "Could not read call history",+ "apps.memoryUnavailable": "Could not read memory status",+ "apps.importing": "Importing conversations before creating memories",+ "apps.firstRunning": "Creating the first memories",+ "apps.firstQueued": "Preparing the first memories",+ "apps.readingActivity": "Loading activity",+ "apps.emptyMemories": "No memories created yet",+ "apps.callReadFailure":+ "You can still view saved memories. Retrying will not make a new call.",+ "apps.memoryReadFailure":+ "A failed read does not mean there are no memories.",+ "apps.savingConversations":+ "Conversations are still being saved in the background.",+ "apps.waitingMemories": "History is saved. New memories will appear here.",+ "apps.reread": "Retry",+ "apps.viewCalls": "View history",+ "apps.viewMemory": "View memories",+ "apps.backgroundDown":+ "The background service is not running; apps cannot look up memories right now",+ "apps.restart": "Restart",+ "apps.runtime": "Runtime status",+ "apps.backgroundRunning": "Running in background",+ "apps.connectionUnchecked": "Connection needs review",+ "apps.disconnected": "Service disconnected",+ "apps.authorizedOnly": "Only processes authorized content",+ "apps.sync": "Conversation sync",+ "apps.organizing": "Memory processing",+ "apps.access": "App access",+ "apps.checkingAccess": "App connection check",+ "apps.checking": "Checking…",+ "apps.recheck": "Check again",+ "apps.accessState": "App connection status",+ "apps.staleAccess":+ "Could not read app connection status; showing the last known state.",+ "apps.reconnect": "Reconnect",+ "apps.myApps": "My apps",+ "apps.list": "App list",+ "apps.syncEnabled": "Continuous sync enabled",+ "apps.recallAllowed": "Can request authorized memories",+ "apps.historyAllowed": "History access authorized",+ "apps.connectionPending": "Connection incomplete",+ "apps.details": "View details",+ "apps.listUnavailable": "App list unavailable",+ "apps.emptyApps": "No apps to display yet",+ "apps.checkingNow": "Checking",+ "apps.checkingState": "Checking status",+ "apps.notEnabled": "Not enabled",+ "apps.enableFailed": "Could not enable",+ "apps.unknownTime": "Time unknown",+ "apps.today": "Today",+ "apps.newMemory": "New memory",+ "apps.updatedMemory": "Updated memory",+ "apps.unlinked": "Not connected yet",+ "apps.lastRead": "Last read: ",+ "apps.recentSync": "Last synced {time}",+ "apps.connectedCount": "{count} apps connected",+ "apps.connectedCount.one": "{count} apps connected",+ "apps.pendingCount": "{count} apps need review",+ "apps.pendingCount.one": "{count} apps need review",+ "apps.mixedCount": "{count} apps connected · Pending review: {pending}",+ "apps.mixedCount.one": "{count} app connected · Pending review: {pending}",+ "apps.unknownAccess":+ "App connection status is unavailable; the connected app count cannot be confirmed.",+ "apps.unknownPermissions":+ "Could not read memory permissions for {names}; connection status is unconfirmed.",+ "apps.enabledCount": "{count} apps enabled",+ "apps.enabledCount.one": "{count} apps enabled",+ "apps.appCount": "{count} apps",+ "apps.appCount.one": "{count} apps",+ "apps.viewAll": "View all {count} apps",+ "apps.viewAll.one": "View all {count} apps",+ "apps.checkedAt": "Last checked: {time}",+ "apps.revision": "Version {count}",+ "apps.conversationTime": "Conversation time",+ "apps.importTime": "Import time",+ "apps.incompleteCalls":+ " · Some calls were not recorded; the list may be incomplete",+ "apps.timeoutWarning":+ "{host} could not look up memories recently. The background service may be busy and should recover automatically.",+ "apps.autoHostFailed": "{name} could not connect automatically{reason}.",+ "apps.failureReason": ": {reason}",+ "apps.autoSyncFailed":+ "Continuous sync could not be enabled automatically for {name}. {reason}",+ "apps.noAutoRetry": "It will not retry automatically.",+ "apps.cardUnavailable":+ "{label} is temporarily unavailable. Other features are unaffected, and it should recover automatically.",+ "apps.navMemories": "Memories",+ "apps.navigation": "Main navigation",+ "apps.skip": "Skip to main content",+ "apps.local": "Stored locally",+ "apps.localHint":+ "Memories are stored on this device. Relevant content is sent to the service when you use a cloud model or an authorized assistant.",+ "memory:记忆抽取": "Memory extraction",+ "memory:关系归纳": "Relationship synthesis",+ "memory:深度整理": "Deep processing",+ "memory:跨域整理": "Cross-domain processing",+ "memory:当前模型已变化": "Current model changed",+ "memory:本地会话内容已变化": "Local conversation content changed",+ "memory:这段对话含过长原文,暂未整理;原文已保留":+ "This conversation contains text too long to process; the original is preserved",+ "memory:记忆库分页": "Memory library pages",+ "memory:上一页": "Previous page",+ "memory:下一页": "Next page",+ "memory:等待可用生成模型": "Waiting for an available generation model",+ "memory:还没有启用生成模型": "No generation model enabled yet",+ "memory:缺少生成模型 API Key": "Generation model API key is missing",+ "memory:模型凭据暂不可用": "Model credentials are temporarily unavailable",+ "memory:本机凭据存储暂不可用":+ "Local credential storage is temporarily unavailable",+ "memory:需要授权访问本机钥匙串。请重新打开 App 并完成一次授权":+ "Keychain access needs authorization. Reopen the app and approve access.",+ "memory:读取本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "Keychain read timed out. Save the model configuration again to recover.",+ "memory:写入本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "Keychain write timed out. Save the model configuration again to recover.",+ "memory:模型认证失败。更新 key 后,到设置里点一次检测,会自动接着处理":+ "Model authentication failed. Update the key and run a check in Settings to resume processing.",+ "memory:模型账户余额不足。充值或换 key 后,到设置里点一次检测,会自动接着处理":+ "Model account balance is insufficient. Top up or change the key, then run a check in Settings to resume processing.",+ "memory:模型服务拒绝访问。更新权限后,到设置里点一次检测,会自动接着处理":+ "Model service denied access. Update permissions and run a check in Settings to resume processing.",+ "memory:模型服务限流": "Model service rate limited",+ "memory:模型服务暂不可用": "Model service temporarily unavailable",+ "memory:模型服务响应超时": "Model service timed out",+ "memory:模型请求不兼容,请核对配置":+ "Model request is incompatible; check the configuration",+ "memory:模型请求未成功": "Model request failed",+ "memory:HY Memory 不可用": "HY Memory unavailable",+ "memory:HY Memory 启动失败": "HY Memory failed to start",+ "memory:暂时没能整理,稍后会自动重试":+ "Could not process this yet; will retry automatically",+ "memory:这次没能整理成功,正在重试": "Could not process this time; retrying",+ "memory:生成模型换过了,这批会重新整理":+ "Generation model changed; these items will be processed again",+ "memory:整理方式换过了,这批会重新整理":+ "Processing settings changed; these items will be processed again",+ "memory:已提炼": "Extracted",+ "memory:旧版确认记录": "Legacy confirmation record",+ "memory:创建": "Created",+ "memory:纠正": "Correct",+ "memory:调整使用范围": "Access scope changed",+ "memory:撤销修改": "Change undone",+ "memory:模型更新": "Model update",+ "memory:被新记忆取代": "Replaced by a new memory",+ "memory:其他操作": "Other action",+ "memory:删除(记录)": "Deletion",+ "memory:修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "Change saved, but the latest list could not be loaded. Old answers are no longer used; reload the list.",+ "memory:纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "Correction saved, but the latest list could not be loaded. Old answers are no longer used; reload the list.",+ "memory:未收到操作结果,请重试。": "No result was received. Please retry.",+ "memory:批量处理结果已保留,但列表刷新失败,请重新读取记忆库。":+ "Bulk action results are retained, but the list could not refresh. Reload the memory library.",+ "memory:批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。":+ "Bulk action results are retained, but the list could not refresh. It will reload automatically later.",+ "memory:召回范围已保存,但列表刷新失败。请稍后重新打开记忆页。":+ "Recall scope saved, but the list could not refresh. Reopen Memories later.",+ "memory:重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?":+ "Processing again may call the model. Only conversations with uncertain results will be retried. Continue?",+ "memory:原始对话暂时无法读取": "Could not load original conversations",+ "memory:没有匹配的原始对话": "No matching original conversations",+ "memory:还没有导入的原始对话": "No original conversations imported yet",+ "memory:查看已读内容": "View saved content",+ "memory:已保存原文": "Original text saved",+ "memory:刷新已读内容": "Refresh saved content",+ "memory:正在核对本机已保存记录…": "Checking saved local records…",+ "memory:原始消息": "Original messages",+ "memory:会话": "Conversations",+ "memory:用户发言": "User messages",+ "memory:Agent 发言": "Agent message",+ "memory:作者未知": "Unknown author",+ "memory:原始时间未知": "Original time unknown",+ "memory:工具记录": "Tool record",+ "memory:原始时间来自已保存记录。":+ "Original timestamps come from saved records.",+ "memory:已保存的原文样例": "Saved original-text examples",+ "memory:最多展示 3 段,不代表全部历史或推荐记忆。":+ "Up to 3 examples; not the full history or recommended memories.",+ "memory:查看完整对话": "View full conversation",+ "memory:原文较长,此处仅展示前 600 个字符。":+ "Long original text; only the first 600 characters are shown here.",+ "memory:这个来源还没有保存原文。":+ "No original text saved from this source yet.",+ "memory:完整对话": "Full conversation",+ "memory:关闭完整对话": "Close full conversation",+ "memory:用户": "User",+ "memory:暂时无法读取已保存内容,旧回执已收起。请检查授权或重试。":+ "Could not read saved content. The previous receipt is closed; check permissions or retry.",+ "memory:这段原文暂不可读,可能已被撤回授权。请刷新回执。":+ "This original text is unavailable; access may have been revoked. Refresh the receipt.",+ "memory:外部记忆召回范围": "External memory lookup scope",+ "memory:外部记忆召回": "External memory lookup",+ "memory:调整召回范围": "Adjust lookup scope",+ "memory:所有关联工具": "All connected tools",+ "memory:已停止外部记忆召回": "External memory lookup stopped",+ "memory:原有限定范围": "Previous limited scope",+ "memory:选择召回范围": "Choose lookup scope",+ "memory:停止外部记忆召回": "Stop external memory lookup",+ "memory:正在保存…": "Saving…",+ "memory:保存召回范围": "Save lookup scope",+ "memory:取消范围修改": "Cancel scope changes",+ "memory:原文检索仍按来源授权;已带出的内容不会撤回。":+ "Original-text searches still follow source permissions; content already provided will not be recalled.",+ "memory:记忆已更新,请重新打开这条记忆后再调整范围。":+ "Memory has changed. Reopen it before adjusting the scope.",+ "memory:范围修改未提交,当前范围保持不变。请修正后重试。":+ "Scope changes were not submitted. The current scope is unchanged; fix the issue and retry.",+ "memory:保存结果尚未确认,请重试。":+ "Save result is unconfirmed. Please retry.",+ "memory:原话已保存在本机;当前内容、模型接收方或授权版本尚未通过核对,未继续整理。":+ "The original is saved on this device; the content, model recipient or permission version did not pass review, so processing did not continue.",+ "memory:HY 未返回可核对的已有记忆,未创建替代内容;原始记录已保留,可重试处理。":+ "HY returned no existing memories that could be verified, and no replacement was created. Original records are retained; you can retry processing.",+ "memory:历史引用尚未绑定到原始来源,当前批次未完成,原话已保留。":+ "Historical citations are not yet linked to their original sources. This batch is incomplete; the original is retained.",+ "memory:记忆内容未通过来源与作者核验,当前批次未完成,原话已保留。":+ "The memory content did not pass source and author verification. This batch is incomplete; the original is retained.",+ "memory:所选记忆已不可读取,请重新读取记忆库。":+ "The selected memory can no longer be read. Reload the memory library.",+ "memory:还没连上本地 Core,正在重试…":+ "Local Core is not connected yet; retrying…",+ "memory:记忆内容或使用权限已变化,回答已停止。请重新提问。":+ "The memory content or access permissions changed, so the answer was stopped. Ask again.",+ "memory:这条记忆的来源授权已撤回,暂时不能读取。":+ "Source access for this memory was revoked, so it cannot be read right now.",+ "memory:记忆已被更新,请刷新后重试。":+ "This memory was updated. Refresh and retry.",+ "memory:已删除的记忆不能修改。": "Deleted memories cannot be edited.",+ "memory:这条记忆已经删除。": "This memory has been deleted.",+ "memory:这条记忆已被更新的记忆取代,只能查看或删除。":+ "This memory was replaced by an updated memory and can only be viewed or deleted.",+ "memory:没有更早的修改可以撤销。": "There are no earlier changes to undo.",+ "memory:来源原话已不存在,无法建立这条记忆。":+ "The original source text no longer exists, so this memory cannot be created.",+ "memory:这次操作与已完成的请求不一致。":+ "This action does not match the completed request.",+ "memory:输入内容不符合要求。": "The input does not meet the requirements.",+ "memory:本地记忆库正忙,请稍后重试。":+ "The local memory library is busy. Please retry later.",+ "memory:记忆": "Memories",+ "memory:记忆空间": "Memory space",+ "memory:全部应用": "All apps",+ "memory:来源": "Source",+ "memory:主题": "Topic",+ "memory:归纳": "Synthesis",+ "memory:全部记忆": "All memories",+ "memory:来源待核对": "Source needs review",+ "memory:所选来源待核对": "Selected source needs review",+ "memory:未知来源": "Unknown source",+ "memory:记忆读取失败": "Could not load memories",+ "memory:正在读取…": "Loading…",+ "memory:正在更新…": "Updating…",+ "memory:读取失败": "Could not load",+ "memory:正在核对来源…": "Checking sources…",+ "memory:正在导入历史会话,记忆将陆续出现":+ "Importing earlier conversations; memories will appear gradually",+ "memory:记忆工作台": "Memory workspace",+ "memory:来源与主题": "Sources and topics",+ "memory:记忆或原始对话": "Memories or original conversations",+ "memory:原始对话": "Original conversations",+ "memory:地图组织方式": "Map grouping",+ "memory:筛选地图记忆": "Filter map memories",+ "memory:搜索原始对话": "Search original conversations",+ "memory:搜索记忆": "Search memories",+ "memory:筛选记忆…": "Filter memories…",+ "memory:向记忆提问": "Ask memories a question",+ "memory:询问全部已授权可用记忆…":+ "Ask about all authorized, available memories…",+ "memory:发送问题": "Send question",+ "memory:刷新地图记忆": "Refresh map memories",+ "memory:关闭新增记忆提示": "Dismiss new memory notice",+ "memory:地图记忆列表": "Map memory list",+ "memory:记忆读取失败,请重试。": "Could not load memories. Please retry.",+ "memory:重新读取地图记忆": "Reload map memories",+ "memory:没有匹配的记忆": "No matching memories",+ "memory:本页没有匹配的主题记忆": "No matching topic memories on this page",+ "memory:还没有已生成的记忆": "No memories created yet",+ "memory:地图记忆分页": "Map memory pages",+ "memory:上一页记忆": "Previous memory page",+ "memory:下一页记忆": "Next memory page",+ "memory:记忆关系图": "Memory graph",+ "memory:记忆关联": "Memory connections",+ "memory:刚导入的原话,还不是沉淀后的记忆":+ "Newly imported original text, not yet memories",+ "memory:来源归属": "Source connections",+ "memory:可在沉淀记忆后查看视图": "Create memories to view the graph",+ "memory:查看选中来源原文": "View selected source text",+ "memory:查看选中记忆原文": "View selected memory text",+ "memory:查看原文": "View original conversation",+ "memory:整理已有关系": "Build existing connections",+ "memory:正在读取原文…": "Loading original conversation…",+ "memory:选择一条原始对话": "Select an original conversation",+ "memory:记忆暂时无法读取": "Memories are temporarily unavailable",+ "memory:当前筛选没有可显示的记忆": "No memories to display for this filter",+ "memory:正在读取记忆…": "Loading memories…",+ "memory:已保存的对话还未生成记忆":+ "Saved conversations have not become memories yet",+ "memory:还没有可显示的记忆": "No memories to display yet",+ "memory:连线表示来源归属": "Lines show source connections",+ "memory:记忆详情": "Memory details",+ "memory:来源原文": "Source original text",+ "memory:关联节点": "Related node",+ "memory:关闭记忆详情": "Close memory details",+ "memory:关闭详情": "Close details",+ "memory:正在读取这条记忆…": "Loading this memory…",+ "memory:这条记忆的原文暂时无法读取,选择已保留。":+ "Could not load this memory's original text. Selection is preserved.",+ "memory:重试读取原文": "Retry loading conversation",+ "memory:已沉淀的记忆": "Created memories",+ "memory:正在读取记忆详情…": "Loading memory details…",+ "memory:沉淀记忆后查看详情": "Create memories to see details",+ "memory:时间未知": "Time unknown",+ "memory:来源原文已不可读取": "Source original text is unavailable",+ "memory:关联记忆": "Related memories",+ "memory:正在读取完整对话…": "Loading full conversation…",+ "memory:重试读取完整对话": "Retry loading full conversation",+ "memory:看完整对话": "View full conversation",+ "memory:今天": "Today",+ "memory:你": "You",+ "memory:助手": "Assistant",+ "memory:工具": "Tool",+ "memory:未知": "Unknown",+ "memory:作者待核对": "Author needs review",+ "memory:你说": "You said",+ "memory:助手原话": "Original assistant message",+ "memory:已沉淀": "Created",+ "memory:已删除": "Deleted",+ "memory:已被取代": "Superseded",+ "memory:状态待核对": "Status needs review",+ "memory:编辑": "Edit",+ "memory:原始依据": "Original evidence",+ "memory:这段原文当前不可查看。":+ "This original text is currently unavailable.",+ "memory:版本记录": "Version history",+ "memory:更多管理": "More actions",+ "memory:撤销上次修改": "Undo last change",+ "memory:删除记忆": "Delete memory",+ "memory:编辑记忆": "Edit memory",+ "memory:返回记忆": "Back to memory",+ "memory:修改这条记忆,原始对话保持不变。":+ "Edit this memory; the original conversation stays unchanged.",+ "memory:记忆内容": "Memory content",+ "memory:使用范围保持不变": "Access scope stays unchanged",+ "memory:已有新版本": "A newer version exists",+ "memory:你的草稿已保留,先查看新版本再决定如何修改。":+ "Your draft is retained. Review the new version before making changes.",+ "memory:查看新版本": "View new version",+ "memory:基于此版本继续编辑": "Continue editing from this version",+ "memory:取消": "Cancel",+ "memory:保存": "Save",+ "memory:重试": "Retry",+ "memory:删除": "Delete",+ "memory:对话": "Conversation",+ "memory:保存修改": "Save changes",+ "memory:对应记忆": "Related memory",+ "memory:查看记忆": "View memories",+ "memory:删除这条记忆?": "Delete this memory?",+ "memory:删除后不再用于新的召回,来源 App 中的原始对话不会删除。":+ "It will no longer be used for new lookups. Original conversations in the source app will not be deleted.",+ "memory:已经发送给应用的内容无法远程收回。":+ "Content already sent to apps cannot be recalled remotely.",+ "memory:放弃尚未保存的修改?": "Discard unsaved changes?",+ "memory:来源权限已变化或原文不可用。":+ "Source permissions changed or the original text is unavailable.",+ "memory:暂时无法读取新版本,草稿已保留。":+ "Could not load the new version. Your draft is retained.",+ "memory:修改未提交;草稿已保留。请按提示修正后重试。":+ "Changes were not submitted; your draft is retained. Fix the issue and retry.",+ "memory:修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。":+ "Changes are unconfirmed; your draft is retained. Refresh and check before retrying to avoid a duplicate submission.",+ "memory:删除未提交。请核对这条记忆的状态后重试。":+ "Deletion was not submitted. Check this memory's status before retrying.",+ "memory:删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。":+ "Deletion is unconfirmed. Check the memory's status; the deletion scope will not expand automatically.",+ "memory:撤销未提交。请按提示修正后重试。":+ "Undo was not submitted. Fix the issue and retry.",+ "memory:撤销尚未确认,请先核对当前记忆版本,避免重复撤销。":+ "Undo is unconfirmed. Check the current memory version before retrying to avoid undoing twice.",+ "memory:添加记忆": "Add memory",+ "memory:关闭新增记忆": "Close add-memory dialog",+ "memory:关闭": "Close",+ "memory:记下这件事": "Write it down",+ "memory:例如:项目周会不排在周五。":+ "For example: Do not schedule the project meeting on Fridays.",+ "memory:整理模型:": "Processing model: ",+ "memory:尚未配置,原话仍可保存":+ "Not configured; you can still save the original",+ "memory:正在读取": "Loading",+ "memory:配置模型": "Configure model",+ "memory:保存中…": "Saving…",+ "memory:保存原话": "Save original",+ "memory:最近添加": "Recently added",+ "memory:原话已保存,等待可用模型":+ "Original saved; waiting for an available model",+ "memory:原话已保存,等待整理": "Original saved; waiting for processing",+ "memory:正在整理": "Processing",+ "memory:原话已保存,整理未完成": "Original saved; processing incomplete",+ "memory:整理已完成": "Processing complete",+ "memory:原话已保存,未提取出可用记忆":+ "Original saved; no usable memory extracted",+ "memory:最近添加的内容读取失败。": "Could not read recently added notes.",+ "memory:整理状态暂时不可用,原话已保存。":+ "Processing status is temporarily unavailable; the original is saved.",+ "memory:已保存,正在后台沉淀记忆":+ "Saved; creating memories in the background",+ "memory:未能确认保存结果,输入已保留。重试不会重复添加。":+ "Could not confirm the save result. Your text is retained; retrying will not add a duplicate.",+ "memory:整理未能开始,原话仍已保存。":+ "Processing could not start; the original is still saved.",+ "memory:整理结果尚未确认,原话仍已保存。请刷新后核对。":+ "Processing is not yet confirmed; the original is saved. Refresh to check.",+ "memory:模型服务要求检查余额或付款状态,原话仍已保存。":+ "The model service requires a balance or payment check; the original remains saved.",+ "memory:这台设备打不开 3D 视图,已显示关联列表。":+ "3D view is unavailable on this device. Showing the connections as a list.",+ "memory:图谱工具": "Graph controls",+ "memory:放大": "Zoom in",+ "memory:放大图谱": "Zoom in on graph",+ "memory:缩小": "Zoom out",+ "memory:缩小图谱": "Zoom out of graph",+ "memory:重置视角": "Reset view",+ "memory:重置图谱视角": "Reset graph view",+ "memory:查看读取详情": "View read details",+ "memory:原文暂时无法读取": "Could not load original text",+ "memory:暂时无法读取这段对话,已保留当前记忆。":+ "Could not load this conversation. The current memory remains selected.",+ "memory:已清除筛选,定位到关联记忆。":+ "Filters cleared to find the related memory.",+ "memory:所选记忆不在当前筛选内,已取消选择。":+ "The selected memory is not in this filter; selection cleared.",+ "memory:列表分隔符": ", ",+ "memory:冒号": ":",+ "memory:手动添加": "Added manually",+ "memory:导入的已有记忆": "Imported existing memory",+ "memory:记忆与原文": "Memories and original text",+ "memory:第 {revision} 版": "Version {revision}",+ "memory:对话时间 ": "Conversation time",+ "memory:沉淀时间 ": "Created at",+ "memory:原对话 ": "Original conversation ",+ "memory:{count} 条记录没有原始时间,未用导入时间代替。":+ "{count} records have no original timestamp; import time was not substituted.",+ "memory:作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。":+ "Author counts reflect saved records, not completed memory extraction or verified meaning.",+ "memory:统计于 ": "Statistics as of ",+ "memory: · 导入数量仍在更新,可刷新核对":+ " · Import count is still updating; refresh to check",+ "memory:对话于 {day}": "Conversation on {day}",+ "memory:导入于 {day}": "Imported on {day}",+ "memory:已开始处理所选对话": "Processing selected conversations",+ "memory:处理请求已受理": "Processing request received",+ "memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":+ "Model connection confirmed. Memories will appear in the list as they are created.",+ "memory:已导入 {count} 段对话,整理成记忆后会出现在这里。":+ "Imported {count} conversations. Memories will appear here after processing.",+ "memory:历史已保存在本机,记忆就绪后会出现在这里。":+ "History is saved on this device. Memories will appear here when ready.",+ "memory:连接应用并导入历史后,可以开始沉淀记忆。":+ "Connect an app and import history to start creating memories.",+ "memory:当前已生成 0 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。":+ "No memories created yet. A received request is not complete; original conversations, processing jobs and memories are counted separately.",+ "memory:返回应用": "Back to apps",+ "memory:共 {count} 条 · 正在核对来源…": "{count} total · Checking sources…",+ "memory:共 {count} 条 · 正在核对来源….one":+ "{count} total · Checking sources…",+ "memory:共 {count} 条": "{count} items total",+ "memory:共 {count} 条.one": "{count} items total",+ "memory: · 正在核对…": " · Checking…",+ "memory:新增 {count} 条记忆": "{count} new memories",+ "memory:新增 {count} 条记忆.one": "{count} new memories",+ "memory:沉淀于 ": "Created at ",+ "memory:共 {count} 条,第 {page} / {pages} 页":+ "{count} total · Page {page} of {pages}",+ "memory:共 {count} 条,第 {page} / {pages} 页.one":+ "{count} total · Page {page} of {pages}",+ "memory:已沉淀 {count} 条记忆": "{count} memories created",+ "memory:已沉淀 {count} 条记忆.one": "{count} memories created",+ "memory:关键词“{query}”": "Keyword “{query}”",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条":+ "{count} memories created{filter} · Showing {shown}",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条.one":+ "{count} memories created{filter} · Showing {shown}",+ "memory:({filter})": " ({filter})",+ "memory:第 {page} 页": "Page {page}",+ "memory:原话已保存,正在等待整理:":+ "Original text saved, awaiting processing: ",+ "memory:记忆未在生成": "Memories are not being created",+ "memory:还没有开始生成记忆:{reason}({count} 条待处理)":+ "Memories are not being created: {reason} ({count} pending)",+ "memory:去配置生成模型": "Configure generation model",+ "calls.directHost": "Direct call (diagnostic)",+ "calls.headline.timedOut": "{host} could not look up memories in time",+ "calls.headline.unavailable": "{host} could not look up memories right now",+ "calls.headline.denied": "{host} was not authorized to look up memories",+ "calls.headline.empty": "{host} found no matching memories",+ "calls.headline.found": "{host} found {count} related items",+ "calls.headline.found.one": "{host} found {count} related items",+ "calls.detail.timedOut":+ "Memories are being processed. The lookup timed out, so this answer did not include memories.",+ "calls.detail.unavailable":+ "MemHub is temporarily unavailable, so this answer did not include memories.",+ "calls.detail.denied": "Current permissions do not allow this lookup.",+ "calls.detail.partialDelivered":+ "Provided to {host} · some content is still being processed",+ "calls.detail.partial": "Some content is still being processed",+ "calls.detail.delivered": "Provided to {host}",+ "calls.detail.notDelivered": "Not provided to the app",+ "calls.detail.empty": "No matching memories this time",+ "calls.detail.success": "Lookup succeeded",+ "calls.title": "Usage history",+ "calls.query": "This memory lookup",+ "calls.backApps": "Back to apps",+ "calls.backHistory": "Back to history",+ "calls.filter": "Filter by app",+ "calls.allApps": "All apps",+ "calls.recent": "Recent history",+ "calls.refresh": "Refresh history",+ "calls.clearPage": "Clear this page",+ "calls.clearAll": "Clear all history",+ "calls.clearAllShort": "Clear all",+ "calls.loading": "Loading usage history",+ "calls.clearing": "Clearing selected history",+ "calls.readFailed": "Could not load history. Refresh and try again.",+ "calls.unavailable": "Usage history is unavailable. Refresh later.",+ "calls.incomplete":+ "Some calls were not recorded; the list may be incomplete.",+ "calls.callDetail": "Call details",+ "calls.source": " · Source: {source}",+ "calls.stats":+ "Found {raw} original passages · {memories} memories · {seconds} seconds",+ "calls.metadata": "Record details",+ "calls.privacy":+ "For privacy, your original question and the answer are not stored here; only the time, source and result are kept.",+ "calls.exactTime": "Exact time",+ "calls.app": "Apps",+ "calls.type": "Type",+ "calls.result": "Result status",+ "calls.tool": "Look up memories",+ "calls.notRecorded": "Not recorded",+ "calls.missingRow":+ "This record is no longer on this page. Return to history to find it.",+ "calls.list": "Call history",+ "calls.emptyPage": "No records on this page",+ "calls.empty": "No usage history yet",+ "calls.pagination": "History pages",+ "calls.previous": "Previous page",+ "calls.next": "Next page",+ "calls.policy": "Kept for {days} days, up to {count} records",+ "calls.confirmAllTitle": "Clear all usage history?",+ "calls.confirmPageTitle": "Clear {count} records on this page?",+ "calls.confirmPageTitle.one": "Clear {count} records on this page?",+ "calls.confirmAllDescription":+ "Delete all retained call records, not only this page or filter. Original conversations and memories, permissions and retention rules are unchanged. This cannot be undone.",+ "calls.confirmPageDescription":+ "Delete only these call records. Original conversations and memories, permissions and retention rules are unchanged. This cannot be undone.",+ "calls.confirmAll": "Confirm clear all",+ "calls.confirmPage": "Confirm clear",+ "calls.cancel": "Cancel",+ "calls.clearedAll": "All history was cleared.",+ "calls.clearedPage": "Selected history was cleared.",+ "calls.clearAllFailed":+ "Could not clear usage history. Existing records are unchanged; check and retry.",+ "calls.clearPageFailed":+ "Could not clear selected history. Existing records are unchanged; check and retry.",+ "calls.clearUnknown":+ "Could not confirm the result. Check the reloaded history; clearing was not retried automatically.",+ "calls.references": "Related content",+ "calls.referencesLoading": "Loading related content",+ "calls.referencesFailed":+ "Could not load related content. Refresh and try again.",+ "calls.raw": "Original conversation",+ "calls.memory": "Memories",+ "calls.changed": "Version changed",+ "calls.pending": "Needs review",+ "calls.notAvailable": "Unavailable",+ "calls.openRaw": "View original conversation",+ "calls.openMemory": "View memories",+ "calls.noReferences": "No related content found",+ "calls.rawBody": "Original conversation text",+ "calls.rawLoading": "Loading original conversation",+ "calls.rawFailed":+ "The original conversation is unavailable or its version has changed.",+ "calls.state.grounded": "Lookup succeeded",+ "calls.state.empty": "Lookup succeeded; no matching memories",+ "calls.state.partial":+ "Lookup succeeded; some content is still being processed",+ "calls.state.timed_out": "Lookup timed out; no memories provided",+ "calls.state.unavailable": "MemHub is temporarily unavailable",+ "calls.state.denied": "This lookup is not authorized",+ "calls.return.timed_out":+ "MemHub is importing and processing memories. The lookup did not finish in time, so {host} answered without memories. It will resume once processing is complete.",+ "calls.return.unavailable":+ "MemHub is temporarily unavailable; this answer did not include memories.",+ "calls.return.denied":+ "Current permissions do not allow this lookup; no memories were provided to the app.",+ "calls.return.partial": "Some content is still being processed.",+ "clock.unknown": "Time unknown",+ "clock.today": "Today {clock}",+ settings: "Settings",+ languageTitle: "Interface language",+ languageLabel: "Language",+ languageSystem: "Use system language",+ languageChinese: "Simplified Chinese",+ languageEnglish: "English",+ languageSpanish: "Spanish",+ languageDescription:+ "Choose the interface language. This setting does not change your conversations or memories.",+ languageSaveError: "Could not save the language setting. Please retry.",+ languageLoadError: "Could not load the language setting. Please retry.",+ nativeErrorTitle: "MemHub could not start",+ startupPreparing: "Starting and preparing the memory service…",+} as const;++export const englishMessages = {+ ...baseEnglishMessages,+ ...currentEnglishMessages,+} as const;diff --git a/memhub/packages/i18n/src/gui-i18n-guide.ts b/memhub/packages/i18n/src/gui-i18n-guide.tsnew file mode 100644index 0000000..f0f5823--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-guide.ts@@ -0,0 +1,215 @@+/** Presentation-only guide copy. Original memories and generated handoff drafts stay untouched. */+export const guideChineseMessages = {+ guideEyebrow: "上手体验",+ guideTitle: "让下一次对话接得上",+ guideBack: "返回记忆",+ guideChooseScene: "选择使用场景",+ guideSame: "新对话接着做",+ guideSameDescription: "同一个应用,换个会话,仍能找回之前的决定。",+ guideSwitch: "换个应用继续",+ guideSwitchDescription: "工作没有换,只是换了一个 AI。先把相关背景接上。",+ guideNew: "让新工具了解我",+ guideNewDescription: "从你愿意提供的一条背景开始,不必从头自我介绍。",+ guideReadError: "暂时无法读取记忆,可稍后重试。",+ guideDetailError: "这条记忆暂不可读,请换一条或刷新。",+ guideChanged: "记忆内容或授权已变化,请刷新后重新核对。",+ guideConnectionChanged: "连接状态已变化,尚未复制。请重新选择方式。",+ guideCopiedOpened: "已复制并请求打开 {host}。尚未发送,请核对输入框。",+ guideCopiedNotFilled: "已完整复制,未能预填。可在目标应用粘贴,尚未发送。",+ guideCopiedNotOpened: "已完整复制,但未能打开目标应用。尚未发送。",+ guideCopied: "已完整复制。尚未发送,也没有新增读取授权。",+ guideValidationError: "无法核对当前记忆与授权,旧预览已收起。请刷新后重试。",+ guideCopyError: "未能核对最新内容或完成复制。请重试;没有打开目标应用。",+ guideManual: "端内添加",+ guideOriginalApp: "原应用",+ guideListSeparator: "、",+ guideSaved: "本机已保存 {count} 条原始消息 · ",+ "guideSaved.one": "本机已保存 {count} 条原始消息 · ",+ guideReadingMemories: "正在读取已整理记忆",+ guideLoaded: "本页已加载 {count} 条可用记忆",+ "guideLoaded.one": "本页已加载 {count} 条可用记忆",+ guideSeparate: "。两个阶段分别计数。",+ guideChooseBackground: "选择背景",+ guideCheckSources: "核对来源",+ guideTry: "到新对话试用",+ guideLoading: "正在读取本机已有记忆…",+ guideEmptyTitle: "先留下一条真正有用的背景",+ guideEmptyDescription:+ "目前没有可用于这次体验的记忆。已导入的原文不等于已经整理好;候选内容也不会被自动带出。",+ guideAdd: "去添加记忆",+ guideConnections: "查看导入与连接",+ guideRefresh: "刷新",+ guideBackgroundTitle: "这次用到的背景",+ guideRefreshExample: "刷新示例",+ guideChooseMemory: "选择一条记忆",+ guideLoadedScope: "从当前已加载的 {count} 条可用记忆中选择,不代表全部历史。",+ "guideLoadedScope.one":+ "从当前已加载的 {count} 条可用记忆中选择,不代表全部历史。",+ guideCheckingEvidence: "正在核对原始依据…",+ guideRevision: "{source} · 版本 {revision} · 系统整理,需你核对",+ guideScope: "适用范围:",+ guideAllApps: "已设为跨应用可用,不等于个人偏好",+ guidePrivate: "已停止外部记忆召回;手动带出需另行确认",+ guideLimited: "限定范围,未扩大外部召回范围",+ guideEvidence: "原始依据 · {count} 段",+ "guideEvidence.one": "原始依据 · {count} 段",+ guideUnknownSource: "未知来源",+ guideYou: "你",+ guideUnknownAuthor: "作者未识别",+ guideUnknownTime: "时间未知",+ guideUnavailable:+ "原文或当前授权不可用。换一条背景或刷新后再试,不会带出这条内容。",+ guideDraftTitle: "下一段对话的开场白",+ guideChooseApp: "在哪个应用试用",+ guideCopyOnly: "自行选择应用 · 仅复制",+ guideHostsError: "暂时无法读取连接状态,可重试或仅复制背景。",+ guideNoApp: "尚未选择已连接的应用。手动带入不等于安装连接。",+ guideWired: "上次自检可达,本次是否用对仍需核对。",+ guideInstalled: "已安装连接,尚未验证读取。",+ guideNotInstalled: "尚未安装读取连接。",+ guideManage: "管理应用连接",+ guideChooseRoute: "选择带入方式",+ guideContext: "带入背景",+ guideQuery: "让应用查询",+ guideTopic: "要接续的主题",+ guideQueryHint: "只带查询,不把上方的预期答案塞进新会话。",+ guideNewHint: "仅带你选择的这一条,不自动生成个人画像。",+ guideContextHint: "完整带入这一条背景与引用;这不是自动召回测试。",+ guidePreview: "开场白完整预览",+ guidePreviewPlaceholder: "原始依据可用后显示开场白",+ guideChecking: "正在核对…",+ guideCopy: "复制开场白",+ guideCopyOpen: "复制并打开 {host}",+ guideNoReceipt: "尚无本次外部调用回执。新对话是否引用了正确的背景?",+ guideVerified: "我已核对结果",+ guideMissing: "没有找回来",+ guideFeedbackOk: "你的反馈:已核对。这不是系统自动验收记录。",+ guideFeedbackMissing:+ "你的反馈:没有找回来。先检查来源是否导入、记忆范围与应用连接。",+ guideInvitation: "上手体验邀请",+ guideInvitationHint: "用一条自己的记忆,试着接续下一次对话。",+ guideTryOnce: "试一次",+ guideLater: "稍后再看",+ guideDismiss: "关闭上手邀请",+} as const;+export const guideSpanishMessages: Record<+ keyof typeof guideChineseMessages,+ string+> = {+ guideEyebrow: "Primeros pasos",+ guideTitle: "Retoma tu próxima conversación",+ guideBack: "Volver a memorias",+ guideChooseScene: "Elegir un escenario",+ guideSame: "Continuar en una conversación nueva",+ guideSameDescription:+ "Recupera decisiones anteriores en una conversación nueva de la misma aplicación.",+ guideSwitch: "Continuar en otra aplicación",+ guideSwitchDescription:+ "El trabajo es el mismo; solo cambia la IA. Incorpora primero el contexto relevante.",+ guideNew: "Darte a conocer a una herramienta nueva",+ guideNewDescription:+ "Empieza por el contexto que quieras compartir, sin tener que presentarte desde cero.",+ guideReadError: "No se pudieron leer las memorias. Inténtalo más tarde.",+ guideDetailError: "Esta memoria no se puede leer. Elige otra o actualiza.",+ guideChanged:+ "La memoria o los permisos cambiaron. Actualiza y vuelve a comprobarlos.",+ guideConnectionChanged:+ "La conexión cambió; no se copió nada. Vuelve a elegir el método.",+ guideCopiedOpened:+ "Se copió y se solicitó abrir {host}. No se envió; revisa el campo de entrada.",+ guideCopiedNotFilled:+ "Se copió todo, pero no se pudo rellenar el campo. Puedes pegarlo en la aplicación; no se envió.",+ guideCopiedNotOpened:+ "Se copió todo, pero no se pudo abrir la aplicación de destino. No se envió.",+ guideCopied:+ "Se copió todo. No se envió ni se concedieron permisos de lectura nuevos.",+ guideValidationError:+ "No se pudieron verificar la memoria y los permisos actuales. Se ocultó la vista previa anterior; actualiza e inténtalo de nuevo.",+ guideCopyError:+ "No se pudo verificar o copiar el contenido actualizado. Inténtalo de nuevo; no se abrió la aplicación de destino.",+ guideManual: "Añadido en la aplicación",+ guideOriginalApp: "Aplicación original",+ guideListSeparator: ", ",+ guideSaved: "{count} mensajes originales guardados localmente · ",+ "guideSaved.one": "{count} mensaje original guardado localmente · ",+ guideReadingMemories: "Leyendo las memorias procesadas",+ guideLoaded: "{count} memorias disponibles cargadas en esta página",+ "guideLoaded.one": "{count} memoria disponible cargada en esta página",+ guideSeparate: ". Ambas etapas se cuentan por separado.",+ guideChooseBackground: "Elegir contexto",+ guideCheckSources: "Revisar orígenes",+ guideTry: "Probar en una conversación nueva",+ guideLoading: "Leyendo las memorias locales…",+ guideEmptyTitle: "Guarda primero un contexto realmente útil",+ guideEmptyDescription:+ "No hay memorias disponibles para esta prueba. Importar los originales no significa que ya estén procesados; los candidatos tampoco se compartirán automáticamente.",+ guideAdd: "Añadir una memoria",+ guideConnections: "Ver importaciones y conexiones",+ guideRefresh: "Actualizar",+ guideBackgroundTitle: "Contexto para esta prueba",+ guideRefreshExample: "Actualizar ejemplo",+ guideChooseMemory: "Elegir una memoria",+ guideLoadedScope:+ "Elige entre las {count} memorias disponibles cargadas; no representan todo el historial.",+ "guideLoadedScope.one":+ "Solo hay {count} memoria disponible cargada; no representa todo el historial.",+ guideCheckingEvidence: "Verificando los originales…",+ guideRevision:+ "{source} · revisión {revision} · organizado por el sistema; debes revisarlo",+ guideScope: "Alcance: ",+ guideAllApps:+ "Disponible entre aplicaciones; no implica una preferencia personal",+ guidePrivate:+ "Recuperación externa detenida; compartir manualmente requiere otra confirmación",+ guideLimited: "Alcance limitado; no se amplió la recuperación externa",+ guideEvidence: "Originales · {count} fragmentos",+ "guideEvidence.one": "Originales · {count} fragmento",+ guideUnknownSource: "Origen desconocido",+ guideYou: "Tú",+ guideUnknownAuthor: "Autor sin identificar",+ guideUnknownTime: "Fecha desconocida",+ guideUnavailable:+ "El original o el permiso actual no están disponibles. Elige otro contexto o actualiza; este contenido no se compartirá.",+ guideDraftTitle: "Mensaje inicial de la próxima conversación",+ guideChooseApp: "Aplicación para la prueba",+ guideCopyOnly: "Elegir aplicación manualmente · solo copiar",+ guideHostsError:+ "No se pudo leer la conexión. Reintenta o copia solo el contexto.",+ guideNoApp:+ "No se seleccionó una aplicación conectada. Incorporar contexto manualmente no instala una conexión.",+ guideWired:+ "La última comprobación tuvo éxito; aún debes revisar que se use correctamente.",+ guideInstalled: "Conexión instalada; lectura todavía sin verificar.",+ guideNotInstalled: "La conexión de lectura no está instalada.",+ guideManage: "Administrar conexiones de aplicaciones",+ guideChooseRoute: "Elegir cómo incorporar el contexto",+ guideContext: "Incorporar contexto",+ guideQuery: "Pedir a la aplicación que consulte",+ guideTopic: "Tema que quieres retomar",+ guideQueryHint:+ "Incluye solo la consulta, no la respuesta esperada de arriba.",+ guideNewHint:+ "Solo se incluye la memoria elegida; no se crea un perfil personal automáticamente.",+ guideContextHint:+ "Incluye este contexto completo y sus referencias; no es una prueba de recuperación automática.",+ guidePreview: "Vista previa del mensaje inicial completo",+ guidePreviewPlaceholder:+ "El mensaje inicial aparecerá cuando estén disponibles los originales",+ guideChecking: "Verificando…",+ guideCopy: "Copiar mensaje inicial",+ guideCopyOpen: "Copiar y abrir {host}",+ guideNoReceipt:+ "No hay un recibo de llamada externa para esta prueba. ¿La nueva conversación citó el contexto correcto?",+ guideVerified: "Ya revisé el resultado",+ guideMissing: "No lo recuperó",+ guideFeedbackOk:+ "Tu respuesta: revisado. Esto no es una verificación automática del sistema.",+ guideFeedbackMissing:+ "Tu respuesta: no se recuperó. Comprueba la importación del origen, el alcance de la memoria y la conexión de la aplicación.",+ guideInvitation: "Invitación a primeros pasos",+ guideInvitationHint:+ "Prueba a retomar la próxima conversación con una memoria tuya.",+ guideTryOnce: "Probar",+ guideLater: "Ver más tarde",+ guideDismiss: "Cerrar invitación",+};diff --git a/memhub/packages/i18n/src/gui-i18n-health-guide.test.ts b/memhub/packages/i18n/src/gui-i18n-health-guide.test.tsnew file mode 100644index 0000000..545671a--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-health-guide.test.ts@@ -0,0 +1,30 @@+import { expect, it } from "vitest";+import { type MessageKey, translate } from "./gui-i18n.js";+import {+ guideChineseMessages,+ guideSpanishMessages,+} from "./gui-i18n-guide.js";+import {+ healthChineseMessages,+ healthSpanishMessages,+} from "./gui-i18n-health.js";++it("covers every health and guide key without accidental Chinese fallback", () => {+ const params = (message: string) =>+ [...message.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)]+ .map((match) => match[1])+ .sort();+ for (const [chinese, spanish] of [+ [healthChineseMessages, healthSpanishMessages],+ [guideChineseMessages, guideSpanishMessages],+ ]) {+ expect(Object.keys(spanish).sort()).toEqual(Object.keys(chinese).sort());+ for (const [key, value] of Object.entries(chinese)) {+ const translated = spanish[key as keyof typeof spanish];+ expect(translated, key).toBeTruthy();+ expect(params(translated), key).toEqual(params(value));+ expect(translate("es", key as MessageKey), key).toBe(translated);+ expect(translate("zh-CN", key as MessageKey), key).toBe(value);+ }+ }+});diff --git a/memhub/packages/i18n/src/gui-i18n-health.ts b/memhub/packages/i18n/src/gui-i18n-health.tsnew file mode 100644index 0000000..90e50e3--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-health.ts@@ -0,0 +1,147 @@+export const healthChineseMessages = {+ healthTitle: "运行诊断",+ healthLocal: "本地服务",+ healthBackground: "后台服务",+ healthSources: "各来源累计条数",+ healthProcessing: "记忆提炼",+ healthHosts: "AI 接通情况",+ healthDetailed: "详细日志",+ healthDetailedTitle: "详细日志(排查用)",+ healthDetailedHint: "默认关闭。仅在开发人员请你协助排查时开启。",+ healthDetailedError: "详细日志设置失败,请重试。",+ healthRefresh: "重新读取状态",+ healthIncident: "记录问题时间点",+ healthIncidentDesktop: "请在桌面 App 中记录问题时间点。",+ healthIncidentPrompt: "简单描述刚才遇到的问题(可不填)",+ healthIncidentCopied: "问题编号已复制:{id}",+ healthIncidentError: "问题时间点未能记录,请重试。",+ healthReadFailed: "暂时无法读取",+ healthStale: " · 数据已过期,以下为上次读取结果。",+ healthReading: "正在读取状态…",+ healthRereading: "正在重新读取,以下为上次读取结果…",+ healthReadSuccessTime: "上次成功读取",+ healthReadFailedTime: "读取失败时间",+ healthReadingSources: "正在读取本地服务与来源状态…",+ healthPrevious: "上次读取",+ healthPreviousPrefix: "上次读取:",+ healthRunning: "运行中",+ healthCoreVersion: "{state} · 版本 {version} · 实例 {instance}",+ healthCoreDisconnected: "还没连上本地 Core。",+ healthBackgroundUnavailable:+ "当前环境无法检查后台服务,请在支持此功能的桌面 App 中查看。",+ healthRuntime: "Core:{core} · 宿主桥接:{broker}",+ healthSourceCount: "{conversations} 个会话 · {messages} 条消息",+ healthNoSources: "还没有已连接的来源。",+ healthTaskCounts:+ "{running} 处理中 · {pending} 排队 · {completed} 已完成 · {failed} 失败",+ healthImportDetails: "导入与整理详情",+ healthRawTurns: "原文与完整对话轮次",+ healthRawCounts: "{raw} 条原文 · {turns} 个完整 turn",+ healthHy: "HY 整理",+ healthHyCounts:+ "{calls} 次调用 · {completed} 完成 · {unknown} 结果不确定 · {failed} 失败 · {cancelled} 取消",+ healthOutput: "产出",+ healthMemories: "{count} 条记忆",+ "healthMemories.one": "{count} 条记忆",+ healthWorkbuddy: "WorkBuddy 查记忆",+ healthWorkbuddyCounts:+ "{injected} 次注入 · {timedOut} 次超时 · {unavailable} 次不可用",+ healthBlocked: "{kind}卡在 {reason}({count} 条)",+ healthRetrying: "{count} 条这次没能整理成功,正在重试",+ "healthRetrying.one": "{count} 条这次没能整理成功,正在重试",+ healthNoIssues: "暂无需要处理的问题。",+ healthHostsUnavailable: "在浏览器里读不到;请在桌面 App 里查看。",+ healthNoHosts: "本机没有检测到可接入的 AI 工具。",+ healthBackgroundHealthy: "后台服务可用",+ healthBackgroundStopped: "后台服务已停止",+ healthBackgroundDegraded: "后台服务部分不可用",+ healthBackgroundUntrusted: "后台服务身份未通过核验",+ healthBackgroundUnknown: "后台状态尚未确认",+ healthStopped: "已停止",+ healthUnhealthy: "无法连接",+ healthUntrusted: "身份未通过核验",+ healthUnknown: "尚未确认",+ healthNotChecked: "未检查",+ healthWired: "已接通",+ healthBlind: "已安装,但取不到记忆",+ healthUnreachable: "未接通",+} as const;++export const healthSpanishMessages: Record<+ keyof typeof healthChineseMessages,+ string+> = {+ healthTitle: "Diagnóstico",+ healthLocal: "Servicio local",+ healthBackground: "Servicio en segundo plano",+ healthSources: "Totales por origen",+ healthProcessing: "Procesamiento de memorias",+ healthHosts: "Conexiones de IA",+ healthDetailed: "Registros detallados",+ healthDetailedTitle: "Registros detallados (diagnóstico)",+ healthDetailedHint:+ "Desactivados de forma predeterminada. Actívalos solo si el equipo de desarrollo te pide ayuda para diagnosticar un problema.",+ healthDetailedError:+ "No se pudieron cambiar los registros detallados. Inténtalo de nuevo.",+ healthRefresh: "Volver a leer el estado",+ healthIncident: "Registrar el momento del problema",+ healthIncidentDesktop:+ "Registra el momento del problema desde la aplicación de escritorio.",+ healthIncidentPrompt: "Describe brevemente el problema (opcional)",+ healthIncidentCopied: "Identificador del problema copiado: {id}",+ healthIncidentError:+ "No se pudo registrar el momento del problema. Inténtalo de nuevo.",+ healthReadFailed: "No se pudo leer el estado",+ healthStale:+ " · Los datos están desactualizados; se muestra la última lectura.",+ healthReading: "Leyendo el estado…",+ healthRereading: "Volviendo a leer; se muestra la lectura anterior…",+ healthReadSuccessTime: "Última lectura correcta",+ healthReadFailedTime: "Hora de la lectura fallida",+ healthReadingSources: "Leyendo el servicio local y los orígenes…",+ healthPrevious: "Lectura anterior",+ healthPreviousPrefix: "Lectura anterior: ",+ healthRunning: "En ejecución",+ healthCoreVersion: "{state} · versión {version} · instancia {instance}",+ healthCoreDisconnected: "Aún no se conectó con Core local.",+ healthBackgroundUnavailable:+ "No se puede comprobar el servicio en este entorno. Usa una aplicación de escritorio compatible.",+ healthRuntime: "Core: {core} · puente de aplicaciones: {broker}",+ healthSourceCount: "{conversations} conversaciones · {messages} mensajes",+ healthNoSources: "Todavía no hay orígenes conectados.",+ healthTaskCounts:+ "{running} en proceso · {pending} en espera · {completed} completadas · {failed} fallidas",+ healthImportDetails: "Detalles de importación y procesamiento",+ healthRawTurns: "Originales y turnos completos",+ healthRawCounts: "{raw} originales · {turns} turnos completos",+ healthHy: "Procesamiento HY",+ healthHyCounts:+ "{calls} llamadas · {completed} completadas · {unknown} sin confirmar · {failed} fallidas · {cancelled} canceladas",+ healthOutput: "Resultados",+ healthMemories: "{count} memorias",+ "healthMemories.one": "{count} memoria",+ healthWorkbuddy: "Consultas de WorkBuddy",+ healthWorkbuddyCounts:+ "{injected} incorporaciones · {timedOut} tiempos agotados · {unavailable} no disponibles",+ healthBlocked: "{kind}: bloqueo por {reason} ({count})",+ healthRetrying: "{count} no se pudieron procesar esta vez; reintentando",+ "healthRetrying.one": "{count} no se pudo procesar esta vez; reintentando",+ healthNoIssues: "No hay problemas pendientes.",+ healthHostsUnavailable:+ "No se puede leer desde el navegador; consulta la aplicación de escritorio.",+ healthNoHosts:+ "No se detectaron herramientas de IA compatibles en este equipo.",+ healthBackgroundHealthy: "Servicio en segundo plano disponible",+ healthBackgroundStopped: "Servicio en segundo plano detenido",+ healthBackgroundDegraded: "Servicio en segundo plano parcialmente disponible",+ healthBackgroundUntrusted: "No se pudo verificar la identidad del servicio",+ healthBackgroundUnknown: "Estado en segundo plano sin confirmar",+ healthStopped: "Detenido",+ healthUnhealthy: "Sin conexión",+ healthUntrusted: "Identidad sin verificar",+ healthUnknown: "Sin confirmar",+ healthNotChecked: "Sin comprobar",+ healthWired: "Conectada",+ healthBlind: "Instalada, sin acceso a memorias",+ healthUnreachable: "Sin conectar",+};diff --git a/memhub/packages/i18n/src/gui-i18n-memory.ts b/memhub/packages/i18n/src/gui-i18n-memory.tsnew file mode 100644index 0000000..83ee152--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-memory.ts@@ -0,0 +1,787 @@+// Memory screens copy. Keys are "memory:" plus the exact Chinese interface+// text, so existing consumers keep passing Chinese strings without colliding+// with other catalogs. Imported content must never be looked up here.+export const memoryChineseMessages = {+ "memory:记忆抽取": "记忆抽取",+ "memory:关系归纳": "关系归纳",+ "memory:深度整理": "深度整理",+ "memory:跨域整理": "跨域整理",+ "memory:当前模型已变化": "当前模型已变化",+ "memory:本地会话内容已变化": "本地会话内容已变化",+ "memory:这段对话含过长原文,暂未整理;原文已保留":+ "这段对话含过长原文,暂未整理;原文已保留",+ "memory:记忆库分页": "记忆库分页",+ "memory:上一页": "上一页",+ "memory:下一页": "下一页",+ "memory:等待可用生成模型": "等待可用生成模型",+ "memory:还没有启用生成模型": "还没有启用生成模型",+ "memory:缺少生成模型 API Key": "缺少生成模型 API Key",+ "memory:模型凭据暂不可用": "模型凭据暂不可用",+ "memory:本机凭据存储暂不可用": "本机凭据存储暂不可用",+ "memory:需要授权访问本机钥匙串。请重新打开 App 并完成一次授权":+ "需要授权访问本机钥匙串。请重新打开 App 并完成一次授权",+ "memory:读取本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "读取本机钥匙串超时。重新保存一遍模型配置即可恢复",+ "memory:写入本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "写入本机钥匙串超时。重新保存一遍模型配置即可恢复",+ "memory:模型认证失败。更新 key 后,到设置里点一次检测,会自动接着处理":+ "模型认证失败。更新 key 后,到设置里点一次检测,会自动接着处理",+ "memory:模型账户余额不足。充值或换 key 后,到设置里点一次检测,会自动接着处理":+ "模型账户余额不足。充值或换 key 后,到设置里点一次检测,会自动接着处理",+ "memory:模型服务拒绝访问。更新权限后,到设置里点一次检测,会自动接着处理":+ "模型服务拒绝访问。更新权限后,到设置里点一次检测,会自动接着处理",+ "memory:模型服务限流": "模型服务限流",+ "memory:模型服务暂不可用": "模型服务暂不可用",+ "memory:模型服务响应超时": "模型服务响应超时",+ "memory:模型请求不兼容,请核对配置": "模型请求不兼容,请核对配置",+ "memory:模型请求未成功": "模型请求未成功",+ "memory:HY Memory 不可用": "HY Memory 不可用",+ "memory:HY Memory 启动失败": "HY Memory 启动失败",+ "memory:暂时没能整理,稍后会自动重试": "暂时没能整理,稍后会自动重试",+ "memory:这次没能整理成功,正在重试": "这次没能整理成功,正在重试",+ "memory:生成模型换过了,这批会重新整理": "生成模型换过了,这批会重新整理",+ "memory:整理方式换过了,这批会重新整理": "整理方式换过了,这批会重新整理",+ "memory:已提炼": "已提炼",+ "memory:旧版确认记录": "旧版确认记录",+ "memory:创建": "创建",+ "memory:纠正": "纠正",+ "memory:调整使用范围": "调整使用范围",+ "memory:撤销修改": "撤销修改",+ "memory:模型更新": "模型更新",+ "memory:被新记忆取代": "被新记忆取代",+ "memory:其他操作": "其他操作",+ "memory:删除(记录)": "删除",+ "memory:修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ "memory:纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。",+ "memory:未收到操作结果,请重试。": "未收到操作结果,请重试。",+ "memory:批量处理结果已保留,但列表刷新失败,请重新读取记忆库。":+ "批量处理结果已保留,但列表刷新失败,请重新读取记忆库。",+ "memory:批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。":+ "批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。",+ "memory:召回范围已保存,但列表刷新失败。请稍后重新打开记忆页。":+ "召回范围已保存,但列表刷新失败。请稍后重新打开记忆页。",+ "memory:重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?":+ "重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?",+ "memory:原始对话暂时无法读取": "原始对话暂时无法读取",+ "memory:没有匹配的原始对话": "没有匹配的原始对话",+ "memory:还没有导入的原始对话": "还没有导入的原始对话",+ "memory:查看已读内容": "查看已读内容",+ "memory:已保存原文": "已保存原文",+ "memory:刷新已读内容": "刷新已读内容",+ "memory:正在核对本机已保存记录…": "正在核对本机已保存记录…",+ "memory:原始消息": "原始消息",+ "memory:会话": "会话",+ "memory:用户发言": "用户发言",+ "memory:Agent 发言": "Agent 发言",+ "memory:作者未知": "作者未知",+ "memory:原始时间未知": "原始时间未知",+ "memory:工具记录": "工具记录",+ "memory:原始时间来自已保存记录。": "原始时间来自已保存记录。",+ "memory:已保存的原文样例": "已保存的原文样例",+ "memory:最多展示 3 段,不代表全部历史或推荐记忆。":+ "最多展示 3 段,不代表全部历史或推荐记忆。",+ "memory:查看完整对话": "查看完整对话",+ "memory:原文较长,此处仅展示前 600 个字符。":+ "原文较长,此处仅展示前 600 个字符。",+ "memory:这个来源还没有保存原文。": "这个来源还没有保存原文。",+ "memory:完整对话": "完整对话",+ "memory:关闭完整对话": "关闭完整对话",+ "memory:用户": "用户",+ "memory:暂时无法读取已保存内容,旧回执已收起。请检查授权或重试。":+ "暂时无法读取已保存内容,旧回执已收起。请检查授权或重试。",+ "memory:这段原文暂不可读,可能已被撤回授权。请刷新回执。":+ "这段原文暂不可读,可能已被撤回授权。请刷新回执。",+ "memory:外部记忆召回范围": "外部记忆召回范围",+ "memory:外部记忆召回": "外部记忆召回",+ "memory:调整召回范围": "调整召回范围",+ "memory:所有关联工具": "所有关联工具",+ "memory:已停止外部记忆召回": "已停止外部记忆召回",+ "memory:原有限定范围": "原有限定范围",+ "memory:选择召回范围": "选择召回范围",+ "memory:停止外部记忆召回": "停止外部记忆召回",+ "memory:正在保存…": "正在保存…",+ "memory:保存召回范围": "保存召回范围",+ "memory:取消范围修改": "取消范围修改",+ "memory:原文检索仍按来源授权;已带出的内容不会撤回。":+ "原文检索仍按来源授权;已带出的内容不会撤回。",+ "memory:记忆已更新,请重新打开这条记忆后再调整范围。":+ "记忆已更新,请重新打开这条记忆后再调整范围。",+ "memory:范围修改未提交,当前范围保持不变。请修正后重试。":+ "范围修改未提交,当前范围保持不变。请修正后重试。",+ "memory:保存结果尚未确认,请重试。": "保存结果尚未确认,请重试。",+ "memory:原话已保存在本机;当前内容、模型接收方或授权版本尚未通过核对,未继续整理。":+ "原话已保存在本机;当前内容、模型接收方或授权版本尚未通过核对,未继续整理。",+ "memory:HY 未返回可核对的已有记忆,未创建替代内容;原始记录已保留,可重试处理。":+ "HY 未返回可核对的已有记忆,未创建替代内容;原始记录已保留,可重试处理。",+ "memory:历史引用尚未绑定到原始来源,当前批次未完成,原话已保留。":+ "历史引用尚未绑定到原始来源,当前批次未完成,原话已保留。",+ "memory:记忆内容未通过来源与作者核验,当前批次未完成,原话已保留。":+ "记忆内容未通过来源与作者核验,当前批次未完成,原话已保留。",+ "memory:所选记忆已不可读取,请重新读取记忆库。":+ "所选记忆已不可读取,请重新读取记忆库。",+ "memory:还没连上本地 Core,正在重试…": "还没连上本地 Core,正在重试…",+ "memory:记忆内容或使用权限已变化,回答已停止。请重新提问。":+ "记忆内容或使用权限已变化,回答已停止。请重新提问。",+ "memory:这条记忆的来源授权已撤回,暂时不能读取。":+ "这条记忆的来源授权已撤回,暂时不能读取。",+ "memory:记忆已被更新,请刷新后重试。": "记忆已被更新,请刷新后重试。",+ "memory:已删除的记忆不能修改。": "已删除的记忆不能修改。",+ "memory:这条记忆已经删除。": "这条记忆已经删除。",+ "memory:这条记忆已被更新的记忆取代,只能查看或删除。":+ "这条记忆已被更新的记忆取代,只能查看或删除。",+ "memory:没有更早的修改可以撤销。": "没有更早的修改可以撤销。",+ "memory:来源原话已不存在,无法建立这条记忆。":+ "来源原话已不存在,无法建立这条记忆。",+ "memory:这次操作与已完成的请求不一致。": "这次操作与已完成的请求不一致。",+ "memory:输入内容不符合要求。": "输入内容不符合要求。",+ "memory:本地记忆库正忙,请稍后重试。": "本地记忆库正忙,请稍后重试。",+ "memory:记忆": "记忆",+ "memory:记忆空间": "记忆空间",+ "memory:全部应用": "全部应用",+ "memory:来源": "来源",+ "memory:主题": "主题",+ "memory:归纳": "归纳",+ "memory:全部记忆": "全部记忆",+ "memory:来源待核对": "来源待核对",+ "memory:所选来源待核对": "所选来源待核对",+ "memory:未知来源": "未知来源",+ "memory:记忆读取失败": "记忆读取失败",+ "memory:正在读取…": "正在读取…",+ "memory:正在更新…": "正在更新…",+ "memory:读取失败": "读取失败",+ "memory:正在核对来源…": "正在核对来源…",+ "memory:正在导入历史会话,记忆将陆续出现": "正在导入历史会话,记忆将陆续出现",+ "memory:记忆工作台": "记忆工作台",+ "memory:来源与主题": "来源与主题",+ "memory:记忆或原始对话": "记忆或原始对话",+ "memory:原始对话": "原始对话",+ "memory:地图组织方式": "地图组织方式",+ "memory:筛选地图记忆": "筛选地图记忆",+ "memory:搜索原始对话": "搜索原始对话",+ "memory:搜索记忆": "搜索记忆",+ "memory:筛选记忆…": "筛选记忆…",+ "memory:向记忆提问": "向记忆提问",+ "memory:询问全部已授权可用记忆…": "询问全部已授权可用记忆…",+ "memory:发送问题": "发送问题",+ "memory:刷新地图记忆": "刷新地图记忆",+ "memory:关闭新增记忆提示": "关闭新增记忆提示",+ "memory:地图记忆列表": "地图记忆列表",+ "memory:记忆读取失败,请重试。": "记忆读取失败,请重试。",+ "memory:重新读取地图记忆": "重新读取地图记忆",+ "memory:没有匹配的记忆": "没有匹配的记忆",+ "memory:本页没有匹配的主题记忆": "本页没有匹配的主题记忆",+ "memory:还没有已生成的记忆": "还没有已生成的记忆",+ "memory:地图记忆分页": "地图记忆分页",+ "memory:上一页记忆": "上一页记忆",+ "memory:下一页记忆": "下一页记忆",+ "memory:记忆关系图": "记忆关系图",+ "memory:主题视角(非事项)": "主题视角(非事项)",+ "memory:来源视角": "来源视角",+ "memory:记忆关联": "记忆关联",+ "memory:刚导入的原话,还不是沉淀后的记忆": "刚导入的原话,还不是沉淀后的记忆",+ "memory:来源归属": "来源归属",+ "memory:可在沉淀记忆后查看视图": "可在沉淀记忆后查看视图",+ "memory:查看选中来源原文": "查看选中来源原文",+ "memory:查看选中记忆原文": "查看选中记忆原文",+ "memory:查看原文": "查看原文",+ "memory:整理已有关系": "整理已有关系",+ "memory:正在读取原文…": "正在读取原文…",+ "memory:选择一条原始对话": "选择一条原始对话",+ "memory:记忆暂时无法读取": "记忆暂时无法读取",+ "memory:当前筛选没有可显示的记忆": "当前筛选没有可显示的记忆",+ "memory:正在读取记忆…": "正在读取记忆…",+ "memory:已保存的对话还未生成记忆": "已保存的对话还未生成记忆",+ "memory:还没有可显示的记忆": "还没有可显示的记忆",+ "memory:连线表示来源归属": "连线表示来源归属",+ "memory:记忆详情": "记忆详情",+ "memory:来源原文": "来源原文",+ "memory:关联节点": "关联节点",+ "memory:关闭记忆详情": "关闭记忆详情",+ "memory:关闭详情": "关闭详情",+ "memory:正在读取这条记忆…": "正在读取这条记忆…",+ "memory:这条记忆的原文暂时无法读取,选择已保留。":+ "这条记忆的原文暂时无法读取,选择已保留。",+ "memory:重试读取原文": "重试读取原文",+ "memory:已沉淀的记忆": "已沉淀的记忆",+ "memory:正在读取记忆详情…": "正在读取记忆详情…",+ "memory:沉淀记忆后查看详情": "沉淀记忆后查看详情",+ "memory:时间未知": "时间未知",+ "memory:来源原文已不可读取": "来源原文已不可读取",+ "memory:关联记忆": "关联记忆",+ "memory:正在读取完整对话…": "正在读取完整对话…",+ "memory:重试读取完整对话": "重试读取完整对话",+ "memory:看完整对话": "看完整对话",+ "memory:今天": "今天",+ "memory:你": "你",+ "memory:助手": "助手",+ "memory:工具": "工具",+ "memory:未知": "未知",+ "memory:作者待核对": "作者待核对",+ "memory:你说": "你说",+ "memory:助手原话": "助手原话",+ "memory:已沉淀": "已沉淀",+ "memory:已删除": "已删除",+ "memory:已被取代": "已被取代",+ "memory:状态待核对": "状态待核对",+ "memory:编辑": "编辑",+ "memory:原始依据": "原始依据",+ "memory:这段原文当前不可查看。": "这段原文当前不可查看。",+ "memory:版本记录": "版本记录",+ "memory:更多管理": "更多管理",+ "memory:撤销上次修改": "撤销上次修改",+ "memory:删除记忆": "删除记忆",+ "memory:编辑记忆": "编辑记忆",+ "memory:返回记忆": "返回记忆",+ "memory:修改这条记忆,原始对话保持不变。": "修改这条记忆,原始对话保持不变。",+ "memory:记忆内容": "记忆内容",+ "memory:使用范围保持不变": "使用范围保持不变",+ "memory:已有新版本": "已有新版本",+ "memory:你的草稿已保留,先查看新版本再决定如何修改。":+ "你的草稿已保留,先查看新版本再决定如何修改。",+ "memory:查看新版本": "查看新版本",+ "memory:基于此版本继续编辑": "基于此版本继续编辑",+ "memory:取消": "取消",+ "memory:保存": "保存",+ "memory:重试": "重试",+ "memory:删除": "删除",+ "memory:对话": "对话",+ "memory:保存修改": "保存修改",+ "memory:对应记忆": "对应记忆",+ "memory:查看记忆": "查看记忆",+ "memory:删除这条记忆?": "删除这条记忆?",+ "memory:删除后不再用于新的召回,来源 App 中的原始对话不会删除。":+ "删除后不再用于新的召回,来源 App 中的原始对话不会删除。",+ "memory:已经发送给应用的内容无法远程收回。":+ "已经发送给应用的内容无法远程收回。",+ "memory:放弃尚未保存的修改?": "放弃尚未保存的修改?",+ "memory:来源权限已变化或原文不可用。": "来源权限已变化或原文不可用。",+ "memory:暂时无法读取新版本,草稿已保留。": "暂时无法读取新版本,草稿已保留。",+ "memory:修改未提交;草稿已保留。请按提示修正后重试。":+ "修改未提交;草稿已保留。请按提示修正后重试。",+ "memory:修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。":+ "修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。",+ "memory:删除未提交。请核对这条记忆的状态后重试。":+ "删除未提交。请核对这条记忆的状态后重试。",+ "memory:删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。":+ "删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。",+ "memory:撤销未提交。请按提示修正后重试。": "撤销未提交。请按提示修正后重试。",+ "memory:撤销尚未确认,请先核对当前记忆版本,避免重复撤销。":+ "撤销尚未确认,请先核对当前记忆版本,避免重复撤销。",+ "memory:添加记忆": "添加记忆",+ "memory:关闭新增记忆": "关闭新增记忆",+ "memory:关闭": "关闭",+ "memory:记下这件事": "记下这件事",+ "memory:例如:项目周会不排在周五。": "例如:项目周会不排在周五。",+ "memory:整理模型:": "整理模型:",+ "memory:尚未配置,原话仍可保存": "尚未配置,原话仍可保存",+ "memory:正在读取": "正在读取",+ "memory:配置模型": "配置模型",+ "memory:保存中…": "保存中…",+ "memory:保存原话": "保存原话",+ "memory:最近添加": "最近添加",+ "memory:重新整理": "重新整理",+ "memory:原话已保存,等待可用模型": "原话已保存,等待可用模型",+ "memory:原话已保存,等待整理": "原话已保存,等待整理",+ "memory:正在整理": "正在整理",+ "memory:原话已保存,整理未完成": "原话已保存,整理未完成",+ "memory:整理已完成": "整理已完成",+ "memory:原话已保存,未提取出可用记忆": "原话已保存,未提取出可用记忆",+ "memory:最近添加的内容读取失败。": "最近添加的内容读取失败。",+ "memory:整理状态暂时不可用,原话已保存。": "整理状态暂时不可用,原话已保存。",+ "memory:已保存,正在后台沉淀记忆": "已保存,正在后台沉淀记忆",+ "memory:未能确认保存结果,输入已保留。重试不会重复添加。":+ "未能确认保存结果,输入已保留。重试不会重复添加。",+ "memory:整理未能开始,原话仍已保存。": "整理未能开始,原话仍已保存。",+ "memory:整理结果尚未确认,原话仍已保存。请刷新后核对。":+ "整理结果尚未确认,原话仍已保存。请刷新后核对。",+ "memory:模型服务要求检查余额或付款状态,原话仍已保存。":+ "模型服务要求检查余额或付款状态,原话仍已保存。",+ "memory:这台设备打不开 3D 视图,已显示关联列表。":+ "这台设备打不开 3D 视图,已显示关联列表。",+ "memory:图谱工具": "图谱工具",+ "memory:放大": "放大",+ "memory:放大图谱": "放大图谱",+ "memory:缩小": "缩小",+ "memory:缩小图谱": "缩小图谱",+ "memory:重置视角": "重置视角",+ "memory:重置图谱视角": "重置图谱视角",+ "memory:查看读取详情": "查看读取详情",+ "memory:配置整理模型": "配置整理模型",+ "memory:原文暂时无法读取": "原文暂时无法读取",+ "memory:暂时无法读取这段对话,已保留当前记忆。":+ "暂时无法读取这段对话,已保留当前记忆。",+ "memory:已清除筛选,定位到关联记忆。": "已清除筛选,定位到关联记忆。",+ "memory:所选记忆不在当前筛选内,已取消选择。":+ "所选记忆不在当前筛选内,已取消选择。",+ "memory:列表分隔符": "、",+ "memory:冒号": ":",+ "memory:手动添加": "手动添加",+ "memory:导入的已有记忆": "导入的已有记忆",+ "memory:记忆与原文": "记忆与原文",+ "memory:第 {revision} 版": "第 {revision} 版",+ "memory:对话时间 ": "对话时间 ",+ "memory:沉淀时间 ": "沉淀时间 ",+ "memory:原对话 ": "原对话 ",+ "memory:{count} 条记录没有原始时间,未用导入时间代替。":+ "{count} 条记录没有原始时间,未用导入时间代替。",+ "memory:作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。":+ "作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。",+ "memory:统计于 ": "统计于 ",+ "memory: · 导入数量仍在更新,可刷新核对": " · 导入数量仍在更新,可刷新核对",+ "memory:对话于 {day}": "对话于 {day}",+ "memory:导入于 {day}": "导入于 {day}",+ "memory:已开始处理所选对话": "已开始处理所选对话",+ "memory:处理请求已受理": "处理请求已受理",+ "memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":+ "模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。",+ "memory:已导入 {count} 段对话,整理成记忆后会出现在这里。":+ "已导入 {count} 段对话,整理成记忆后会出现在这里。",+ "memory:历史已保存在本机,记忆就绪后会出现在这里。":+ "历史已保存在本机,记忆就绪后会出现在这里。",+ "memory:连接应用并导入历史后,可以开始沉淀记忆。":+ "连接应用并导入历史后,可以开始沉淀记忆。",+ "memory:当前已生成 0 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。":+ "当前已生成 0 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。",+ "memory:返回应用": "返回应用",+ "memory:共 {count} 条 · 正在核对来源…": "共 {count} 条 · 正在核对来源…",+ "memory:共 {count} 条 · 正在核对来源….one": "共 {count} 条 · 正在核对来源…",+ "memory:共 {count} 条": "共 {count} 条",+ "memory:共 {count} 条.one": "共 {count} 条",+ "memory: · 正在核对…": " · 正在核对…",+ "memory:新增 {count} 条记忆": "新增 {count} 条记忆",+ "memory:新增 {count} 条记忆.one": "新增 {count} 条记忆",+ "memory:沉淀于 ": "沉淀于 ",+ "memory:共 {count} 条,第 {page} / {pages} 页":+ "共 {count} 条,第 {page} / {pages} 页",+ "memory:共 {count} 条,第 {page} / {pages} 页.one":+ "共 {count} 条,第 {page} / {pages} 页",+ "memory:已沉淀 {count} 条记忆": "已沉淀 {count} 条记忆",+ "memory:已沉淀 {count} 条记忆.one": "已沉淀 {count} 条记忆",+ "memory:关键词“{query}”": "关键词“{query}”",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条":+ "已沉淀 {count} 条{filter} · 当前展示 {shown} 条",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条.one":+ "已沉淀 {count} 条{filter} · 当前展示 {shown} 条",+ "memory:({filter})": "({filter})",+ "memory:第 {page} 页": "第 {page} 页",+ "memory:原话已保存,正在等待整理:": "原话已保存,正在等待整理:",+ "memory:记忆未在生成": "记忆未在生成",+ "memory:还没有开始生成记忆:{reason}({count} 条待处理)":+ "还没有开始生成记忆:{reason}({count} 条待处理)",+ "memory:去配置生成模型": "去配置生成模型",+} as const;++export const memorySpanishMessages: Record<+ keyof typeof memoryChineseMessages,+ string+> = {+ "memory:记忆抽取": "Extracción de memorias",+ "memory:关系归纳": "Síntesis de relaciones",+ "memory:深度整理": "Procesamiento profundo",+ "memory:跨域整理": "Procesamiento entre áreas",+ "memory:当前模型已变化": "El modelo actual cambió",+ "memory:本地会话内容已变化":+ "El contenido de las conversaciones locales cambió",+ "memory:这段对话含过长原文,暂未整理;原文已保留":+ "Esta conversación contiene texto demasiado largo y no se procesó; el original se conservó",+ "memory:记忆库分页": "Paginación de la biblioteca de memorias",+ "memory:上一页": "Página anterior",+ "memory:下一页": "Página siguiente",+ "memory:等待可用生成模型": "Esperando un modelo disponible",+ "memory:还没有启用生成模型": "No hay un modelo de generación activo",+ "memory:缺少生成模型 API Key": "Falta la clave API del modelo",+ "memory:模型凭据暂不可用": "Credenciales del modelo no disponibles",+ "memory:本机凭据存储暂不可用": "Almacén local de credenciales no disponible",+ "memory:需要授权访问本机钥匙串。请重新打开 App 并完成一次授权":+ "Se necesita permiso para acceder al llavero. Vuelve a abrir la aplicación y completa la autorización",+ "memory:读取本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "La lectura del llavero agotó el tiempo. Vuelve a guardar la configuración del modelo",+ "memory:写入本机钥匙串超时。重新保存一遍模型配置即可恢复":+ "La escritura del llavero agotó el tiempo. Vuelve a guardar la configuración del modelo",+ "memory:模型认证失败。更新 key 后,到设置里点一次检测,会自动接着处理":+ "Falló la autenticación. Actualiza la clave y comprueba la conexión en Configuración para continuar",+ "memory:模型账户余额不足。充值或换 key 后,到设置里点一次检测,会自动接着处理":+ "Saldo del proveedor insuficiente. Recarga o cambia la clave y comprueba la conexión en Configuración",+ "memory:模型服务拒绝访问。更新权限后,到设置里点一次检测,会自动接着处理":+ "El proveedor rechazó el acceso. Actualiza los permisos y comprueba la conexión en Configuración",+ "memory:模型服务限流": "Límite de solicitudes del proveedor",+ "memory:模型服务暂不可用": "Servicio del modelo no disponible",+ "memory:模型服务响应超时": "El modelo agotó el tiempo de respuesta",+ "memory:模型请求不兼容,请核对配置":+ "Solicitud incompatible; revisa la configuración",+ "memory:模型请求未成功": "La solicitud al modelo no se completó",+ "memory:HY Memory 不可用": "HY Memory no está disponible",+ "memory:HY Memory 启动失败": "HY Memory no pudo iniciarse",+ "memory:暂时没能整理,稍后会自动重试":+ "No se pudo procesar por ahora; se reintentará automáticamente",+ "memory:这次没能整理成功,正在重试":+ "No se pudo procesar esta vez; reintentando",+ "memory:生成模型换过了,这批会重新整理":+ "Cambió el modelo de generación; este lote se volverá a procesar",+ "memory:整理方式换过了,这批会重新整理":+ "Cambió el método de procesamiento; este lote se volverá a procesar",+ "memory:已提炼": "Extraído",+ "memory:旧版确认记录": "Confirmación de una versión anterior",+ "memory:创建": "Creación",+ "memory:纠正": "Corrección",+ "memory:调整使用范围": "Ajuste del ámbito de uso",+ "memory:撤销修改": "Cambio deshecho",+ "memory:模型更新": "Actualización del modelo",+ "memory:被新记忆取代": "Sustituida por una memoria nueva",+ "memory:其他操作": "Otra operación",+ "memory:删除(记录)": "Eliminación",+ "memory:修改已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "Los cambios se guardaron, pero no se pudo leer la lista actualizada. Se dejó de usar la respuesta anterior; vuelve a leerla.",+ "memory:纠正已保存,但读取最新列表失败。已停止使用旧回答,请重新读取。":+ "La corrección se guardó, pero no se pudo leer la lista actualizada. Se dejó de usar la respuesta anterior; vuelve a leerla.",+ "memory:未收到操作结果,请重试。":+ "No se recibió el resultado de la operación. Reinténtalo.",+ "memory:批量处理结果已保留,但列表刷新失败,请重新读取记忆库。":+ "Se conservó el resultado de la operación por lotes, pero no se pudo actualizar la lista. Vuelve a leer la biblioteca de memorias.",+ "memory:批量处理结果已保留,但列表刷新失败,稍后会自动重新读取。":+ "Se conservó el resultado de la operación por lotes, pero no se pudo actualizar la lista. Se volverá a leer automáticamente.",+ "memory:召回范围已保存,但列表刷新失败。请稍后重新打开记忆页。":+ "Se guardó el ámbito de consulta, pero no se pudo actualizar la lista. Vuelve a abrir la página de memorias más tarde.",+ "memory:重新整理可能再次调用模型。只会重跑结果不确定的对话,是否继续?":+ "Volver a procesar puede llamar de nuevo al modelo. Solo se repetirán las conversaciones con resultado incierto. ¿Quieres continuar?",+ "memory:原始对话暂时无法读取":+ "Las conversaciones originales no están disponibles por ahora",+ "memory:没有匹配的原始对话": "No hay conversaciones originales que coincidan",+ "memory:还没有导入的原始对话":+ "Aún no hay conversaciones originales importadas",+ "memory:查看已读内容": "Ver contenido leído",+ "memory:已保存原文": "Texto original guardado",+ "memory:刷新已读内容": "Actualizar contenido leído",+ "memory:正在核对本机已保存记录…":+ "Verificando registros guardados en este equipo…",+ "memory:原始消息": "Mensajes originales",+ "memory:会话": "Conversaciones",+ "memory:用户发言": "Mensajes del usuario",+ "memory:Agent 发言": "Mensajes del agente",+ "memory:作者未知": "Autor desconocido",+ "memory:原始时间未知": "Fecha original desconocida",+ "memory:工具记录": "Registros de herramientas",+ "memory:原始时间来自已保存记录。":+ "Las fechas originales proceden de los registros guardados.",+ "memory:已保存的原文样例": "Ejemplos de texto original guardado",+ "memory:最多展示 3 段,不代表全部历史或推荐记忆。":+ "Se muestran hasta 3 fragmentos, no el historial completo ni memorias recomendadas.",+ "memory:查看完整对话": "Ver conversación completa",+ "memory:原文较长,此处仅展示前 600 个字符。":+ "Texto largo: se muestran los primeros 600 caracteres.",+ "memory:这个来源还没有保存原文。":+ "Aún no hay texto original guardado de este origen.",+ "memory:完整对话": "Conversación completa",+ "memory:关闭完整对话": "Cerrar conversación completa",+ "memory:用户": "Usuario",+ "memory:暂时无法读取已保存内容,旧回执已收起。请检查授权或重试。":+ "No se puede leer el contenido guardado. Se ocultó el informe anterior; revisa los permisos o reintenta.",+ "memory:这段原文暂不可读,可能已被撤回授权。请刷新回执。":+ "Este texto no está disponible; es posible que se hayan revocado sus permisos. Actualiza el informe.",+ "memory:外部记忆召回范围": "Ámbito de consulta externa",+ "memory:外部记忆召回": "Consulta externa de memorias",+ "memory:调整召回范围": "Ajustar ámbito de consulta",+ "memory:所有关联工具": "Todas las herramientas vinculadas",+ "memory:已停止外部记忆召回": "Consulta externa desactivada",+ "memory:原有限定范围": "Ámbito limitado original",+ "memory:选择召回范围": "Elegir ámbito de consulta",+ "memory:停止外部记忆召回": "Desactivar consulta externa",+ "memory:正在保存…": "Guardando…",+ "memory:保存召回范围": "Guardar ámbito de consulta",+ "memory:取消范围修改": "Cancelar cambio de ámbito",+ "memory:原文检索仍按来源授权;已带出的内容不会撤回。":+ "La búsqueda del texto original sigue los permisos del origen. El contenido ya enviado no se retira.",+ "memory:记忆已更新,请重新打开这条记忆后再调整范围。":+ "La memoria cambió. Vuelve a abrirla antes de ajustar el ámbito.",+ "memory:范围修改未提交,当前范围保持不变。请修正后重试。":+ "No se envió el cambio; se conserva el ámbito actual. Corrige el problema y reintenta.",+ "memory:保存结果尚未确认,请重试。":+ "El guardado no está confirmado. Reinténtalo.",+ "memory:原话已保存在本机;当前内容、模型接收方或授权版本尚未通过核对,未继续整理。":+ "El texto está guardado en este equipo. No se continuó el procesamiento porque falta verificar el contenido, el modelo receptor o la versión de autorización.",+ "memory:HY 未返回可核对的已有记忆,未创建替代内容;原始记录已保留,可重试处理。":+ "HY no devolvió memorias verificables. No se creó contenido sustituto; los originales se conservan y puedes reintentar.",+ "memory:历史引用尚未绑定到原始来源,当前批次未完成,原话已保留。":+ "Las referencias históricas aún no están vinculadas a su origen. El lote está incompleto; el texto se conserva.",+ "memory:记忆内容未通过来源与作者核验,当前批次未完成,原话已保留。":+ "No se pudo verificar el origen y autor de la memoria. El lote está incompleto; el texto se conserva.",+ "memory:所选记忆已不可读取,请重新读取记忆库。":+ "La memoria seleccionada ya no está disponible. Actualiza la biblioteca.",+ "memory:还没连上本地 Core,正在重试…":+ "Conectando con Core local; reintentando…",+ "memory:记忆内容或使用权限已变化,回答已停止。请重新提问。":+ "El contenido o los permisos cambiaron. La respuesta se detuvo; vuelve a preguntar.",+ "memory:这条记忆的来源授权已撤回,暂时不能读取。":+ "Se revocó el permiso del origen de esta memoria; no se puede leer.",+ "memory:记忆已被更新,请刷新后重试。":+ "La memoria cambió. Actualiza antes de reintentar.",+ "memory:已删除的记忆不能修改。": "No se puede editar una memoria eliminada.",+ "memory:这条记忆已经删除。": "Esta memoria ya se eliminó.",+ "memory:这条记忆已被更新的记忆取代,只能查看或删除。":+ "Esta memoria fue sustituida; solo puedes verla o eliminarla.",+ "memory:没有更早的修改可以撤销。": "No hay cambios anteriores que deshacer.",+ "memory:来源原话已不存在,无法建立这条记忆。":+ "El texto original ya no existe; no se puede crear la memoria.",+ "memory:这次操作与已完成的请求不一致。":+ "La operación no coincide con la solicitud ya completada.",+ "memory:输入内容不符合要求。": "El contenido no cumple los requisitos.",+ "memory:本地记忆库正忙,请稍后重试。":+ "La biblioteca local está ocupada. Reinténtalo más tarde.",+ "memory:记忆": "Memorias",+ "memory:记忆空间": "Espacio de memorias",+ "memory:全部应用": "Todas las aplicaciones",+ "memory:来源": "Origen",+ "memory:主题": "Temas",+ "memory:归纳": "Patrones",+ "memory:全部记忆": "Todas las memorias",+ "memory:来源待核对": "Origen sin verificar",+ "memory:所选来源待核对": "Origen seleccionado sin verificar",+ "memory:未知来源": "Origen desconocido",+ "memory:记忆读取失败": "Error al leer las memorias",+ "memory:正在读取…": "Leyendo…",+ "memory:正在更新…": "Actualizando…",+ "memory:读取失败": "Error de lectura",+ "memory:正在核对来源…": "Verificando orígenes…",+ "memory:正在导入历史会话,记忆将陆续出现":+ "Importando el historial; las memorias aparecerán progresivamente",+ "memory:记忆工作台": "Panel de memorias",+ "memory:来源与主题": "Orígenes y temas",+ "memory:记忆或原始对话": "Memorias o conversaciones originales",+ "memory:原始对话": "Conversaciones originales",+ "memory:地图组织方式": "Organización del mapa",+ "memory:筛选地图记忆": "Filtrar memorias del mapa",+ "memory:搜索原始对话": "Buscar conversaciones originales",+ "memory:搜索记忆": "Buscar memorias",+ "memory:筛选记忆…": "Filtrar memorias…",+ "memory:向记忆提问": "Preguntar a las memorias",+ "memory:询问全部已授权可用记忆…":+ "Pregunta a todas las memorias autorizadas disponibles…",+ "memory:发送问题": "Enviar pregunta",+ "memory:刷新地图记忆": "Actualizar memorias",+ "memory:关闭新增记忆提示": "Cerrar aviso de nuevas memorias",+ "memory:地图记忆列表": "Lista de memorias del mapa",+ "memory:记忆读取失败,请重试。":+ "No se pudieron leer las memorias. Reinténtalo.",+ "memory:重新读取地图记忆": "Volver a leer las memorias",+ "memory:没有匹配的记忆": "No hay memorias que coincidan",+ "memory:本页没有匹配的主题记忆": "No hay memorias de este tema en la página",+ "memory:还没有已生成的记忆": "Aún no hay memorias generadas",+ "memory:地图记忆分页": "Paginación de memorias",+ "memory:上一页记忆": "Página anterior de memorias",+ "memory:下一页记忆": "Página siguiente de memorias",+ "memory:记忆关系图": "Grafo de memorias",+ "memory:主题视角(非事项)": "Vista por temas",+ "memory:来源视角": "Vista por origen",+ "memory:记忆关联": "Relaciones entre memorias",+ "memory:刚导入的原话,还不是沉淀后的记忆":+ "Conversaciones importadas, aún sin convertir en memorias",+ "memory:来源归属": "Relación con el origen",+ "memory:可在沉淀记忆后查看视图":+ "La vista estará disponible cuando se generen memorias",+ "memory:查看选中来源原文": "Ver texto del origen seleccionado",+ "memory:查看选中记忆原文": "Ver texto de la memoria seleccionada",+ "memory:查看原文": "Ver texto original",+ "memory:整理已有关系": "Organizar relaciones existentes",+ "memory:正在读取原文…": "Leyendo texto original…",+ "memory:选择一条原始对话": "Selecciona una conversación original",+ "memory:记忆暂时无法读取": "Las memorias no están disponibles",+ "memory:当前筛选没有可显示的记忆": "No hay memorias para este filtro",+ "memory:正在读取记忆…": "Leyendo memorias…",+ "memory:已保存的对话还未生成记忆":+ "Las conversaciones guardadas aún no han generado memorias",+ "memory:还没有可显示的记忆": "Aún no hay memorias para mostrar",+ "memory:连线表示来源归属": "Las líneas indican el origen",+ "memory:记忆详情": "Detalles de la memoria",+ "memory:来源原文": "Texto original",+ "memory:关联节点": "Nodo relacionado",+ "memory:关闭记忆详情": "Cerrar detalles de la memoria",+ "memory:关闭详情": "Cerrar detalles",+ "memory:正在读取这条记忆…": "Leyendo esta memoria…",+ "memory:这条记忆的原文暂时无法读取,选择已保留。":+ "No se puede leer el texto original. La selección se conserva.",+ "memory:重试读取原文": "Reintentar lectura del original",+ "memory:已沉淀的记忆": "Memorias guardadas",+ "memory:正在读取记忆详情…": "Leyendo detalles…",+ "memory:沉淀记忆后查看详情":+ "Los detalles estarán disponibles cuando se generen memorias",+ "memory:时间未知": "Hora desconocida",+ "memory:来源原文已不可读取": "El texto original ya no está disponible",+ "memory:关联记忆": "Memorias relacionadas",+ "memory:正在读取完整对话…": "Leyendo conversación completa…",+ "memory:重试读取完整对话": "Reintentar lectura de la conversación",+ "memory:看完整对话": "Ver conversación completa",+ "memory:今天": "Hoy",+ "memory:你": "Tú",+ "memory:助手": "Asistente",+ "memory:工具": "Herramienta",+ "memory:未知": "Desconocido",+ "memory:作者待核对": "Autor sin verificar",+ "memory:你说": "Tus palabras",+ "memory:助手原话": "Palabras del asistente",+ "memory:已沉淀": "Guardada",+ "memory:已删除": "Eliminada",+ "memory:已被取代": "Sustituida",+ "memory:状态待核对": "Estado pendiente de comprobar",+ "memory:编辑": "Editar",+ "memory:原始依据": "Evidencia original",+ "memory:这段原文当前不可查看。": "Este texto original no está disponible.",+ "memory:版本记录": "Historial de versiones",+ "memory:更多管理": "Más opciones",+ "memory:撤销上次修改": "Deshacer último cambio",+ "memory:删除记忆": "Eliminar memoria",+ "memory:编辑记忆": "Editar memoria",+ "memory:返回记忆": "Volver a la memoria",+ "memory:修改这条记忆,原始对话保持不变。":+ "Edita esta memoria sin modificar la conversación original.",+ "memory:记忆内容": "Contenido de la memoria",+ "memory:使用范围保持不变": "El ámbito de uso no cambia",+ "memory:已有新版本": "Hay una nueva versión",+ "memory:你的草稿已保留,先查看新版本再决定如何修改。":+ "Tu borrador se conserva. Revisa la nueva versión antes de editar.",+ "memory:查看新版本": "Ver nueva versión",+ "memory:基于此版本继续编辑": "Continuar editando esta versión",+ "memory:取消": "Cancelar",+ "memory:保存": "Guardar",+ "memory:重试": "Reintentar",+ "memory:删除": "Eliminar",+ "memory:对话": "Conversación",+ "memory:保存修改": "Guardar cambios",+ "memory:对应记忆": "Memoria correspondiente",+ "memory:查看记忆": "Ver memoria",+ "memory:删除这条记忆?": "¿Eliminar esta memoria?",+ "memory:删除后不再用于新的召回,来源 App 中的原始对话不会删除。":+ "Dejará de usarse en nuevas consultas. La conversación original de la aplicación no se eliminará.",+ "memory:已经发送给应用的内容无法远程收回。":+ "No es posible retirar el contenido ya enviado a las aplicaciones.",+ "memory:放弃尚未保存的修改?": "¿Descartar los cambios sin guardar?",+ "memory:来源权限已变化或原文不可用。":+ "Los permisos del origen han cambiado o el texto no está disponible.",+ "memory:暂时无法读取新版本,草稿已保留。":+ "No se pudo leer la nueva versión. Tu borrador se conserva.",+ "memory:修改未提交;草稿已保留。请按提示修正后重试。":+ "Los cambios no se enviaron. Tu borrador se conserva; corrígelo y reinténtalo.",+ "memory:修改尚未确认,草稿已保留。请先刷新核对,避免重复提交。":+ "Los cambios no están confirmados. Tu borrador se conserva; actualiza antes de volver a enviarlo.",+ "memory:删除未提交。请核对这条记忆的状态后重试。":+ "La eliminación no se envió. Verifica el estado de la memoria antes de reintentar.",+ "memory:删除尚未确认。请重新核对记忆状态,不会自动扩大删除范围。":+ "La eliminación no está confirmada. Verifica el estado; no se eliminará ningún contenido adicional automáticamente.",+ "memory:撤销未提交。请按提示修正后重试。":+ "No se envió la acción de deshacer. Corrige el problema y reintenta.",+ "memory:撤销尚未确认,请先核对当前记忆版本,避免重复撤销。":+ "La acción de deshacer no está confirmada. Verifica la versión antes de reintentar.",+ "memory:添加记忆": "Añadir memoria",+ "memory:关闭新增记忆": "Cerrar nueva memoria",+ "memory:关闭": "Cerrar",+ "memory:记下这件事": "¿Qué quieres recordar?",+ "memory:例如:项目周会不排在周五。":+ "Por ejemplo: no programar reuniones del proyecto los viernes.",+ "memory:整理模型:": "Modelo: ",+ "memory:尚未配置,原话仍可保存": "Sin configurar; puedes guardar el texto",+ "memory:正在读取": "Leyendo",+ "memory:配置模型": "Configurar modelo",+ "memory:保存中…": "Guardando…",+ "memory:保存原话": "Guardar texto",+ "memory:最近添加": "Añadidas recientemente",+ "memory:重新整理": "Volver a procesar",+ "memory:原话已保存,等待可用模型": "Texto guardado; esperando un modelo",+ "memory:原话已保存,等待整理": "Texto guardado; pendiente de procesar",+ "memory:正在整理": "Procesando",+ "memory:原话已保存,整理未完成": "Texto guardado; procesamiento incompleto",+ "memory:整理已完成": "Procesamiento completado",+ "memory:原话已保存,未提取出可用记忆":+ "Texto guardado; no se extrajeron memorias utilizables",+ "memory:最近添加的内容读取失败。": "No se pudieron leer las notas recientes.",+ "memory:整理状态暂时不可用,原话已保存。":+ "Estado del procesamiento no disponible. El texto está guardado.",+ "memory:已保存,正在后台沉淀记忆":+ "Guardado; generando memorias en segundo plano",+ "memory:未能确认保存结果,输入已保留。重试不会重复添加。":+ "No se pudo confirmar el guardado. Tu texto se conserva; reintentar no lo duplicará.",+ "memory:整理未能开始,原话仍已保存。":+ "No se pudo iniciar el procesamiento. El texto sigue guardado.",+ "memory:整理结果尚未确认,原话仍已保存。请刷新后核对。":+ "El resultado no está confirmado. El texto sigue guardado; actualiza para verificarlo.",+ "memory:模型服务要求检查余额或付款状态,原话仍已保存。":+ "Revisa el saldo o los pagos del proveedor. El texto sigue guardado.",+ "memory:这台设备打不开 3D 视图,已显示关联列表。":+ "La vista 3D no está disponible en este equipo. Se muestran las relaciones en una lista.",+ "memory:图谱工具": "Herramientas del grafo",+ "memory:放大": "Acercar",+ "memory:放大图谱": "Acercar grafo",+ "memory:缩小": "Alejar",+ "memory:缩小图谱": "Alejar grafo",+ "memory:重置视角": "Restablecer vista",+ "memory:重置图谱视角": "Restablecer vista del grafo",+ "memory:查看读取详情": "Ver detalles de lectura",+ "memory:配置整理模型": "Configurar modelo",+ "memory:原文暂时无法读取": "Texto original no disponible",+ "memory:暂时无法读取这段对话,已保留当前记忆。":+ "No se puede leer la conversación. La memoria actual se conserva.",+ "memory:已清除筛选,定位到关联记忆。":+ "Filtros eliminados; memoria relacionada localizada.",+ "memory:所选记忆不在当前筛选内,已取消选择。":+ "La memoria seleccionada no está en este filtro. Se canceló la selección.",+ "memory:列表分隔符": ", ",+ "memory:冒号": ":",+ "memory:手动添加": "Añadida manualmente",+ "memory:导入的已有记忆": "Memoria existente importada",+ "memory:记忆与原文": "Memoria y texto original",+ "memory:第 {revision} 版": "Versión {revision}",+ "memory:对话时间 ": "Conversación: ",+ "memory:沉淀时间 ": "Guardada: ",+ "memory:原对话 ": "Conversación original ",+ "memory:{count} 条记录没有原始时间,未用导入时间代替。":+ "{count} registros sin fecha original; no se sustituyó por la fecha de importación.",+ "memory:作者数量按当前记录分类统计,不代表记忆抽取已完成或语义已核实。":+ "Los autores se cuentan según los registros actuales; no implica que la extracción o la verificación semántica hayan terminado.",+ "memory:统计于 ": "Medido el ",+ "memory: · 导入数量仍在更新,可刷新核对":+ " · La importación continúa; actualiza para verificar",+ "memory:对话于 {day}": "Conversación del {day}",+ "memory:导入于 {day}": "Importada el {day}",+ "memory:已开始处理所选对话": "Procesamiento de conversaciones iniciado",+ "memory:处理请求已受理": "Solicitud de procesamiento aceptada",+ "memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":+ "Modelo conectado. Las primeras memorias aparecerán progresivamente en la lista.",+ "memory:已导入 {count} 段对话,整理成记忆后会出现在这里。":+ "{count} conversaciones importadas. Las memorias aparecerán al procesarlas.",+ "memory:历史已保存在本机,记忆就绪后会出现在这里。":+ "El historial está guardado en este equipo. Las memorias aparecerán cuando estén listas.",+ "memory:连接应用并导入历史后,可以开始沉淀记忆。":+ "Conecta aplicaciones e importa el historial para empezar a generar memorias.",+ "memory:当前已生成 0 条记忆。请求已受理不等于已经完成,原始对话、模型处理任务和记忆数量分别统计。":+ "Aún hay 0 memorias generadas. Una solicitud aceptada no implica que haya finalizado. Las conversaciones, las tareas y las memorias se cuentan por separado.",+ "memory:返回应用": "Volver a aplicaciones",+ "memory:共 {count} 条 · 正在核对来源…":+ "{count} memorias · Verificando orígenes…",+ "memory:共 {count} 条 · 正在核对来源….one":+ "{count} memoria · Verificando orígenes…",+ "memory:共 {count} 条": "{count} memorias",+ "memory:共 {count} 条.one": "{count} memoria",+ "memory: · 正在核对…": " · Verificando…",+ "memory:新增 {count} 条记忆": "{count} memorias nuevas",+ "memory:新增 {count} 条记忆.one": "{count} memoria nueva",+ "memory:沉淀于 ": "Guardada: ",+ "memory:共 {count} 条,第 {page} / {pages} 页":+ "{count} memorias · Página {page} / {pages}",+ "memory:共 {count} 条,第 {page} / {pages} 页.one":+ "{count} memoria · Página {page} / {pages}",+ "memory:已沉淀 {count} 条记忆": "{count} memorias guardadas",+ "memory:已沉淀 {count} 条记忆.one": "{count} memoria guardada",+ "memory:关键词“{query}”": "Búsqueda: «{query}»",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条":+ "{count} memorias guardadas{filter} · {shown} visibles",+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条.one":+ "{count} memoria guardada{filter} · {shown} visibles",+ "memory:({filter})": " ({filter})",+ "memory:第 {page} 页": "Página {page}",+ "memory:原话已保存,正在等待整理:":+ "Texto guardado; pendiente de procesar: ",+ "memory:记忆未在生成": "Generación de memorias detenida",+ "memory:还没有开始生成记忆:{reason}({count} 条待处理)":+ "Aún no se generan memorias: {reason} ({count} pendientes)",+ "memory:去配置生成模型": "Configurar modelo de generación",+};diff --git a/memhub/packages/i18n/src/gui-i18n-messages.ts b/memhub/packages/i18n/src/gui-i18n-messages.tsnew file mode 100644index 0000000..e21e422--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-messages.ts@@ -0,0 +1,185 @@+import {+ applicationsChineseMessages,+ applicationsSpanishMessages,+} from "./gui-i18n-applications.js";+import {+ callsChineseMessages,+ callsSpanishMessages,+} from "./gui-i18n-calls.js";+import {+ currentChineseMessages,+ currentSpanishMessages,+} from "./gui-i18n-current.js";+import {+ guideChineseMessages,+ guideSpanishMessages,+} from "./gui-i18n-guide.js";+import {+ healthChineseMessages,+ healthSpanishMessages,+} from "./gui-i18n-health.js";+import {+ memoryChineseMessages,+ memorySpanishMessages,+} from "./gui-i18n-memory.js";+import {+ onboardingChineseMessages,+ onboardingSpanishMessages,+} from "./gui-i18n-onboarding.js";+import {+ recoveryChineseMessages,+ recoverySpanishMessages,+} from "./gui-i18n-recovery.js";+import {+ settingsChineseMessages,+ settingsSpanishMessages,+} from "./gui-i18n-settings.js";+import {+ workbenchChineseMessages,+ workbenchSpanishMessages,+} from "./gui-i18n-workbench.js";++const languageChineseMessages = {+ settings: "设置",+ languageTitle: "界面语言",+ languageLabel: "语言",+ languageSystem: "跟随系统",+ languageChinese: "简体中文",+ languageEnglish: "英语",+ languageSpanish: "西班牙语",+ languageDescription: "选择界面语言。此设置不会更改你的对话或记忆内容。",+ languageSaveError: "无法保存语言设置,请重试。",+ languageLoadError: "无法加载语言设置,请重试。",+ nativeErrorTitle: "MemHub 无法启动",+ startupPreparing: "正在启动,正在准备记忆服务…",+} as const;++const languageSpanishMessages: Record<+ keyof typeof languageChineseMessages,+ string+> = {+ settings: "Configuración",+ languageTitle: "Idioma de la interfaz",+ languageLabel: "Idioma",+ languageSystem: "Usar el idioma del sistema",+ languageChinese: "Chino simplificado",+ languageEnglish: "Inglés",+ languageSpanish: "Español",+ languageDescription:+ "Elige el idioma de la interfaz. Esta opción no modifica tus conversaciones ni tus memorias.",+ languageSaveError: "No se pudo guardar el idioma. Inténtalo de nuevo.",+ languageLoadError: "No se pudo cargar el idioma. Inténtalo de nuevo.",+ nativeErrorTitle: "MemHub no pudo iniciarse",+ startupPreparing: "Iniciando y preparando el servicio de memorias…",+};++type Catalog = {+ name: string;+ chinese: Readonly<Record<string, string>>;+ spanish: Readonly<Record<string, string>>;+};++/** Every domain catalog, in a fixed order; exported for collision tests. */+export const guiCatalogs: readonly Catalog[] = [+ {+ name: "current",+ chinese: currentChineseMessages,+ spanish: currentSpanishMessages,+ },+ {+ name: "workbench",+ chinese: workbenchChineseMessages,+ spanish: workbenchSpanishMessages,+ },+ {+ name: "guide",+ chinese: guideChineseMessages,+ spanish: guideSpanishMessages,+ },+ {+ name: "health",+ chinese: healthChineseMessages,+ spanish: healthSpanishMessages,+ },+ {+ name: "recovery",+ chinese: recoveryChineseMessages,+ spanish: recoverySpanishMessages,+ },+ {+ name: "settings",+ chinese: settingsChineseMessages,+ spanish: settingsSpanishMessages,+ },+ {+ name: "onboarding",+ chinese: onboardingChineseMessages,+ spanish: onboardingSpanishMessages,+ },+ {+ name: "applications",+ chinese: applicationsChineseMessages,+ spanish: applicationsSpanishMessages,+ },+ {+ name: "memory",+ chinese: memoryChineseMessages,+ spanish: memorySpanishMessages,+ },+ {+ name: "calls",+ chinese: callsChineseMessages,+ spanish: callsSpanishMessages,+ },+ {+ name: "language",+ chinese: languageChineseMessages,+ spanish: languageSpanishMessages,+ },+];++/**+ * Merge catalogs without silent overrides: a key may appear in two catalogs+ * only when both its Chinese and Spanish texts are identical.+ */+export function mergeCatalogs(catalogs: readonly Catalog[]) {+ const chinese: Record<string, string> = {};+ const spanish: Record<string, string> = {};+ const owner: Record<string, string> = {};+ for (const catalog of catalogs) {+ for (const [key, value] of Object.entries(catalog.chinese)) {+ const translated = catalog.spanish[key];+ if (Object.hasOwn(owner, key)) {+ if (chinese[key] !== value || spanish[key] !== translated)+ throw new Error(+ `GUI message "${key}" differs between ${owner[key]} and ${catalog.name}`,+ );+ continue;+ }+ owner[key] = catalog.name;+ chinese[key] = value;+ if (translated !== undefined) spanish[key] = translated;+ }+ }+ return { chinese, spanish };+}++const merged = mergeCatalogs(guiCatalogs);++/** The complete Chinese GUI catalog defines the supported message keys. */+export const chineseMessages = merged.chinese as typeof guideChineseMessages &+ typeof healthChineseMessages &+ typeof recoveryChineseMessages &+ typeof settingsChineseMessages &+ typeof onboardingChineseMessages &+ typeof applicationsChineseMessages &+ typeof memoryChineseMessages &+ typeof callsChineseMessages &+ typeof languageChineseMessages &+ typeof workbenchChineseMessages &+ typeof currentChineseMessages;++/** Spanish may be partial; untranslated messages use the Chinese catalog. */+export const spanishMessages = merged.spanish as Partial<+ Record<keyof typeof chineseMessages, string>+>;diff --git a/memhub/packages/i18n/src/gui-i18n-onboarding.test.ts b/memhub/packages/i18n/src/gui-i18n-onboarding.test.tsnew file mode 100644index 0000000..8ae0d60--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-onboarding.test.ts@@ -0,0 +1,48 @@+import { expect, it } from "vitest";+import { translate } from "./gui-i18n.js";+import {+ onboardingChineseMessages,+ onboardingSpanishMessages,+} from "./gui-i18n-onboarding.js";++it("provides Spanish copy for every onboarding message with identical interpolation parameters", () => {+ for (const key of Object.keys(+ onboardingChineseMessages,+ ) as (keyof typeof onboardingChineseMessages)[]) {+ const chinese = onboardingChineseMessages[key];+ const spanish = onboardingSpanishMessages[key];+ expect(spanish, key).toBeTruthy();+ expect(+ [...spanish.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)]+ .map((match) => match[1])+ .sort(),+ key,+ ).toEqual(+ [...chinese.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)]+ .map((match) => match[1])+ .sort(),+ );+ expect(translate("zh-CN", key)).toBe(chinese);+ expect(translate("es", key)).toBe(spanish);+ }+});+it("keeps product names, paths and error codes intact during interpolation", () => {+ expect(translate("es", "onboardingImportHistory", { name: "Cursor" })).toBe(+ "Importar el historial de Cursor",+ );+ expect(+ translate("zh-CN", "onboardingImportHistory", { name: "Cursor" }),+ ).toBe("导入 Cursor 历史");+ expect(+ translate("es", "onboardingModelOperationFailed", {+ code: "fixture_error",+ }),+ ).toBe("La operación no se completó: fixture_error");+ expect(+ translate("es", "onboardingConnectionPartial", {+ success: 1,+ failed: 2,+ names: "Cursor, /fixture/source",+ }),+ ).toContain("Cursor, /fixture/source");+});diff --git a/memhub/packages/i18n/src/gui-i18n-onboarding.ts b/memhub/packages/i18n/src/gui-i18n-onboarding.tsnew file mode 100644index 0000000..36e13ed--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-onboarding.ts@@ -0,0 +1,408 @@+/** Onboarding copy is also its stable Chinese fallback key. Never use these keys as workflow state. */+export const onboardingSpanishMessages = {+ "把熟悉的背景,带到这里": "Trae aquí el contexto que ya tienes",+ "你的记忆,从这里接上": "Tus memorias empiezan aquí",+ "这张卡还没测过。点一次「设为当前模型」会先自动测,如果还是不行,说明端点、key 或模型名有一处不对。":+ "Esta configuración aún no se ha probado. Al seleccionarla como modelo actual se probará automáticamente. Si falla, comprueba el servicio, la clave y el nombre del modelo.",+ "这类模型接口暂时用不了,换一张卡。":+ "Este tipo de servicio de modelos no está disponible. Elige otra configuración.",+ "这张卡缺了向量化模型,补上才能启用。":+ "Falta el modelo de embeddings. Añádelo antes de habilitar esta configuración.",+ "这张卡已经不在了,可能刚被删掉。刷新一下。":+ "Esta configuración ya no existe; puede que se haya eliminado. Actualiza la lista.",+ "这张卡刚被改过。刷新一下再试,免得覆盖掉别处的改动。":+ "Esta configuración cambió. Actualiza antes de reintentar para no sobrescribir otros cambios.",+ onboardingModelOperationFailed: "La operación no se completó: {code}",+ onboardingModelSkipDestination: "Omitir y entrar a Aplicaciones",+ 首次设置进度: "Progreso de la configuración inicial",+ 导入历史: "Importar historial",+ 连接应用: "Conectar apps",+ 沉淀记忆: "Crear memorias",+ 本地存储: "Almacenamiento local",+ "对话与记忆保存在本机;使用云模型或已授权的助手时,相关内容会发送给对应服务。":+ "Las conversaciones y memorias se guardan en este dispositivo. Al usar modelos en la nube o asistentes autorizados, el contenido pertinente se envía al servicio correspondiente.",+ "来源位置、身份或状态已变化,请重新选择并核对。尚未提交本次授权。":+ "La ubicación, identidad o estado de la fuente ha cambiado. Vuelve a seleccionarla y comprobarla. Todavía no se ha enviado esta autorización.",+ "来源位置、身份或状态已变化,正在等待本次提交回执。不会自动扩大已提交范围。":+ "La ubicación, identidad o estado de la fuente ha cambiado. Se espera la confirmación del envío; su alcance no se ampliará automáticamente.",+ 测试实例不接入应用: "La instancia de prueba no conecta aplicaciones",+ "请先把 MemHub 拖到“应用程序”并从那里重新打开,才能接入应用。":+ "Para conectar aplicaciones, arrastra MemHub a Aplicaciones y vuelve a abrirlo desde allí.",+ "部分应用未能完成接入,已成功的设置会保留,可进入应用后单独处理。":+ "No se pudieron conectar algunas aplicaciones. Se conservará la configuración completada y podrás resolver las demás desde la aplicación.",+ onboardingConnectionPartial:+ "Aplicaciones conectadas: {success}; pendientes: {failed}: {names}. Puedes resolverlas por separado desde la aplicación.",+ "首次设置的完成状态未能保存。已确认的导入回执不受影响;下次启动可能再次出现此页。":+ "No se pudo guardar la finalización de la configuración inicial. Las importaciones confirmadas no se ven afectadas; esta página podría reaparecer al iniciar.",+ "首次设置的完成状态尚未确认。已确认的导入回执不受影响;下次启动可能再次出现此页。":+ "La finalización de la configuración inicial aún no está confirmada. Las importaciones confirmadas no se ven afectadas; esta página podría reaparecer al iniciar.",+ "位置检测未完成,尚未读取历史。可以重新检测,或先进入工作台。":+ "No se completó la detección de ubicaciones y no se ha leído el historial. Puedes volver a detectar o entrar al espacio de trabajo.",+ "暂时无法核对来源,尚未提交授权。选择已保留,可以重试。":+ "No se pueden comprobar las fuentes por ahora. No se ha enviado la autorización. Tu selección se conserva; puedes reintentar.",+ "本次没有来源获准导入。请核对下方原因后重试,或到应用页查看状态。":+ "No se autorizó la importación de ninguna fuente. Comprueba los motivos y reintenta, o consulta el estado en Aplicaciones.",+ "开始导入的结果尚未确认,选择已保留。可以重试,或进入应用页核对。":+ "El inicio de la importación aún no está confirmado. Tu selección se conserva. Puedes reintentar o comprobarlo en Aplicaciones.",+ 未完成: "Sin completar",+ 核对中: "Comprobando",+ 仍进入应用页: "Entrar igualmente a Aplicaciones",+ 仍进入工作台: "Entrar igualmente al espacio de trabajo",+ 仍进入设置: "Entrar igualmente a Configuración",+ 重试保存并进入: "Reintentar guardar y entrar",+ "稍后添加,先进入": "Entrar y añadir más tarde",+ "正在开始导入…": "Iniciando importación…",+ 开始导入: "Iniciar importación",+ "不用从头介绍自己。从常用的 App 开始,把已有背景带过来。":+ "No necesitas presentarte de nuevo. Trae el contexto de las aplicaciones que ya utilizas.",+ "确认前只检查应用信息,不读取对话,也不安装连接。":+ "Antes de confirmar, solo se comprueba la información de las aplicaciones. No se leen conversaciones ni se instalan conexiones.",+ "本机 AI 应用": "Aplicaciones de IA en este dispositivo",+ 重新检测位置: "Volver a detectar ubicaciones",+ "检测中…": "Detectando…",+ 重新检测: "Volver a detectar",+ 候选应用: "Aplicaciones disponibles",+ "正在检测其他应用…": "Detectando otras aplicaciones…",+ 检测未完成: "Detección sin completar",+ 已全选: "Todas seleccionadas",+ 全选: "Seleccionar todas",+ onboardingImportHistory: "Importar el historial de {name}",+ 正在核对本机保存位置: "Comprobando la ubicación de almacenamiento local",+ 已发现: "Encontrada",+ 位置待核对: "Ubicación pendiente de comprobar",+ "当前没有候选来源。可以稍后在应用页添加历史包。":+ "No hay fuentes disponibles. Puedes añadir un archivo de historial más tarde en Aplicaciones.",+ "候选来源尚未加载。可以检测位置,或先进入工作台。":+ "Las fuentes aún no se han cargado. Puedes detectar ubicaciones o entrar al espacio de trabajo.",+ 本次导入: "Esta importación",+ "个 App 的历史对话": "aplicaciones con historial de conversaciones",+ "把零散的会话,": "Reúne conversaciones dispersas",+ 汇成完整的记忆: "en memorias completas",+ "少一些重复交代,多一些理解。":+ "Menos explicaciones repetidas, más comprensión.",+ onboardingMoreApps: "Desplázate para ver más · Quedan {count} aplicaciones",+ "onboardingMoreApps.one":+ "Desplázate para ver más · Queda {count} aplicación",+ onboardingAllApps: "Se muestran las {count} aplicaciones",+ 默认位置: "Ubicación predeterminada",+ 自定义位置: "Ubicación personalizada",+ 尚未检测: "Sin detectar",+ 检测中: "Detectando",+ 未发现: "No encontrada",+ 无法访问: "Sin acceso",+ 位置无效: "Ubicación no válida",+ "需要更新 Core": "Es necesario actualizar Core",+ "候选位置不存在,可能尚无历史或路径不同。":+ "La ubicación no existe. Puede que no haya historial o que la ruta sea diferente.",+ "无法检查此位置,请核对目录访问权限后重试。":+ "No se puede comprobar esta ubicación. Revisa los permisos de acceso a la carpeta y reintenta.",+ "此位置未通过安全检查,不能读取。":+ "Esta ubicación no superó la comprobación de seguridad y no se puede leer.",+ "当前 Core 未提供可确认的位置身份,需更新后再选择。":+ "Core no proporcionó una identidad de ubicación verificable. Actualízalo antes de seleccionar.",+ 暂不支持历史导入: "La importación de historial aún no está disponible",+ "当前来源不可读取,请重新检测。":+ "No se puede leer esta fuente. Vuelve a detectarla.",+ "来源目录暂时不可读取,请核对位置和权限。":+ "No se puede leer la carpeta de la fuente. Comprueba su ubicación y permisos.",+ "来源目录身份已变化,请返回重新检测。":+ "La identidad de la carpeta ha cambiado. Vuelve atrás y detecta de nuevo.",+ "来源权限已变化,请返回重新确认。":+ "Los permisos de la fuente han cambiado. Vuelve atrás y confírmalos de nuevo.",+ "此来源尚未获得读取授权。":+ "Esta fuente aún no tiene autorización de lectura.",+ "自定义来源位置需要重新确认。":+ "Debes volver a confirmar la ubicación personalizada de la fuente.",+ "当前 Core 未启用历史导入。":+ "Core no tiene habilitada la importación de historial.",+ onboardingImportRefused:+ "La importación aún no está autorizada ({reason}). Comprueba la fuente y reintenta.",+ 确认自定义位置: "Confirmar ubicación personalizada",+ 关闭位置确认: "Cerrar confirmación de ubicación",+ "此位置来自当前配置,并非应用默认目录。确认位置不会开始读取历史。":+ "Esta ubicación procede de la configuración actual y no es la carpeta predeterminada de la aplicación. Confirmarla no inicia la lectura del historial.",+ onboardingConfirmHistory:+ "Confirmo que esta es la ubicación del historial de {name}",+ 取消: "Cancelar",+ 确认此位置: "Confirmar esta ubicación",+ "对话正在汇入,记忆从这里开始":+ "Tus conversaciones llegan; tus memorias empiezan aquí",+ "导入进行中 · 顺手连接应用":+ "Importación en curso · Conecta tus aplicaciones",+ "对话已保存,记忆尚待生成。":+ "Las conversaciones se han guardado. Las memorias aún no se han generado.",+ "导入在后台继续,无需等待。":+ "La importación continúa en segundo plano; no necesitas esperar.",+ "正在重新核对来源;已保存数量仍按任务回执显示。":+ "Comprobando de nuevo las fuentes. Las cantidades guardadas siguen basándose en las confirmaciones de las tareas.",+ "本次历史导入已暂停,已保存的对话还在。":+ "Esta importación de historial está pausada. Las conversaciones guardadas se conservan.",+ "导入等待处理,已保存的对话还在。":+ "La importación está pendiente. Las conversaciones guardadas se conservan.",+ 停止后续操作: "Detener las operaciones siguientes",+ 暂停导入: "Pausar importación",+ 继续导入: "Reanudar importación",+ "配置模型,沉淀记忆": "Configurar un modelo para crear memorias",+ 导入与原文: "Importación y contenido original",+ "本次导入已结束。已保存的对话无需重复导入。":+ "Esta importación ha terminado. No es necesario volver a importar las conversaciones guardadas.",+ "对话先保存在本机。你可以同时设置后续连接。":+ "Primero se guardan las conversaciones en este dispositivo. Mientras tanto, puedes configurar las conexiones.",+ "导入不会自动开放应用读取权限。配置模型后,才会开始生成记忆。":+ "Importar no concede automáticamente acceso de lectura a las aplicaciones. Las memorias comenzarán a generarse cuando configures un modelo.",+ onboardingHistoryWindow:+ "Se ha detectado un gran volumen de conversaciones. Para controlar el uso y mantener coherentes las cronologías, solo se importarán los últimos 3 días de todas las aplicaciones.",+ 导入说明: "Información de importación",+ 正在导入你的会话: "Importando tus conversaciones",+ "后台将持续为你导入,可以放心进入下一步":+ "La importación continuará en segundo plano; puedes pasar al siguiente paso",+ 未开始的导入: "Importaciones no iniciadas",+ "未能开始导入,其他已接受任务不受影响。":+ "No se pudo iniciar la importación. Las demás tareas aceptadas no se ven afectadas.",+ 查看未导入的应用: "Ver aplicaciones sin importar",+ 让记忆继续生长: "Haz crecer tus memorias",+ 连接你的应用: "Conecta tus aplicaciones",+ "适用于本次选择且支持的应用。":+ "Solo para las apps seleccionadas y compatibles.",+ 一键接入应用: "Conectar con un clic",+ "安装记忆连接,让所选应用用上 MemHub 中的相关记忆。":+ "Instala la conexión para que las apps elegidas usen memorias relevantes de MemHub.",+ "当前使用独立测试数据目录,不会修改本机应用的连接配置。":+ "Se utiliza una carpeta independiente de datos de prueba. No se modificará la configuración de conexión de las aplicaciones locales.",+ "点击底部按钮后,后台分别接入各应用;某个应用失败不影响其他应用。":+ "Al continuar, cada app se conecta en segundo plano. Si una falla, las demás siguen.",+ "暂时无法连接应用,当前不会安装连接。":+ "No se pueden conectar aplicaciones por ahora. No se instalará ninguna conexión.",+ onboardingBatchStopped:+ "Se detuvieron las operaciones siguientes; las ya enviadas se comprobarán según sus confirmaciones.",+ onboardingBatchResult: "Confirmadas: {confirmed}; sin confirmar: {failed}.",+ "已确认项保留,请核对未确认任务后重试。":+ "Se conservan las operaciones confirmadas. Comprueba las tareas sin confirmar antes de reintentar.",+ 本次应用导入进度: "Progreso de importación de las aplicaciones",+ 正在导入: "Importando",+ 已暂停: "En pausa",+ 已中断: "Interrumpida",+ 导入遇到问题: "Problema de importación",+ 导入完成: "Importación completada",+ 已取消: "Cancelada",+ 已保存: "Guardada",+ onboardingAppProgress: "Progreso de importación de {name}",+ onboardingSavedMessages: "Mensajes guardados: {count}",+ onboardingScannedOutsideRange:+ "Mensajes examinados: {count}; no hay conversaciones dentro del periodo elegido",+ onboardingScannedNothingToSave:+ "Mensajes examinados: {count}; no hay conversaciones para guardar",+ onboardingScannedFilteringRecent:+ "Mensajes examinados: {count}; filtrando los últimos 3 días",+ onboardingScannedFiltering: "Mensajes examinados: {count}; filtrando",+ onboardingScannedNotSaved: "Mensajes examinados: {count}; aún sin guardar",+ 没有可保存的历史对话: "No hay conversaciones del historial para guardar",+ 状态待核对: "Estado pendiente de comprobar",+ 读取授权不可用: "Autorización de lectura no disponible",+ onboardingReadErrors: " · Errores de lectura: {count}",+ "配置详情,按需要调整": "Ajusta la configuración según tus necesidades",+ "连接未通过,配置已保留": "La conexión falló; tu configuración se conserva",+ "选好模型,让记忆开始沉淀": "Elige un modelo para crear memorias",+ "连接设置已保存\n成功项保留,不重复执行。":+ "Se guardaron los ajustes de conexión.\nSe conservan los cambios completados, sin repetirlos.",+ "已选择:持续同步 · 一键接入":+ "Seleccionado: sincronización continua · Conexión con un clic",+ "沉淀记忆 · 使用你选择的模型": "Crea memorias · Con el modelo que elijas",+ "当前无法启用模型,已填写内容保留。":+ "No se puede habilitar el modelo por ahora. Los datos introducidos se conservan.",+ "模型连接测试通过,可以启用并开始沉淀记忆。":+ "La prueba de conexión fue satisfactoria. Puedes habilitar el modelo y empezar a crear memorias.",+ "先测试模型连通性;测试通过后再启用。":+ "Prueba primero la conexión del modelo. Habilítalo cuando la prueba sea satisfactoria.",+ "跳过,先进入应用": "Omitir por ahora",+ "正在测试模型…": "Probando el modelo…",+ 测试模型连通性: "Probar conexión",+ "正在启用…": "Habilitando…",+ 确认启用: "Confirmar y habilitar",+ 核对提交状态: "Comprobar estado del envío",+ 模型配置: "Configuración del modelo",+ 模型参数: "Parámetros del modelo",+ "选择服务商,填入 API Key。核对已有配置后再继续。":+ "Selecciona un proveedor e introduce su API Key. Comprueba la configuración antes de continuar.",+ 模型服务商: "Proveedor del modelo",+ 选择服务商: "Seleccionar proveedor",+ "已安全保存,留空保留":+ "Guardada de forma segura; deja el campo vacío para conservarla",+ "输入服务商提供的 API Key": "Introduce la API Key del proveedor",+ "连接未通过,请检查 API Key、模型与接口地址后重试。配置已保留。":+ "La conexión falló. Comprueba la API Key, el modelo y la dirección del servicio antes de reintentar. La configuración se conserva.",+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”。":+ "MemHub necesita acceso al llavero. Cuando el sistema lo solicite, selecciona «Permitir siempre».",+ "留空保留已保存密钥;填写新密钥后需重新测试。":+ "Deja el campo vacío para conservar la clave guardada. Si introduces otra clave, deberás repetir la prueba.",+ "密钥保存在系统安全存储中,不写入对话或日志。":+ "La clave se guarda en el almacenamiento seguro del sistema, no en conversaciones ni registros.",+ 配置详情与高级设置: "Detalles y configuración avanzada",+ 服务商待选择: "Proveedor pendiente de seleccionar",+ 模型待填写: "Modelo pendiente de introducir",+ 本地向量模型: "Modelo de embeddings local",+ 向量模型待填写: "Modelo de embeddings pendiente de introducir",+ 思考已关闭: "Razonamiento desactivado",+ 思考未关闭: "Razonamiento no desactivado",+ "预设已填好,只有自定义服务或特殊需求才需要修改。":+ "Los valores predefinidos ya están completos. Solo necesitas modificarlos para servicios personalizados o necesidades específicas.",+ 返回服务商选择: "Volver a seleccionar proveedor",+ 配置名称: "Nombre de la configuración",+ 模型名称: "Nombre del modelo",+ 协议: "Protocolo",+ "Anthropic(暂不支持)": "Anthropic (aún no compatible)",+ "HY 托管(当前不可用)": "HY administrado (no disponible)",+ 向量模型: "Modelo de embeddings",+ "本地 ONNX · 内置": "ONNX local · Integrado",+ 自定义向量: "Embeddings personalizados",+ "超时(秒)": "Tiempo de espera (segundos)",+ 最大并发: "Concurrencia máxima",+ 上下文窗口: "Ventana de contexto",+ "自动 / 可选": "Automática / Opcional",+ 关闭思考模式: "Desactivar el modo de razonamiento",+ "自定义向量配置可展开;远程向量服务须遵守凭据边界。":+ "Puedes desplegar la configuración de embeddings personalizados. Los servicios remotos deben respetar los límites de las credenciales.",+ "切换服务商或模型后,需要重新测试并启用。":+ "Si cambias de proveedor o modelo, deberás repetir la prueba y habilitarlo de nuevo.",+ 向量模型名称: "Nombre del modelo de embeddings",+ 向量协议: "Protocolo de embeddings",+ "同源 OpenAI-compatible(共用 Key)":+ "OpenAI-compatible del mismo origen (clave compartida)",+ "本机 Ollama": "Ollama local",+ "向量 Base URL": "Base URL de embeddings",+ "远程向量地址须与生成服务同源;本机地址仍需校验。":+ "La dirección remota de embeddings debe compartir origen con el servicio de generación. Las direcciones locales también deben validarse.",+ 核对创建结果: "Comprobar resultado de la creación",+ "放弃旧记录,重新配置":+ "Descartar el registro anterior y configurar de nuevo",+ 模型提交状态: "Estado del envío del modelo",+ "正在测试连接…": "Probando la conexión…",+ "正在提交保存与启用,请等待回执…":+ "Enviando la solicitud de guardado y habilitación. Espera la confirmación…",+ "操作结果未确认,已填写内容保留,请核对后重试。":+ "El resultado de la operación no está confirmado. Los datos introducidos se conservan. Compruébalo antes de reintentar.",+ 本次沉淀: "Creación de memorias",+ 让记忆从这里开始: "Tus memorias empiezan aquí",+ 对话来源: "Fuentes de conversaciones",+ 尚无已选来源: "No hay fuentes seleccionadas",+ onboardingSourcesSummary: "{names} y otras aplicaciones ({count} en total)",+ onboardingImportedConversations:+ "Conversaciones importadas: {count}. Los controles de las fuentes siguen determinando qué contenido se sincroniza después en este dispositivo.",+ "处理服务:": "Servicio de procesamiento: ",+ 待选择: "Pendiente de seleccionar",+ "相关对话会发送给所选服务商。":+ "Las conversaciones pertinentes se enviarán al proveedor seleccionado.",+ "测试连接只发送测试内容。启用后会使用此模型整理已导入和之后同步的会话。":+ "La prueba de conexión solo envía contenido de prueba. Al habilitarlo, este modelo procesará las conversaciones importadas y las que se sincronicen después.",+ "当前不能在此启用模型。": "No se puede habilitar el modelo aquí por ahora.",+ 接口地址待核对: "Dirección del servicio pendiente de comprobar",+ "配置已修改,需要重新测试。":+ "La configuración cambió. Debes repetir la prueba.",+ onboardingIntegerRange: "Introduce un número entero entre {min} y {max}.",+ "请填写配置名称。": "Introduce un nombre para la configuración.",+ "请填写实际可用的模型 ID。": "Introduce un ID de modelo disponible.",+ "请填写有效的模型接口地址。":+ "Introduce una dirección válida para el servicio del modelo.",+ "请填写 API Key。": "Introduce una API Key.",+ "请填写向量模型 ID。": "Introduce el ID del modelo de embeddings.",+ "配置结果尚未确认,请在模型设置中核对后重试。":+ "El resultado de la configuración no está confirmado. Compruébalo en la configuración del modelo antes de reintentar.",+ "模型连接测试通过,可以启用。":+ "La prueba de conexión fue satisfactoria. Puedes habilitar el modelo.",+ "连接未通过,请核对模型、密钥和接收方。":+ "La conexión falló. Comprueba el modelo, la clave y el destinatario.",+ "配置或测试结果暂未确认,请核对后重试。":+ "El resultado de la configuración o la prueba aún no está confirmado. Compruébalo antes de reintentar.",+ 自定义兼容服务: "Servicio compatible personalizado",+ 所选连接已启用: "Se habilitaron las conexiones seleccionadas",+ 本次未选择应用连接: "No se seleccionaron conexiones de aplicaciones",+ 尚未填写接收方: "Destinatario pendiente de introducir",+ 本机内置向量模型: "Modelo de embeddings integrado en este dispositivo",+ "操作未确认,草稿已保留。":+ "La operación no está confirmada. El borrador se conserva.",+ "操作已完成,但配置列表暂未刷新。已保留操作回执,请刷新核对,不要重复保存。":+ "La operación terminó, pero la lista no se actualizó. Se conservó la confirmación. Actualiza para comprobarla; no vuelvas a guardar.",+ "暂时无法刷新模型配置,已确认的配置仍保留。请重试刷新。":+ "No se puede actualizar la configuración de modelos. La configuración confirmada se conserva. Vuelve a actualizar.",+ "请先核对上次模型测试结果,暂不修改或启用配置。":+ "Comprueba primero el resultado de la última prueba. No modifiques ni habilites la configuración todavía.",+ "未找到上次创建记录。确认放弃旧记录后可重新配置;系统不会自动重试。":+ "No se encontró el registro de creación anterior. Puedes configurar de nuevo tras confirmar que lo descartas. No se reintentará automáticamente.",+ "创建结果仍待核对,不会重复创建。请稍后再次核对。":+ "El resultado de la creación sigue pendiente. No se repetirá la creación. Vuelve a comprobarlo más tarde.",+ "本地恢复记录已变化,仍保持锁定。请重新打开后核对。":+ "El registro local de recuperación cambió y sigue bloqueado. Vuelve a abrir para comprobarlo.",+ "已发现模型配置,旧创建记录仍保留。请先核对已有配置。":+ "Se encontró una configuración de modelo y se conserva el registro de creación anterior. Comprueba primero la configuración existente.",+ "旧创建记录尚未安全解除,配置仍保持锁定。请重新核对。":+ "El registro anterior aún no se ha liberado de forma segura. La configuración sigue bloqueada. Vuelve a comprobarlo.",+ "配置未保存,请检查模型地址和参数后重试;已填写内容保留。":+ "No se guardó la configuración. Comprueba la dirección y los parámetros del modelo antes de reintentar. Los datos introducidos se conservan.",+ "创建结果尚未确认,请核对已保存结果,不要重复提交。":+ "El resultado de la creación no está confirmado. Comprueba lo guardado; no repitas el envío.",+ "模型配置已变化,旧测试结果不会用于启用,请重新核对配置。":+ "La configuración del modelo cambió. No se usará la prueba anterior para habilitarlo. Comprueba de nuevo la configuración.",+ "暂时无法核对测试服务,本次未发送测试,请恢复连接后重试。":+ "No se puede comprobar el servicio de prueba. No se envió ninguna prueba. Restablece la conexión antes de reintentar.",+ "另一个模型的测试结果尚未确认,请先在该模型上核对测试结果。":+ "La prueba de otro modelo sigue sin confirmar. Comprueba primero el resultado de ese modelo.",+ "测试结果尚未确认。再次点击测试连接将核对原操作,不会重复发送测试。":+ "La prueba sigue sin confirmar. Al pulsar de nuevo se comprobará la operación original, sin repetir el envío.",+ "请先点击测试连接,通过后再设为当前模型。":+ "Prueba primero la conexión. Cuando sea satisfactoria, podrás seleccionar el modelo actual.",+ "这是当前正在使用的模型,请先切换到别的模型再删除。":+ "Este es el modelo en uso. Cambia a otro antes de eliminarlo.",+ "模型配置操作未成功,请核对输入后重试。":+ "La operación de configuración del modelo no se completó. Comprueba los datos antes de reintentar.",+ "它没有 MCP 通道,无法发放可撤销的记忆凭证":+ "No dispone de un canal MCP para emitir credenciales revocables de memorias",+ 当前安装不支持一键插入: "Esta instalación no admite la conexión con un clic",+ 桌面端的连接组件不可用:+ "El componente de conexión de escritorio no está disponible",+ 安装后没有拿到安装回执: "No se recibió una confirmación después de instalar",+ 记忆使用权限没有获批: "No se aprobó el permiso para usar memorias",+ 配置文件被改过: "Se modificó el archivo de configuración",+ "有无法确认的残留,需要人工核对":+ "Quedan elementos sin confirmar que requieren revisión manual",+ 权限存储暂不可用: "El almacenamiento de permisos no está disponible",+ 应用控制通道暂不可用:+ "El canal de control de la aplicación no está disponible",+ "请先把 MemHub 拖到“应用程序”文件夹,再接入应用":+ "Arrastra primero MemHub a la carpeta Aplicaciones para conectar aplicaciones",+ 本机运行时暂不可用: "El entorno de ejecución local no está disponible",+ 桌面端读取接入状态超时:+ "Se agotó el tiempo de lectura del estado de conexión de escritorio",+} as const;++export const onboardingChineseMessages = {+ ...(Object.fromEntries(+ Object.keys(onboardingSpanishMessages).map((key) => [key, key]),+ ) as Record<keyof typeof onboardingSpanishMessages, string>),+ onboardingConnectionPartial:+ "{success} 个应用已接入,{failed} 个未完成:{names}。可进入应用后单独处理。",+ onboardingImportHistory: "导入 {name} 历史",+ onboardingMoreApps: "向下查看更多 · 还有 {count} 个应用",+ "onboardingMoreApps.one": "向下查看更多 · 还有 {count} 个应用",+ onboardingAllApps: "已显示全部 {count} 个应用",+ onboardingImportRefused: "尚未获准导入({reason})。请核对来源后重试。",+ onboardingConfirmHistory: "确认这是 {name} 的历史位置",+ onboardingHistoryWindow:+ "检测到会话数据量较大。为控制用量并保持各应用时间线一致,本次所有应用仅导入最近 3 天的对话。",+ onboardingBatchStopped: "已停止后续操作;已发出的操作仍按回执核对。",+ onboardingBatchResult: "已确认 {confirmed} 项,{failed} 项未确认。",+ onboardingAppProgress: "{name} 导入进度",+ onboardingSavedMessages: "已保存 {count} 条消息",+ onboardingScannedOutsideRange:+ "已扫描 {count} 条,本次没有符合时间范围的对话",+ onboardingScannedNothingToSave: "已扫描 {count} 条,本次没有可保存的对话",+ onboardingScannedFilteringRecent: "已扫描 {count} 条,正在筛选最近 3 天",+ onboardingScannedFiltering: "已扫描 {count} 条,正在筛选",+ onboardingScannedNotSaved: "已扫描 {count} 条,尚未保存",+ onboardingReadErrors: " · {count} 条读取异常",+ onboardingSourcesSummary: "{names} 等 {count} 个应用",+ onboardingImportedConversations:+ "已导入 {count} 条对话;来源开关继续控制之后同步到本机的内容。",+ onboardingIntegerRange: "请输入 {min} 至 {max} 的整数。",+ onboardingModelOperationFailed: "操作没成功:{code}",+ onboardingModelSkipDestination: "跳过后进入应用",+} as const;diff --git a/memhub/packages/i18n/src/gui-i18n-recovery.test.ts b/memhub/packages/i18n/src/gui-i18n-recovery.test.tsnew file mode 100644index 0000000..67c05db--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-recovery.test.ts@@ -0,0 +1,23 @@+import { expect, it } from "vitest";+import { translate } from "./gui-i18n.js";+import {+ recoveryChineseMessages,+ recoverySpanishMessages,+} from "./gui-i18n-recovery.js";++it("covers every recovery key in Spanish with identical interpolation parameters", () => {+ const params = (message: string) =>+ [...message.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)]+ .map((match) => match[1])+ .sort();+ for (const key of Object.keys(+ recoveryChineseMessages,+ ) as (keyof typeof recoveryChineseMessages)[]) {+ expect(recoverySpanishMessages[key], key).toBeTruthy();+ expect(params(recoverySpanishMessages[key]), key).toEqual(+ params(recoveryChineseMessages[key]),+ );+ expect(translate("es", key), key).toBe(recoverySpanishMessages[key]);+ expect(translate("zh-CN", key), key).toBe(recoveryChineseMessages[key]);+ }+});diff --git a/memhub/packages/i18n/src/gui-i18n-recovery.ts b/memhub/packages/i18n/src/gui-i18n-recovery.tsnew file mode 100644index 0000000..9dfdc3b--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-recovery.ts@@ -0,0 +1,209 @@+/** Recovery, diagnostics and native chrome. Never translate diagnostic payloads. */+export const recoveryChineseMessages = {+ startupReadError: "暂时无法读取启动状态,请重试。",+ startupRetry: "重新读取",+ startupOpening: "正在打开 MemHub…",+ nativeHelp: "帮助",+ nativeExportLogs: "导出日志(发给开发排查)",+ nativeExportError: "日志未能导出,请稍后重试。",+ nativeLogin: "登录时启动 {product}",+ nativeTrialUnavailable: "(阶段包不可用)",+ nativeCliManaged: "(由 CLI 管理)",+ nativeStatusUnavailable: "(状态不可用)",+ nativeDevelopmentUnavailable: "(开发模式不可用)",+ nativeOpen: "打开 {product}",+ nativeQuit: "退出 {product}(后台服务继续运行)",+ nativeLoginError: "无法更改登录启动设置,请重试。",+ nativeMoveTitle: "请先将 MemHub 拖到“应用程序”文件夹",+ nativeMoveDetail:+ "从“应用程序”重新打开后,MemHub 才会接入其他应用并安装命令行工具。",+ nativeAcknowledge: "知道了",+ graphWidthTitle: "现有记忆库和内置模型对不上",+ graphWidthDescription:+ "你现在的记忆库按 {stored} 维建的,内置模型出的是 {expected} 维。两者接不上,不选一个的话抽取会一直失败。",+ graphWidthKeep:+ "保留现有记忆库(默认):继续用原来的 embedding 配置,{count} 条记忆和关系图都不动",+ graphWidthRebuild:+ "改用内置模型:现有关系图会被归档(不删除),{count} 条记忆的关系需要重新建一遍",+ graphWidthExport: "先导出再决定:现在什么都不动,导出之后再回来选",+ graphWidthExported: "已导出到 {path}。原库没有动,现在可以再选一次。",+ graphWidthUnknown: "宽度选择尚未确认,现有记忆库未被改动。请重试。",+ graphWidthConfirm: "就这么办",+ importUserProgress:+ "正在导入你的历史对话,已导入 {count} 个会话。记忆会陆续生成,你可以先正常使用。",+ "importUserProgress.one":+ "正在导入你的历史对话,已导入 {count} 个会话。记忆会陆续生成,你可以先正常使用。",+ importUserModel: "模型还没有配置好,新的对话暂时不会整理成记忆。",+ importUserIncomplete: "有些内容没有处理完成,请前往设置查看。",+ importUserSettings: "去设置",+ diagnosticExportDesktop: "请在桌面 App 中导出诊断信息。",+ diagnosticExported: "日志已导出:{filename}",+ diagnosticFile: "诊断文件",+ diagnosticExportFailed: "诊断信息未能导出,请重试。",+ debugTitle: "Debug 日志",+ debugCount: "{count} 条日志,本次启动",+ "debugCount.one": "{count} 条日志,本次启动",+ debugDiagnostics: "诊断",+ debugUsageSubtitle: "记忆沉淀模型用量",+ debugTabs: "诊断页面",+ debugLogsTab: "日志",+ debugUsageTab: "模型用量",+ debugFullscreen: "全屏显示",+ debugExitFullscreen: "退出全屏",+ debugFullscreenLabel: "全屏显示日志",+ debugExitFullscreenLabel: "退出全屏显示日志",+ usageRange15m: "最近 15 分钟",+ usageRange1h: "最近 1 小时",+ usageRange6h: "最近 6 小时",+ usageRange24h: "最近 24 小时",+ usageRange7d: "最近 7 天",+ usageRange: "时间范围",+ usageRangeLabel: "模型用量时间范围",+ usageLoading: "正在读取…",+ usageReadError: "读取失败",+ usageLive: "每 5 秒刷新",+ usageTotalTokens: "总 Tokens",+ usageRequests: "请求数",+ usageChartRegion: "各 Prompt 每分钟 Token 曲线",+ usageChartTitle: "各 Prompt 花费曲线",+ usageChartSubtitle: "每分钟 · Total Tokens",+ usageBreakdown: "Prompt 明细",+ usageCurrentRange: "当前时间范围",+ usageRequestCount: "{count} 次",+ "usageRequestCount.one": "{count} 次",+ usageEmpty: "这个时间范围内没有沉淀模型调用",+ usageNoChart: "暂无曲线数据",+ usageChartAria: "按分钟显示各 Prompt 的 Token 花费",+ debugPause: "暂停实时刷新",+ debugResume: "继续实时刷新",+ debugRefresh: "立即刷新",+ debugClose: "关闭 Debug 日志",+ debugSearchPlaceholder: "搜索事件、组件、错误码或内容",+ debugSearch: "搜索日志",+ debugSource: "日志来源",+ debugAllSources: "全部来源",+ debugCapture: "采集级别",+ debugDisplay: "显示级别",+ debugAll: "全部",+ debugMatches: "{count} 条匹配",+ "debugMatches.one": "{count} 条匹配",+ debugLive: "实时刷新",+ debugPaused: "已暂停",+ debugTruncated: "日志过多,已截断",+ debugReadError: "读取失败",+ debugLoading: "正在读取日志…",+ debugEmpty: "没有匹配的日志",+ debugOpened: "Debug 日志已打开",+ debugOpen: "打开 Debug 日志",+} as const;++export const recoverySpanishMessages: Record<+ keyof typeof recoveryChineseMessages,+ string+> = {+ startupReadError: "No se pudo leer el estado de inicio. Inténtalo de nuevo.",+ startupRetry: "Volver a leer",+ startupOpening: "Abriendo MemHub…",+ nativeHelp: "Ayuda",+ nativeExportLogs: "Exportar registros (para diagnóstico)",+ nativeExportError:+ "No se pudieron exportar los registros. Inténtalo más tarde.",+ nativeLogin: "Iniciar {product} al iniciar sesión",+ nativeTrialUnavailable: " (no disponible en esta versión de prueba)",+ nativeCliManaged: " (administrado por CLI)",+ nativeStatusUnavailable: " (estado no disponible)",+ nativeDevelopmentUnavailable: " (no disponible en desarrollo)",+ nativeOpen: "Abrir {product}",+ nativeQuit: "Salir de {product} (el servicio sigue en segundo plano)",+ nativeLoginError:+ "No se pudo cambiar el inicio de sesión. Inténtalo de nuevo.",+ nativeMoveTitle: "Arrastra MemHub a la carpeta Aplicaciones primero",+ nativeMoveDetail:+ "Abre MemHub desde Aplicaciones para conectarlo con otras aplicaciones e instalar las herramientas de línea de comandos.",+ nativeAcknowledge: "Entendido",+ graphWidthTitle: "La biblioteca y el modelo integrado no coinciden",+ graphWidthDescription:+ "La biblioteca usa {stored} dimensiones y el modelo integrado produce {expected}. Son incompatibles: la extracción seguirá fallando hasta que elijas una opción.",+ graphWidthKeep:+ "Conservar la biblioteca actual (predeterminado): seguir con la configuración de embedding anterior; no se modifican las {count} memorias ni el grafo",+ graphWidthRebuild:+ "Usar el modelo integrado: el grafo actual se archivará (no se eliminará); será necesario reconstruir las relaciones de {count} memorias",+ graphWidthExport:+ "Exportar antes de decidir: no cambiar nada por ahora; volver a elegir después de exportar",+ graphWidthExported:+ "Se exportó a {path}. La biblioteca original no cambió; ahora puedes volver a elegir.",+ graphWidthUnknown:+ "La elección de dimensiones aún no está confirmada; la biblioteca actual no se ha modificado. Inténtalo de nuevo.",+ graphWidthConfirm: "Confirmar esta elección",+ importUserProgress:+ "Importando tus conversaciones anteriores: {count} conversaciones importadas. Las memorias aparecerán gradualmente; puedes seguir usando la aplicación.",+ "importUserProgress.one":+ "Importando tus conversaciones anteriores: {count} conversación importada. Las memorias aparecerán gradualmente; puedes seguir usando la aplicación.",+ importUserModel:+ "El modelo aún no está configurado; las conversaciones nuevas no se convertirán en memorias por ahora.",+ importUserIncomplete:+ "Parte del contenido no terminó de procesarse. Consulta la configuración.",+ importUserSettings: "Ir a configuración",+ diagnosticExportDesktop:+ "Exporta el diagnóstico desde la aplicación de escritorio.",+ diagnosticExported: "Registros exportados: {filename}",+ diagnosticFile: "archivo de diagnóstico",+ diagnosticExportFailed:+ "No se pudo exportar el diagnóstico. Inténtalo de nuevo.",+ debugTitle: "Registros de depuración",+ debugCount: "{count} registros en este inicio",+ "debugCount.one": "{count} registro en este inicio",+ debugDiagnostics: "Diagnóstico",+ debugUsageSubtitle: "Uso del modelo que genera memorias",+ debugTabs: "Páginas de diagnóstico",+ debugLogsTab: "Registros",+ debugUsageTab: "Uso del modelo",+ debugFullscreen: "Pantalla completa",+ debugExitFullscreen: "Salir de pantalla completa",+ debugFullscreenLabel: "Mostrar los registros en pantalla completa",+ debugExitFullscreenLabel: "Salir de la pantalla completa de registros",+ usageRange15m: "Últimos 15 minutos",+ usageRange1h: "Última hora",+ usageRange6h: "Últimas 6 horas",+ usageRange24h: "Últimas 24 horas",+ usageRange7d: "Últimos 7 días",+ usageRange: "Rango de tiempo",+ usageRangeLabel: "Rango de tiempo del uso del modelo",+ usageLoading: "Leyendo…",+ usageReadError: "No se pudo leer el uso",+ usageLive: "Se actualiza cada 5 segundos",+ usageTotalTokens: "Tokens totales",+ usageRequests: "Solicitudes",+ usageChartRegion: "Tokens por minuto de cada prompt",+ usageChartTitle: "Consumo por prompt",+ usageChartSubtitle: "Por minuto · Total Tokens",+ usageBreakdown: "Detalle por prompt",+ usageCurrentRange: "Rango de tiempo actual",+ usageRequestCount: "{count} solicitudes",+ "usageRequestCount.one": "{count} solicitud",+ usageEmpty: "No hubo llamadas al modelo de memorias en este rango de tiempo",+ usageNoChart: "Aún no hay datos para la curva",+ usageChartAria: "Tokens consumidos por minuto de cada prompt",+ debugPause: "Pausar actualización en vivo",+ debugResume: "Reanudar actualización en vivo",+ debugRefresh: "Actualizar ahora",+ debugClose: "Cerrar registros de depuración",+ debugSearchPlaceholder:+ "Buscar eventos, componentes, códigos de error o contenido",+ debugSearch: "Buscar registros",+ debugSource: "Origen de los registros",+ debugAllSources: "Todos los orígenes",+ debugCapture: "Nivel de captura",+ debugDisplay: "Nivel mostrado",+ debugAll: "Todos",+ debugMatches: "{count} coincidencias",+ "debugMatches.one": "{count} coincidencia",+ debugLive: "Actualización en vivo",+ debugPaused: "En pausa",+ debugTruncated: "Demasiados registros; se truncaron",+ debugReadError: "No se pudieron leer los registros",+ debugLoading: "Leyendo registros…",+ debugEmpty: "No hay registros coincidentes",+ debugOpened: "Registros de depuración abiertos",+ debugOpen: "Abrir registros de depuración",+};diff --git a/memhub/packages/i18n/src/gui-i18n-settings.test.ts b/memhub/packages/i18n/src/gui-i18n-settings.test.tsnew file mode 100644index 0000000..66a82c3--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-settings.test.ts@@ -0,0 +1,22 @@+import { expect, it } from "vitest";+import { translate } from "./gui-i18n.js";+import {+ settingsChineseMessages,+ settingsSpanishMessages,+} from "./gui-i18n-settings.js";++it("provides Spanish settings copy with matching interpolation parameters", () => {+ for (const key of Object.keys(+ settingsSpanishMessages,+ ) as (keyof typeof settingsSpanishMessages)[]) {+ const params = (value: string) =>+ [...value.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)]+ .map((match) => match[1])+ .sort();+ expect(settingsSpanishMessages[key], key).toBeTruthy();+ expect(params(settingsSpanishMessages[key]), key).toEqual(+ params(settingsChineseMessages[key]),+ );+ expect(translate("es", key), key).not.toMatch(/[\u3400-\u9fff]/);+ }+});diff --git a/memhub/packages/i18n/src/gui-i18n-settings.ts b/memhub/packages/i18n/src/gui-i18n-settings.tsnew file mode 100644index 0000000..84e01f0--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-settings.ts@@ -0,0 +1,359 @@+/** GUI copy only: never apply this catalog to persisted memories or provider data. */+export const settingsSpanishMessages = {+ "这里需要 API Key,不是网址。请填写服务方提供的密钥。":+ "Aquí se necesita una clave API, no una URL. Introduce la clave del proveedor.",+ "服务商拒绝了这个 API Key(401)。请确认密钥属于当前填写的服务地址。":+ "El proveedor rechazó la clave API (401). Comprueba que corresponda a la dirección del servicio.",+ "服务商没有这个模型名,请对照服务商的模型列表核对。":+ "El proveedor no reconoce este modelo. Comprueba su lista de modelos.",+ "连不上接口地址,请检查网络和服务地址是否正确。":+ "No se pudo conectar al servicio. Comprueba la red y la dirección.",+ 未提供接口地址: "No se indicó una dirección del servicio",+ "请填写生成模型名。": "Introduce el identificador del modelo de generación.",+ "请填写完整的 http:// 或 https:// 接口地址。":+ "Introduce una dirección completa del servicio con http:// o https://.",+ "请填写向量模型名。": "Introduce el identificador del modelo de embeddings.",+ "请填写完整的向量模型接口地址。":+ "Introduce la dirección completa del servicio de embeddings.",+ "这份配置在测试期间被改过,刚才测的是改动后的版本。配置已保存但未启用,请重新测试并启用。":+ "La configuración cambió durante la prueba; se probó la versión modificada. Está guardada, pero no habilitada. Vuelve a probarla y habilitarla.",+ "测试结果来自这份配置更早的版本。配置已保存但未启用,请重新测试并启用。":+ "La prueba corresponde a una versión anterior. La configuración está guardada, pero no habilitada. Vuelve a probarla y habilitarla.",+ "配置已保存,连接测试未通过。请核对配置后重试,历史对话尚未发送。":+ "Configuración guardada; la prueba de conexión falló. Compruébala y reintenta. No se han enviado conversaciones anteriores.",+ "配置已保存,尚未确认启用成功。请核对配置后重试。":+ "Configuración guardada; la activación aún no está confirmada. Compruébala y reintenta.",+ "配置尚未完成测试和启用,请核对后重试。":+ "La prueba y activación no se completaron. Comprueba la configuración y reintenta.",+ "配置尚未保存成功,已填写内容保留,可核对后重试。":+ "No se confirmó el guardado. Se conserva lo introducido; compruébalo y reintenta.",+ "只需配置生成模型。向量嵌入已内置在本机,不为 System 1、System 2 分开选模型。":+ "Solo necesitas configurar el modelo de generación. Los embeddings están integrados localmente; System 1 y System 2 no requieren modelos separados.",+ "无法读取测试恢复记录,暂不发送新的测试。":+ "No se pudo leer el registro de recuperación de pruebas. No se enviarán nuevas pruebas por ahora.",+ "上次模型测试结果待核对,暂不修改或启用配置。":+ "El resultado de la última prueba está pendiente. No se modificará ni habilitará la configuración por ahora.",+ 核对测试结果: "Comprobar resultado de la prueba",+ "上次模型创建结果待核对,暂不开始新的操作。":+ "La última creación está pendiente de comprobar. No se iniciarán nuevas operaciones por ahora.",+ 核对创建结果: "Comprobar resultado de la creación",+ "配置已保存,正在测试连接…": "Configuración guardada. Probando conexión…",+ "连接通过,正在启用模型…": "Conexión correcta. Habilitando modelo…",+ 刷新配置列表: "Actualizar configuraciones",+ 自定义一个模型: "Configurar un modelo personalizado",+ 已保存的模型配置: "Configuración de modelo guardada",+ "已保存,已启用": "Guardada y habilitada",+ "已保存,连接通过": "Guardada; conexión correcta",+ "已保存,测试未通过": "Guardada; prueba fallida",+ "已保存,待测试": "Guardada; pendiente de prueba",+ 版本: "Versión",+ "需要允许 MemHub 访问钥匙串。系统询问时请选择“始终允许”;已保存的配置不会丢失。":+ "MemHub necesita acceso al llavero. Cuando el sistema lo solicite, selecciona «Permitir siempre». La configuración guardada se conservará.",+ "测试只向此接口发送测试内容,不发送历史对话。":+ "La prueba solo envía contenido de prueba a este servicio, no conversaciones anteriores.",+ 重试测试并启用: "Reintentar prueba y habilitar",+ 测试并启用: "Probar y habilitar",+ 编辑配置: "Editar configuración",+ 新增配置: "Añadir configuración",+ 编辑: "Editar",+ "。修改后需重新测试并设为当前模型,内容授权不会自动更新。":+ ". Después de modificar, vuelve a probar y seleccionar el modelo actual. La autorización de contenido no se actualizará automáticamente.",+ "配置已在其他位置变化,草稿已保留。请取消编辑后重新打开核对。":+ "La configuración cambió en otro lugar. Se conserva el borrador. Cancela la edición y vuelve a abrirla para comprobarla.",+ 服务商预设: "Preajuste del proveedor",+ 自定义兼容服务: "Servicio compatible personalizado",+ "只是帮你填好接口地址和一个模型名,不代表这个模型当前可用。 请对照服务商的模型列表核对后再保存。":+ "Solo completa la dirección y un identificador de modelo; no garantiza su disponibilidad. Comprueba la lista del proveedor antes de guardar.",+ 协议: "Protocolo",+ "与模型服务提供的接口协议保持一致。":+ "Debe coincidir con el protocolo del servicio del modelo.",+ 配置名称: "Nombre de la configuración",+ "用于区分配置,不影响模型请求。":+ "Sirve para distinguir configuraciones; no afecta a las solicitudes al modelo.",+ 生成模型名: "Identificador del modelo de generación",+ "例如:gpt-4o-mini…": "Por ejemplo: gpt-4o-mini…",+ "填写服务方提供的完整模型标识。":+ "Introduce el identificador completo que proporciona el proveedor.",+ "高级:自行配置向量模型": "Avanzado: configurar embeddings",+ 向量配置模式: "Modo de configuración de embeddings",+ 本地内置: "Integrado localmente",+ 自定义向量模型: "Modelo de embeddings personalizado",+ 向量模型名: "Identificador del modelo de embeddings",+ "例如:text-embedding-3-small…": "Por ejemplo: text-embedding-3-small…",+ 向量模型来源: "Proveedor de embeddings",+ "本机 Ollama": "Ollama local",+ "同源 OpenAI-compatible(共用 API Key)":+ "OpenAI-compatible del mismo origen (comparte clave API)",+ "向量模型 Base URL": "Base URL de embeddings",+ "为避免凭据外泄,向量地址必须与生成模型同源。":+ "Para evitar filtraciones de credenciales, la dirección de embeddings debe tener el mismo origen que la del modelo de generación.",+ "使用内置本地向量模型;不会发送内容给远程向量服务。":+ "Usa los embeddings locales integrados. No se envía contenido a un servicio remoto de embeddings.",+ 自定义向量: "Embeddings personalizados",+ 尚未填写模型: "Modelo sin indicar",+ 尚未填写地址: "Dirección sin indicar",+ "填写服务接口地址,不是聊天网页地址。":+ "Introduce la dirección del servicio, no la página web del chat.",+ "(可选)": " (opcional)",+ "保存后不会再次显示…": "No volverá a mostrarse después de guardar…",+ "留空保留已保存密钥;填写新密钥后需重新测试和启用。":+ "Déjala vacía para conservar la clave guardada. Si introduces otra, vuelve a probar y habilitar.",+ "换了服务商后需要填写新的 API Key,已保存的密钥不会带到新地址。":+ "Al cambiar de proveedor necesitas otra clave API. La clave guardada no se enviará a la nueva dirección.",+ "保存在系统安全存储中,不随安装包分发。":+ "Se guarda en el almacén seguro del sistema; no se distribuye con la aplicación.",+ "关闭思考链(向支持的厂商下发 thinking-off 参数)":+ "Desactivar razonamiento (envía thinking-off a proveedores compatibles)",+ 保存修改: "Guardar cambios",+ 保存配置: "Guardar configuración",+ "正在启用配置…": "Habilitando configuración…",+ 测试并完成配置: "Probar y completar configuración",+ 保存并测试启用: "Guardar, probar y habilitar",+ 取消编辑: "Cancelar edición",+ "密钥保存在系统安全存储;测试仅发送测试内容。":+ "La clave se guarda en el almacén seguro del sistema. La prueba solo envía contenido de prueba.",+ 当前使用: "En uso",+ 未启用: "No habilitada",+ 测试目标: "Destino de prueba",+ "。仅发送测试内容,不发送历史对话。":+ ". Solo se envía contenido de prueba, no conversaciones anteriores.",+ 测试连接: "Probar conexión",+ 设为当前模型: "Seleccionar como modelo actual",+ 删除: "Eliminar",+ "粘贴 API Key": "Pegar clave API",+ "密钥尚未保存成功,已填写内容保留,可重试。":+ "No se confirmó el guardado de la clave. Se conserva lo introducido; puedes reintentar.",+ 生成接收方: "Destinatario de generación",+ 向量接收方: "Destinatario de embeddings",+ 本机: "Este dispositivo",+ "。启用此配置后按上方选择处理历史及未来允许来源。":+ ". Al habilitar, se procesarán las fuentes históricas y futuras autorizadas según la selección anterior.",+ "保存 key": "Guardar clave",+ "还没有 key?去申请": "¿No tienes clave? Solicítala",+ 删除这张卡: "Eliminar esta configuración",+ "密钥已配置,当前读取状态待确认。":+ "Clave configurada; su lectura está pendiente de confirmar.",+ "等待 key:其余都已经填好了,贴上 key 就能用。":+ "Falta la clave; los demás campos ya están completos.",+ "key 已保存,还没测过这个模型能不能用。":+ "Clave guardada; el modelo todavía no se ha probado.",+ "Ollama(本机)": "Ollama (local)",+ "内置 bge-small-zh-v1.5": "Integrado: bge-small-zh-v1.5",+ 通过: "Correcta",+ "HY 托管模型尚不可用": "El modelo administrado de HY no está disponible",+ "缺少 API Key": "Falta la clave API",+ 服务不可达: "Servicio inaccesible",+ "认证失败;更新 key 后再检测,会自动接着处理":+ "Autenticación fallida. Actualiza la clave y vuelve a comprobar para continuar el procesamiento",+ 请求频率受限: "Límite de solicitudes alcanzado",+ "模型账户余额不足;充值或换 key 后再检测,会自动接着处理":+ "Saldo insuficiente. Recarga o cambia la clave y comprueba de nuevo para continuar el procesamiento",+ 没有找到模型: "Modelo no encontrado",+ "该网关不提供模型列表,已改由生成调用验证":+ "Este servicio no ofrece una lista de modelos; se verificó mediante generación",+ 服务返回不符合协议: "Respuesta incompatible con el protocolo",+ 结构化输出未通过: "La salida estructurada no superó la prueba",+ "需要填写 Embedding 模型": "Es necesario indicar un modelo de embeddings",+ "Embedding 模型不可用": "Modelo de embeddings no disponible",+ "请先核对上次模型测试结果,暂不修改或启用配置。":+ "Comprueba primero el resultado de la última prueba. No modifiques ni habilites la configuración todavía.",+ "本地恢复记录已变化,仍保持锁定。请重新打开后核对。":+ "El registro local de recuperación cambió y sigue bloqueado. Vuelve a abrir para comprobarlo.",+ 测试结果: "Resultado de la prueba",+ "暂不支持一键插入:它没有 MCP 通道,无法发放可撤销的记忆凭证。":+ "No admite la conexión con un clic: no tiene canal MCP y no se pueden emitir credenciales revocables de memoria.",+ 应用控制通道暂不可用:+ "El canal de control de la aplicación no está disponible",+ // Fragments appended to an app failure; Spanish carries its own separator.+ appFailureReason: " Motivo: {reason}.",+ appFailureReread:+ " Tampoco se pudo volver a leer la conexión; el estado mostrado podría no estar actualizado.",+ 模型: "Modelo",+ 连接其他应用: "Conectar otras aplicaciones",+ 帮助与诊断: "Ayuda y diagnóstico",+ 设置分组: "Secciones de configuración",+ 记忆模型: "Modelo de memorias",+ 当前模型: "Modelo actual",+ "正在读取模型…": "Leyendo el modelo…",+ 模型状态暂不可读: "Estado del modelo no disponible",+ 尚未配置模型: "No hay un modelo configurado",+ 修改模型: "Modificar modelo",+ 配置模型: "Configurar modelo",+ 刷新模型状态: "Actualizar estado del modelo",+ "本机 / 受管端点": "Servicio local / administrado",+ 接口地址待核对: "Dirección del servicio pendiente de comprobar",+ "模型状态未能读取,请重试。":+ "No se pudo leer el estado del modelo. Reintenta.",+ "模型状态刷新未成功,仍显示上次确认的模型状态;请重试。":+ "No se pudo actualizar el estado. Se muestra el último estado confirmado; reintenta.",+ "上次模型测试或创建还待核对,配置暂时不能改动。请先在下方模型配置区核对结果; 现有配置和原文不会被改动。":+ "La última prueba o creación del modelo está pendiente de comprobar, así que la configuración no se puede modificar por ahora. Compruébala primero en la sección de configuración del modelo, más abajo; no se modificarán la configuración ni los textos originales.",+ 用模型沉淀记忆: "Generar memorias con el modelo",+ "开启后,导入和同步到本机的会话会交给当前模型整理成记忆,会产生模型调用。 停止后不再调用模型、不再整理记忆,但会话仍会照常导入和保存;已排队的内容会留着,重新开启后继续。 模型配置始终保留,重新开启不需要重新填写。":+ "Al activarlo, las conversaciones importadas y sincronizadas en este equipo se envían al modelo actual para convertirlas en memorias, lo que genera llamadas al modelo. Al detenerlo, ya no se llama al modelo ni se procesan memorias, pero las conversaciones se siguen importando y guardando; lo que está en cola se conserva y continúa al volver a activarlo. La configuración del modelo se conserva siempre; no hace falta volver a introducirla.",+ "启用未能确认,仍显示上次确认的状态;请重试。":+ "No se pudo confirmar la activación; se muestra el último estado confirmado. Reinténtalo.",+ "停止未能确认,模型可能仍在整理记忆,请重试。":+ "No se pudo confirmar la detención; es posible que el modelo siga procesando memorias. Reinténtalo.",+ "当前安装还不能读取这个开关,请确认后台服务已启动后重试。":+ "Esta instalación aún no puede leer este interruptor. Comprueba que el servicio en segundo plano esté activo y reinténtalo.",+ 关于: "Acerca de",+ "此应用还没有读取授权,请先授权它的对话目录。":+ "Esta aplicación aún no tiene permiso de lectura. Autoriza primero su carpeta de conversaciones.",+ "此应用的读取授权已撤销,请重新授权。":+ "Se revocó el permiso de lectura de esta aplicación. Vuelve a autorizarla.",+ "此应用的对话目录已被重建,请重新授权。":+ "La carpeta de conversaciones de esta aplicación se volvió a crear. Vuelve a autorizarla.",+ "此应用的对话目录现在读不到,请确认应用已安装并产生过对话。":+ "No se puede leer la carpeta de conversaciones de esta aplicación. Comprueba que esté instalada y que tenga conversaciones.",+ "此应用的对话目录已变更,请按最新目录重新授权。":+ "La carpeta de conversaciones de esta aplicación cambió. Vuelve a autorizarla con la carpeta actual.",+ "此应用还没有读取授权,请先授权它的对话目录。完成后再开启持续同步。":+ "Esta aplicación aún no tiene permiso de lectura. Autoriza primero su carpeta de conversaciones y después activa la sincronización continua.",+ "此应用的读取授权已撤销,请重新授权。完成后再开启持续同步。":+ "Se revocó el permiso de lectura de esta aplicación. Vuelve a autorizarla y después activa la sincronización continua.",+ "此应用的对话目录已被重建,请重新授权。完成后再开启持续同步。":+ "La carpeta de conversaciones de esta aplicación se volvió a crear. Vuelve a autorizarla y después activa la sincronización continua.",+ "此应用的对话目录现在读不到,请确认应用已安装并产生过对话。完成后再开启持续同步。":+ "No se puede leer la carpeta de conversaciones de esta aplicación. Comprueba que esté instalada y que tenga conversaciones, y después activa la sincronización continua.",+ "此应用的对话目录已变更,请按最新目录重新授权。完成后再开启持续同步。":+ "La carpeta de conversaciones de esta aplicación cambió. Vuelve a autorizarla con la carpeta actual y después activa la sincronización continua.",+ "此应用的读取授权已失效,请重新授权后再开启持续同步。":+ "El permiso de lectura de esta aplicación ya no es válido. Vuelve a autorizarla y después activa la sincronización continua.",+ "此应用的授权或目录已变化,已按最新状态显示,请确认后再试。":+ "El permiso o la carpeta de esta aplicación cambiaron. Se muestra el estado actual; compruébalo y vuelve a intentarlo.",+ 模型配置表单: "Formulario de configuración del modelo",+ "部分运行状态暂时无法读取,当前显示最后读到的状态,请重试。":+ "Algunos estados no están disponibles. Se muestra la última lectura; reintenta.",+ "当前安装还不能设置登录后后台启动。":+ "Esta instalación no permite configurar el inicio en segundo plano al iniciar sesión.",+ "登录后后台启动设置未能确认,请重试。":+ "No se pudo confirmar el inicio en segundo plano. Reintenta.",+ "当前安装还不能退出界面,请从菜单栏退出。":+ "Esta instalación no permite cerrar la interfaz desde aquí. Usa la barra de menús.",+ "退出界面未能确认,请重试。":+ "No se pudo confirmar el cierre de la interfaz. Reintenta.",+ 登录后启动后台服务: "Iniciar el servicio al iniciar sesión",+ "无需打开界面,持续同步、整理和提供记忆。":+ "Sincroniza, organiza y ofrece memorias sin abrir la interfaz.",+ 导出日志: "Exportar registros",+ "把本机运行日志打包成一个文件,发给开发排查。":+ "Empaqueta los registros locales en un archivo para su diagnóstico.",+ "确定退出 One Memory 界面吗?": "¿Cerrar la interfaz de MemHub?",+ "后台服务会继续同步、整理和提供记忆。":+ "El servicio en segundo plano seguirá sincronizando, organizando y ofreciendo memorias.",+ 取消: "Cancelar",+ 退出界面: "Cerrar interfaz",+ 应用详情: "Detalles de la aplicación",+ 返回应用: "Volver a Aplicaciones",+ 同步开关: "Sincronización",+ "开启后处理历史待办,并持续接收此应用的新会话。":+ "Al activar, procesa el historial pendiente y recibe las nuevas conversaciones de esta aplicación.",+ "正在读取已有对话,首次开启可能需要一两分钟,请不要重复点击。":+ "Leyendo conversaciones existentes. El primer inicio puede tardar uno o dos minutos; no vuelvas a pulsar.",+ "将补充冻结期间的新对话;原有 pending Job 继续处理。":+ "Se incorporarán las conversaciones del periodo pausado; los trabajos pendientes existentes seguirán procesándose.",+ 一键插入应用: "Conectar con un clic",+ "安装记忆连接,并默认允许此应用使用已授权记忆。":+ "Instala la conexión y permite a esta aplicación usar las memorias autorizadas.",+ 允许使用记忆: "Permitir el uso de memorias",+ 连接状态: "Estado de conexión",+ 已接通: "Conectada",+ "已安装,但取不到记忆": "Instalada, sin acceso a memorias",+ 未接通: "Sin conexión",+ 状态待核对: "Estado pendiente de comprobar",+ 检测中: "Detectando",+ 未开启关联: "Conexión no habilitada",+ "正在开启处理…": "Activando procesamiento…",+ "正在冻结处理…": "Pausando procesamiento…",+ 处理中: "Procesando",+ 已冻结: "En pausa",+ "此应用的处理开关结果未能确认,其他应用不受影响。":+ "No se pudo confirmar el cambio de procesamiento de esta aplicación. Las demás no se ven afectadas.",+ "暂时无法刷新来源状态,请重试;未更改同步或读取权限。":+ "No se pudo actualizar el estado de la fuente. Reintenta; no se modificaron los permisos de sincronización ni de lectura.",+ "暂时无法读取连接状态,当前状态待核对;请重试。":+ "No se pudo leer el estado de conexión. Está pendiente de comprobar; reintenta.",+ "已接通。已经打开的对话不会中途出现这个工具,请新开一轮。":+ "Conectada. La herramienta no aparecerá en conversaciones ya abiertas; inicia una nueva.",+ "本次连接探测失败,当前状态待核对;未把上次读取当作本次成功。":+ "La comprobación de conexión falló. El estado está pendiente; la lectura anterior no se considera un éxito actual.",+ 上次读取: "Última lectura",+ appSettingsTitle: "Configuración de {name}",+ appMemoryScope:+ "Permite que {name} consulte las memorias dentro del alcance autorizado.",+ appRestart:+ "La herramienta de memorias no está en la conversación actual de {name}. Cierra completamente {name} y vuelve a abrirla; aparecerá en una conversación nueva.",+ appConnectFailed:+ "No se completó la conexión de esta aplicación. Las demás no se ven afectadas.{reason}",+ appDisconnectFailed:+ "No se pudo eliminar la conexión ni revocar el permiso. {name} aún puede usar memorias. Reintenta.{reason}",+ appPermissionFailed:+ "No se pudo confirmar el permiso de uso de memorias de esta aplicación. Reintenta.{reason}",+ appRevokedModified:+ "Se revocó el permiso; {name} ya no puede consultar memorias. El archivo de configuración cambió y MemHub no lo eliminó automáticamente. Quita manualmente la conexión de MemHub.",+ appRevokedRetained:+ "Se revocó el permiso; {name} ya no puede consultar memorias. No se eliminó el archivo de conexión. Compruébalo de nuevo.",+ appRevokedReview:+ "Se revocó el permiso; {name} ya no puede consultar memorias. No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",+ appRemovalReview:+ "No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",+ "Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":+ "Las credenciales de conexión de Cursor se actualizaron. Cierra completamente Cursor y vuelve a abrirlo; después, inicia una conversación nueva.",+ 连接其他工具: "Conectar otras herramientas",+ "本机连接材料仅在桌面 App 中可用。":+ "El material de conexión local solo está disponible en la aplicación de escritorio.",+ "仅本机 MCP / 命令工具。纯网页聊天不支持直接连接本机。":+ "Solo herramientas MCP / comandos locales. Los chats exclusivamente web no pueden conectarse directamente a este dispositivo.",+ "列表内工具请用上方一键安装,此处仅供未列出的工具。":+ "Para las herramientas de la lista, usa la instalación directa de arriba. Esta sección es para otras herramientas.",+ "正在读取本机连接配置…": "Leyendo la configuración de conexión local…",+ "未能读取连接配置。": "No se pudo leer la configuración de conexión.",+ 重试: "Reintentar",+ 连接材料格式: "Formato del material de conexión",+ 连接提示词: "Instrucciones de conexión",+ "MCP 配置": "Configuración MCP",+ 命令: "Comando",+ 本机连接材料: "Material de conexión local",+ "包含本机路径,不含记忆和密钥。片段会运行本机 MemHub 连接程序;粘贴前请确认,MemHub 需保持运行。":+ "Incluye rutas locales, pero no memorias ni claves. Los fragmentos ejecutan el conector local de MemHub. Revísalos antes de pegarlos y mantén MemHub en ejecución.",+ "已复制,尚未建立连接。":+ "Copiado. La conexión todavía no se ha establecido.",+ "复制失败,可在上方选中文本复制。":+ "No se pudo copiar. Puedes seleccionar el texto de arriba y copiarlo manualmente.",+ 复制提示词: "Copiar instrucciones",+ 复制配置: "Copiar configuración",+ 复制命令: "Copiar comando",+ 记忆库分页: "Paginación de la biblioteca de memorias",+ 上一页: "Página anterior",+ 下一页: "Página siguiente",+} as const;++const chineseOverrides: Partial<+ Record<keyof typeof settingsSpanishMessages, string>+> = {+ "确定退出 One Memory 界面吗?": "确定退出 MemHub 界面吗?",+ appSettingsTitle: "{name} 应用设置",+ appMemoryScope: "让 {name} 查询已授权范围内的记忆。",+ appRestart:+ "记忆工具没有进到 {name} 当前对话。完全退出 {name} 后重新打开,新对话里才会出现。",+ appConnectFailed: "此应用的一键接入未完成,其他应用不受影响。{reason}",+ appDisconnectFailed:+ "连接未能移除,记忆权限也未能撤销,{name} 仍可使用记忆,请重试。{reason}",+ appPermissionFailed: "此应用的记忆使用权限未能确认,请重试。{reason}",+ appFailureReason: "原因:{reason}。",+ appFailureReread: "当前接入状态也未能重新读取,显示的可能不是最新状态。",+ appRevokedModified:+ "已撤销记忆权限,{name} 已查不到记忆。配置文件被改过,MemHub 没有自动删除;请手动移除其中的 MemHub 连接。",+ appRevokedRetained:+ "已撤销记忆权限,{name} 已查不到记忆。连接文件没有移除,请重新核对。",+ appRevokedReview:+ "已撤销记忆权限,{name} 已查不到记忆。但无法确认连接已全部移除,需要你手动核对:{paths}。",+ appRemovalReview: "无法确认连接已全部移除,需要你手动核对:{paths}。",+};+export const settingsChineseMessages = Object.fromEntries(+ Object.keys(settingsSpanishMessages).map((key) => [+ key,+ chineseOverrides[key as keyof typeof settingsSpanishMessages] ?? key,+ ]),+) as Record<keyof typeof settingsSpanishMessages, string>;diff --git a/memhub/packages/i18n/src/gui-i18n-workbench.ts b/memhub/packages/i18n/src/gui-i18n-workbench.tsnew file mode 100644index 0000000..1be6df2--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n-workbench.ts@@ -0,0 +1,683 @@+// Interface copy only: model answers, memory content and graph labels are opaque.+export const workbenchChineseMessages = {+ "memory:{count} 条": "{count} 条",+ "memory:已可用 · {count} 段原文": "已可用 · {count} 段原文",+ "memory:主题视角(非事项)": "主题视角(非事项)",+ "memory:来源视角": "来源视角",+ "memory:{count} 条记忆 · 当前已加载": "{count} 条记忆 · 当前已加载",+ "memory:最近 {count} 条": "最近 {count} 条",+ "memory:已确认": "已确认",+ "memory:记忆库": "记忆库",+ "memory:问记忆": "问记忆",+ "memory:历史对话": "历史对话",+ "memory:项目记忆": "项目记忆",+ "memory:编码偏好": "编码偏好",+ "memory:长期模式": "长期模式",+ "memory:意图": "意图",+ "memory:近 3 个月": "近 3 个月",+ "memory:近 6 个月": "近 6 个月",+ "memory:近 1 年": "近 1 年",+ "memory:全部历史": "全部历史",+ "memory:{count} 条这次没能整理成功,正在重试":+ "{count} 条这次没能整理成功,正在重试",+ "memory:{count} 处理中": "{count} 处理中",+ "memory: · 处理中 {running} / 待派发 {active}":+ " · 处理中 {running} / 待派发 {active}",+ "memory: · {count} 条任务状态待核对": " · {count} 条任务状态待核对",+ "memory: · {count} 条任务状态异常,正在恢复":+ " · {count} 条任务状态异常,正在恢复",+ "memory:{count} 等待": "{count} 等待",+ "memory:最新 {count} 条待处理": "最新 {count} 条待处理",+ "memory:历史积压 {count} 条": "历史积压 {count} 条",+ "memory:(约 {count} 分钟)": "(约 {count} 分钟)",+ "memory:(约 {count} 小时)": "(约 {count} 小时)",+ "memory:(约 {count} 天)": "(约 {count} 天)",+ "memory:同步尝试 {count} 次": "同步尝试 {count} 次",+ "memory:尚未尝试同步": "尚未尝试同步",+ "memory: · 状态更新于 {date}": " · 状态更新于 {date}",+ "memory:HY Memory 当前没有这条记忆,仅重试同步不能补齐。":+ "HY Memory 当前没有这条记忆,仅重试同步不能补齐。",+ "memory:同步需要可用的本机整理模型或本地嵌入授权。":+ "同步需要可用的本机整理模型或本地嵌入授权。",+ "memory:这条记忆或模型版本已经变化,先刷新核对再决定下一步。":+ "这条记忆或模型版本已经变化,先刷新核对再决定下一步。",+ "memory:这条记忆已改,搜索索引还没开始同步。":+ "这条记忆已改,搜索索引还没开始同步。",+ "memory:最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。":+ "最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。",+ "memory:这条记忆已改,搜索索引还没跟上。": "这条记忆已改,搜索索引还没跟上。",+ "memory:搜索里还是改之前那句话。": "搜索里还是改之前那句话。",+ "memory:重试同步": "重试同步",+ "memory:配置整理模型": "配置整理模型",+ "memory:未提炼 · 在窗口外": "未提炼 · 在窗口外",+ "memory:未提炼 · 排队中": "未提炼 · 排队中",+ "wb.select": "请选择",+ "memory:模型综合": "模型综合",+ "memory:原文摘录": "原文摘录",+ "memory:没有命中": "没有命中",+ "memory:正在生成": "正在生成",+ "memory:正在检索记忆": "正在检索记忆",+ "memory: · 基于 {count} 条已确认记忆": " · 基于 {count} 条已确认记忆",+ "memory: · 基于 {count} 条已确认记忆.one": " · 基于 {count} 条已确认记忆",+ "memory:整理需要处理": "整理需要处理",+ "memory:正在整理记忆": "正在整理记忆",+ "memory:整理状态": "整理状态",+ "memory:重新整理": "重新整理",+ "memory:自动提炼范围": "自动提炼范围",+ "memory:手动提炼下一批": "手动提炼下一批",+ "memory:刷新核对": "刷新核对",+ "memory:正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。":+ "正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。",+ "memory:选择:{content}": "选择:{content}",+ "memory:处理失败:{content}": "处理失败:{content}",+ "memory:已选 {count} 条": "已选 {count} 条",+ "memory:已选 {count} 条.one": "已选 {count} 条",+ "memory:删除所选 {count} 条": "删除所选 {count} 条",+ "memory:删除所选 {count} 条.one": "删除所选 {count} 条",+ "memory:重试失败的 {count} 条": "重试失败的 {count} 条",+ "memory:重试失败的 {count} 条.one": "重试失败的 {count} 条",+ "memory:没有{status}的记忆。": "没有{status}的记忆。",+ "memory:已{action} {count} 条": "已{action} {count} 条",+ "memory:已{action} {count} 条.one": "已{action} {count} 条",+ "memory:,{count} 条未完成": ",{count} 条未完成",+ "memory:,{count} 条未完成.one": ",{count} 条未完成",+ "memory:未能{action}:{error}": "未能{action}:{error}",+ "memory:重试{action}": "重试{action}",+ // Action names inside the bulk templates below; the Chinese is the bare verb.+ "memory:删除(操作)": "删除",+ "memory:处理(操作)": "处理",+ "memory:{count} 条原话": "{count} 条原话",+ "memory:{count} 条原话.one": "{count} 条原话",+ "memory:有 {count} 段对话的整理结果不确定":+ "有 {count} 段对话的整理结果不确定",+ "memory:有 {count} 段对话的整理结果不确定.one":+ "有 {count} 段对话的整理结果不确定",+ "memory:{count} 次整理已完成": "{count} 次整理已完成",+ "memory:{count} 次整理已完成.one": "{count} 次整理已完成",+ "memory: · {count} 条在窗口外(原文可搜)":+ " · {count} 条在窗口外(原文可搜)",+ "memory: · {count} 条在窗口外(原文可搜).one":+ " · {count} 条在窗口外(原文可搜)",+ "memory: · 已规划 {planned} 批,当前第 {current} 批":+ " · 已规划 {planned} 批,当前第 {current} 批",+ "memory:{kind}卡在 {reason}({count} 条)":+ "{kind}卡在 {reason}({count} 条)",+ "memory:已加载 {count} 条记忆": "已加载 {count} 条记忆",+ "memory:已加载 {count} 条记忆.one": "已加载 {count} 条记忆",+ "memory:回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。":+ "回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。",+ "memory:选择一条记忆": "选择一条记忆",+ "memory:查看它的来源、使用范围和修改历史。":+ "查看它的来源、使用范围和修改历史。",+ "memory:查看替代它的记忆": "查看替代它的记忆",+ "memory:查看它取代的旧记忆": "查看它取代的旧记忆",+ "memory:保存纠正": "保存纠正",+ "memory:修改历史": "修改历史",+ "memory:已可用": "已可用",+ "memory:处理中…": "处理中…",+ "memory:搜索": "搜索",+ "memory:记忆治理状态": "记忆治理状态",+ "memory:记忆空间模式": "记忆空间模式",+ "memory:来源状态待核对,记忆库暂不可读取。":+ "来源状态待核对,记忆库暂不可读取。",+ "memory:记忆库读取失败,请重试。": "记忆库读取失败,请重试。",+ "memory:重新读取记忆库": "重新读取记忆库",+ "memory:正在读取记忆库…": "正在读取记忆库…",+ "memory:批量操作结果": "批量操作结果",+ "memory:批量操作": "批量操作",+ "memory:取消选择": "取消选择",+ "memory:向已确认记忆提问": "向已确认记忆提问",+ "memory:搜索记忆库": "搜索记忆库",+ "memory:问答记忆范围": "问答记忆范围",+ "memory:只问个人画像": "只问个人画像",+ "memory:问全部记忆(含项目)": "问全部记忆(含项目)",+ "memory:例如:我对真实数据有什么要求?": "例如:我对真实数据有什么要求?",+ "memory:搜索偏好、决定或经历": "搜索偏好、决定或经历",+ "memory:根据记忆回答": "根据记忆回答",+ "memory:清除搜索": "清除搜索",+ "wb.finding.duplicate": "出自同一句话",+ "wb.finding.duplicateText":+ "「{first}」和「{second}」是从同一句原话里抽出来的,分别挂在 {firstScope} 和 {secondScope} 下。看看是不是一回事。",+ "wb.finding.dormant": "很久没动过",+ "wb.finding.dormantText":+ "{count} 条记忆两个月没再被改过也没再被提起。可能已经过时,值得回头看一眼。",+ "wb.finding.blocked": "卡住了",+ "wb.finding.blockedText":+ "{count} 段对话排在队里,等的不是时间而是一个条件。原文已经在库里,随时搜得到。",+ "wb.finding.blockedText.one":+ "{count} 段对话排在队里,等的不是时间而是一个条件。原文已经在库里,随时搜得到。",+ "wb.unclassified": "未归类",+ "wb.profile": "个人画像",+ "wb.project": "某个项目 {id}",+ "wb.topics": "主题",+ "wb.all": "全部",+ "wb.topicCount": "{count} 个主题成形",+ "wb.topicCount.one": "{count} 个主题成形",+ "wb.singletons": ",另有 {count} 个标签只出现过一次",+ "wb.singletons.one": ",另有 {count} 个标签只出现过一次",+ "wb.memories": "{count} 条记忆",+ "wb.memories.one": "{count} 条记忆",+ "wb.sources": "{count} 个来源",+ "wb.sources.one": "{count} 个来源",+ "wb.once":+ "这个主题只出现在这一条上。可能是它只发生过一次,也可能是同一个主题被拆成了两个名字。",+ "wb.graphTitle": "{label} 的关系图",+ "wb.readSummary": "读这个事项的综述",+ "wb.summaryPrompt":+ "把「{label}」这件事讲清楚:现在到哪一步了、已经定下来的有哪些、还有什么没定。",+ "wb.building": "正在归纳…",+ "wb.build": "用 HY Memory 生成关系",+ "wb.drawn": "画的是 {shown} / 全部 {total} 条记忆",+ "wb.askLabel": "就着这个事项提问",+ "wb.askPlaceholder": "就着这个事项问,回答只用已确认的记忆",+ "wb.ask": "问",+ "wb.originals": "原始对话",+ "wb.evidenceNote": "这条记忆出自下面 {count} 段原话,按时间排",+ "wb.evidenceNote.one": "这条记忆出自下面 {count} 段原话,按时间排",+ "wb.pickCircle": "点图上任意一个圈,这里显示它出自哪些原话",+ "wb.unavailable": "来源原话已不可读取",+ "wb.fullConversation": "看完整对话",+ "wb.you": "你",+ "wb.assistant": "助手",+ "wb.noMemories": "还没有记忆。已经导入的原话可以在「历史对话」里直接搜。",+ "wb.waiting": "有对话排在队里等一个条件。原文已经在库里,随时搜得到。",+ "wb.conditions": "去看看缺什么",+ "wb.findings": "我替你看出这几件事",+ "wb.findingsNote": "都是本机记录算出来的,点一条会在图上标出它依据的记忆",+ "wb.showGraph": "在图上看",+ "wb.loading": "正在读取记忆…",+ "wb.coreStarting": "本地 Core 启动后会自动出现,不用刷新。",+ "wb.nothingToConnect": "这里还没有东西可以连起来。",+ "wb.skeletonNote":+ "授权一个来源之后,先出现的是来源和主题的骨架,记忆会陆续挂上去。",+ "wb.authorize": "去授权一个来源",+ "wb.conversations": "{count} 段",+ "wb.conversations.one": "{count} 段",+ "wb.chipChanges": "这里最近有什么变化",+ "wb.chipSummarize": "把这些归纳成几条",+ "wb.unknownTime": "时间不明",+ "wb.unknownSource": "未知来源",+ "wb.transcriptGone": "这段对话的原文已经不在库里了。",+ "wb.edgeCount": "{label} {count} 条",+ "wb.edgeCount.one": "{label} {count} 条",+ "wb.noRelations": "HY Memory 还没归纳出关系,点击上方按钮运行 System 2",+ "wb.noModelRelations": "还没配置可用模型,无法读取 HY Memory 的归纳关系",+ "provenance.multiple": "多位作者",+ "provenance.person": "用户原文",+ "provenance.agent": "Agent 原文",+ "provenance.unknown": "作者未知",+ "provenance.imported": "导入的已有记忆 · {author}",+ "provenance.manual": "手动添加",+ "provenance.answered": "问答生成",+ "provenance.generated": "由 AI 回复整理",+ "provenance.conversation": "由原始对话整理",+ "arrival.region": "记忆整理状态",+ "arrival.importing": "原文仍在导入",+ "arrival.messages": "已保存 {count} 条消息",+ "arrival.messages.one": "已保存 {count} 条消息",+ "arrival.conversations": "{count} 个会话",+ "arrival.conversations.one": "{count} 个会话",+ "arrival.details": "查看进度与详情",+ "arrival.backlog": "存量数据较大,为保证质量,正在后台分批整理",+ "arrival.items": "{count} 项",+ "arrival.items.one": "{count} 项",+ "arrival.configure": "设置记忆整理",+ "arrival.status": "查看整理状态",+ "arrival.history": "查看已保存的对话",+ "arrival.connect": "关联应用",+ "arrival.retained": "已保存的原文保留在本机。",+ "arrival.description.model-required": "请核对整理模型后继续。",+ "arrival.description.processing": "先整理近期对话,更多记忆会陆续出现",+ "arrival.description.importing": "正在保存原文;导入进度不代表记忆生成进度。",+ "arrival.description.failed": "请先核对失败原因,再决定是否重试。",+ "arrival.description.unavailable":+ "最近确认的信息已保留,当前进度需要重新核对。",+ "arrival.description.refreshing":+ "正在核对本机记录,尚未确认的进度不会计入。",+ "arrival.description.checking": "已保存内容保留,进度待更新。",+ "arrival.description.stopped": "当前整理已停止,可查看状态后继续。",+ "arrival.description.idle": "当前没有正在运行的整理任务。",+ "arrival.description.empty": "关联应用或导入对话文件后,原文会先保存到本机。",+ "arrival.title.refreshing": "已保存内容保留,正在核对进度",+ "arrival.title.checking": "进度待更新",+ "arrival.title.importing": "正在导入对话",+ "arrival.title.processing": "正在沉淀记忆",+ "arrival.title.continue": "待继续",+ "arrival.title.model": "尚未设置整理模型",+ "arrival.title.empty": "还没有保存的对话",+ "handoff.region": "带出记忆",+ "handoff.answer": "带出回答与引用",+ "handoff.selected": "带出所选记忆",+ "handoff.title": "带到其他应用",+ "handoff.closeTitle": "关闭预览",+ "handoff.close": "关闭带出预览",+ "handoff.stats": "{count} 条记忆 · {characters} 字符 · 未省略",+ "handoff.stats.one": "{count} 条记忆 · {characters} 字符 · 未省略",+ "handoff.content": "将带出的完整内容",+ "handoff.target": "目标应用",+ "handoff.other": "其他应用 · 仅复制",+ "handoff.copyOnly": " · 仅复制",+ "handoff.boundary":+ "仅带出上方内容,不包含原始对话。复制不是授权连接,已带出的副本无法从其他应用撤回。",+ "handoff.copy": "复制内容",+ "handoff.open": "复制并打开 {host}",+ "handoff.copyFailed": "复制失败,未打开任何应用。可在预览中选中文本复制。",+ "handoff.opened": "已复制并请求打开 {host}。尚未发送;请核对目标输入框。",+ "handoff.notPrefilled":+ "已完整复制。{host} 未能预填,请在目标应用粘贴;尚未发送。",+ "handoff.openFailed": "内容已完整复制,但未能打开 {host}。尚未发送。",+ "handoff.copied": "已完整复制{target}。尚未发送。",+ "handoff.pasteTarget": ",可粘贴到 {host}",+ "wb.memory": "这条记忆",+ "wb.node": "这个节点",+ "wb.matter": "这个事项",+ "wb.available": "已可用",+ "wb.superseded": "已被取代",+ "wb.deleted": "已删除",+ "wb.revision": "第 {revision} 版",+ "wb.collapse": "收起",+ "wb.oldSearch": "搜索里还是改之前那句话。",+ "wb.missingIndex": "HY Memory 里没有这条记忆,重试也补不上。",+ "wb.retrySync": "重试同步",+ "wb.correctForm": "纠正记忆内容",+ "wb.content": "记忆内容",+ "wb.correct": "纠正",+ "wb.saveCorrection": "保存纠正",+ "wb.cancelEdit": "取消编辑",+ "wb.undo": "撤销上次修改",+ "wb.delete": "删除",+ "wb.nodeNote":+ "这不是一条记忆,是记忆挂靠的东西。直接关系 {direct} 条,两跳可达 {indirect} 条。",+ "wb.direct": "直接",+ "wb.twoHops": "两跳",+ "wb.idle":+ "图上的圈是记忆,线是它们被同一段对话提到过。选中一个,这里会变成它的来历和改法。左边换一个事项,图跟着换。",+ "wb.searching": "正在检索记忆…",+ "wb.generated": "模型综合",+ "wb.extractive": "原文摘录",+ "wb.noHit": "没有命中",+ "wb.answerSource": "{mode} · 依据 {count} 条已确认记忆",+ "wb.answerSource.one": "{mode} · 依据 {count} 条已确认记忆",+ "wb.recalled": "已召回 {count} 条",+ "wb.recalled.one": "已召回 {count} 条",+ "wb.saveMemory": "存为记忆",+ "wb.tooLong": "这个回答太长,超过当前保存上限,暂不能存为记忆。",+ "wb.summary":+ "这是综述,不是记忆。每次都会重新生成,所以它不会和下面这些记忆走散。",+ "wb.thisAnswer": "这次回答",+ "wb.type.source": "来源 App",+ "wb.type.topic": "主题",+ "wb.type.schema": "HY 归纳",+ "wb.type.memory": "记忆",+ "wb.origin.hy_relation": "HY Memory 归纳",+ "wb.origin.same_conversation": "同一次对话",+ "wb.origin.shared_tag": "同一个主题",+ "wb.origin.provenance": "原话来源",+ "wb.relation.evidence_source": "来源于",+ "wb.relation.same_conversation": "同一次对话",+ "wb.relation.shared_tag": "同一个主题",+ "wb.relation.derived_from": "归纳自",+ "wb.relation.tagged_with": "属于主题",+ "wb.relation.related_to": "相关",+} as const;+export const workbenchSpanishMessages: Record<+ keyof typeof workbenchChineseMessages,+ string+> = {+ "memory:{count} 条": "{count} elementos",+ "memory:已可用 · {count} 段原文": "Disponible · {count} textos originales",+ "memory:主题视角(非事项)": "Vista por temas",+ "memory:来源视角": "Vista por origen",+ "memory:{count} 条记忆 · 当前已加载":+ "{count} memorias · Cargadas actualmente",+ "memory:最近 {count} 条": "{count} elementos recientes",+ "memory:已确认": "Confirmada",+ "memory:记忆库": "Biblioteca de memorias",+ "memory:问记忆": "Preguntar a las memorias",+ "memory:历史对话": "Historial de conversaciones",+ "memory:项目记忆": "Memoria del proyecto",+ "memory:编码偏好": "Preferencia de programación",+ "memory:长期模式": "Patrón a largo plazo",+ "memory:意图": "Intención",+ "memory:近 3 个月": "Últimos 3 meses",+ "memory:近 6 个月": "Últimos 6 meses",+ "memory:近 1 年": "Último año",+ "memory:全部历史": "Todo el historial",+ "memory:{count} 条这次没能整理成功,正在重试":+ "Reintentando la generación de {count} elementos que no se pudieron procesar",+ "memory:{count} 处理中": "{count} en procesamiento",+ "memory: · 处理中 {running} / 待派发 {active}":+ " · En curso: {running} / Por asignar: {active}",+ "memory: · {count} 条任务状态待核对":+ " · {count} tareas con estado por verificar",+ "memory: · {count} 条任务状态异常,正在恢复":+ " · Recuperando {count} tareas con estado anómalo",+ "memory:{count} 等待": "{count} en espera",+ "memory:最新 {count} 条待处理": "{count} recientes pendientes",+ "memory:历史积压 {count} 条": "{count} del historial pendientes",+ "memory:(约 {count} 分钟)": " (aprox. {count} minutos)",+ "memory:(约 {count} 小时)": " (aprox. {count} horas)",+ "memory:(约 {count} 天)": " (aprox. {count} días)",+ "memory:同步尝试 {count} 次": "{count} intentos de sincronización",+ "memory:尚未尝试同步": "Aún no se ha intentado sincronizar",+ "memory: · 状态更新于 {date}": " · Estado actualizado: {date}",+ "memory:HY Memory 当前没有这条记忆,仅重试同步不能补齐。":+ "HY Memory no tiene esta memoria; reintentar la sincronización no basta para recuperarla.",+ "memory:同步需要可用的本机整理模型或本地嵌入授权。":+ "La sincronización necesita un modelo local disponible o autorización para embeddings locales.",+ "memory:这条记忆或模型版本已经变化,先刷新核对再决定下一步。":+ "La memoria o la versión del modelo ha cambiado. Actualiza para verificar antes de continuar.",+ "memory:这条记忆已改,搜索索引还没开始同步。":+ "La memoria ha cambiado, pero la sincronización del índice aún no ha comenzado.",+ "memory:最近一次同步未成功;可以先重试,结果仍不确定时再刷新核对。":+ "El último intento falló. Reintenta y, si el resultado sigue siendo incierto, actualiza para verificar.",+ "memory:这条记忆已改,搜索索引还没跟上。":+ "La memoria ha cambiado; el índice de búsqueda aún no está actualizado.",+ "memory:搜索里还是改之前那句话。":+ "La búsqueda aún muestra el texto anterior.",+ "memory:重试同步": "Reintentar sincronización",+ "memory:配置整理模型": "Configurar modelo",+ "memory:未提炼 · 在窗口外": "Sin extraer · Fuera de la ventana",+ "memory:未提炼 · 排队中": "Sin extraer · En cola",+ "wb.select": "Selecciona una opción",+ "memory:模型综合": "Síntesis del modelo",+ "memory:原文摘录": "Extracto original",+ "memory:没有命中": "Sin coincidencias",+ "memory:正在生成": "Generando",+ "memory:正在检索记忆": "Buscando memorias",+ "memory: · 基于 {count} 条已确认记忆":+ " · Basado en {count} memorias confirmadas",+ "memory: · 基于 {count} 条已确认记忆.one":+ " · Basado en {count} memoria confirmada",+ "memory:整理需要处理": "El procesamiento requiere atención",+ "memory:正在整理记忆": "Procesando memorias",+ "memory:整理状态": "Estado del procesamiento",+ "memory:重新整理": "Volver a procesar",+ "memory:自动提炼范围": "Alcance de extracción automática",+ "memory:手动提炼下一批": "Extraer el siguiente lote manualmente",+ "memory:刷新核对": "Actualizar y verificar",+ "memory:正在导入历史会话,记忆库暂时只显示一部分;导入完成后会自动补全,不需要重试。":+ "Se está importando el historial. La biblioteca muestra solo una parte y se completará automáticamente, sin reintentos.",+ "memory:选择:{content}": "Seleccionar: {content}",+ "memory:处理失败:{content}": "Error de procesamiento: {content}",+ "memory:已选 {count} 条": "{count} memorias seleccionadas",+ "memory:已选 {count} 条.one": "{count} memoria seleccionada",+ "memory:删除所选 {count} 条": "Eliminar {count} memorias seleccionadas",+ "memory:删除所选 {count} 条.one": "Eliminar {count} memoria seleccionada",+ "memory:重试失败的 {count} 条": "Reintentar {count} operaciones fallidas",+ "memory:重试失败的 {count} 条.one": "Reintentar {count} operación fallida",+ "memory:没有{status}的记忆。": "No hay memorias con estado {status}.",+ "memory:已{action} {count} 条":+ "Acción completada ({action}): {count} registros",+ "memory:已{action} {count} 条.one":+ "Acción completada ({action}): {count} registro",+ "memory:,{count} 条未完成": "; {count} registros sin completar",+ "memory:,{count} 条未完成.one": "; {count} registro sin completar",+ "memory:未能{action}:{error}": "No se pudo {action}: {error}",+ "memory:重试{action}": "Volver a {action}",+ "memory:删除(操作)": "eliminar",+ "memory:处理(操作)": "procesar",+ "memory:{count} 条原话": "{count} textos originales",+ "memory:{count} 条原话.one": "{count} texto original",+ "memory:有 {count} 段对话的整理结果不确定":+ "El resultado del procesamiento de {count} conversaciones es incierto",+ "memory:有 {count} 段对话的整理结果不确定.one":+ "El resultado del procesamiento de {count} conversación es incierto",+ "memory:{count} 次整理已完成": "{count} procesamientos completados",+ "memory:{count} 次整理已完成.one": "{count} procesamiento completado",+ "memory: · {count} 条在窗口外(原文可搜)":+ " · {count} registros fuera de la ventana (originales disponibles para buscar)",+ "memory: · {count} 条在窗口外(原文可搜).one":+ " · {count} registro fuera de la ventana (original disponible para buscar)",+ "memory: · 已规划 {planned} 批,当前第 {current} 批":+ " · {planned} lotes planificados; lote actual: {current}",+ "memory:{kind}卡在 {reason}({count} 条)":+ "{kind} bloqueado por {reason} ({count} registros)",+ "memory:已加载 {count} 条记忆": "{count} memorias cargadas",+ "memory:已加载 {count} 条记忆.one": "{count} memoria cargada",+ "memory:回答只使用已确认记忆。每个答案都可以回到对应记忆和来源原话。":+ "Las respuestas solo usan memorias confirmadas. Cada respuesta permite consultar las memorias y los originales correspondientes.",+ "memory:选择一条记忆": "Selecciona una memoria",+ "memory:查看它的来源、使用范围和修改历史。":+ "Consulta su origen, alcance de uso e historial de cambios.",+ "memory:查看替代它的记忆": "Ver las memorias que la sustituyen",+ "memory:查看它取代的旧记忆": "Ver las memorias anteriores sustituidas",+ "memory:保存纠正": "Guardar corrección",+ "memory:修改历史": "Historial de cambios",+ "memory:已可用": "Disponible",+ "memory:处理中…": "Procesando…",+ "memory:搜索": "Buscar",+ "memory:记忆治理状态": "Estado de las memorias",+ "memory:记忆空间模式": "Modos del espacio de memorias",+ "memory:来源状态待核对,记忆库暂不可读取。":+ "El estado de las fuentes está por verificar. La biblioteca no se puede leer por ahora.",+ "memory:记忆库读取失败,请重试。":+ "No se pudo leer la biblioteca de memorias. Reintenta.",+ "memory:重新读取记忆库": "Volver a leer la biblioteca",+ "memory:正在读取记忆库…": "Leyendo la biblioteca de memorias…",+ "memory:批量操作结果": "Resultado de la operación por lotes",+ "memory:批量操作": "Operaciones por lotes",+ "memory:取消选择": "Cancelar selección",+ "memory:向已确认记忆提问": "Preguntar a las memorias confirmadas",+ "memory:搜索记忆库": "Buscar en la biblioteca de memorias",+ "memory:问答记忆范围": "Alcance de las consultas de memoria",+ "memory:只问个人画像": "Consultar solo el perfil personal",+ "memory:问全部记忆(含项目)":+ "Consultar todas las memorias, incluidos proyectos",+ "memory:例如:我对真实数据有什么要求?":+ "Por ejemplo: ¿qué requisitos tengo sobre los datos reales?",+ "memory:搜索偏好、决定或经历":+ "Buscar preferencias, decisiones o experiencias",+ "memory:根据记忆回答": "Responder con las memorias",+ "memory:清除搜索": "Limpiar búsqueda",+ "wb.finding.duplicate": "Proceden del mismo texto",+ "wb.finding.duplicateText":+ "«{first}» y «{second}» se extrajeron del mismo texto original y están en {firstScope} y {secondScope}, respectivamente. Revisa si describen lo mismo.",+ "wb.finding.dormant": "Sin cambios desde hace tiempo",+ "wb.finding.dormantText":+ "{count} memorias llevan dos meses sin cambios ni menciones. Podrían estar desactualizadas; conviene revisarlas.",+ "wb.finding.blocked": "Pendientes de una condición",+ "wb.finding.blockedText":+ "{count} conversaciones están en cola por una condición, no por tiempo. Sus originales ya están guardados y se pueden buscar.",+ "wb.finding.blockedText.one":+ "{count} conversación está en cola por una condición, no por tiempo. Su original ya está guardado y se puede buscar.",+ "wb.unclassified": "Sin clasificar",+ "wb.profile": "Perfil personal",+ "wb.project": "Proyecto {id}",+ "wb.topics": "Temas",+ "wb.all": "Todo",+ "wb.topicCount": "{count} temas definidos",+ "wb.topicCount.one": "{count} tema definido",+ "wb.singletons": "; además, {count} etiquetas aparecen solo una vez",+ "wb.singletons.one": "; además, {count} etiqueta aparece solo una vez",+ "wb.memories": "{count} memorias",+ "wb.memories.one": "{count} memoria",+ "wb.sources": "{count} fuentes",+ "wb.sources.one": "{count} fuente",+ "wb.once":+ "Este tema aparece solo en esta memoria. Puede haber ocurrido una sola vez o estar dividido entre dos nombres.",+ "wb.graphTitle": "Mapa de relaciones de {label}",+ "wb.readSummary": "Leer síntesis de este asunto",+ "wb.summaryPrompt":+ "Explica el asunto «{label}»: en qué punto está, qué se ha decidido y qué sigue pendiente.",+ "wb.building": "Sintetizando…",+ "wb.build": "Generar relaciones con HY Memory",+ "wb.drawn": "Se muestran {shown} / {total} memorias en total",+ "wb.askLabel": "Preguntar sobre este asunto",+ "wb.askPlaceholder":+ "Pregunta sobre este asunto; la respuesta solo usa memorias confirmadas",+ "wb.ask": "Preguntar",+ "wb.originals": "Conversaciones originales",+ "wb.evidenceNote":+ "Esta memoria procede de {count} fragmentos originales, ordenados por fecha",+ "wb.evidenceNote.one":+ "Esta memoria procede de {count} fragmento original, ordenado por fecha",+ "wb.pickCircle":+ "Selecciona un círculo del mapa para ver sus textos originales",+ "wb.unavailable": "El texto original de la fuente ya no se puede leer",+ "wb.fullConversation": "Ver conversación completa",+ "wb.you": "Tú",+ "wb.assistant": "Asistente",+ "wb.noMemories":+ "Todavía no hay memorias. Puedes buscar los originales importados en el historial de conversaciones.",+ "wb.waiting":+ "Hay conversaciones pendientes de una condición. Sus originales ya están guardados y se pueden buscar.",+ "wb.conditions": "Ver qué falta",+ "wb.findings": "Observaciones sobre tus memorias",+ "wb.findingsNote":+ "Calculadas con registros locales. Selecciona una para destacar las memorias que la sustentan",+ "wb.showGraph": "Ver en el mapa",+ "wb.loading": "Leyendo memorias…",+ "wb.coreStarting":+ "Aparecerán cuando arranque el Core local; no hace falta actualizar.",+ "wb.nothingToConnect": "Todavía no hay elementos que relacionar.",+ "wb.skeletonNote":+ "Al autorizar una fuente, primero aparecen las fuentes y los temas; las memorias se incorporan después.",+ "wb.authorize": "Autorizar una fuente",+ "wb.conversations": "{count} conversaciones",+ "wb.conversations.one": "{count} conversación",+ "wb.chipChanges": "Qué ha cambiado aquí últimamente",+ "wb.chipSummarize": "Resume estas memorias en varios puntos",+ "wb.unknownTime": "Fecha desconocida",+ "wb.unknownSource": "Fuente desconocida",+ "wb.transcriptGone":+ "El original de esta conversación ya no está en la biblioteca.",+ "wb.edgeCount": "{label}: {count} relaciones",+ "wb.edgeCount.one": "{label}: {count} relación",+ "wb.noRelations":+ "HY Memory todavía no ha sintetizado relaciones. Usa el botón superior para ejecutar System 2",+ "wb.noModelRelations":+ "No hay un modelo disponible configurado para leer las relaciones de HY Memory",+ "provenance.multiple": "Varios autores",+ "provenance.person": "Texto original del usuario",+ "provenance.agent": "Texto original del agente",+ "provenance.unknown": "Autor desconocido",+ "provenance.imported": "Memoria existente importada · {author}",+ "provenance.manual": "Añadida manualmente",+ "provenance.answered": "Generada en una consulta",+ "provenance.generated": "Creada a partir de una respuesta de IA",+ "provenance.conversation": "Creada a partir de la conversación original",+ "arrival.region": "Estado del procesamiento de memorias",+ "arrival.importing": "Los originales siguen importándose",+ "arrival.messages": "Se guardaron {count} mensajes",+ "arrival.messages.one": "Se guardó {count} mensaje",+ "arrival.conversations": "{count} conversaciones",+ "arrival.conversations.one": "{count} conversación",+ "arrival.details": "Ver progreso y detalles",+ "arrival.backlog":+ "El historial es extenso; se procesa en segundo plano por lotes para mantener la calidad",+ "arrival.items": "{count} tareas",+ "arrival.items.one": "{count} tarea",+ "arrival.configure": "Configurar procesamiento",+ "arrival.status": "Ver estado del procesamiento",+ "arrival.history": "Ver conversaciones guardadas",+ "arrival.connect": "Vincular aplicaciones",+ "arrival.retained": "Los originales guardados se conservan en este equipo. ",+ "arrival.description.model-required":+ "Comprueba el modelo de procesamiento para continuar.",+ "arrival.description.processing":+ "Se procesan primero las conversaciones recientes; las memorias aparecerán progresivamente",+ "arrival.description.importing":+ "Se están guardando los originales; el progreso de importación no indica el de creación de memorias.",+ "arrival.description.failed":+ "Comprueba primero el motivo del fallo antes de decidir si reintentar.",+ "arrival.description.unavailable":+ "Se conserva la última información confirmada; hay que comprobar el progreso actual.",+ "arrival.description.refreshing":+ "Se comprueban los registros locales; el progreso sin confirmar no se contabiliza.",+ "arrival.description.checking":+ "Se conserva el contenido guardado; el progreso está pendiente de actualizar.",+ "arrival.description.stopped":+ "El procesamiento está detenido; consulta su estado para continuar.",+ "arrival.description.idle": "No hay tareas de procesamiento en curso.",+ "arrival.description.empty":+ "Al vincular aplicaciones o importar archivos de conversaciones, los originales se guardan primero en este equipo.",+ "arrival.title.refreshing":+ "Se conserva el contenido guardado; comprobando el progreso",+ "arrival.title.checking": "Progreso pendiente de actualizar",+ "arrival.title.importing": "Importando conversaciones",+ "arrival.title.processing": "Creando memorias",+ "arrival.title.continue": "Pendiente de continuar",+ "arrival.title.model": "Modelo de procesamiento sin configurar",+ "arrival.title.empty": "Todavía no hay conversaciones guardadas",+ "handoff.region": "Llevar memorias",+ "handoff.answer": "Llevar la respuesta y sus referencias",+ "handoff.selected": "Llevar las memorias seleccionadas",+ "handoff.title": "Llevar a otras aplicaciones",+ "handoff.closeTitle": "Cerrar vista previa",+ "handoff.close": "Cerrar vista previa de transferencia",+ "handoff.stats": "{count} memorias · {characters} caracteres · Sin omisiones",+ "handoff.stats.one":+ "{count} memoria · {characters} caracteres · Sin omisiones",+ "handoff.content": "Contenido completo que se transferirá",+ "handoff.target": "Aplicación de destino",+ "handoff.other": "Otra aplicación · Solo copiar",+ "handoff.copyOnly": " · Solo copiar",+ "handoff.boundary":+ "Solo se transfiere el contenido anterior, sin conversaciones originales. Copiar no autoriza una conexión; las copias transferidas no se pueden retirar de otras aplicaciones.",+ "handoff.copy": "Copiar contenido",+ "handoff.open": "Copiar y abrir {host}",+ "handoff.copyFailed":+ "No se pudo copiar y no se abrió ninguna aplicación. Puedes seleccionar el texto de la vista previa para copiarlo.",+ "handoff.opened":+ "Se copió el contenido y se solicitó abrir {host}. No se ha enviado; comprueba el campo de destino.",+ "handoff.notPrefilled":+ "Se copió todo el contenido. No se pudo rellenar {host}; pégalo en la aplicación. No se ha enviado.",+ "handoff.openFailed":+ "Se copió todo el contenido, pero no se pudo abrir {host}. No se ha enviado.",+ "handoff.copied": "Se copió todo el contenido{target}. No se ha enviado.",+ "handoff.pasteTarget": "; puedes pegarlo en {host}",+ "wb.memory": "Esta memoria",+ "wb.node": "Este nodo",+ "wb.matter": "Este asunto",+ "wb.available": "Disponible",+ "wb.superseded": "Sustituida",+ "wb.deleted": "Eliminada",+ "wb.revision": "Versión {revision}",+ "wb.collapse": "Contraer",+ "wb.oldSearch": "La búsqueda aún muestra el texto anterior.",+ "wb.missingIndex":+ "Esta memoria no existe en HY Memory; reintentar no la recuperará.",+ "wb.retrySync": "Reintentar sincronización",+ "wb.correctForm": "Corregir el contenido de la memoria",+ "wb.content": "Contenido de la memoria",+ "wb.correct": "Corregir",+ "wb.saveCorrection": "Guardar corrección",+ "wb.cancelEdit": "Cancelar edición",+ "wb.undo": "Deshacer último cambio",+ "wb.delete": "Eliminar",+ "wb.nodeNote":+ "No es una memoria, sino un elemento al que se vinculan memorias. Relaciones directas: {direct}; a dos saltos: {indirect}.",+ "wb.direct": "Directa",+ "wb.twoHops": "Dos saltos",+ "wb.idle":+ "Los círculos son memorias; las líneas indican que aparecen en la misma conversación. Selecciona uno para ver su origen y corregirlo. Cambia de asunto a la izquierda para cambiar el mapa.",+ "wb.searching": "Buscando memorias…",+ "wb.generated": "Síntesis del modelo",+ "wb.extractive": "Extracto original",+ "wb.noHit": "Sin coincidencias",+ "wb.answerSource": "{mode} · Basado en {count} memorias confirmadas",+ "wb.answerSource.one": "{mode} · Basado en {count} memoria confirmada",+ "wb.recalled": "Se recuperaron {count} memorias",+ "wb.recalled.one": "Se recuperó {count} memoria",+ "wb.saveMemory": "Guardar como memoria",+ "wb.tooLong":+ "La respuesta supera el límite de extensión y por ahora no se puede guardar como memoria.",+ "wb.summary":+ "Es una síntesis, no una memoria. Se vuelve a generar cada vez para mantenerse vinculada a las memorias siguientes.",+ "wb.thisAnswer": "Esta respuesta",+ "wb.type.source": "Aplicación de origen",+ "wb.type.topic": "Tema",+ "wb.type.schema": "Síntesis de HY",+ "wb.type.memory": "Memoria",+ "wb.origin.hy_relation": "Síntesis de HY Memory",+ "wb.origin.same_conversation": "Misma conversación",+ "wb.origin.shared_tag": "Mismo tema",+ "wb.origin.provenance": "Fuente original",+ "wb.relation.evidence_source": "Procede de",+ "wb.relation.same_conversation": "Misma conversación",+ "wb.relation.shared_tag": "Mismo tema",+ "wb.relation.derived_from": "Sintetizado a partir de",+ "wb.relation.tagged_with": "Pertenece al tema",+ "wb.relation.related_to": "Relacionado con",+};diff --git a/memhub/packages/i18n/src/gui-i18n.test.ts b/memhub/packages/i18n/src/gui-i18n.test.tsnew file mode 100644index 0000000..c415d67--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n.test.ts@@ -0,0 +1,165 @@+import { describe, expect, expectTypeOf, it } from "vitest";++import {+ type GuiLocale,+ isLanguagePreference,+ isLanguageSnapshot,+ type LanguagePreference,+ type LanguageSnapshot,+ type MessageKey,+ resolveGuiLocale,+ translate,+} from "./gui-i18n.js";++const messageKeys = [+ "settings",+ "languageTitle",+ "languageLabel",+ "languageSystem",+ "languageChinese",+ "languageEnglish",+ "languageSpanish",+ "languageDescription",+ "languageSaveError",+ "languageLoadError",+ "nativeErrorTitle",+] as const satisfies readonly MessageKey[];++describe("GUI language contracts", () => {+ it("pins the language preference and snapshot types", () => {+ expectTypeOf<LanguagePreference>().toEqualTypeOf<+ "system" | "zh-CN" | "en" | "es"+ >();+ expectTypeOf<GuiLocale>().toEqualTypeOf<"zh-CN" | "en" | "es">();+ expectTypeOf<LanguageSnapshot>().toEqualTypeOf<{+ preference: LanguagePreference;+ locale: GuiLocale;+ revision: number;+ }>();+ });++ it.each(["system", "zh-CN", "en", "es"])("accepts preference %s", (value) => {+ expect(isLanguagePreference(value)).toBe(true);+ });++ it.each([undefined, null, "", "EN", "ES", "es-MX", {}, [], 1, true])(+ "rejects invalid preferences: %j",+ (value) => expect(isLanguagePreference(value)).toBe(false),+ );++ it("validates snapshots and nonnegative safe integer revisions", () => {+ expect(+ isLanguageSnapshot({ preference: "system", locale: "es", revision: 0 }),+ ).toBe(true);+ expect(+ isLanguageSnapshot({+ preference: "en",+ locale: "en",+ revision: 1,+ }),+ ).toBe(true);+ expect(+ isLanguageSnapshot({+ preference: "zh-CN",+ locale: "zh-CN",+ revision: Number.MAX_SAFE_INTEGER,+ }),+ ).toBe(true);+ for (const value of [+ undefined,+ null,+ [],+ {},+ { preference: "en", locale: "es", revision: 0 },+ { preference: "es", locale: "zh-CN", revision: 0 },+ { preference: "zh-CN", locale: "es", revision: 0 },+ { preference: "system", locale: "system", revision: 0 },+ { preference: "system", locale: "es" },+ ...[-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "0"].map(+ (revision) => ({ preference: "system", locale: "es", revision }),+ ),+ ]) {+ expect(isLanguageSnapshot(value)).toBe(false);+ }+ });+});++describe("GUI locale resolution", () => {+ it.each([+ "es",+ "es-ES",+ "es-MX",+ "ES-ar",+ "es-419",+ "es-Latn-ES",+ "es-u-nu-latn",+ ])("resolves Spanish primary language %s", (language) =>+ expect(resolveGuiLocale("system", language)).toBe("es"),+ );++ it.each(["en", "en-US", "en-GB"])(+ "resolves English primary language %s",+ (language) => expect(resolveGuiLocale("system", language)).toBe("en"),+ );++ it.each(["zh", "zh-CN", "zh-SG", "zh-Hans"])(+ "resolves Simplified Chinese family %s",+ (language) => expect(resolveGuiLocale("system", language)).toBe("zh-CN"),+ );++ it.each([+ undefined,+ "",+ "zh-TW",+ "fr-ES",+ "en-US-u-rg-eszzzz",+ "es_MX",+ "es--ES",+ "es-",+ " es ",+ "es,en",+ "not-a-locale!",+ ])("falls back to English for %j", (language) =>+ expect(resolveGuiLocale("system", language)).toBe("en"),+ );++ it("prioritizes explicit preferences over the system language", () => {+ expect(resolveGuiLocale("es", "zh-CN")).toBe("es");+ expect(resolveGuiLocale("zh-CN", "es-MX")).toBe("zh-CN");+ expect(resolveGuiLocale("en", "es-MX")).toBe("en");+ expect(resolveGuiLocale("es", "invalid_locale")).toBe("es");+ });+});++describe("GUI messages", () => {+ it.each(messageKeys)(+ "provides Chinese, English and Spanish text for %s",+ (key) => {+ expect(translate("zh-CN", key).length).toBeGreaterThan(0);+ expect(translate("en", key).length).toBeGreaterThan(0);+ expect(translate("es", key).length).toBeGreaterThan(0);+ expect(translate("en", key)).not.toBe(translate("zh-CN", key));+ expect(translate("es", key)).not.toBe(translate("zh-CN", key));+ },+ );++ it("provides stable settings and language names", () => {+ expect(translate("zh-CN", "settings")).toBe("设置");+ expect(translate("en", "settings")).toBe("Settings");+ expect(translate("es", "settings")).toBe("Configuración");+ expect(translate("zh-CN", "nativeErrorTitle")).toBe("MemHub 无法启动");+ expect(translate("es", "nativeErrorTitle")).toBe(+ "MemHub no pudo iniciarse",+ );+ expect(translate("es", "languageSpanish")).toBe("Español");+ expect(translate("en", "languageEnglish")).toBe("English");+ });++ it("interpolates plain text once without interpreting substituted values", () => {+ expect(+ translate("en", "calls.detail.delivered", {+ host: "<img src=x onerror=alert(1)>$&{count}",+ }),+ ).toBe("Provided to <img src=x onerror=alert(1)>$&{count}");+ });+});diff --git a/memhub/packages/i18n/src/gui-i18n.ts b/memhub/packages/i18n/src/gui-i18n.tsnew file mode 100644index 0000000..a64aa36--- /dev/null+++ b/memhub/packages/i18n/src/gui-i18n.ts@@ -0,0 +1,129 @@+import i18next from "i18next";++import { englishMessages } from "./gui-i18n-english.js";+import { chineseMessages, spanishMessages } from "./gui-i18n-messages.js";++export const SUPPORTED_LOCALES = ["zh-CN", "en", "es"] as const;++export type GuiLocale = (typeof SUPPORTED_LOCALES)[number];+export type LanguagePreference = "system" | GuiLocale;+export type MessageKey = keyof typeof chineseMessages;++export interface LanguageSnapshot {+ preference: LanguagePreference;+ locale: GuiLocale;+ revision: number;+}++const resources = {+ "zh-CN": { translation: chineseMessages },+ en: { translation: englishMessages },+ es: { translation: spanishMessages },+} as const;++const translator = i18next.createInstance();+void translator.init({+ resources,+ lng: "en",+ fallbackLng: ["en", "zh-CN"],+ supportedLngs: [...SUPPORTED_LOCALES],+ initImmediate: false,+ keySeparator: false,+ nsSeparator: false,+ pluralSeparator: ".",+ returnNull: false,+ showSupportNotice: false,+ interpolation: {+ escapeValue: false,+ prefix: "{",+ suffix: "}",+ },+});++export function isGuiLocale(value: unknown): value is GuiLocale {+ return (+ typeof value === "string" &&+ (SUPPORTED_LOCALES as readonly string[]).includes(value)+ );+}++export function isLanguagePreference(+ value: unknown,+): value is LanguagePreference {+ return value === "system" || isGuiLocale(value);+}++export function isLanguageSnapshot(value: unknown): value is LanguageSnapshot {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return false;+ const snapshot = value as Record<string, unknown>;+ return (+ isLanguagePreference(snapshot.preference) &&+ isGuiLocale(snapshot.locale) &&+ (snapshot.preference === "system" ||+ snapshot.preference === snapshot.locale) &&+ typeof snapshot.revision === "number" &&+ Number.isSafeInteger(snapshot.revision) &&+ snapshot.revision >= 0+ );+}++export function resolveGuiLocale(+ preference: LanguagePreference,+ systemLanguage?: string,+): GuiLocale {+ if (preference !== "system") return preference;+ if (!systemLanguage) return "en";+ try {+ const [canonicalLanguage] = Intl.getCanonicalLocales(systemLanguage);+ const language = canonicalLanguage?.split("-")[0]?.toLowerCase();+ if (language === "zh") {+ const parts = canonicalLanguage?.split("-") ?? [];+ const unsupportedTraditional =+ parts.includes("Hant") ||+ parts.some((part) => ["TW", "HK", "MO"].includes(part));+ return unsupportedTraditional ? "en" : "zh-CN";+ }+ if (language === "es") return "es";+ if (language === "en") return "en";+ return "en";+ } catch {+ return "en";+ }+}++export function isMessageKey(value: string): value is MessageKey {+ return Object.hasOwn(chineseMessages, value);+}++export function translate(+ locale: GuiLocale,+ key: MessageKey,+ params?: Record<string, string | number>,+): string {+ return translator.getFixedT(locale)(key, {+ ...params,+ defaultValue: chineseMessages[key],+ });+}++export function translateCount(+ locale: GuiLocale,+ key: MessageKey,+ count: number,+ params?: Record<string, string | number>,+): string {+ const category = new Intl.PluralRules(locale).select(count);+ const variant = `${key}.${category}`;+ const selected = isMessageKey(variant) ? variant : key;+ return translate(locale, selected, {+ ...params,+ count: params?.count ?? new Intl.NumberFormat(locale).format(count),+ });+}++export function plainCount(locale: GuiLocale, value: number): string | number {+ return locale === "zh-CN"+ ? value+ : new Intl.NumberFormat(locale).format(value);+}diff --git a/memhub/packages/i18n/src/index.ts b/memhub/packages/i18n/src/index.tsnew file mode 100644index 0000000..6de581c--- /dev/null+++ b/memhub/packages/i18n/src/index.ts@@ -0,0 +1,2 @@+export * from "./gui-i18n.js";+export * from "./gui-i18n-current.js";diff --git a/memhub/packages/i18n/tsconfig.build.json b/memhub/packages/i18n/tsconfig.build.jsonnew file mode 100644index 0000000..81c5f02--- /dev/null+++ b/memhub/packages/i18n/tsconfig.build.json@@ -0,0 +1,11 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "declaration": true,+ "emitDeclarationOnly": true,+ "noEmit": false,+ "outDir": "dist",+ "rootDir": "src"+ },+ "include": ["src/index.ts"]+}diff --git a/memhub/packages/i18n/tsconfig.json b/memhub/packages/i18n/tsconfig.jsonnew file mode 100644index 0000000..8239c56--- /dev/null+++ b/memhub/packages/i18n/tsconfig.json@@ -0,0 +1,10 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/memhub/pnpm-lock.yaml b/memhub/pnpm-lock.yamlindex 739ec0b..58cda93 100644--- a/memhub/pnpm-lock.yaml+++ b/memhub/pnpm-lock.yaml@@ -60,6 +60,9 @@ importers:'@one-memory/host-bridge':specifier: workspace:*version: link:../../packages/host-bridge+ '@one-memory/i18n':+ specifier: workspace:*+ version: link:../../packages/i18n'@one-memory/runtime-control':specifier: workspace:*version: link:../../packages/runtime-control@@ -116,6 +119,9 @@ importers:'@one-memory/contracts':specifier: workspace:*version: link:../../packages/contracts+ '@one-memory/i18n':+ specifier: workspace:*+ version: link:../../packages/i18n'@one-memory/operations':specifier: workspace:*version: link:../../packages/operations@@ -200,6 +206,19 @@ importers:specifier: ^4.1.11version: 4.1.11(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))+ packages/i18n:+ dependencies:+ i18next:+ specifier: ^25.8.13+ version: 25.10.10([email protected])+ devDependencies:+ typescript:+ specifier: ^7.0.2+ version: 7.0.2+ vitest:+ specifier: ^4.1.11+ version: 4.1.11(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))+packages/operations:dependencies:'@one-memory/contracts':@@ -1619,7 +1638,7 @@ packages:resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==}- deprecated: Glob versions prior to v9 are no longer supported+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}@@ -1664,6 +1683,14 @@ packages:resolution: {integrity: sha512-0euwPCRyAPSgGdzD1IVN9nJYHtBhJwb6XPfbpQcYbPCwrBidX6GzxmchnaF4sfF/jPb74Ojx5g4yTg3sixlyPw==}engines: {node: '>= 14'}+ resolution: {integrity: sha512-cqUW2Z3EkRx7NqSyywjkgCLK7KLCL6IFVFcONG7nVYIJ3ekZ1/N5jUsihHV6Bq37NfhgtczxJcxduELtjTwkuQ==}+ peerDependencies:+ typescript: ^5 || ^6+ peerDependenciesMeta:+ typescript:+ optional: true+resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.@@ -3837,6 +3864,12 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@babel/runtime': 7.29.7+ optionalDependencies:+ typescript: 7.0.2+dependencies:once: 1.4.0diff --git a/memhub/scripts/export_public_snapshot.py b/memhub/scripts/export_public_snapshot.pyindex 7235e7c..4f3e07d 100644--- a/memhub/scripts/export_public_snapshot.py+++ b/memhub/scripts/export_public_snapshot.py@@ -38,6 +38,7 @@ PUBLIC_DOCS = frozenset("docs/ARCHITECTURE.md","docs/DEVELOPMENT_LOOP.md","docs/INSTALLATION.md",+ "docs/LOCALIZATION.md","docs/cli/EXPERIENCE.md","docs/contracts/diagnostic-logging.md","docs/contracts/host-context-transport-v1.md",diff --git a/memhub/scripts/set-release-version.mjs b/memhub/scripts/set-release-version.mjsindex 999bb22..66f97c3 100644--- a/memhub/scripts/set-release-version.mjs+++ b/memhub/scripts/set-release-version.mjs@@ -16,6 +16,7 @@ const packageFiles = ["apps/web/package.json","packages/contracts/package.json","packages/host-bridge/package.json",+ "packages/i18n/package.json","packages/operations/package.json","packages/runtime-control/package.json",];diff --git a/memhub/scripts/set-release-version.test.mjs b/memhub/scripts/set-release-version.test.mjsindex d9777ad..da1bc33 100644--- a/memhub/scripts/set-release-version.test.mjs+++ b/memhub/scripts/set-release-version.test.mjs@@ -17,6 +17,7 @@ test("updates every release-bearing manifest in one transaction-sized command","apps/web/package.json","packages/contracts/package.json","packages/host-bridge/package.json",+ "packages/i18n/package.json","packages/operations/package.json","packages/runtime-control/package.json",];@@ -45,7 +46,7 @@ test("updates every release-bearing manifest in one transaction-sized command",const receipt = await setReleaseVersion("1.2.3-rc.1", root, 7);- assert.equal(receipt.changed.length, 11);+ assert.equal(receipt.changed.length, 12);assert.equal(receipt.build_number, 7);for (const relative of packageFiles) {const document = JSON.parse(@@ -81,6 +82,7 @@ test("maps an internal SemVer prerelease to deterministic PEP 440 metadata", asy"apps/web/package.json","packages/contracts/package.json","packages/host-bridge/package.json",+ "packages/i18n/package.json","packages/operations/package.json","packages/runtime-control/package.json",];@@ -132,6 +134,7 @@ test("refuses an ambiguous Core lockfile instead of changing an arbitrary packag"apps/web/package.json","packages/contracts/package.json","packages/host-bridge/package.json",+ "packages/i18n/package.json","packages/operations/package.json","packages/runtime-control/package.json",];diff --git a/memhub/scripts/test_export_public_snapshot.py b/memhub/scripts/test_export_public_snapshot.pyindex 3f564f1..08abf94 100644--- a/memhub/scripts/test_export_public_snapshot.py+++ b/memhub/scripts/test_export_public_snapshot.py@@ -27,6 +27,7 @@ def test_public_export_has_only_reviewed_root_files(tmp_path: Path) -> None:assert not (target / forbidden).exists()for required in ("docs/INSTALLATION.md",+ "docs/LOCALIZATION.md","docs/harness-support/README.md","docs/harness-support/hermes.md","scripts/build-release-assets.mjs",diff --git a/memhub/scripts/verify-release-version.mjs b/memhub/scripts/verify-release-version.mjsindex c6abebf..2e61833 100644--- a/memhub/scripts/verify-release-version.mjs+++ b/memhub/scripts/verify-release-version.mjs@@ -25,6 +25,7 @@ const packageFiles = ["apps/web/package.json","packages/contracts/package.json","packages/host-bridge/package.json",+ "packages/i18n/package.json","packages/operations/package.json","packages/runtime-control/package.json",];diff --git a/memhub/scripts/verify_structure.py b/memhub/scripts/verify_structure.pyindex 8569682..00b90f2 100644--- a/memhub/scripts/verify_structure.py+++ b/memhub/scripts/verify_structure.py@@ -7,11 +7,13 @@ REQUIRED_PATHS = ("NOTICE","docs/ARCHITECTURE.md","docs/DEVELOPMENT_LOOP.md",+ "docs/LOCALIZATION.md","apps/core/pyproject.toml","apps/cli/package.json","apps/web/package.json","apps/desktop/package.json","packages/contracts/package.json",+ "packages/i18n/package.json","scripts/audit_core_test_design.py","scripts/generate_core_test_index.py","scripts/summarize_core_test_report.py",