diff --git a/CHANGELOG.md b/CHANGELOG.md index fe22a802..b9292847 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Sparkle update. [desktop/CHANGELOG.md](desktop/CHANGELOG.md) retains legacy desk ## [Unreleased] +- Localization checks now recognize native memory form-helper labels. Phone search and diagnostics expose render-time translation keys, and obsolete search/provider/input translations are removed. - The macOS custom-provider sheet shrinks again after a connection-check error clears. - Skills mounted checks follow the shared browser-consumer module names while retaining all assertions and driver source binding. diff --git a/desktop/src/l10n/zh.ts b/desktop/src/l10n/zh.ts index c3a050c1..035885f0 100644 --- a/desktop/src/l10n/zh.ts +++ b/desktop/src/l10n/zh.ts @@ -345,7 +345,6 @@ export const zh: Record = { "Enter Full Screen": "进入全屏幕", "enter send newline keyboard chats": "回车 发送 换行 键盘 聊天 enter send newline keyboard chats", "Enter sends the message": "按 Enter 键发送消息", - "Enter the base URL to load the server’s models.": "输入基础 URL 后即可加载服务器的模型。", "Enter this code at %@, then come back.": "请在 %@ 输入此代码,然后回到这里。", "Environment": "环境变量", "erase remove wipe relay data identity": "抹除 移除 清除 中继 数据 身份 删除账户", @@ -699,7 +698,6 @@ export const zh: Record = { "Scroll to Latest": "滚动到最新消息", "Scroll to latest (%@)": "滚动到最新 (%@)", "Search": "搜索", - "Search actions, chats, messages, and settings": "搜索操作、聊天、消息和设置", "Search or add a model ID": "搜索或添加模型 ID", "Search plugins and bots": "搜索插件和智能体", "Searching files": "正在搜索文件", @@ -853,7 +851,6 @@ export const zh: Record = { "Turn %@ off": "关闭 %@", "Turn %@ on": "开启 %@", "Type": "类型", - "Type your answer": "输入你的回答", "unassigned": "未分配", "Undo": "撤销", "Unknown Device": "未知设备", @@ -1181,8 +1178,8 @@ export const zh: Record = { "Label and digest come from the Runner. Not authenticated provenance, and no update replaces the original copy.": "标签和摘要来自 Runner。不是经过认证的来源证明,也没有更新会替换原始副本。", "Compare source with copy…": "比较源与副本…", "Compare on %@, copy %@ against the selected source. Read-only.": "在 %1$@ 上比较副本 %2$@ 与所选源。只读。", - "%@ only in the source.": "仅存在于源中的 %1$d 项。", - "%@ only in the copy.": "仅存在于副本中的 %1$d 项。", - "%@ differ between source and copy.": "源与副本之间有 %1$d 项不同。", + "%@ only in the source.": "仅存在于源中的 %@ 项。", + "%@ only in the copy.": "仅存在于副本中的 %@ 项。", + "%@ differ between source and copy.": "源与副本之间有 %@ 项不同。", "Nothing was changed and nothing is enabled here. Applying a difference needs its own confirmed action.": "此处未做任何更改,也未启用任何功能。应用差异需要另行确认的操作。", }; diff --git a/docs/architecture/languages.md b/docs/architecture/languages.md index e9dc585f..fac702d9 100644 --- a/docs/architecture/languages.md +++ b/docs/architecture/languages.md @@ -7,3 +7,5 @@ The apps speak English and Simplified Chinese, and the key of every string is it - **Windows and Linux app** (`desktop/src/l10n`): `L("New Bot…")`, `L("%@ is working…", name)`, and `Lc("Pairing", "device state")`, with the macOS app's keys, over `zh.ts`. Settings › General › App Language saves the pick in the app's preferences, and every window builds its page again on the route it is on (`App.tsx` keys the router on `languageKey`), so the windows, their sizes, and the selection stay. The menu bar's words come from the page, so a new language gives it new words too. The opt-in native shell (`BEANS_NATIVE=1`) uses `desktop/l10n` with the same English keys for chrome, settings and onboarding controls; memory-note strings still go through `native_language.go` until that surface moves onto the shared table. - **What the CLI words stays as it arrives**, with one exception: a routine's `schedule_text` ("Weekdays at 9:00 AM") is rebuilt in Chinese by `Format.schedule` in the macOS app and `scheduleText` on the phone. Notices, permission summaries, and the demo data are English. - `pnpm run l10n` (`scripts/l10n.ts`) reads every `L("…")`, `Lc("…", "…")`, and `t("…")` in the three apps' sources and reports a string with no translation, a translation nothing uses, and a translation that takes different values than its key; `--merge …` adds `{ "English": "中文" }` files to the tables first. + +Phone search categories and diagnostics status translate explicit finite keys during rendering. Diagnostics keeps the English status key in state so a language change rewords the current status. Desktop memory status and operation functions expose literal translation keys to the audit. Obsolete entries are removed when their source label is replaced. diff --git a/docs/architecture/memory-ui.md b/docs/architecture/memory-ui.md index 03e18b7e..12d77405 100644 --- a/docs/architecture/memory-ui.md +++ b/docs/architecture/memory-ui.md @@ -37,7 +37,7 @@ Recall budgets validate the core bounds: 1–5,000 ms, 1–32,768 response bytes ## Capabilities and status -Controls consume negotiated capabilities, not a backend-name matrix. Advanced actions require both the feature and its exact verb in `advanced_actions`; absent or empty action lists hide them. Vector document editing uses `memory_edit` / `edit` with only `document_id` and `text`; advanced document deletion is unavailable. Health preserves `ready`, `degraded`, `setup_required`, the optional reason and the deletion-pending flag. Opening the bot sheet reads local configuration and operation metadata, not remote Health. Service checks are explicit; action refreshes update an already checked status. +Controls consume negotiated capabilities, not a backend-name matrix. The macOS bot sheet disables a control whose capability is absent and keeps it visible (Reflect and provider controls included). Advanced actions require both the feature and its exact verb in `advanced_actions`; absent or empty action lists hide them. Vector document editing uses `memory_edit` / `edit` with only `document_id` and `text`; advanced document deletion is unavailable. Health preserves `ready`, `degraded`, `setup_required`, the optional reason and the deletion-pending flag. Opening the bot sheet reads local configuration and operation metadata, not remote Health. Service checks are explicit; action refreshes update an already checked status. Operation state remains queued, submitted, processing, completed, failed or delivery_unknown. Only completed means stored. Pending deletion is not verified erasure. The helpers retain core-issued operation IDs and deletion epochs without issuing automatic retries, retain, reflect or deletion requests. @@ -59,4 +59,10 @@ Native note labels, generic error keys, budget/count sentences and conflict conf `pnpm --dir desktop exec vitest run src/model/memoryService.test.ts src/model/memorySetup.test.ts` exercises consent transitions, secret/options patches, bounded requests, masked status and exact setup approvals with fixture transports. `macos/Tests/MemoryServiceDraft.swift` and `macos/Tests/MemorySetupDraft.swift` are isolated Foundation executables compiled with their memory model sources, without a full application build. Fixture verification performs no remote retain, reflect, asset acquisition or DDL. +The macOS memory forms resolve their shared helper labels, action titles, consent warnings and formatted target descriptions through the Simplified Chinese string table. `sh macos/Tests/run-memory-ui.sh` compiles the production AppKit controllers with isolated transports, then checks translated disabled-action discoverability, query-field keyboard focus and accessibility titles. `BEANS_MEMORY_UI_IMAGE` optionally writes a controller rendering for inspection. This fixture does not establish installed-app navigation, complete keyboard traversal or assistive-technology acceptance. + +Negotiated advanced-feature menus localize presentation without changing the selected wire feature or verb. The native fixture also checks OpenViking binding-field labels, the memory-service entry title and local validation/consent/setup error presentation in Chinese. Local CPU and whole-bank confirmation fragments use the same language lookup. + `desktop/src/ui/sheets/memoryLayout.browser-check.js` checks mounted production sheets in an offline browser fixture. After scrolling or focusing a target, `assertMemorySheetLayout(fieldLabels, actionLabels)` verifies viewport containment and center-point hit ownership for controls and visible header/footer regions. The fixture checks last fields at maximum body scroll and keyboard access to footer actions without sending service requests. + +The localization scanner recognizes literal labels, choices and placeholders passed to the known native memory form helpers. Tuple descriptors and finite error/action labels expose explicit `L` literals; identifiers used as protocol values retain their exact displayed strings. Unrelated strings and commented-out helper calls do not satisfy a translation entry. Desktop memory status and operation functions expose literal translation keys. diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index f1b3db39..e9e6c45a 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -699,7 +699,6 @@ "Scroll to Latest" = "滚动到最新消息"; "Scroll to latest (⌘J)" = "滚动到最新 (⌘J)"; "Search" = "搜索"; -"Search actions, chats, messages, and settings" = "搜索操作、聊天、消息和设置"; "Search or add a model ID" = "搜索或添加模型 ID"; "Search plugins and bots" = "搜索插件和智能体"; "Searching files" = "正在搜索文件"; @@ -1024,6 +1023,247 @@ "Leave unchanged" = "保持不变"; "This can change service data or invoke paid downstream models. No background schedule is authorized. Deletes do not prove backup/history erasure." = "这可能更改服务数据或调用付费下游模型。未授权后台定时任务。删除不能证明备份和历史记录已擦除。"; "Refresh preferences and connection" = "刷新偏好设置和连接"; + +/* Native memory forms localize labels through their shared form helpers. */ +"New memory connection" = "新建记忆服务连接"; +"Edit memory connection" = "编辑记忆服务连接"; +"New embedding profile" = "新建嵌入配置"; +"Replace embedding profile" = "替换嵌入配置"; +"Keep stored secret (masked)" = "保留已存储的密钥(已隐藏)"; +"Keep — no stored secret" = "保持不变——未存储密钥"; +"Backend" = "后端"; +"Endpoint action" = "端点操作"; +"Endpoint" = "端点"; +"Service key / PostgreSQL password" = "服务密钥 / PostgreSQL 密码"; +"Embedding profile (pgvector / LanceDB)" = "嵌入配置(pgvector / LanceDB)"; +"Saved endpoints and private bindings are never read back. Leave endpoint and options unchanged to preserve them. Setting a new endpoint associates the selected secret action atomically; verify that the key belongs to that target." = "已保存的端点和私有绑定不会被读回。保持端点和选项不变即可保留它们。设置新端点会同时应用所选密钥操作;请确认密钥属于该目标。"; +"Remote memory and API embeddings process plaintext outside the relay's zero-knowledge guarantee. Your service may use paid extraction, embedding, reranking or synthesis models. Disconnection does not erase remote data." = "远程记忆和 API 嵌入在中继的零知识保障之外处理明文。服务可能使用付费提取、嵌入、重排序或生成模型。断开连接不会擦除远程数据。"; +"Schema" = "数据库架构"; +"PostgreSQL login role" = "PostgreSQL 登录角色"; +"Initialization" = "初始化"; +"Local LanceDB" = "本地 LanceDB"; +"Authorization" = "授权"; +"Add bot authorization" = "添加智能体授权"; +"Allow insecure memory transport?" = "允许不安全的记忆传输?"; +"Change memory connection target/options?" = "更改记忆连接目标和选项?"; +"Remove binding from draft" = "从草稿中移除绑定"; +"The saved profile is masked. This form replaces all known metadata; fill every field from your model contract. Cancel preserves the existing profile." = "已保存的配置隐藏了敏感信息。此表单会替换所有已知元数据;请按模型约定填写每个字段。取消会保留现有配置。"; +"API embeddings send document/query plaintext to the specified endpoint and may incur provider costs. Local CPU uses only explicitly approved ONNX runtime, model and tokenizer assets; there is no automatic download or paid fallback." = "API 嵌入将文档和查询明文发送到指定端点,可能产生服务商费用。本地 CPU 仅使用明确获批的 ONNX 运行时、模型和分词器资源;不会自动下载或使用付费备用方案。"; +"Embedding mode" = "嵌入模式"; +"Compatible API" = "兼容 API"; +"Local CPU (ONNX)" = "本地 CPU(ONNX)"; +"Exact model" = "确切模型"; +"Pinned model revision" = "固定模型修订版本"; +"Exact dimensions" = "确切维度"; +"Normalization" = "归一化"; +"Distance" = "距离"; +"Document prefix — exact text" = "文档前缀——确切文本"; +"Query prefix — exact text" = "查询前缀——确切文本"; +"Exact /embeddings endpoint" = "确切 /embeddings 端点"; +"Model SHA-256" = "模型 SHA-256"; +"Tokenizer SHA-256" = "分词器 SHA-256"; +"Maximum tokenizer tokens" = "分词器最大词元数"; +"Input IDs tensor" = "输入 ID 张量"; +"Attention mask tensor" = "注意力掩码张量"; +"Token type IDs tensor (optional)" = "词元类型 ID 张量(可选)"; +"Output tensor" = "输出张量"; +"Padding token ID" = "填充词元 ID"; +"Padding type ID" = "填充类型 ID"; +"Padding token — exact text" = "填充词元——确切文本"; +"Pooling" = "池化"; +"Save portable metadata first. Use Install Local Assets on the account page for exact Runner paths or approved HTTPS sources, license, sizes and hashes; setup requires a separate one-use preview approval." = "请先保存可移植元数据。在账户页面使用“安装本地资源”提供确切运行端路径或获批 HTTPS 来源、许可证、大小及哈希;设置需要单独批准一次性预览。"; +"Save an insecure embedding endpoint?" = "保存不安全的嵌入端点?"; +"Save this vector-space profile?" = "保存此向量空间配置?"; +"Selected Runner" = "所选运行端"; +"Supplied files stay Runner-local. Download sources must be exact HTTPS URLs approved by that Runner's administrator origin allowlist; no redirects, retries, extraction, automatic downloads or paid fallback. Runtime ABI/signing and the model tensor contract must match the Runner." = "提供的文件保留在运行端本地。下载来源必须是该运行端管理员来源白名单批准的确切 HTTPS URL;不会重定向、重试、解压、自动下载或使用付费备用方案。运行时 ABI、签名及模型张量约定必须与运行端匹配。"; +"Preview exact assets" = "预览确切资源"; +"Check approved runtime status" = "检查获批运行时状态"; +"Acquire and load these exact assets?" = "获取并加载这些确切资源?"; +"Discard preview / edit assets" = "放弃预览 / 编辑资源"; +"Source" = "来源"; +"Exact path / URL" = "确切路径 / URL"; +"License" = "许可证"; +"Exact byte count" = "确切字节数"; +"Full lowercase SHA-256" = "完整小写 SHA-256"; +"pgvector initialization" = "pgvector 初始化"; +"Preview reads the actual connected database, role, session, schema readiness and complete SQL. Apply can create the previewed extension/schema/tables only after confirmation." = "预览读取实际连接的数据库、角色、会话、架构就绪状态及完整 SQL。只有确认后,应用操作才能创建预览中的扩展、架构和表。"; +"LanceDB local binding" = "LanceDB 本地绑定"; +"Exact absolute directory on assigned Runner" = "已分配运行端上的确切绝对目录"; +"Allow creation of the exact previewed table" = "允许创建预览中的确切表"; +"Export LanceDB plaintext" = "导出 LanceDB 明文"; +"Import LanceDB plaintext" = "导入 LanceDB 明文"; +"Exact new destination file on assigned Runner" = "已分配运行端上的确切新目标文件"; +"Exact source file on assigned Runner" = "已分配运行端上的确切源文件"; +"Transfer is plaintext, scoped to this account and bot. The preview binds document count, checksum and full vector-space fingerprint/generation. Export never overwrites a file. A different Runner needs explicit transfer; account sync does not move database files." = "传输使用明文,范围限定于此账户和智能体。预览绑定文档数量、校验和及完整向量空间指纹和世代。导出绝不会覆盖文件。不同运行端需要明确传输;账户同步不会移动数据库文件。"; +"Obtain exact preview" = "获取确切预览"; +"Apply the displayed exact preview?" = "应用显示的确切预览?"; +"Discard preview / edit target" = "放弃预览 / 编辑目标"; +"Add connection" = "添加连接"; +"Edit selected connection" = "编辑所选连接"; +"Disconnect selected connection…" = "断开所选连接…"; +"Embedding profiles" = "嵌入配置"; +"Add API / local CPU profile" = "添加 API / 本地 CPU 配置"; +"Replace selected profile metadata…" = "替换所选配置元数据…"; +"Remove selected profile…" = "移除所选配置…"; +"Install local assets / check runtime…" = "安装本地资源 / 检查运行时…"; +"Reload masked configuration" = "重新加载隐藏敏感信息的配置"; +"Remote services and API embeddings receive plaintext outside the encrypted relay. Their downstream model usage can cost money. Local LanceDB plus local CPU embeddings avoids remote transfer unless you explicitly enable a remote service operation. Capture and group capture are separate per-bot choices, off for new bots." = "远程服务和 API 嵌入在加密中继之外接收明文。它们使用下游模型可能产生费用。本地 LanceDB 配合本地 CPU 嵌入可避免远程传输,除非你明确启用远程服务操作。对话记录和群聊记录是各智能体独立的选项,新智能体默认关闭。"; +"Names and secret-presence status are shown; endpoint credentials and private options are masked. Saving does not provision a service, initialize a schema, acquire assets or grant background spending. Disconnection does not delete remote banks. Backups and Lance history may retain deleted data." = "显示名称及是否存在密钥;端点凭据和私有选项隐藏。保存不会配置服务、初始化架构、获取资源或授权后台支出。断开连接不会删除远程记忆库。备份及 Lance 历史可能保留已删除的数据。"; +"Disconnect memory connection?" = "断开记忆服务连接?"; +"Remove embedding profile?" = "移除嵌入配置?"; +"Mental-model auto-refresh after consolidation and cron schedules stay disabled. No routine/background-spending authorization or enforceable total-cost evidence is available. Explicit create/refresh/commit can incur downstream charges; token limits are not dollar caps." = "整合后自动刷新心智模型及 cron 定时任务保持关闭。目前没有例行任务或后台支出授权,也没有可强制执行的总费用依据。手动创建、刷新或提交可能产生下游费用;词元限制不是金额上限。"; +"Negotiated feature" = "已协商功能"; +"Action" = "操作"; +"Run this exact advanced action?" = "运行此确切高级操作?"; +"Save explicit service memory…" = "手动保存服务记忆…"; +"Native Hindsight reflect…" = "Hindsight 原生反思…"; +"Connection and consent" = "连接及授权"; +"Account memory connection" = "账户记忆服务连接"; +"Account connections…" = "账户连接…"; +"Remote recall sends the turn's task text. Capture applies only to future eligible completed user/assistant text, never historical backfill, attachments, hidden thinking or tool payloads. Group text may include other participants and requires separate consent. Scrubbing is best effort, not DLP." = "远程检索发送本轮任务文本。记录仅适用于今后符合条件且已完成的用户和助手文本,绝不补录历史内容、附件、隐藏思考或工具载荷。群聊文本可能包含其他参与者的内容,需要单独授权。脱敏只能尽力而为,并非数据泄漏防护。"; +"Plaintext reaches the configured memory endpoint and its downstream extraction, embedding or reranking models outside the encrypted relay. Those services may charge you. Unattended delivery/retries, consolidation and mental-model schedules are not enabled: enforceable total-cost policy is unavailable. US$ refers to currency, not location." = "明文在加密中继之外到达配置的记忆端点及其下游提取、嵌入或重排序模型。这些服务可能收费。无人值守投递和重试、整合及心智模型定时任务未启用,因为尚无可强制执行的总费用策略。US$ 指货币,并非地点。"; +"Maximum capture deliveries per turn (0–4)" = "每轮最多记录投递次数(0–4)"; +"Automatic recall limits" = "自动检索限制"; +"Timeout milliseconds (1–5000)" = "超时毫秒数(1–5000)"; +"Maximum response bytes (1–32768)" = "最大响应字节数(1–32768)"; +"Maximum results (1–20)" = "最大结果数(1–20)"; +"Maximum context characters (100–8000)" = "最大上下文字符数(100–8000)"; +"Check service health / capabilities" = "检查服务健康状态 / 能力"; +"Explicit service memory" = "手动服务记忆"; +"Search / reflection query" = "搜索 / 反思查询"; +"Search this bot's memory…" = "搜索此智能体的记忆…"; +"Native reflect is offered only when negotiated. pgvector and LanceDB do not extract facts or manage mental models. No similarity search is labelled reflection, and no paid synthesis fallback is enabled." = "只有协商支持后才提供原生反思。pgvector 和 LanceDB 不提取事实或管理心智模型。相似度搜索不会被标为反思,也不会启用付费生成备用方案。"; +"Documents and provenance" = "文档及来源"; +"Exact document ID from a result or operation" = "结果或操作中的确切文档 ID"; +"Inspect document and source provenance" = "查看文档及来源"; +"Delete this document…" = "删除此文档…"; +"Clear this bot's service bank…" = "清空此智能体的服务记忆库…"; +"Pending deletion is not verified erasure. In-flight work can keep cleanup pending; backups and Lance history can retain data. Disabling capture or disconnecting does not erase remote data." = "删除待完成不代表已验证擦除。进行中的操作可能使清理继续等待;备份和 Lance 历史可能保留数据。停用记录或断开连接不会擦除远程数据。"; +"Deliveries and operations" = "投递及操作"; +"Core-issued operation" = "核心签发的操作"; +"Load operations / deletion status" = "加载操作 / 删除状态"; +"Check selected operation" = "检查所选操作"; +"Cancel selected operation…" = "取消所选操作…"; +"Retry selected delivery…" = "重试所选投递…"; +"Advanced capabilities" = "高级能力"; +"Open negotiated provider controls…" = "打开已协商的服务商控制…"; +"Hindsight profile/config, directives, mental models/history, observations and curation stay distinct from OpenViking sessions/resources/tasks. Only verified capabilities become actionable. Advanced operations can incur downstream costs and require explicit confirmation." = "Hindsight 配置、指令、心智模型及历史、观察和整理与 OpenViking 会话、资源和任务保持区分。只有已验证能力才能操作。高级操作可能产生下游费用,需要明确确认。"; +"Assigned Runner setup" = "已分配运行端设置"; +"Setup action" = "设置操作"; +"pgvector initialization preview" = "pgvector 初始化预览"; +"LanceDB local directory binding" = "LanceDB 本地目录绑定"; +"LanceDB plaintext export" = "LanceDB 明文导出"; +"LanceDB plaintext import" = "LanceDB 明文导入"; +"Preview selected setup…" = "预览所选设置…"; +"Allow remote memory plaintext and costs?" = "允许远程记忆明文传输及费用?"; +"Also capture future group text?" = "同时记录今后的群聊文本?"; +"Save explicit service memory?" = "手动保存服务记忆?"; +"Run native Hindsight reflect?" = "运行 Hindsight 原生反思?"; +"Search service memory?" = "搜索服务记忆?"; +"Retry this delivery?" = "重试此投递?"; +"Cancel this operation?" = "取消此操作?"; +"Clear this bot's service bank?" = "清空此智能体的服务记忆库?"; +"Delete this service document?" = "删除此服务文档?"; +"Exact service-issued ID" = "服务签发的确切 ID"; +"Result limit (1–20)" = "结果数量限制(1–20)"; +"Offset (0–100000)" = "偏移量(0–100000)"; +"Exact document ID" = "确切文档 ID"; +"Replacement document text" = "替换文档文本"; +"Skepticism (1–5)" = "怀疑程度(1–5)"; +"Literalism (1–5)" = "按字面理解程度(1–5)"; +"Empathy (1–5)" = "共情程度(1–5)"; +"Reflect mission" = "反思任务"; +"Retain mission" = "记忆提取任务"; +"Retain chunk size" = "记忆提取分块大小"; +"Extraction mode — exact service value" = "提取模式——确切服务值"; +"Retain instructions" = "记忆提取指令"; +"Extract labels (mixed leaves unchanged)" = "提取标签(混合状态保持不变)"; +"Recall maximum tokens" = "检索最大词元数"; +"Recall budget" = "检索预算"; +"Reflect maximum iterations" = "反思最大迭代次数"; +"Reflect maximum tokens" = "反思最大词元数"; +"Optional explicit mental-model ID" = "可选的明确心智模型 ID"; +"Source query" = "源查询"; +"Directive content" = "指令内容"; +"Tags — one per line" = "标签——每行一个"; +"Maximum tokens" = "最大词元数"; +"Priority" = "优先级"; +"Active directive" = "启用指令"; +"Replacement memory text" = "替换记忆文本"; +"Occurred start (ISO 8601)" = "发生起始时间(ISO 8601)"; +"Occurred end (ISO 8601)" = "发生结束时间(ISO 8601)"; +"Reason" = "原因"; +"Visible speaker" = "可见发言者"; +"Visible message text" = "可见消息文本"; +"Bot-relative resources path" = "相对于智能体的资源路径"; +"Exact HTTP(S) source URL — no credentials/query/fragment" = "确切 HTTP(S) 源 URL——不得含凭据、查询参数或片段"; +"get" = "获取"; +"update" = "更新"; +"reset" = "重置"; +"list" = "列出"; +"create" = "创建"; +"refresh" = "刷新"; +"history" = "历史"; +"delete" = "删除"; +"scopes" = "范围"; +"clear" = "清空"; +"clear derived" = "清空派生内容"; +"edit" = "编辑"; +"chunks" = "分块"; +"add message" = "添加消息"; +"commit" = "提交"; +"add" = "添加"; +"read" = "读取"; +"cancel" = "取消"; +"delete record" = "删除记录"; +"Bot: %@ · assigned Runner: %@. Bank scope is derived from the account key and stable bot ID; rename/provider changes retain scope. Namespaces are logical isolation, not server authorization." = "智能体:%@ · 已分配运行端:%@。记忆库范围由账户密钥及稳定的智能体 ID 派生;改名或更换服务商不会改变范围。命名空间仅提供逻辑隔离,并非服务器授权。"; +"Bot: %@. Setup runs on this bot's assigned Runner. It never replaces existing schemas or silently synchronizes local database files." = "智能体:%@。设置在此智能体已分配的运行端上执行。绝不会替换现有数据库架构或静默同步本地数据库文件。"; +"Profile: %@. Model: %@, revision: %@. Save a local CPU profile with matching model/tokenizer hashes first. Paths refer to the selected Runner, not necessarily this Mac." = "配置:%@。模型:%@,修订版本:%@。请先保存模型和分词器哈希匹配的本地 CPU 配置。路径属于所选运行端,不一定是此 Mac。"; +"Bot: %@. %@. Responses remain untrusted historical data. Mutating and model-backed actions require an exact confirmation; reads run only when you press Run." = "智能体:%@。%@。响应仍是不可信的历史数据。修改数据及使用模型的操作需要明确确认;读取仅在点击运行后执行。"; +"bank profile" = "记忆库概况"; +"bank config" = "记忆库配置"; +"directives" = "指令"; +"mental models" = "心智模型"; +"mental model history" = "心智模型历史"; +"observations" = "观察记录"; +"memory edit" = "编辑记忆"; +"memory invalidate" = "使记忆失效"; +"memory restore" = "恢复记忆"; +"documents" = "文档"; +"sessions" = "会话"; +"resources" = "资源"; +"tasks" = "任务"; +"Authorization mode" = "授权模式"; +"Account identity" = "账户标识"; +"User identity" = "用户标识"; +"Bot authorization secret" = "智能体授权密钥"; +"Memory Service…" = "记忆服务…"; +"Memory request failed" = "记忆请求失败"; +"memory unavailable" = "记忆服务不可用"; +"unsupported memory operation" = "不支持此记忆操作"; +"invalid memory input" = "记忆输入无效"; +"memory target changed" = "记忆目标已更改"; +"confirmation required" = "需要确认"; +"invalid memory reply" = "记忆响应无效"; +"lancedb_cloud_transport_unavailable" = "LanceDB 云端传输不可用"; +"invalid secret" = "密钥无效"; +"invalid budget" = "预算无效"; +"invalid capture cap" = "记录投递次数上限无效"; +"plaintext consent required" = "需要明文传输授权"; +"group consent required" = "需要群聊记录授权"; +"group capture requires conversation" = "记录群聊需要先启用对话记录"; +"connection required" = "需要连接"; +"enforced spending policy required" = "需要可强制执行的支出策略"; +"backend options mismatch" = "后端选项不匹配"; +"invalid setup reply" = "设置响应无效"; +"invalid asset plan" = "资源计划无效"; +"invalid asset source" = "资源来源无效"; +"approval not found" = "未找到批准记录"; +"approval expired" = "批准已过期"; +"approval stale" = "批准目标已变更"; +"approval action mismatch" = "批准操作不匹配"; +"local CPU" = "本地 CPU"; +"whole bot bank" = "智能体的整个记忆库"; "This build connects only to its isolated Beans CLI port %d. Restore that port in Settings › Advanced." = "此构建仅连接其隔离的 Beans CLI 端口 %d。请在“设置 › 高级”中恢复该端口。"; /* Local diagnostics review and explicit sharing. */ @@ -1046,3 +1286,11 @@ "Could not export the report. Choose a writable destination and try again." = "无法导出报告。请选择可写入的位置后重试。"; "Send input" = "发送输入"; "Could not send input" = "无法发送输入"; + +/* Exact protocol identifiers and provider name. */ +"none" = "none"; +"l2" = "l2"; +"cosine" = "cosine"; +"dot" = "dot"; +"euclidean" = "euclidean"; +"Hindsight" = "Hindsight"; diff --git a/macos/Sources/Beans/Settings/MemoryBotSetupViewController.swift b/macos/Sources/Beans/Settings/MemoryBotSetupViewController.swift index 606cdca8..d182a4d8 100644 --- a/macos/Sources/Beans/Settings/MemoryBotSetupViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryBotSetupViewController.swift @@ -17,7 +17,7 @@ final class MemoryBotSetupViewController: MemoryFormViewController { @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } override func loadView() { super.loadView() - note("Bot: \(botID). Setup runs on this bot's assigned Runner. It never replaces existing schemas or silently synchronizes local database files.") + note(L("Bot: %@. Setup runs on this bot's assigned Runner. It never replaces existing schemas or silently synchronizes local database files.", botID)) switch action { case .pgvector: heading("pgvector initialization"); note("Preview reads the actual connected database, role, session, schema readiness and complete SQL. Apply can create the previewed extension/schema/tables only after confirmation.") case .lanceBinding: diff --git a/macos/Sources/Beans/Settings/MemoryConnectionViewController.swift b/macos/Sources/Beans/Settings/MemoryConnectionViewController.swift index 5fd72210..0aafe763 100644 --- a/macos/Sources/Beans/Settings/MemoryConnectionViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryConnectionViewController.swift @@ -180,7 +180,7 @@ private final class MemoryOpenVikingBindingForm: NSStackView { bot.addItem(withTitle: L("Choose exact bot")) for value in bots { bot.addItem(withTitle: "\(value.name) · \(value.id)"); bot.lastItem?.representedObject = value.id } mode.addItems(withTitles: [L("Bot USER key"), L("Trusted gateway")]) - for (label, view) in [("Bot", bot as NSView), ("Authorization mode", mode), ("Account identity", account), ("User identity", user), ("Bot authorization secret", secret)] { + for (label, view) in [(L("Bot"), bot as NSView), (L("Authorization mode"), mode), (L("Account identity"), account), (L("User identity"), user), (L("Bot authorization secret"), secret)] { let stack = Build.stack([Build.label(L(label), font: .systemFont(ofSize: 12)), view], spacing: 4) view.translatesAutoresizingMaskIntoConstraints = false; view.setAccessibilityLabel(L(label)) addArrangedSubview(stack); stack.widthAnchor.constraint(equalTo: widthAnchor).isActive = true diff --git a/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift b/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift index 09f388bf..00184bac 100644 --- a/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift @@ -32,11 +32,11 @@ final class MemoryEmbeddingViewController: MemoryFormViewController { addRow("API key", view: secret, to: apiColumn) addForm(localColumn) for (key, label, value) in [ - ("model_sha256", "Model SHA-256", ""), ("tokenizer_sha256", "Tokenizer SHA-256", ""), - ("max_tokens", "Maximum tokenizer tokens", ""), ("input_ids", "Input IDs tensor", ""), - ("attention_mask", "Attention mask tensor", ""), ("token_type_ids", "Token type IDs tensor (optional)", ""), - ("output", "Output tensor", ""), ("pad_id", "Padding token ID", ""), - ("pad_type_id", "Padding type ID", ""), ("pad_token", "Padding token — exact text", ""), + ("model_sha256", L("Model SHA-256"), ""), ("tokenizer_sha256", L("Tokenizer SHA-256"), ""), + ("max_tokens", L("Maximum tokenizer tokens"), ""), ("input_ids", L("Input IDs tensor"), ""), + ("attention_mask", L("Attention mask tensor"), ""), ("token_type_ids", L("Token type IDs tensor (optional)"), ""), + ("output", L("Output tensor"), ""), ("pad_id", L("Padding token ID"), ""), + ("pad_type_id", L("Padding type ID"), ""), ("pad_token", L("Padding token — exact text"), ""), ] { fields[key] = addText(label, value: value, to: localColumn) } pooling = NSPopUpButton(); pooling.addItems(withTitles: ["mean", "cls", "pooled"]); addRow("Pooling", view: pooling, to: localColumn) specialTokens = NSButton(checkboxWithTitle: L("Add special tokens (per tokenizer contract)"), target: nil, action: nil) @@ -75,7 +75,7 @@ final class MemoryEmbeddingViewController: MemoryFormViewController { if profile.endpoint?.hasPrefix("http:") == true { guard await confirm("Save an insecure embedding endpoint?", details: L("Exact endpoint %@. Memory text and authentication cross plaintext HTTP when this profile is used. The connection also requires explicit insecure-HTTP approval.", profile.endpoint!)) else { return } } - guard await confirm("Save this vector-space profile?", details: L("Profile %@, model %@, revision %@, dimensions %d. Exact endpoint: %@. Secret action: %@. Verify the selected secret belongs to this target. Existing indexes are not re-embedded or migrated by this action. Remote API processing can incur costs; local mode clears any API key. No fallback or download is enabled.", profileID, profile.model, profile.revision, Int(profile.dimensions), profile.endpoint ?? "local CPU", String(describing: patch))) else { return } + guard await confirm("Save this vector-space profile?", details: L("Profile %@, model %@, revision %@, dimensions %d. Exact endpoint: %@. Secret action: %@. Verify the selected secret belongs to this target. Existing indexes are not re-embedded or migrated by this action. Remote API processing can incur costs; local mode clears any API key. No fallback or download is enabled.", profileID, profile.model, profile.revision, Int(profile.dimensions), profile.endpoint ?? L("local CPU"), String(describing: patch))) else { return } try await service.saveEmbedding(id: profileID, profile: profile, secret: patch) finishSave() } diff --git a/macos/Sources/Beans/Settings/MemoryFormViewController.swift b/macos/Sources/Beans/Settings/MemoryFormViewController.swift index 09b624e8..11d41eac 100644 --- a/macos/Sources/Beans/Settings/MemoryFormViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryFormViewController.swift @@ -121,9 +121,9 @@ class MemoryFormViewController: SheetViewController { } func showError(_ error: Error) { // RPC errors may contain untrusted backend payloads. Show known local errors only. - if let local = error as? MemoryUIError { errorLabel.stringValue = L(local.errorDescription ?? "Memory request failed") } - else if let draft = error as? MemoryServiceDraftError { errorLabel.stringValue = L(draft.rawValue.replacingOccurrences(of: "_", with: " ")) } - else if let setup = error as? MemorySetupError { errorLabel.stringValue = L(setup.rawValue.replacingOccurrences(of: "_", with: " ")) } + if let local = error as? MemoryUIError { errorLabel.stringValue = local.errorDescription.map(memoryTokenLabel) ?? L("Memory request failed") } + else if let draft = error as? MemoryServiceDraftError { errorLabel.stringValue = memoryTokenLabel(draft.rawValue.replacingOccurrences(of: "_", with: " ")) } + else if let setup = error as? MemorySetupError { errorLabel.stringValue = memoryTokenLabel(setup.rawValue.replacingOccurrences(of: "_", with: " ")) } else { errorLabel.stringValue = L("Memory request failed. Check the connection or obtain a fresh preview, then try again. Your draft is preserved.") } NSAccessibility.post(element: errorLabel, notification: .valueChanged) } @@ -184,3 +184,65 @@ final class MemoryResultViewController: SheetViewController { setButtons(confirm: L("Done"), cancel: nil) } } + +// Finite local error and negotiated action labels; wire values remain unchanged. +func memoryTokenLabel(_ key: String) -> String { + switch key { + case "get": return L("get") + case "update": return L("update") + case "reset": return L("reset") + case "list": return L("list") + case "create": return L("create") + case "refresh": return L("refresh") + case "history": return L("history") + case "delete": return L("delete") + case "scopes": return L("scopes") + case "clear": return L("clear") + case "clear derived": return L("clear derived") + case "edit": return L("edit") + case "chunks": return L("chunks") + case "add message": return L("add message") + case "commit": return L("commit") + case "add": return L("add") + case "read": return L("read") + case "cancel": return L("cancel") + case "delete record": return L("delete record") + case "bank profile": return L("bank profile") + case "bank config": return L("bank config") + case "directives": return L("directives") + case "mental models": return L("mental models") + case "mental model history": return L("mental model history") + case "observations": return L("observations") + case "memory edit": return L("memory edit") + case "memory invalidate": return L("memory invalidate") + case "memory restore": return L("memory restore") + case "documents": return L("documents") + case "sessions": return L("sessions") + case "resources": return L("resources") + case "tasks": return L("tasks") + case "memory unavailable": return L("memory unavailable") + case "unsupported memory operation": return L("unsupported memory operation") + case "invalid memory input": return L("invalid memory input") + case "memory target changed": return L("memory target changed") + case "confirmation required": return L("confirmation required") + case "invalid memory reply": return L("invalid memory reply") + case "lancedb_cloud_transport_unavailable": return L("lancedb_cloud_transport_unavailable") + case "invalid secret": return L("invalid secret") + case "invalid budget": return L("invalid budget") + case "invalid capture cap": return L("invalid capture cap") + case "plaintext consent required": return L("plaintext consent required") + case "group consent required": return L("group consent required") + case "group capture requires conversation": return L("group capture requires conversation") + case "connection required": return L("connection required") + case "enforced spending policy required": return L("enforced spending policy required") + case "backend options mismatch": return L("backend options mismatch") + case "invalid setup reply": return L("invalid setup reply") + case "invalid asset plan": return L("invalid asset plan") + case "invalid asset source": return L("invalid asset source") + case "approval not found": return L("approval not found") + case "approval expired": return L("approval expired") + case "approval stale": return L("approval stale") + case "approval action mismatch": return L("approval action mismatch") + default: return L(key) + } +} diff --git a/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift b/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift index de6bb874..7f9135d8 100644 --- a/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift @@ -17,7 +17,7 @@ final class MemoryLocalAssetsViewController: MemoryFormViewController { @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } override func loadView() { super.loadView() - note("Profile: \(profile.id). Model: \(profile.model), revision: \(profile.modelRevision). Save a local CPU profile with matching model/tokenizer hashes first. Paths refer to the selected Runner, not necessarily this Mac.") + note(L("Profile: %@. Model: %@, revision: %@. Save a local CPU profile with matching model/tokenizer hashes first. Paths refer to the selected Runner, not necessarily this Mac.", profile.id, profile.model, profile.modelRevision)) row("Selected Runner", runnerMenu) for kind in [MemoryAssetKind.runtime, .model, .tokenizer] { heading(kind.rawValue.capitalized) @@ -97,7 +97,7 @@ private final class MemoryAssetForm: NSStackView { self.kind = kind; super.init(frame: .zero) orientation = .vertical; alignment = .leading; spacing = 7; translatesAutoresizingMaskIntoConstraints = false source.addItems(withTitles: [L("Supplied absolute path on Runner"), L("Explicit HTTPS download")]) - for (label, view) in [("Source", source as NSView), ("Exact path / URL", location), ("License", license), ("Exact byte count", bytes), ("Full lowercase SHA-256", hashField)] { + for (label, view) in [(L("Source"), source as NSView), (L("Exact path / URL"), location), (L("License"), license), (L("Exact byte count"), bytes), (L("Full lowercase SHA-256"), hashField)] { let stack = Build.stack([Build.label(L(label), font: .systemFont(ofSize: 12)), view], spacing: 4) view.translatesAutoresizingMaskIntoConstraints = false; view.setAccessibilityLabel("\(kind.rawValue) \(L(label))") addArrangedSubview(stack); stack.widthAnchor.constraint(equalTo: widthAnchor).isActive = true diff --git a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift index 46318865..6fed9f7e 100644 --- a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift +++ b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift @@ -40,7 +40,7 @@ final class BotMemoryServiceViewController: MemoryFormViewController { @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } override func loadView() { super.loadView() - note("Bot: \(botID) · assigned Runner: \(runnerID). Bank scope is derived from the account key and stable bot ID; rename/provider changes retain scope. Namespaces are logical isolation, not server authorization.") + note(L("Bot: %@ · assigned Runner: %@. Bank scope is derived from the account key and stable bot ID; rename/provider changes retain scope. Namespaces are logical isolation, not server authorization.", botID, runnerID)) heading("Connection and consent") row("Account memory connection", connectionMenu) connectionMenu.addItem(withTitle: L("Disabled — local memory only")); connectionMenu.target = self; connectionMenu.action = #selector(connectionChanged) @@ -52,7 +52,7 @@ final class BotMemoryServiceViewController: MemoryFormViewController { note("Plaintext reaches the configured memory endpoint and its downstream extraction, embedding or reranking models outside the encrypted relay. Those services may charge you. Unattended delivery/retries, consolidation and mental-model schedules are not enabled: enforceable total-cost policy is unavailable. US$ refers to currency, not location.") budgets["cap"] = text("Maximum capture deliveries per turn (0–4)", value: "1") heading("Automatic recall limits") - for (key, label, value) in [("timeout", "Timeout milliseconds (1–5000)", "2000"), ("bytes", "Maximum response bytes (1–32768)", "16384"), ("results", "Maximum results (1–20)", "8"), ("context", "Maximum context characters (100–8000)", "4000")] { budgets[key] = text(label, value: value) } + for (key, label, value) in [("timeout", L("Timeout milliseconds (1–5000)"), "2000"), ("bytes", L("Maximum response bytes (1–32768)"), "16384"), ("results", L("Maximum results (1–20)"), "8"), ("context", L("Maximum context characters (100–8000)"), "4000")] { budgets[key] = text(label, value: value) } healthButton = MemoryActionButton("Check service health / capabilities") { [weak self] in self?.checkHealth() }; addForm(healthButton) heading("Explicit service memory") let textScroll = NSScrollView(); textScroll.documentView = retainText; textScroll.hasVerticalScroller = true; textScroll.borderType = .bezelBorder @@ -126,11 +126,10 @@ final class BotMemoryServiceViewController: MemoryFormViewController { if selected?.availability == .blocked { health = nil } let caps = health?.capabilities ?? .init() retainButton.isEnabled = caps.supports(.retain); recallButton?.isEnabled = caps.supports(.recall) - reflectButton.isEnabled = caps.supports(.reflect); reflectButton.isHidden = !caps.supports(.reflect) + reflectButton.isEnabled = caps.supports(.reflect) inspectButton?.isEnabled = caps.supports(.inspect); deleteButton?.isEnabled = caps.supports(.deleteDocument) clearButton?.isEnabled = caps.supports(.clear) advancedButton?.isEnabled = MemoryAdvancedViewController.features(backend: currentConnection?.backend, capabilities: caps).isEmpty == false - advancedButton?.isHidden = advancedButton?.isEnabled != true statusButton?.isEnabled = selectedOperation != nil && caps.supports(.operationStatus) cancelOperationButton?.isEnabled = selectedOperation != nil && caps.supports(.cancelOperation) retryButton?.isEnabled = selectedOperation.map { caps.supports(.retain) && ($0.state == .failed || ($0.state == .deliveryUnknown && caps.idempotentRetain)) } ?? false @@ -258,7 +257,7 @@ final class BotMemoryServiceViewController: MemoryFormViewController { run { [self] in let preferences = try await service.getPreferences(botID: botID), list = try await service.listConnections() guard let connection = list.connections.first(where: { $0.id == preferences.connectionID }) else { throw MemoryUIError.staleTarget } - guard await confirm(clear ? "Clear this bot's service bank?" : "Delete this service document?", details: L("Bot %@; connection %@ (%@), revision %llu · %@; deletion epoch %llu. Target: %@. This fences queued writes; pending cleanup does not mean erasure. Service backups and Lance history may retain data.", botID, connection.name, connection.id, connection.revision.counter, connection.revision.deviceID, preferences.deletionEpoch, document ?? "whole bot bank")) else { return } + guard await confirm(clear ? "Clear this bot's service bank?" : "Delete this service document?", details: L("Bot %@; connection %@ (%@), revision %llu · %@; deletion epoch %llu. Target: %@. This fences queued writes; pending cleanup does not mean erasure. Service backups and Lance history may retain data.", botID, connection.name, connection.id, connection.revision.counter, connection.revision.deviceID, preferences.deletionEpoch, document ?? L("whole bot bank"))) else { return } var parameters: [String: Any] = ["bot_id": botID, "confirm": true, "connection_revision": try JSONSerialization.jsonObject(with: JSONEncoder().encode(connection.revision)), "deletion_epoch": preferences.deletionEpoch] if let document { parameters["document_id"] = document } authorityRecovered = false diff --git a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift index 4eb97f88..321c0e2e 100644 --- a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift +++ b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift @@ -36,10 +36,10 @@ final class MemoryAdvancedViewController: MemoryFormViewController { override func loadView() { super.loadView() supported = Self.features(backend: backend, capabilities: capabilities) - note("Bot: \(botID). \(backend.rawValue). Responses remain untrusted historical data. Mutating and model-backed actions require an exact confirmation; reads run only when you press Run.") + note(L("Bot: %@. %@. Responses remain untrusted historical data. Mutating and model-backed actions require an exact confirmation; reads run only when you press Run.", botID, backend.rawValue)) note("Mental-model auto-refresh after consolidation and cron schedules stay disabled. No routine/background-spending authorization or enforceable total-cost evidence is available. Explicit create/refresh/commit can incur downstream charges; token limits are not dollar caps.") row("Negotiated feature", featureMenu); row("Action", actionMenu) - featureMenu.addItems(withTitles: supported.map { $0.rawValue.replacingOccurrences(of: "_", with: " ") }) + featureMenu.addItems(withTitles: supported.map { memoryTokenLabel($0.rawValue.replacingOccurrences(of: "_", with: " ")) }) featureMenu.target = self; featureMenu.action = #selector(featureChanged) actionMenu.target = self; actionMenu.action = #selector(actionChanged) addForm(inputColumn) @@ -76,7 +76,7 @@ final class MemoryAdvancedViewController: MemoryFormViewController { actionMenu.removeAllItems() if let feature { for action in actions(for: feature) { - actionMenu.addItem(withTitle: L(action.replacingOccurrences(of: "_", with: " "))) + actionMenu.addItem(withTitle: memoryTokenLabel(action.replacingOccurrences(of: "_", with: " "))) actionMenu.lastItem?.representedObject = action } } diff --git a/macos/Tests/MemoryUIControllerChecks.swift b/macos/Tests/MemoryUIControllerChecks.swift index 70ee8d36..22f34a31 100644 --- a/macos/Tests/MemoryUIControllerChecks.swift +++ b/macos/Tests/MemoryUIControllerChecks.swift @@ -1,6 +1,10 @@ import AppKit -func L(_ text: String, _ arguments: CVarArg...) -> String { arguments.isEmpty ? text : String(format: text, arguments: arguments) } +private var fixtureLanguageBundle: Bundle? +func L(_ text: String, _ arguments: CVarArg...) -> String { + let translated = fixtureLanguageBundle?.localizedString(forKey: text, value: text, table: nil) ?? text + return arguments.isEmpty ? translated : String(format: translated, arguments: arguments) +} enum Theme { enum Font { static let caption = NSFont.systemFont(ofSize: 11); static let body = NSFont.systemFont(ofSize: 13) } } struct Bot { let id: String, name: String, runnerID: String } struct Device { enum Status { case online, pairing, offline }; let id: String, name: String } @@ -129,6 +133,51 @@ private func check(_ condition: Bool, _ message: String) { if !condition { fatal window.contentViewController = nil } } + if let resources = ProcessInfo.processInfo.environment["BEANS_MEMORY_UI_RESOURCES"] { + fixtureLanguageBundle = Bundle(path: resources + "/zh-Hans.lproj") + check(fixtureLanguageBundle != nil, "Chinese fixture resources unavailable") + let localized = BotMemoryServiceViewController(botID: "bot", name: "Fixture", runnerID: "runner", service: api, setup: setup, currentRunner: { "runner" }) + localized.loadViewIfNeeded() + let window = NSWindow(contentViewController: localized) + window.setContentSize(localized.view.fittingSize) + window.contentView?.layoutSubtreeIfNeeded() + let controls = localized.controls(in: localized.view) + check(localized.reflectButton.title == "Hindsight 原生反思…" && !localized.reflectButton.isHidden && !localized.reflectButton.isEnabled, "unsupported reflection loses translated discoverability") + check(controls.compactMap { $0 as? NSButton }.contains { $0.title == "打开已协商的服务商控制…" && !$0.isHidden && !$0.isEnabled }, "unsupported provider controls lose translated discoverability") + let query = controls.compactMap { $0 as? NSTextField }.first { $0.accessibilityLabel() == "搜索 / 反思查询" }! + check(window.makeFirstResponder(query) && query.currentEditor() != nil, "translated query cannot receive keyboard focus") + check(localized.capture.title == "记录今后已完成的对话文本", "capture translation unavailable: \(localized.capture.title)") + check(localized.capture.accessibilityTitle() == localized.capture.title, "translated capture loses its accessibility title") + let localizedAdvanced = MemoryAdvancedViewController(service: api, botID: "bot", backend: .openViking, capabilities: try JSONDecoder().decode(MemoryServiceCapabilities.self, from: Data("{\"advanced\":[\"sessions\",\"resources\",\"tasks\"],\"advanced_actions\":{\"sessions\":[\"list\",\"create\"],\"resources\":[\"list\"],\"tasks\":[\"list\"]}}".utf8))) + localizedAdvanced.loadViewIfNeeded() + let featureMenu = localizedAdvanced.controls(in: localizedAdvanced.view).compactMap { $0 as? NSPopUpButton }.first { $0.accessibilityLabel() == "已协商功能" }! + check(featureMenu.itemTitles == ["会话", "资源", "任务"], "negotiated feature menu falls back to English") + localizedAdvanced.select(feature: .sessions, action: "list") + check(try localizedAdvanced.command().action == "list", "localized menu changes the negotiated wire action") + let localizedConnection = MemoryConnectionViewController(service: api, saved: nil, embeddings: [], bots: [("bot", "Fixture")]) + localizedConnection.loadViewIfNeeded(); localizedConnection.backendMenu.selectItem(at: 1) + NSApplication.shared.sendAction(localizedConnection.backendMenu.action!, to: localizedConnection.backendMenu.target, from: localizedConnection.backendMenu) + let bindingLabels = localizedConnection.controls(in: localizedConnection.view).compactMap { $0.accessibilityLabel() } + check(["授权模式", "账户标识", "用户标识"].allSatisfy(bindingLabels.contains), "OpenViking binding fields fall back to English") + localized.showError(MemoryUIError.invalidInput) + check(localized.errorLabel.stringValue == "记忆输入无效", "native validation error falls back to English") + localized.showError(MemoryServiceDraftError.plaintextConsentRequired) + check(localized.errorLabel.stringValue == "需要明文传输授权", "native consent error falls back to English") + localized.showError(MemorySetupError.approvalExpired) + check(localized.errorLabel.stringValue == "批准已过期", "native setup error falls back to English") + let serviceEntry = MemoryActionButton("Memory Service…") + check(serviceEntry.title == "记忆服务…", "local editor service entry falls back to English") + print("PASS: negotiated Chinese feature menus preserve wire actions; OpenViking binding labels, service entry and native error surfaces are translated") + window.makeFirstResponder(nil) + if let output = ProcessInfo.processInfo.environment["BEANS_MEMORY_UI_IMAGE"], + let bitmap = localized.view.bitmapImageRepForCachingDisplay(in: localized.view.bounds) { + localized.view.cacheDisplay(in: localized.view.bounds, to: bitmap) + try bitmap.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: output)) + } + window.contentViewController = nil + fixtureLanguageBundle = nil + print("PASS: Simplified Chinese native memory labels, disabled discoverability, keyboard editing focus and accessibility titles") + } print("PASS: guarded native drafts, failure recovery, exact secrets, capability/consent gates, typed OpenViking, light/dark scroll sizing") // AppKit's shared application can keep an async command-line main alive after all // checks return. This fixture owns its process; terminate after completed proof. diff --git a/macos/Tests/MemoryUIFlows.swift b/macos/Tests/MemoryUIFlows.swift index 038a55ea..0e194527 100644 --- a/macos/Tests/MemoryUIFlows.swift +++ b/macos/Tests/MemoryUIFlows.swift @@ -124,7 +124,7 @@ func runMemoryUIFlows() async throws -> [MemoryFormViewController] { check(preferenceWrites.count == 2 && preferenceWrites.last!.1["bot_id"] as? String == "bot", "preference failure recovery writes wrong bot") check(preferenceWrites.last!.1["unattended_capture"] as? Bool == false, "capture enables unbounded worker") button("Check service health / capabilities", bot).performClick(nil); await bot.pendingTask?.value - check(bot.retainButton.isEnabled && !bot.reflectButton.isEnabled && bot.reflectButton.isHidden, "negotiated pgvector shows native reflection") + check(bot.retainButton.isEnabled && !bot.reflectButton.isEnabled && !bot.reflectButton.isHidden && !button("Open negotiated provider controls…", bot).isHidden, "missing capability hides a control instead of disabling it") let editor = descendants(bot.view).compactMap { $0 as? NSTextView }.first { $0.accessibilityLabel() == "Explicit memory text" }! editor.string = "synthetic fixture memory" var result = ""; bot.resultHandler = { result = $0 } diff --git a/macos/Tests/run-memory-ui.sh b/macos/Tests/run-memory-ui.sh index 9908a5dc..b6a158bb 100755 --- a/macos/Tests/run-memory-ui.sh +++ b/macos/Tests/run-memory-ui.sh @@ -20,7 +20,7 @@ swiftc -parse-as-library -swift-version 5 -D BEANS_MEMORY_UI_STANDALONE \ "$root/macos/Tests/MemoryUIControllerChecks.swift" \ "$root/macos/Tests/MemoryUIFlows.swift" \ -o "$output/memory-ui" -"$output/memory-ui" "$@" +BEANS_MEMORY_UI_RESOURCES="$root/macos/Resources" "$output/memory-ui" "$@" for fixture in MemoryServiceDraft MemorySetupDraft MemoryUIPreviewExpiry; do printf 'Compiling Foundation fixture: %s\n' "$fixture" swiftc -parse-as-library -swift-version 5 \ diff --git a/mobile/app/settings/diagnostics.tsx b/mobile/app/settings/diagnostics.tsx index a5bf041c..2d4ea4b1 100644 --- a/mobile/app/settings/diagnostics.tsx +++ b/mobile/app/settings/diagnostics.tsx @@ -18,12 +18,28 @@ function sameAuthority(a: ReturnType, b: ReturnType; generation: number }; +type DiagnosticsStatus = '' | 'Generating report…' | 'Review this report before sharing.' | 'This report schema is not supported. Update Beans.' | 'The diagnostics report is invalid.' | 'Could not generate the diagnostics report.' | 'Report copied.' | 'Could not copy the report.' | 'Could not share the report.'; + +function statusLabel(status: DiagnosticsStatus) { + switch (status) { + case 'Generating report…': return t('Generating report…'); + case 'Review this report before sharing.': return t('Review this report before sharing.'); + case 'This report schema is not supported. Update Beans.': return t('This report schema is not supported. Update Beans.'); + case 'The diagnostics report is invalid.': return t('The diagnostics report is invalid.'); + case 'Could not generate the diagnostics report.': return t('Could not generate the diagnostics report.'); + case 'Report copied.': return t('Report copied.'); + case 'Could not copy the report.': return t('Could not copy the report.'); + case 'Could not share the report.': return t('Could not share the report.'); + case '': return t('Generate a report to review sanitized setup evidence.'); + } +} + export default function DiagnosticsScreen() { useLanguage(); const p = usePalette(); const [review, setReview] = useState(); const [busy, setBusy] = useState(false); - const [status, setStatus] = useState(''); + const [status, setStatus] = useState(''); const focused = useRef(false), generation = useRef(0), pending = useRef(false); const revoke = useCallback(() => { generation.current++; @@ -92,7 +108,7 @@ export default function DiagnosticsScreen() {
- {status ? t(status) : t('Generate a report to review sanitized setup evidence.')} + {statusLabel(status)} {review && {review.host ? t('Disclosed relay host/port: {host}', { host: review.host }) : t('No relay host is disclosed.')}} diff --git a/mobile/src/i18n/zh.ts b/mobile/src/i18n/zh.ts index 032e81fd..d3f590d6 100644 --- a/mobile/src/i18n/zh.ts +++ b/mobile/src/i18n/zh.ts @@ -23,6 +23,12 @@ export const zh: Record = { "Unknown images stay text-only. Unknown tools are unverified. Tools No cannot run Beans tool-bearing bot turns; tool-free inference remains available.": "图像支持未知时仅发送文本。工具支持未知时尚未验证。工具选择否时无法执行 Beans 带工具的智能体轮次;仍可执行无工具推理。", "Files": "文件", "Messages": "消息", + "Test result": "测试结果", + "Before screenshot": "操作前截图", + "After screenshot": "操作后截图", + "Check": "检查", + "Passed": "已通过", + "Not verified": "未验证", "Search covers downloaded history only": "搜索仅涵盖已下载的历史记录", "{count} bot": "{count} 个智能体", "{count} bots": "{count} 个智能体", diff --git a/mobile/src/ui/ChatsScreen.tsx b/mobile/src/ui/ChatsScreen.tsx index 486db9fd..9ded2e97 100644 --- a/mobile/src/ui/ChatsScreen.tsx +++ b/mobile/src/ui/ChatsScreen.tsx @@ -415,7 +415,7 @@ function SearchResultRow({ item, bots, query, onPress }: { item: SearchRow; bots const members = item.chat.bot_ids.map((id) => bots.get(id)).filter((bot): bot is Bot => !!bot); const at = item.createdAt ?? lastActivity(item.chat); return ( - [styles.searchRow, { backgroundColor: pressed ? p.fill : "transparent" }]}> + [styles.searchRow, { backgroundColor: pressed ? p.fill : "transparent" }]}> @@ -424,7 +424,7 @@ function SearchResultRow({ item, bots, query, onPress }: { item: SearchRow; bots - {item.kind !== "chat" ? {t(item.kind === "file" ? "Files" : "Messages")} : null} + {item.kind !== "chat" ? {(item.kind === "file" ? t("Files") : t("Messages"))} : null} ); } diff --git a/scripts/l10n-swift.test.ts b/scripts/l10n-swift.test.ts new file mode 100644 index 00000000..6a671465 --- /dev/null +++ b/scripts/l10n-swift.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "vitest"; +import { memorySwiftKeys } from "./l10n-swift.ts"; +const path = "Settings/MemoryEmbeddingViewController.swift"; + +test("memory helpers expose only display arguments, including choices and placeholders", () => { + const keys = memorySwiftKeys(` + row("Endpoint", endpoint); text("Name", value: "private value", placeholder: "Enter name"); + popup("Distance", choices: ["cosine", "dot"]); note("Costs, limits (and scope)"); + Field("wire_id", "Display ID", required: true); MemoryActionButton("Save") {} + `, path); + expect([...keys].sort()).toEqual(["Endpoint", "Name", "Enter name", "Distance", "cosine", "dot", "Costs, limits (and scope)", "Display ID", "Save"].sort()); + expect(keys.has("private value")).toBe(false); + expect(keys.has("wire_id")).toBe(false); +}); + +test("conditional labels include results but never comparison constants", () => { + const keys = memorySwiftKeys(`L(kind == "not a label" ? "New" : "Edit"); confirm(clear ? "Clear" : "Delete", details: "already translated elsewhere")`, path); + expect([...keys].sort()).toEqual(["New", "Edit", "Clear", "Delete"].sort()); +}); + +test("truly unused entries, comments, arbitrary variables and unrelated helpers stay unused", () => { + const source = `// note("Comment") + /* row("Old", field) */ + let unused = "Unused"; note(runtimeValue); output("Untranslated output"); + text("Actual label", value: "not localized");`; + const keys = memorySwiftKeys(source, path); + expect([...keys]).toEqual(["Actual label"]); + expect(["Unused", "Comment", "Old"].filter(key => !keys.has(key))).toEqual(["Unused", "Comment", "Old"]); + expect([...memorySwiftKeys(source, "Unrelated.swift")]).toEqual([]); +}); + +test("quoted punctuation and nested conditions do not leak non-label values", () => { + const keys = memorySwiftKeys(`text("Name, with (punctuation)", value: choose("secret", nil)); L(a ? (b ? "Inner" : "Other") : "Outer")`, path); + expect(keys.has("Name, with (punctuation)")).toBe(true); + expect(keys.has("secret")).toBe(false); + expect([...keys].sort()).toEqual(["Name, with (punctuation)", "Inner", "Other", "Outer"].sort()); +}); + +test("escaped quotes and newlines belong to the literal label", () => { + const source = String.raw`note("Say \"hello\"\nnow"); row("Private path", file("not a key"));`; + expect([...memorySwiftKeys(source, path)]).toEqual(['Say "hello"\nnow', "Private path"]); +}); + + +test("nested comments and quoted source samples never count as calls", () => { + const source = String.raw`/* outer /* inner */ note("Not used") */ + let sample = """note("Also unused")""" + let raw = #"note("Raw unused")"# + note("Used")`; + expect([...memorySwiftKeys(source, path)]).toEqual(["Used"]); +}); + +test("parentheses around a condition do not hide either label branch", () => { + expect([...memorySwiftKeys('note((enabled) ? "Shown A" : ("Shown B"))', path)]) + .toEqual(["Shown A", "Shown B"]); +}); diff --git a/scripts/l10n-swift.ts b/scripts/l10n-swift.ts new file mode 100644 index 00000000..43bcdf7c --- /dev/null +++ b/scripts/l10n-swift.ts @@ -0,0 +1,118 @@ +// Additional finite key expressions used by the native memory form helpers. +// This does not infer arbitrary Swift variables or count every string in a file. +// Keep offsets stable while distinguishing executable calls from comments and strings. +function swiftSource(source: string): { text: string; code: string } { + const text = source.split(""); const code = source.split(""); + const blank = (from: number, to: number, comment = false) => { + for (let j = from; j < to; j++) { code[j] = " "; if (comment) text[j] = " "; } + }; + for (let i = 0; i < source.length;) { + const start = i; + if (source.startsWith("//", i)) { + const end = source.indexOf("\n", i); i = end < 0 ? source.length : end; + blank(start, i, true); + } else if (source.startsWith("/*", i)) { + let depth = 1; i += 2; + while (i < source.length && depth) { + if (source.startsWith("/*", i)) { depth++; i += 2; } + else if (source.startsWith("*/", i)) { depth--; i += 2; } + else i++; + } + blank(start, i, true); + } else { + const opening = /^(#*)("""|")/.exec(source.slice(i)); + if (!opening) { i++; continue; } + const hashes = opening[1]!; const close = opening[2]! + hashes; + i += opening[0].length; + while (i < source.length) { + if (source.startsWith("\\" + hashes, i)) { i += 2 + hashes.length; continue; } + if (source.startsWith(close, i)) { i += close.length; break; } + i++; + } + blank(start, Math.min(i, source.length)); + } + } + return { text: text.join(""), code: code.join("") }; +} +function fullyParenthesized(value: string): boolean { + if (!value.startsWith("(") || !value.endsWith(")")) return false; + const { code } = swiftSource(value); let depth = 0; + for (let i = 0; i < code.length; i++) { + if (code[i] === "(") depth++; + else if (code[i] === ")" && --depth === 0) return i === code.length - 1; + } + return false; +} +function parts(source: string, delimiter: string): string[] { + const result: string[] = []; let start = 0, depth = 0, ternary = 0, quoted = false, escaped = false; + for (let i = 0; i < source.length; i++) { + const c = source[i]!; + if (quoted) { if (escaped) escaped = false; else if (c === "\\") escaped = true; else if (c === '"') quoted = false; continue; } + if (c === '"') quoted = true; + else if ("([{".includes(c)) depth++; + else if (c === "?" && source[i + 1] !== "?" && source[i - 1] !== "?" && source[i + 1] !== ".") ternary++; + else if (c === ":" && ternary) ternary--; + else if (")]}".includes(c)) depth--; + if (c === delimiter && depth === 0 && ternary === 0) { result.push(source.slice(start, i)); start = i + 1; } + } + result.push(source.slice(start)); return result; +} +function literals(expression: string): string[] { + const value = expression.trim(); + if (fullyParenthesized(value)) return literals(value.slice(1, -1)); + if (/^"(?:[^"\\]|\\.)*"$/.test(value)) { + if (value.includes("\\(")) return []; // runtime interpolation is not a finite key + return [value.slice(1, -1).replace(/\\([ntr"\\])/g, (_, c) => (({ n: "\n", t: "\t", r: "\r" } as Record)[c] ?? c))]; + } + // A conditional chooses its result branches, not strings in the condition. + let depth = 0, quoted = false, escaped = false, question = -1, nested = 0; + for (let i = 0; i < value.length; i++) { + const c = value[i]!; + if (quoted) { if (escaped) escaped = false; else if (c === "\\") escaped = true; else if (c === '"') quoted = false; continue; } + if (c === '"') quoted = true; + else if ("([{".includes(c)) depth++; + else if (")]}".includes(c)) depth--; + else if (depth === 0 && c === "?" && value[i + 1] !== "?" && value[i - 1] !== "?" && value[i + 1] !== ".") { if (question < 0) question = i; else nested++; } + else if (depth === 0 && c === ":" && question >= 0) { if (nested) nested--; else return [...literals(value.slice(question + 1, i)), ...literals(value.slice(i + 1))]; } + } + return []; +} +export function memorySwiftKeys(source: string, path: string): Set { + const keys = new Set(); + const memoryForm = new Set([ + "Settings/MemoryFormViewController.swift", "Settings/MemoryConnectionViewController.swift", + "Settings/MemoryEmbeddingViewController.swift", "Settings/MemoryLocalAssetsViewController.swift", + "Settings/MemoryBotSetupViewController.swift", "Settings/MemorySettingsViewController.swift", + "Sheets/MemoryAdvancedViewController.swift", "Sheets/BotMemoryServiceViewController.swift", + ]).has(path); + const parsed = swiftSource(source); + source = parsed.text; + const call = /\b(L|MemoryActionButton|heading|note|row|text|popup|toggle|confirm|optionRow|addRow|addText|Field)\s*\(/g; + for (const match of parsed.code.matchAll(call)) { + const name = match[1]!; + if (name !== "MemoryActionButton" && !memoryForm) continue; + const start = match.index! + match[0].length; + let depth = 1, quoted = false, escaped = false, end = start; + for (; end < source.length && depth; end++) { + const c = source[end]!; + if (quoted) { if (escaped) escaped = false; else if (c === "\\") escaped = true; else if (c === '"') quoted = false; continue; } + if (c === '"') quoted = true; else if (c === "(") depth++; else if (c === ")") depth--; + } + if (depth) continue; + const args = parts(source.slice(start, end - 1), ","); + const first = name === "Field" ? args[1] : args[0]; + if (name === "L" && args[1]?.trim().startsWith("context:")) { + const contexts = literals(args[1].replace(/^\s*context\s*:\s*/, "")); + for (const key of literals(first ?? "")) for (const context of contexts) keys.add(`${key}|${context}`); + } else if (first) for (const key of literals(first)) keys.add(key); + if (name === "popup") { + const choices = args.find(arg => /^\s*choices\s*:/.test(arg))?.replace(/^\s*choices\s*:\s*/, ""); + if (choices?.startsWith("[") && choices.endsWith("]")) for (const option of parts(choices.slice(1, -1), ",")) for (const key of literals(option)) keys.add(key); + } + if (name === "text") { + const placeholder = args.find(arg => /^\s*placeholder\s*:/.test(arg))?.replace(/^\s*placeholder\s*:\s*/, ""); + if (placeholder) for (const key of literals(placeholder)) keys.add(key); + } + } + return keys; +} diff --git a/scripts/l10n.ts b/scripts/l10n.ts index c19c38cc..6ecd9e97 100644 --- a/scripts/l10n.ts +++ b/scripts/l10n.ts @@ -3,6 +3,7 @@ // Chinese entry, and a format key and its translation should take the same values. `pnpm run l10n` lists what is missing, unused, or mismatched; // `--merge …` adds `{ "English": "中文" }` files to the tables first. +import { memorySwiftKeys } from "./l10n-swift.ts" import { globSync, existsSync } from "node:fs" import { readFile, writeFile } from "node:fs/promises" import { join } from "node:path" @@ -131,6 +132,9 @@ function report(name: string, used: Map, table: Table) { } const macKeys = await keysIn(join(ROOT, "macos/Sources/Beans"), "**/*.swift", /\bL\(\s*"((?:[^"\\]|\\.)*)"(?:,\s*context:\s*"((?:[^"\\]|\\.)*)")?/g, () => false) +for await (const path of scan(join(ROOT, "macos/Sources/Beans"), "**/*.swift")) { + for (const key of memorySwiftKeys(await readFile(join(ROOT, "macos/Sources/Beans", path), "utf8"), path)) macKeys.set(key, path) +} const phoneKeys = await keysIn(join(ROOT, "mobile"), "{app,src}/**/*.{ts,tsx}", /\bt\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/g, (path) => path.includes("i18n/") || path.endsWith(".test.ts")) const desktopKeys = await desktopKeysIn(join(ROOT, "desktop"))