From b6729172718eb9cc053ddf6fd1687055bad2cf93 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Tue, 13 Oct 2026 14:50:33 -0300 Subject: [PATCH 01/15] fix(macos): disable memory controls without capability instead of hiding them The bot memory sheet hid Reflect and the provider-controls button when the capability was not negotiated. Keep both visible and disabled; the regression asserts they stay visible. Refs #101. --- docs/architecture/memory-ui.md | 2 +- .../Sources/Beans/Sheets/BotMemoryServiceViewController.swift | 3 +-- macos/Tests/MemoryUIFlows.swift | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/architecture/memory-ui.md b/docs/architecture/memory-ui.md index d887ee8a..69cade54 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. diff --git a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift index 46318865..5b767401 100644 --- a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift +++ b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift @@ -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 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 } From 2a5488958920f62e3cebc5635e08175d8b19f754 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Wed, 14 Oct 2026 12:44:05 -0300 Subject: [PATCH 02/15] fix(macos): localize native memory forms and verify translated controls --- docs/architecture/memory-ui.md | 2 + .../zh-Hans.lproj/Localizable.strings | 197 ++++++++++++++++++ .../MemoryBotSetupViewController.swift | 2 +- .../MemoryLocalAssetsViewController.swift | 2 +- .../BotMemoryServiceViewController.swift | 2 +- .../Sheets/MemoryAdvancedViewController.swift | 2 +- macos/Tests/MemoryUIControllerChecks.swift | 31 ++- macos/Tests/run-memory-ui.sh | 2 +- 8 files changed, 234 insertions(+), 6 deletions(-) diff --git a/docs/architecture/memory-ui.md b/docs/architecture/memory-ui.md index 69cade54..57242b9a 100644 --- a/docs/architecture/memory-ui.md +++ b/docs/architecture/memory-ui.md @@ -59,4 +59,6 @@ Native note labels, generic error keys, budget/count sentences and conflict conf `bun test desktop/src/model/memoryService.test.ts desktop/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. + `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. diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index f1b3db39..26f5e242 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -1024,6 +1024,203 @@ "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." = "智能体:%@。%@。响应仍是不可信的历史数据。修改数据及使用模型的操作需要明确确认;读取仅在点击运行后执行。"; "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. */ 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/MemoryLocalAssetsViewController.swift b/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift index de6bb874..9d8c45cf 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) diff --git a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift index 5b767401..3bc7b8ce 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) diff --git a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift index 4eb97f88..75e592d3 100644 --- a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift +++ b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift @@ -36,7 +36,7 @@ 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: " ") }) diff --git a/macos/Tests/MemoryUIControllerChecks.swift b/macos/Tests/MemoryUIControllerChecks.swift index 70ee8d36..23ca9b71 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,31 @@ 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") + 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/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 \ From 423dd35214af0d3215b55fd923ce3773d326f6d6 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Wed, 14 Oct 2026 13:30:04 -0300 Subject: [PATCH 03/15] fix(macos): translate negotiated memory features and error surfaces --- docs/architecture/memory-ui.md | 2 + .../zh-Hans.lproj/Localizable.strings | 44 +++++++++++++++++++ .../MemoryEmbeddingViewController.swift | 2 +- .../BotMemoryServiceViewController.swift | 2 +- .../Sheets/MemoryAdvancedViewController.swift | 2 +- macos/Tests/MemoryUIControllerChecks.swift | 20 +++++++++ 6 files changed, 69 insertions(+), 3 deletions(-) diff --git a/docs/architecture/memory-ui.md b/docs/architecture/memory-ui.md index 57242b9a..d8cd2e34 100644 --- a/docs/architecture/memory-ui.md +++ b/docs/architecture/memory-ui.md @@ -61,4 +61,6 @@ Native note labels, generic error keys, budget/count sentences and conflict conf 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. diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 26f5e242..014f872b 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -1221,6 +1221,50 @@ "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. */ diff --git a/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift b/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift index 09f388bf..24d5c11f 100644 --- a/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryEmbeddingViewController.swift @@ -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/Sheets/BotMemoryServiceViewController.swift b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift index 3bc7b8ce..c953945c 100644 --- a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift +++ b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift @@ -257,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 75e592d3..41335045 100644 --- a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift +++ b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift @@ -39,7 +39,7 @@ final class MemoryAdvancedViewController: MemoryFormViewController { 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 { L($0.rawValue.replacingOccurrences(of: "_", with: " ")) }) featureMenu.target = self; featureMenu.action = #selector(featureChanged) actionMenu.target = self; actionMenu.action = #selector(actionChanged) addForm(inputColumn) diff --git a/macos/Tests/MemoryUIControllerChecks.swift b/macos/Tests/MemoryUIControllerChecks.swift index 23ca9b71..22f34a31 100644 --- a/macos/Tests/MemoryUIControllerChecks.swift +++ b/macos/Tests/MemoryUIControllerChecks.swift @@ -148,6 +148,26 @@ private func check(_ condition: Bool, _ message: String) { if !condition { fatal 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) { From e835c85258920cff8a995d9f5694ebac6f7f2d14 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:19:07 -0300 Subject: [PATCH 04/15] fix(l10n): recognize native memory form translation keys --- CHANGELOG.md | 1 + docs/architecture/memory-ui.md | 2 + .../zh-Hans.lproj/Localizable.strings | 8 ++ .../MemoryConnectionViewController.swift | 2 +- .../MemoryEmbeddingViewController.swift | 10 +-- .../Settings/MemoryFormViewController.swift | 68 ++++++++++++++++- .../MemoryLocalAssetsViewController.swift | 2 +- .../BotMemoryServiceViewController.swift | 2 +- .../Sheets/MemoryAdvancedViewController.swift | 4 +- scripts/l10n-swift.test.ts | 42 +++++++++++ scripts/l10n-swift.ts | 75 +++++++++++++++++++ scripts/l10n.ts | 4 + 12 files changed, 207 insertions(+), 13 deletions(-) create mode 100644 scripts/l10n-swift.test.ts create mode 100644 scripts/l10n-swift.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 24d9159a..d8afeb32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Sparkle update. [desktop/CHANGELOG.md](desktop/CHANGELOG.md) retains legacy desk ## [Unreleased] +- Native memory localization checks now recognize form-helper labels and explicit finite error/action keys while still reporting unused translations. - Fresh Beans accounts use `beans-v2`, isolated v2 homes and ports 4874/4875, mandatory protocol-5/format capability, versioned backup phrases and pairing links; incompatible old storage and phrases are rejected without migration or reset. - New releases use Beans-only asset/package names and retain the existing Ed25519 anchor and immutable historical manifests. Update eligibility requires fresh-format relay health and supported protocol floors before Runner replacement. - Production Grok OAuth is disabled before callback/network access pending a verified Beans contract; existing provider, avatar and memory mechanisms remain unchanged. diff --git a/docs/architecture/memory-ui.md b/docs/architecture/memory-ui.md index d8cd2e34..b16840eb 100644 --- a/docs/architecture/memory-ui.md +++ b/docs/architecture/memory-ui.md @@ -64,3 +64,5 @@ The macOS memory forms resolve their shared helper labels, action titles, consen 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. diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 014f872b..6809228f 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -1287,3 +1287,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/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 24d5c11f..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) 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 9d8c45cf..7f9135d8 100644 --- a/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift +++ b/macos/Sources/Beans/Settings/MemoryLocalAssetsViewController.swift @@ -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 c953945c..6fed9f7e 100644 --- a/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift +++ b/macos/Sources/Beans/Sheets/BotMemoryServiceViewController.swift @@ -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 diff --git a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift index 41335045..321c0e2e 100644 --- a/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift +++ b/macos/Sources/Beans/Sheets/MemoryAdvancedViewController.swift @@ -39,7 +39,7 @@ final class MemoryAdvancedViewController: MemoryFormViewController { 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 { L($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/scripts/l10n-swift.test.ts b/scripts/l10n-swift.test.ts new file mode 100644 index 00000000..3f6c60fd --- /dev/null +++ b/scripts/l10n-swift.test.ts @@ -0,0 +1,42 @@ +import { expect, test } from "bun:test"; +import { memorySwiftKeys } from "./l10n-swift"; +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"]); +}); diff --git a/scripts/l10n-swift.ts b/scripts/l10n-swift.ts new file mode 100644 index 00000000..1da4c950 --- /dev/null +++ b/scripts/l10n-swift.ts @@ -0,0 +1,75 @@ +// 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. +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 (value.startsWith("(") && value.endsWith(")")) 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); + // Strip comments without removing strings, so commented-out calls stay unused. + source = source.replace(/"(?:[^"\\]|\\.)*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : " ".repeat(token.length)); + const call = /\b(L|MemoryActionButton|heading|note|row|text|popup|toggle|confirm|optionRow|addRow|addText|Field)\s*\(/g; + for (const match of source.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 f3ce6c3b..6a763e9d 100644 --- a/scripts/l10n.ts +++ b/scripts/l10n.ts @@ -4,6 +4,7 @@ // `--merge …` adds `{ "English": "中文" }` files to the tables first. import { Glob } from "bun" +import { memorySwiftKeys } from "./l10n-swift" import { join } from "node:path" const ROOT = join(import.meta.dir, "..") @@ -130,6 +131,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 Bun.file(join(ROOT, "macos/Sources/Beans", path)).text(), 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")) From 923126c010f7cef9a4f05a50d6f05dab62eefa99 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:24:45 -0300 Subject: [PATCH 05/15] fix(l10n): distinguish Swift labels from source samples --- scripts/l10n-swift.test.ts | 14 +++++++++++ scripts/l10n-swift.ts | 51 +++++++++++++++++++++++++++++++++++--- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/scripts/l10n-swift.test.ts b/scripts/l10n-swift.test.ts index 3f6c60fd..fb21b478 100644 --- a/scripts/l10n-swift.test.ts +++ b/scripts/l10n-swift.test.ts @@ -40,3 +40,17 @@ 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 index 1da4c950..43bcdf7c 100644 --- a/scripts/l10n-swift.ts +++ b/scripts/l10n-swift.ts @@ -1,5 +1,48 @@ // 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++) { @@ -16,7 +59,7 @@ function parts(source: string, delimiter: string): string[] { } function literals(expression: string): string[] { const value = expression.trim(); - if (value.startsWith("(") && value.endsWith(")")) return literals(value.slice(1, -1)); + 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))]; @@ -42,10 +85,10 @@ export function memorySwiftKeys(source: string, path: string): Set { "Settings/MemoryBotSetupViewController.swift", "Settings/MemorySettingsViewController.swift", "Sheets/MemoryAdvancedViewController.swift", "Sheets/BotMemoryServiceViewController.swift", ]).has(path); - // Strip comments without removing strings, so commented-out calls stay unused. - source = source.replace(/"(?:[^"\\]|\\.)*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : " ".repeat(token.length)); + 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 source.matchAll(call)) { + for (const match of parsed.code.matchAll(call)) { const name = match[1]!; if (name !== "MemoryActionButton" && !memoryForm) continue; const start = match.index! + match[0].length; From 21da450256f9f10161ae9310e570a63fafcde5ff Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 18:01:25 -0300 Subject: [PATCH 06/15] fix(l10n): audit finite client labels and remove obsolete translations --- CHANGELOG.md | 2 +- desktop/src/l10n/zh.ts | 8 +++++--- docs/architecture/languages.md | 2 ++ .../zh-Hans.lproj/Localizable.strings | 1 - mobile/app/settings/diagnostics.tsx | 20 +++++++++++++++++-- mobile/src/ui/ChatsScreen.tsx | 4 ++-- scripts/l10n-lookups.test.ts | 13 ++++++++++++ scripts/l10n-lookups.ts | 20 +++++++++++++++++++ scripts/l10n.ts | 5 +++++ 9 files changed, 66 insertions(+), 9 deletions(-) create mode 100644 scripts/l10n-lookups.test.ts create mode 100644 scripts/l10n-lookups.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d8afeb32..5ac63f82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ Sparkle update. [desktop/CHANGELOG.md](desktop/CHANGELOG.md) retains legacy desk ## [Unreleased] -- Native memory localization checks now recognize form-helper labels and explicit finite error/action keys while still reporting unused translations. +- Localization checks now recognize native memory form-helper labels and finite desktop memory lookups. Phone search and diagnostics expose render-time translation keys, and obsolete search/provider/input translations are removed. - Fresh Beans accounts use `beans-v2`, isolated v2 homes and ports 4874/4875, mandatory protocol-5/format capability, versioned backup phrases and pairing links; incompatible old storage and phrases are rejected without migration or reset. - New releases use Beans-only asset/package names and retain the existing Ed25519 anchor and immutable historical manifests. Update eligibility requires fresh-format relay health and supported protocol floors before Runner replacement. - Production Grok OAuth is disabled before callback/network access pending a verified Beans contract; existing provider, avatar and memory mechanisms remain unchanged. diff --git a/desktop/src/l10n/zh.ts b/desktop/src/l10n/zh.ts index 2de70de2..f1ca1e73 100644 --- a/desktop/src/l10n/zh.ts +++ b/desktop/src/l10n/zh.ts @@ -343,7 +343,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": "抹除 移除 清除 中继 数据 身份 删除账户", @@ -697,7 +696,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": "正在搜索文件", @@ -851,7 +849,6 @@ export const zh: Record = { "Turn %@ off": "关闭 %@", "Turn %@ on": "开启 %@", "Type": "类型", - "Type your answer": "输入你的回答", "unassigned": "未分配", "Undo": "撤销", "Unknown Device": "未知设备", @@ -1105,6 +1102,11 @@ export const zh: Record = { "Deletion pending—not verified erased": "删除待处理,尚未验证已清除", "Deliveries": "投递", "Stored": "已存储", + "Queued, not stored": "已排队,尚未存储", + "Submitted, not stored": "已提交,尚未存储", + "Processing, not stored": "处理中,尚未存储", + "Failed, not stored": "失败,尚未存储", + "Delivery unknown, not confirmed stored": "投递状态未知,未确认存储", "Cancel…": "取消…", "Cleanup remains pending. Backups and Lance history may retain data.": "清理仍待完成。备份及 Lance 历史可能保留数据。", "Deletion actions are locked until authoritative preferences refresh succeeds.": "删除操作已锁定,直到权威偏好设置刷新成功。", diff --git a/docs/architecture/languages.md b/docs/architecture/languages.md index 8e9f917a..f74f8967 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. - **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. - `bun 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. The audit also recognizes the finite desktop memory status/operation maps when the memory sheet passes their indexed values to `L`; unrelated maps and commented-out consumers do not count. Obsolete entries are removed when their source label is replaced. diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 6809228f..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" = "正在搜索文件"; 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/ui/ChatsScreen.tsx b/mobile/src/ui/ChatsScreen.tsx index 96ab5905..8d55bba1 100644 --- a/mobile/src/ui/ChatsScreen.tsx +++ b/mobile/src/ui/ChatsScreen.tsx @@ -399,7 +399,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" }]}> @@ -408,7 +408,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-lookups.test.ts b/scripts/l10n-lookups.test.ts new file mode 100644 index 00000000..7c5c1389 --- /dev/null +++ b/scripts/l10n-lookups.test.ts @@ -0,0 +1,13 @@ +import { expect, test } from 'bun:test'; +import { memoryLookupKeys } from './l10n-lookups'; +const model = 'export const MEMORY_OPERATION_LABELS: Record = { queued: "Queued", completed: "Stored" };'; +test('only a finite map translated by its consumer contributes keys', () => { + expect([...memoryLookupKeys(model, 'L(MEMORY_OPERATION_LABELS[op.state])')]).toEqual(['Queued', 'Stored']); + expect([...memoryLookupKeys(model, 'show(MEMORY_OPERATION_LABELS[op.state])')]).toEqual([]); + expect([...memoryLookupKeys(model + '\nconst unused = "Unused";', 'L(MEMORY_OPERATION_LABELS[op.state])')]).not.toContain('Unused'); +}); +test('comments, source samples and dynamic maps do not satisfy unused translations', () => { + expect([...memoryLookupKeys(model, '// L(MEMORY_OPERATION_LABELS[state])\nconst sample = "L(MEMORY_OPERATION_LABELS[state])";')]).toEqual([]); + expect([...memoryLookupKeys('/* ' + model + ' */', 'L(MEMORY_OPERATION_LABELS[state])')]).toEqual([]); + expect([...memoryLookupKeys(model.replace('"Stored"', 'runtimeLabel'), 'L(MEMORY_OPERATION_LABELS[state])')]).toEqual([]); +}); diff --git a/scripts/l10n-lookups.ts b/scripts/l10n-lookups.ts new file mode 100644 index 00000000..a46913fb --- /dev/null +++ b/scripts/l10n-lookups.ts @@ -0,0 +1,20 @@ +// Finite string maps used by the desktop memory presentation layer. Only a map +// passed through L(map[index]) contributes keys; unrelated constants do not. +function executable(source: string) { + return source.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g, + value => ' '.repeat(value.length)); +} +export function memoryLookupKeys(model: string, view: string): Set { + const used = new Set([...executable(view).matchAll(/\bL\(\s*(MEMORY_(?:STATUS|OPERATION)_LABELS)\s*\[/g)].map(match => match[1])); + const keys = new Set(); + const code = executable(model); + for (const match of model.matchAll(/export const (MEMORY_(?:STATUS|OPERATION)_LABELS): Record<\w+, string> = \{([^}]+)\};/g)) { + if (!used.has(match[1]) || !code.slice(match.index, match.index + 12).startsWith('export const')) continue; + // Reject non-literal or incomplete objects instead of guessing runtime values. + const body = match[2]!; + const entries = [...body.matchAll(/\s*\w+\s*:\s*("(?:[^"\\]|\\.)*")\s*(?:,|$)/g)]; + if (entries.map(entry => entry[0]).join('') !== body) continue; + for (const entry of entries) keys.add(JSON.parse(entry[1]!)); + } + return keys; +} diff --git a/scripts/l10n.ts b/scripts/l10n.ts index 6a763e9d..15a0c2cb 100644 --- a/scripts/l10n.ts +++ b/scripts/l10n.ts @@ -5,6 +5,7 @@ import { Glob } from "bun" import { memorySwiftKeys } from "./l10n-swift" +import { memoryLookupKeys } from "./l10n-lookups" import { join } from "node:path" const ROOT = join(import.meta.dir, "..") @@ -136,6 +137,10 @@ for await (const path of scan(join(ROOT, "macos/Sources/Beans"), "**/*.swift")) } 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")) +for (const key of memoryLookupKeys( + await Bun.file(join(ROOT, "desktop/src/model/memoryService.ts")).text(), + await Bun.file(join(ROOT, "desktop/src/ui/sheets/memoryService.tsx")).text(), +)) desktopKeys.set(key, "src/ui/sheets/memoryService.tsx") const mac = await readMacTable() const phone = await readPhoneTable() From 20c7959103aa68e1ed25b661bbafba4190976b1b Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:04:58 -0300 Subject: [PATCH 07/15] test: isolate storage fixture admission parents (cherry picked from commit d27fe62dcf1ee1da0a5cbb4e5fa16441c9eaae67) --- crates/cli/src/app.rs | 1 + crates/cli/src/catalog.rs | 2 ++ crates/cli/src/config.rs | 25 +++++++++++++++++++++ crates/cli/src/files.rs | 1 + crates/cli/src/identity.rs | 2 ++ crates/cli/src/marketplace.rs | 3 +++ crates/cli/src/memory_service/setup.rs | 1 + crates/cli/src/pairing.rs | 1 + crates/cli/src/plugins/mcp.rs | 1 + crates/cli/src/plugins/mcp_json.rs | 1 + crates/cli/src/plugins/mod.rs | 1 + crates/cli/src/plugins/review.rs | 1 + crates/cli/src/provider_auth/tests.rs | 1 + crates/cli/src/providers.rs | 1 + crates/cli/src/push.rs | 1 + crates/cli/src/requests.rs | 2 ++ crates/cli/src/routines.rs | 1 + crates/cli/src/runtime.rs | 1 + crates/cli/src/scripts.rs | 1 + crates/cli/src/serve.rs | 2 +- crates/cli/src/skill_discovery_test.rs | 1 + crates/cli/src/skill_library_test.rs | 1 + crates/cli/src/turns.rs | 1 + crates/cli/src/update_control.rs | 1 + crates/cli/tests/api_fields.rs | 2 +- crates/cli/tests/appearance.rs | 2 +- crates/cli/tests/device_storage.rs | 2 +- crates/cli/tests/local_search.rs | 2 +- crates/cli/tests/memory_dispatch.rs | 2 +- crates/cli/tests/memory_foundation.rs | 2 +- crates/cli/tests/policy_history_baseline.rs | 2 +- crates/cli/tests/provider_settings.rs | 2 +- crates/cli/tests/serve_ready.rs | 6 +++-- 33 files changed, 65 insertions(+), 11 deletions(-) diff --git a/crates/cli/src/app.rs b/crates/cli/src/app.rs index 27c86eac..cdb757a2 100644 --- a/crates/cli/src/app.rs +++ b/crates/cli/src/app.rs @@ -2202,6 +2202,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-app-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); ScratchApp(app, home) } diff --git a/crates/cli/src/catalog.rs b/crates/cli/src/catalog.rs index cfa448ee..c1a2cba3 100644 --- a/crates/cli/src/catalog.rs +++ b/crates/cli/src/catalog.rs @@ -170,6 +170,7 @@ mod tests { #[test] fn cache_rejects_foreign_origin_and_invalid_content() { let home = std::env::temp_dir().join(format!("beans-catalog-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let config = Config { home: home.clone(), port: 0 }; let mut later: Value = serde_json::from_str(beans_models::BUNDLED).unwrap(); later["updated"] = Value::from("2999-01-01T00:00:00Z"); @@ -219,6 +220,7 @@ mod tests { } }); let home = std::env::temp_dir().join(format!("beans-catalog-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); app.settings.lock().unwrap().relay_url = Some(base.clone()); enable(&app); diff --git a/crates/cli/src/config.rs b/crates/cli/src/config.rs index 7b4b4f98..2dac5b9e 100644 --- a/crates/cli/src/config.rs +++ b/crates/cli/src/config.rs @@ -721,6 +721,31 @@ pub fn now_unix() -> i64 { mod format_tests { use super::*; + #[test] + #[cfg(unix)] + fn missing_fixture_homes_require_independent_existing_parents() { + let root = tempfile::tempdir().unwrap(); + let first = root.path().join("first"); + let second = root.path().join("second"); + // Missing siblings contend on the same parent, even though their names differ. + // Reproduce this only inside an owned root, never against the OS temp directory. + let held = StorageAdmission::acquire_creation(&first).unwrap(); + assert!(StorageAdmission::acquire_creation(&second).is_err()); + assert!(!first.exists() && !second.exists()); + drop(held); + + std::fs::create_dir(&first).unwrap(); + std::fs::create_dir(&second).unwrap(); + let held = StorageAdmission::acquire_creation(&first.join("home")).unwrap(); + let independent = Config { home: second.join("home"), port: 0 }; + independent.ensure_home().unwrap(); + assert!(!first.join("home").exists()); + assert!(independent.home.join("format.json").is_file()); + // The original creation exclusion still rejects the same fixture's startup. + assert!(Config { home: first.join("home"), port: 0 }.ensure_home().is_err()); + drop(held); + } + #[test] #[cfg(unix)] fn a_private_write_is_private_before_its_first_byte() { diff --git a/crates/cli/src/files.rs b/crates/cli/src/files.rs index a3f753d8..04d6b2c6 100644 --- a/crates/cli/src/files.rs +++ b/crates/cli/src/files.rs @@ -337,6 +337,7 @@ mod tests { fn attachment_image_uses_decoded_type_and_size_bounds() { use base64::Engine; let home = std::env::temp_dir().join(format!("beans-files-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); let image = image::DynamicImage::ImageRgb8(image::ImageBuffer::from_fn(2600, 100, |x, y| image::Rgb([(x % 256) as u8, (y % 256) as u8, 60]))); let mut png = Vec::new(); diff --git a/crates/cli/src/identity.rs b/crates/cli/src/identity.rs index e8c9af95..43cc9243 100644 --- a/crates/cli/src/identity.rs +++ b/crates/cli/src/identity.rs @@ -142,6 +142,7 @@ mod publication_tests { use axum::{routing::{get, post}, Json, Router}; for transition in ["none", "forget", "create"] { let home = std::env::temp_dir().join(format!("beans-restore-fence-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); let identity = Identity::generate(); let sealed = crate::crypto::seal_json(&identity.content_pubkey(), &keys::KeyRecord { @@ -191,6 +192,7 @@ mod publication_tests { #[test] fn create_waits_for_reset_publication_boundary() { let home = std::env::temp_dir().join(format!("beans-create-fence-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); create(&app, Some("Synthetic A".into())).unwrap(); let guard = app.plugin_lifecycle.lock(); diff --git a/crates/cli/src/marketplace.rs b/crates/cli/src/marketplace.rs index c6951add..89bd2053 100644 --- a/crates/cli/src/marketplace.rs +++ b/crates/cli/src/marketplace.rs @@ -477,6 +477,7 @@ mod tests { #[test] fn cache_is_bound_to_feed_and_only_newer_indexes_win() { let home = std::env::temp_dir().join(format!("beans-marketplace-cache-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let config = Config { home: home.clone(), port: 0 }; config.ensure_home().unwrap(); let mut cached: Value = serde_json::from_str(BUNDLED_INDEX).unwrap(); @@ -504,6 +505,7 @@ mod tests { #[test] fn newer_index_replaces_old_entries_and_older_one_cannot_downgrade() { let home = std::env::temp_dir().join(format!("beans-marketplace-version-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); let mut newer: Value = serde_json::from_str(BUNDLED_INDEX).unwrap(); newer["updated"] = Value::from("2999-01-01T00:00:00Z"); @@ -540,6 +542,7 @@ mod tests { #[tokio::test] async fn a_bot_added_from_a_template_starts_with_paused_routines_and_a_greeting() { let home = std::env::temp_dir().join(format!("beans-marketplace-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); crate::identity::create(&app, Some("Workbench".into())).unwrap(); let runner_id = app.this_device_id().unwrap(); diff --git a/crates/cli/src/memory_service/setup.rs b/crates/cli/src/memory_service/setup.rs index f68eb1b4..445de976 100644 --- a/crates/cli/src/memory_service/setup.rs +++ b/crates/cli/src/memory_service/setup.rs @@ -389,6 +389,7 @@ mod authority_tests { #[tokio::test] async fn revocation_before_publication_and_paired_positive() { let home=std::env::temp_dir().join(format!("beans-setup-authority-{}",uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app=App::load(crate::config::Config{home:home.clone(),port:0}).unwrap(); crate::identity::create(&app,Some("Fixture Runner".into())).unwrap(); let actor=crate::keys::Machine::generate().pubkey(); diff --git a/crates/cli/src/pairing.rs b/crates/cli/src/pairing.rs index dd29abd4..b3f9980a 100644 --- a/crates/cli/src/pairing.rs +++ b/crates/cli/src/pairing.rs @@ -334,6 +334,7 @@ mod publication_tests { use axum::{routing::{get, post}, Json, Router}; for transition in ["none", "forget", "create"] { let home = std::env::temp_dir().join(format!("beans-join-fence-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); let identity = crate::keys::Identity::generate(); let ephemeral = crypto_box::SecretKey::generate(&mut rand::rngs::OsRng); diff --git a/crates/cli/src/plugins/mcp.rs b/crates/cli/src/plugins/mcp.rs index 318b219b..11d65d06 100644 --- a/crates/cli/src/plugins/mcp.rs +++ b/crates/cli/src/plugins/mcp.rs @@ -2747,6 +2747,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-mcp-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); ScratchApp(app, home) } diff --git a/crates/cli/src/plugins/mcp_json.rs b/crates/cli/src/plugins/mcp_json.rs index 49c79423..57c876bb 100644 --- a/crates/cli/src/plugins/mcp_json.rs +++ b/crates/cli/src/plugins/mcp_json.rs @@ -1661,6 +1661,7 @@ mod tests { #[test] fn a_tool_is_hidden_and_shown_in_the_entrys_tool_exposure() { let home = std::env::temp_dir().join(format!("beans-mcp-hide-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let config = crate::config::Config { home: home.clone(), port: 0 }; config.ensure_home().unwrap(); std::fs::write(home.join("mcp.json"), r#"{"mcpServers": {"docs": {"command": "x", "toolExposure": {"delete_*": "hidden"}}}}"#).unwrap(); diff --git a/crates/cli/src/plugins/mod.rs b/crates/cli/src/plugins/mod.rs index ff0b3305..6a0c6a06 100644 --- a/crates/cli/src/plugins/mod.rs +++ b/crates/cli/src/plugins/mod.rs @@ -989,6 +989,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-plugins-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); ScratchApp(app, home) } diff --git a/crates/cli/src/plugins/review.rs b/crates/cli/src/plugins/review.rs index bf031488..f4cbc4f0 100644 --- a/crates/cli/src/plugins/review.rs +++ b/crates/cli/src/plugins/review.rs @@ -436,6 +436,7 @@ mod tests { use crate::model::{CommandRun, Device}; let home = std::env::temp_dir().join(format!("beans-review-request-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); app.state.lock().unwrap().devices.push(Device { id: "runner".into(), name: "MacBook Air".into(), model: String::new(), os: "macos".into(), os_version: String::new(), diff --git a/crates/cli/src/provider_auth/tests.rs b/crates/cli/src/provider_auth/tests.rs index 2ca69ab9..38713a36 100644 --- a/crates/cli/src/provider_auth/tests.rs +++ b/crates/cli/src/provider_auth/tests.rs @@ -93,6 +93,7 @@ impl Drop for ScratchApp { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-provider-auth-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); ScratchApp(App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(), home) } diff --git a/crates/cli/src/providers.rs b/crates/cli/src/providers.rs index 1372dc06..eb96ab37 100644 --- a/crates/cli/src/providers.rs +++ b/crates/cli/src/providers.rs @@ -481,6 +481,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-providers-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); ScratchApp(App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(), home) } diff --git a/crates/cli/src/push.rs b/crates/cli/src/push.rs index 3bbeefd1..ce913488 100644 --- a/crates/cli/src/push.rs +++ b/crates/cli/src/push.rs @@ -193,6 +193,7 @@ mod tests { use crate::{config::Config, keys::MachineFile}; let home = std::env::temp_dir().join(format!("beans-push-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); *app.machine.lock().unwrap() = Some(MachineFile { format: crate::config::Format::BeansV2, machine_secret: crate::keys::b64(&crate::keys::random_32()), identity_pubkey: "identity".into(), content_pubkey: "content".into(), account_dek: crate::keys::b64(dek), name: "Runner".into(), diff --git a/crates/cli/src/requests.rs b/crates/cli/src/requests.rs index 6cc18353..80a519f7 100644 --- a/crates/cli/src/requests.rs +++ b/crates/cli/src/requests.rs @@ -178,6 +178,7 @@ fn signed_library_compare_is_readonly_and_root_bounded() { let runtime = tokio::runtime::Builder::new_current_thread().enable_all().max_blocking_threads(1).build().unwrap(); runtime.block_on(async { let home = std::env::temp_dir().join(format!("beans-library-compare-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let _cleanup = Cleanup(home.clone()); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); crate::identity::create(&app, Some("Synthetic Runner".into())).unwrap(); @@ -289,6 +290,7 @@ mod custom_provider_tests { async fn phone_request_executes_catalog_http_only_on_selected_runner() { use std::io::{Read, Write}; let home = std::env::temp_dir().join(format!("beans-guided-origin-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); crate::identity::create(&app, Some("Fixture Runner".into())).unwrap(); let runner = app.this_device_id().unwrap(); diff --git a/crates/cli/src/routines.rs b/crates/cli/src/routines.rs index 586c76d9..85071c7f 100644 --- a/crates/cli/src/routines.rs +++ b/crates/cli/src/routines.rs @@ -586,6 +586,7 @@ mod tests { /// `b1` (Chef) assigned to it. fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-routines-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); crate::identity::create(&app, Some("Workbench".into())).unwrap(); let runner_id = app.this_device_id().unwrap(); diff --git a/crates/cli/src/runtime.rs b/crates/cli/src/runtime.rs index 123295d1..2a9f5e96 100644 --- a/crates/cli/src/runtime.rs +++ b/crates/cli/src/runtime.rs @@ -732,6 +732,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-runtime-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); ScratchApp(app, home) } diff --git a/crates/cli/src/scripts.rs b/crates/cli/src/scripts.rs index a3b1f880..ecc52651 100644 --- a/crates/cli/src/scripts.rs +++ b/crates/cli/src/scripts.rs @@ -140,6 +140,7 @@ mod tests { #[tokio::test] async fn models_ask_checks_its_arguments_and_its_provider() { let home = std::env::temp_dir().join(format!("beans-scripts-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); assert!(ModelsAsk::new(&app, "chat", "unknown").is_none(), "a provider with no small model has no models.ask()"); let ask = ModelsAsk::new(&app, "chat", "deepseek").unwrap(); diff --git a/crates/cli/src/serve.rs b/crates/cli/src/serve.rs index 0feec28c..f9779b27 100644 --- a/crates/cli/src/serve.rs +++ b/crates/cli/src/serve.rs @@ -310,7 +310,7 @@ mod tests { } fn scratch() -> PathBuf { - std::env::temp_dir().join(format!("beans-serve-drain-{}", uuid::Uuid::new_v4())) + tempfile::tempdir().unwrap().keep() } fn child_command(home: &Path, models_url: &str, drain_ms: u64, port: u16) -> Command { diff --git a/crates/cli/src/skill_discovery_test.rs b/crates/cli/src/skill_discovery_test.rs index 0936c4b2..af4adf94 100644 --- a/crates/cli/src/skill_discovery_test.rs +++ b/crates/cli/src/skill_discovery_test.rs @@ -7,6 +7,7 @@ fn signed_discovery_rechecks_revocation_after_scan() { let runtime = tokio::runtime::Builder::new_current_thread().enable_all().max_blocking_threads(1).build().unwrap(); runtime.block_on(async { let home = std::env::temp_dir().join(format!("beans-discovery-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); let root = home.join("selected"); std::fs::create_dir_all(&root).unwrap(); diff --git a/crates/cli/src/skill_library_test.rs b/crates/cli/src/skill_library_test.rs index 0826b3ed..e304ea7b 100644 --- a/crates/cli/src/skill_library_test.rs +++ b/crates/cli/src/skill_library_test.rs @@ -9,6 +9,7 @@ fn signed_library_confirmation_boundary() { let runtime = tokio::runtime::Builder::new_current_thread().enable_all().max_blocking_threads(1).build().unwrap(); runtime.block_on(async { let home = std::env::temp_dir().join(format!("beans-library-consumer-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let _cleanup = Cleanup(home.clone()); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); crate::identity::create(&app, Some("Synthetic Runner".into())).unwrap(); diff --git a/crates/cli/src/turns.rs b/crates/cli/src/turns.rs index f0d171fc..ab781ebd 100644 --- a/crates/cli/src/turns.rs +++ b/crates/cli/src/turns.rs @@ -3210,6 +3210,7 @@ mod tests { fn scratch_app() -> ScratchApp { let home = std::env::temp_dir().join(format!("beans-runtime-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); let app = App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(); ScratchApp(app, home) } diff --git a/crates/cli/src/update_control.rs b/crates/cli/src/update_control.rs index 874ae5c6..db462758 100644 --- a/crates/cli/src/update_control.rs +++ b/crates/cli/src/update_control.rs @@ -263,6 +263,7 @@ mod tests { fn scratch_app() -> (Arc, std::path::PathBuf) { let home = std::env::temp_dir().join(format!("beans-update-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&home).unwrap(); (App::load(crate::config::Config { home: home.clone(), port: 0 }).unwrap(), home) } diff --git a/crates/cli/tests/api_fields.rs b/crates/cli/tests/api_fields.rs index 101f74f4..b97bb90b 100644 --- a/crates/cli/tests/api_fields.rs +++ b/crates/cli/tests/api_fields.rs @@ -31,7 +31,7 @@ struct Snapshot { impl Scratch { fn new(paused: bool) -> Self { let id = uuid::Uuid::new_v4(); - let home = std::env::temp_dir().join(format!("beans-api-fields-{id}")); + let home = tempfile::tempdir().unwrap().keep(); let app = App::load(Config { home: home.clone(), port: 0 }).unwrap(); beans::identity::create(&app, Some("fixture".into())).unwrap(); app.set_paused(paused); diff --git a/crates/cli/tests/appearance.rs b/crates/cli/tests/appearance.rs index a8731e87..5f6f34ca 100644 --- a/crates/cli/tests/appearance.rs +++ b/crates/cli/tests/appearance.rs @@ -11,7 +11,7 @@ impl Drop for Scratch { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } fn setup() -> (Scratch, std::sync::Arc, String) { - let scratch = Scratch(std::env::temp_dir().join(format!("beans-appearance-{}", uuid::Uuid::new_v4()))); + let scratch = Scratch(tempfile::tempdir().unwrap().keep()); let app = scratch.app(); identity::create(&app, Some("Appearance test".into())).unwrap(); let runner = app.this_device_id().unwrap(); diff --git a/crates/cli/tests/device_storage.rs b/crates/cli/tests/device_storage.rs index e3d1931b..d413fbcf 100644 --- a/crates/cli/tests/device_storage.rs +++ b/crates/cli/tests/device_storage.rs @@ -9,7 +9,7 @@ impl Drop for Scratch { #[test] fn device_storage_keeps_only_the_app_view_of_tools() { - let scratch = Scratch(std::env::temp_dir().join(format!("beans-device-storage-{}", uuid::Uuid::new_v4()))); + let scratch = Scratch(tempfile::tempdir().unwrap().keep()); let app = App::load(Config { home: scratch.0.clone(), port: 0 }).unwrap(); app.state.lock().unwrap().chats.push(Chat { meta: ChatMeta { diff --git a/crates/cli/tests/local_search.rs b/crates/cli/tests/local_search.rs index f1d89f73..1fbf2b05 100644 --- a/crates/cli/tests/local_search.rs +++ b/crates/cli/tests/local_search.rs @@ -13,7 +13,7 @@ async fn search(app: &std::sync::Arc, query: &str) -> Value { #[tokio::test] async fn local_search_projects_files_and_survives_reopen_and_deletion() { - let scratch = Scratch(std::env::temp_dir().join(format!("beans-search-{}", uuid::Uuid::new_v4()))); + let scratch = Scratch(tempfile::tempdir().unwrap().keep()); let config = Config { home: scratch.0.clone(), port: 0 }; let app = App::load(config.clone()).unwrap(); identity::create(&app, Some("Search fixture".into())).unwrap(); diff --git a/crates/cli/tests/memory_dispatch.rs b/crates/cli/tests/memory_dispatch.rs index d58113ae..efb55e00 100644 --- a/crates/cli/tests/memory_dispatch.rs +++ b/crates/cli/tests/memory_dispatch.rs @@ -8,7 +8,7 @@ use beans::{app::App,config::Config,memory_service::{types::*,dispatch as d,queu struct Scratch { app:Arc, home:std::path::PathBuf, bot:String } impl Scratch { fn new()->Self{ - let home=std::env::temp_dir().join(format!("beans-memory-dispatch-{}",uuid::Uuid::new_v4())); + let home=tempfile::tempdir().unwrap().keep(); let app=App::load(Config{home:home.clone(),port:0}).unwrap(); beans::identity::create(&app,Some("fixture".into())).unwrap(); let bot=app.state.lock().unwrap().bots[0].id.clone(); diff --git a/crates/cli/tests/memory_foundation.rs b/crates/cli/tests/memory_foundation.rs index dfdc5dac..e8f2c839 100644 --- a/crates/cli/tests/memory_foundation.rs +++ b/crates/cli/tests/memory_foundation.rs @@ -66,7 +66,7 @@ fn recall_is_deduplicated_bounded_and_explicitly_untrusted() { struct Scratch(std::path::PathBuf); impl Scratch { - fn new() -> Self { Self(std::env::temp_dir().join(format!("beans-memory-core-{}",uuid::Uuid::new_v4()))) } + fn new() -> Self { Self(tempfile::tempdir().unwrap().keep()) } fn store(&self) -> beans::local_store::LocalStore { beans::local_store::LocalStore::open(&self.0.join("local.sqlite3")).unwrap() } } impl Drop for Scratch { fn drop(&mut self) { let _=std::fs::remove_dir_all(&self.0); } } diff --git a/crates/cli/tests/policy_history_baseline.rs b/crates/cli/tests/policy_history_baseline.rs index e222ee38..407cc60a 100644 --- a/crates/cli/tests/policy_history_baseline.rs +++ b/crates/cli/tests/policy_history_baseline.rs @@ -13,7 +13,7 @@ use tokio_util::sync::CancellationToken; struct Scratch(PathBuf); impl Scratch { fn new() -> Self { - Self(std::env::temp_dir().join(format!("beans-policy-history-{}", uuid::Uuid::new_v4()))) + Self(tempfile::tempdir().unwrap().keep()) } fn load(&self) -> Arc { App::load(Config { home: self.0.clone(), port: 0 }).unwrap() diff --git a/crates/cli/tests/provider_settings.rs b/crates/cli/tests/provider_settings.rs index 67b41bd8..dbf419df 100644 --- a/crates/cli/tests/provider_settings.rs +++ b/crates/cli/tests/provider_settings.rs @@ -11,7 +11,7 @@ impl Drop for Home { #[tokio::test] async fn provider_settings_reads_only_the_requested_api_key() { - let home = Home(std::env::temp_dir().join(format!("beans-provider-settings-{}", uuid::Uuid::new_v4()))); + let home = Home(tempfile::tempdir().unwrap().keep()); let app = App::load(Config { home: home.0.clone(), port: 0 }).unwrap(); let kinds = ["deepseek", "anthropic", "opencode", "opencode-go"]; diff --git a/crates/cli/tests/serve_ready.rs b/crates/cli/tests/serve_ready.rs index 590de411..646e5445 100644 --- a/crates/cli/tests/serve_ready.rs +++ b/crates/cli/tests/serve_ready.rs @@ -38,11 +38,13 @@ async fn prepare_cli() { // cold measurement stays visible and precedes, rather than extends, readiness deadlines. eprintln!("CLI executable preflight (outside readiness deadline): {elapsed:?}"); } -struct Home(std::path::PathBuf); +struct Home(std::path::PathBuf, tempfile::TempDir); impl Home { fn new() -> Self { - Self(std::env::temp_dir().join(format!("beans-ready-{}", uuid::Uuid::new_v4()))) + // Keep the home absent for creation/help assertions, beneath an owned parent. + let parent = tempfile::tempdir().unwrap(); + Self(parent.path().join("home"), parent) } fn serve(&self, port: u16) -> Command { From 306e60649b88a135dd78817f6f12ec2b114aa17f Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Wed, 14 Oct 2026 18:11:45 -0300 Subject: [PATCH 08/15] fix(desktop): run Solid consumers in Chromium Keep Bun unit checks and compile browser consumers through Vite. Provision pinned Chromium for the desktop job. Refs #349 (cherry picked from commit 73e8480dbe56eab4593ebe97c40d31325d008190) --- .github/workflows/test.yml | 2 + bun.lock | 25 ++++- desktop/CHANGELOG.md | 1 + desktop/package.json | 3 +- .../{cards.test.tsx => cards.browser.tsx} | 0 ...composer.test.tsx => composer.browser.tsx} | 0 .../{motion.test.tsx => motion.browser.tsx} | 0 .../{overlay.test.tsx => overlay.browser.tsx} | 0 .../{palette.test.tsx => palette.browser.tsx} | 0 ...ry.test.tsx => skillDiscovery.browser.tsx} | 0 ...rary.test.tsx => skillLibrary.browser.tsx} | 0 desktop/test-browser.ts | 103 ++++++++++++++++++ desktop/tsconfig.json | 2 +- docs/architecture/desktop-app.md | 2 + 14 files changed, 131 insertions(+), 7 deletions(-) rename desktop/src/ui/chat/{cards.test.tsx => cards.browser.tsx} (100%) rename desktop/src/ui/chat/{composer.test.tsx => composer.browser.tsx} (100%) rename desktop/src/ui/{motion.test.tsx => motion.browser.tsx} (100%) rename desktop/src/ui/{overlay.test.tsx => overlay.browser.tsx} (100%) rename desktop/src/ui/{palette.test.tsx => palette.browser.tsx} (100%) rename desktop/src/ui/sheets/{skillDiscovery.test.tsx => skillDiscovery.browser.tsx} (100%) rename desktop/src/ui/sheets/{skillLibrary.test.tsx => skillLibrary.browser.tsx} (100%) create mode 100644 desktop/test-browser.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 520b2670..09f32efe 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -153,6 +153,8 @@ jobs: # src/mygo.ts, the page's bindings to the Go side, is generated and never committed. - run: bun run generate - run: bun run typecheck + - name: Install Chromium for desktop browser checks + run: bun ./node_modules/playwright/cli.js install --with-deps chromium - run: bun run test - run: go test ./... diff --git a/bun.lock b/bun.lock index 8b161c7b..63aa8235 100644 --- a/bun.lock +++ b/bun.lock @@ -24,6 +24,7 @@ "@solidjs/vite-plugin": "3.0.0-next.35", "@types/bun": "latest", "mygo-cli": "0.1.22", + "playwright": "1.59.1", "typescript": "^7", "vite": "^8", }, @@ -706,6 +707,8 @@ "baseline-browser-mapping": ["baseline-browser-mapping@2.11.24", "http://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.24.tgz", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-hYrgxie335U08WqICoGqKRzV1HFXv6zdxwJE4ekCb80CM9a0SVVsN4QPwT67RraRo+9h8IATk6uxHJw7QSkdOg=="], + "beans-desktop": ["beans-desktop@workspace:desktop"], + "browserslist": ["browserslist@4.29.0", "http://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz", { "dependencies": { "baseline-browser-mapping": "^2.11.23", "caniuse-lite": "^1.0.30001810", "electron-to-chromium": "^1.5.427", "node-releases": "^2.0.55", "update-browserslist-db": "^1.3.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA=="], "bun-types": ["bun-types@1.4.2", "http://registry.npmjs.org/bun-types/-/bun-types-1.4.2.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="], @@ -822,7 +825,7 @@ "framer-motion": ["framer-motion@13.4.0", "http://registry.npmjs.org/framer-motion/-/framer-motion-13.4.0.tgz", { "dependencies": { "motion-dom": "^13.3.0", "motion-utils": "^13.3.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-HCpqKM9BTu6UYKtj0u6J1QNxojnnirNcghcSDZ+SkpiL3myxvtsgXPS3ZGEELC2eSma7YiA937rAEXtRyydSXQ=="], - "fsevents": ["fsevents@2.3.3", "http://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + "fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], "fumadocs-core": ["fumadocs-core@16.15.11", "http://registry.npmjs.org/fumadocs-core/-/fumadocs-core-16.15.11.tgz", { "dependencies": { "@fumari/image-size": "^0.1.1", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "mdast-util-mdx": "^3.0.0", "mdast-util-to-markdown": "^2.1.2", "npm-to-yarn": "3.2.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^4.4.3", "tinyglobby": "^0.2.17", "unified": "^11.0.5", "unist-util-visit": "^5.1.0", "vfile": "^6.0.3", "yaml": "^2.9.0", "zbsearch": "^4.0.0" }, "peerDependencies": { "@mdx-js/mdx": "*", "@mixedbread/sdk": "0.x.x", "@modelcontextprotocol/server": "2.x.x", "@orama/core": "1.x.x", "@oramacloud/client": "2.x.x", "@tanstack/react-router": "1.x.x", "@types/estree-jsx": "*", "@types/hast": "*", "@types/mdast": "*", "@types/react": "*", "algoliasearch": "5.x.x", "flexsearch": "*", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x || 8.x.x", "waku": "*", "zod": "4.x.x" }, "optionalPeers": ["@mdx-js/mdx", "@mixedbread/sdk", "@modelcontextprotocol/server", "@orama/core", "@oramacloud/client", "@tanstack/react-router", "@types/estree-jsx", "@types/hast", "@types/mdast", "@types/react", "algoliasearch", "flexsearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku", "zod"] }, "sha512-7pfXOorTguSZz39d4s9KZhTJxlwUJ0mpzwTbkKDQuwfwPyagvFnTCJS3+92VXTu3HW10tShE2o8U2U0DANsNww=="], @@ -936,8 +939,6 @@ "longest-streak": ["longest-streak@3.1.0", "http://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], - "beans-desktop": ["beans-desktop@workspace:desktop"], - "lru-cache": ["lru-cache@5.1.1", "http://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "lucide": ["lucide@1.48.0", "http://registry.npmjs.org/lucide/-/lucide-1.48.0.tgz", {}, "sha512-8FglIlGkcIItJjJfLUiqAufUCdbtnTOsdG02/fxXd4oIt+NrcrEVH8t0ZcKAfawxHckorO5qJ9XDfnJbdf0TOg=="], @@ -1102,6 +1103,10 @@ "picomatch": ["picomatch@4.0.7", "http://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + "playwright": ["playwright@1.59.1", "", { "dependencies": { "playwright-core": "1.59.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw=="], + + "playwright-core": ["playwright-core@1.59.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg=="], + "postcss": ["postcss@8.5.28", "http://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], "postcss-selector-parser": ["postcss-selector-parser@6.0.10", "http://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w=="], @@ -1350,6 +1355,10 @@ "@tanstack/start-plugin-core/srvx": ["srvx@0.11.22", "http://registry.npmjs.org/srvx/-/srvx-0.11.22.tgz", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-LqZxxBDMKuMAZzFzJnDCkFOrs9MZQZr0LvHiO/SuSZVdQaXD7xQ5UWTUxheJrQPve1qk9MG2B/yttUvJxw8egQ=="], + "beans-desktop/@beans/blobatar": ["@beans/blobatar@file:packages/beans-blobatar", { "peerDependencies": { "react": ">=18", "react-native-reanimated": ">=4", "react-native-svg": ">=13", "react-native-worklets": ">=0.5" }, "optionalPeers": ["react", "react-native-reanimated", "react-native-svg", "react-native-worklets"] }], + + "beans-desktop/@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="], + "bun-types/@types/node": ["@types/node@26.5.1", "http://registry.npmjs.org/@types/node/-/node-26.5.1.tgz", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g=="], "fumadocs-ui/cn": ["cn@0.2.6", "http://registry.npmjs.org/cn/-/cn-0.2.6.tgz", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ=="], @@ -1362,14 +1371,14 @@ "js-yaml/argparse": ["argparse@2.0.1", "http://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], - "beans-desktop/@beans/blobatar": ["@beans/blobatar@file:packages/beans-blobatar", { "peerDependencies": { "react": ">=18", "react-native-svg": ">=13" }, "optionalPeers": ["react", "react-native-svg"] }], - "oxc-parser/@oxc-project/types": ["@oxc-project/types@0.120.0", "http://registry.npmjs.org/@oxc-project/types/-/types-0.120.0.tgz", {}, "sha512-k1YNu55DuvAip/MGE1FTsIuU3FUCn6v/ujG9V7Nq5Df/kX2CWb13hhwD0lmJGMGqE+bE1MXvv9SZVnMzEXlWcg=="], "parse-entities/@types/unist": ["@types/unist@2.0.11", "http://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], "parse5/entities": ["entities@6.0.1", "http://registry.npmjs.org/entities/-/entities-6.0.1.tgz", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], + "vite/fsevents": ["fsevents@2.3.3", "http://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + "web/typescript": ["typescript@6.0.3", "http://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], "@neodrag/solid/solid-js/seroval": ["seroval@1.5.6", "http://registry.npmjs.org/seroval/-/seroval-1.5.6.tgz", {}, "sha512-rVQVWjjSvlINzaQPZH5JFqsqEsIWdTxY3iJZCnTL/5gQbXIRooVZKI60tVCkOVfzcRPejboxO2t0P89dg5mQaA=="], @@ -1434,6 +1443,12 @@ "@tanstack/start-plugin-core/@tanstack/router-generator/magic-string": ["magic-string@0.30.21", "http://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "beans-desktop/@types/bun/bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="], + "bun-types/@types/node/undici-types": ["undici-types@8.9.0", "http://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "beans-desktop/@types/bun/bun-types/@types/node": ["@types/node@26.5.1", "http://registry.npmjs.org/@types/node/-/node-26.5.1.tgz", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g=="], + + "beans-desktop/@types/bun/bun-types/undici-types": ["undici-types@8.9.0", "http://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], } } diff --git a/desktop/CHANGELOG.md b/desktop/CHANGELOG.md index fe8b1535..27e89093 100644 --- a/desktop/CHANGELOG.md +++ b/desktop/CHANGELOG.md @@ -6,6 +6,7 @@ and the update window shows it. ## [Unreleased] +- Desktop tests run mounted browser consumers through the Solid Vite compiler and pinned Chromium, alongside the Bun unit checks. - `BEANS_NATIVE=1` opens a native sidebar, transcript and multiline composer alongside the full client. Awaited text/file/reply sends and file selection are account-fenced; updater installation requires closing the native window. The full client and website preview remain available. - Native reconnect waits for authoritative account admission before showing account data or accepting sends. Outgoing native RPCs bind to the captured socket/account authority. Unsent native drafts veto close, quit and install even without a window; changed-account drafts remain recoverable with explicit save/discard controls. - The native sidebar renders saved Blobatar geometry from the shared generator, with exact uploaded-photo precedence. Native memory uses the existing service/setup contract bundle for consent, masking, deletion fences and one-use approvals; a native connections panel shows masked configuration. The full client remains default while editing and animated parity are completed. diff --git a/desktop/package.json b/desktop/package.json index bc4c7e55..18239c9f 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -10,7 +10,7 @@ "dev:web": "vite", "build:web": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", - "test": "bun test src" + "test": "bun test src && bun run test-browser.ts" }, "dependencies": { "@beans/blobatar": "file:../packages/beans-blobatar", @@ -26,6 +26,7 @@ "@solidjs/vite-plugin": "3.0.0-next.35", "@types/bun": "latest", "mygo-cli": "0.1.22", + "playwright": "1.59.1", "typescript": "^7", "vite": "^8" } diff --git a/desktop/src/ui/chat/cards.test.tsx b/desktop/src/ui/chat/cards.browser.tsx similarity index 100% rename from desktop/src/ui/chat/cards.test.tsx rename to desktop/src/ui/chat/cards.browser.tsx diff --git a/desktop/src/ui/chat/composer.test.tsx b/desktop/src/ui/chat/composer.browser.tsx similarity index 100% rename from desktop/src/ui/chat/composer.test.tsx rename to desktop/src/ui/chat/composer.browser.tsx diff --git a/desktop/src/ui/motion.test.tsx b/desktop/src/ui/motion.browser.tsx similarity index 100% rename from desktop/src/ui/motion.test.tsx rename to desktop/src/ui/motion.browser.tsx diff --git a/desktop/src/ui/overlay.test.tsx b/desktop/src/ui/overlay.browser.tsx similarity index 100% rename from desktop/src/ui/overlay.test.tsx rename to desktop/src/ui/overlay.browser.tsx diff --git a/desktop/src/ui/palette.test.tsx b/desktop/src/ui/palette.browser.tsx similarity index 100% rename from desktop/src/ui/palette.test.tsx rename to desktop/src/ui/palette.browser.tsx diff --git a/desktop/src/ui/sheets/skillDiscovery.test.tsx b/desktop/src/ui/sheets/skillDiscovery.browser.tsx similarity index 100% rename from desktop/src/ui/sheets/skillDiscovery.test.tsx rename to desktop/src/ui/sheets/skillDiscovery.browser.tsx diff --git a/desktop/src/ui/sheets/skillLibrary.test.tsx b/desktop/src/ui/sheets/skillLibrary.browser.tsx similarity index 100% rename from desktop/src/ui/sheets/skillLibrary.test.tsx rename to desktop/src/ui/sheets/skillLibrary.browser.tsx diff --git a/desktop/test-browser.ts b/desktop/test-browser.ts new file mode 100644 index 00000000..de25a639 --- /dev/null +++ b/desktop/test-browser.ts @@ -0,0 +1,103 @@ +import { mkdtemp, mkdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { chromium } from "playwright"; +import type { Browser } from "playwright"; +import { createServer } from "vite"; + +const expected: Record = { + "src/ui/chat/cards.browser.tsx": "checkCommandCardInput", + "src/ui/chat/composer.browser.tsx": "checkComposerSendAck", + "src/ui/motion.browser.tsx": "checkReducedMotion", + "src/ui/overlay.browser.tsx": "checkSheetDialogName", + "src/ui/palette.browser.tsx": "checkSearchResults", + "src/ui/sheets/skillDiscovery.browser.tsx": "checkSkillDiscoveryConsumer", + "src/ui/sheets/skillLibrary.browser.tsx": "checkSkillLibraryConsumer", +}; +const files = [...new Bun.Glob("src/**/*.browser.tsx").scanSync()].sort(); +if (Object.keys(expected).some((file) => !files.includes(file))) throw new Error("Required browser consumer missing"); +const evidence = process.env.BROWSER_EVIDENCE_DIR; +if (evidence) await mkdir(evidence, { recursive: true }); +const cache = await mkdtemp(join(tmpdir(), "beans-browser-")); +const server = await createServer({ + cacheDir: cache, + server: { host: "127.0.0.1", port: 0, strictPort: false, open: false }, + plugins: [{ + name: "browser-consumer-fixture", + configureServer(server) { + server.middlewares.use((request, response, next) => { + if (request.url?.split("?")[0] !== "/__browser_check") return next(); + response.setHeader("Content-Type", "text/html"); + response.end(''); + }); + }, + }], +}); +let browser: Browser | undefined; +let failures = 0; +try { + await server.listen(); + const address = server.httpServer?.address(); + if (!address || typeof address === "string") throw new Error("Browser fixture has no listening port"); + browser = await chromium.launch({ headless: true }); + for (const file of files) { + const settings = file.endsWith("/motion.browser.tsx") ? ["reduce", "no-preference"] as const : ["no-preference"] as const; + for (const reducedMotion of settings) { + const context = await browser.newContext({ reducedMotion, viewport: { width: 1200, height: 900 } }); + try { + const page = await context.newPage(); + page.setDefaultTimeout(30_000); + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.stack ?? error.message)); + page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); }); + const mock = file.includes("/sheets/skill") ? "0" : "1"; + await page.goto(`http://127.0.0.1:${address.port}/__browser_check?mock=${mock}&platform=linux`); + await page.evaluate(async () => { + for (const href of ["/src/ui/theme.css", "/src/ui/components.css", "/src/ui/layout.css"]) { + await new Promise((resolve, reject) => { + const link = document.createElement("link"); + link.rel = "stylesheet"; link.href = href; + link.onload = () => resolve(); link.onerror = () => reject(new Error(`Stylesheet failed: ${href}`)); + document.head.append(link); + }); + } + }); + if (file.endsWith("/palette.browser.tsx")) { + // Browser-only state loads in the isolated page, never in the Bun runner. + await page.evaluate(async (path) => { const { store } = await import(path); store.start(); }, "/src/model/store.ts"); + } + const result = page.evaluate(async ({ modulePath, required }) => { + const module = await import(`/${modulePath}`); + const checks = Object.entries(module).filter(([name]) => name.startsWith("check")); + if (!checks.length || checks.some(([, check]) => typeof check !== "function")) throw new Error(`Missing callable checks: ${modulePath}`); + if (required && typeof module[required] !== "function") throw new Error(`Missing required export: ${required}`); + const results: Record = {}; + for (const [name, check] of checks) results[name] = (await (check as () => unknown)()) ?? null; + return results; + }, { modulePath: file, required: expected[file] }); + // Observe the real composer while its asynchronous acknowledgement scenarios run. + if (evidence && file.endsWith("/composer.browser.tsx")) { + const mounted = page.locator("textarea").first().waitFor({ state: "visible" }); + await Promise.race([mounted, result]); + if (await page.locator("textarea").count()) await page.screenshot({ path: join(evidence, "composer-mounted.png") }); + } + const output = await Promise.race([ + result, + new Promise((_, reject) => { const timer = setTimeout(() => reject(new Error(`Consumer deadline: ${file}`)), 30_000); timer.unref(); }), + ]); + if (errors.length) throw new Error(errors.join("\n")); + console.log(JSON.stringify({ file, reducedMotion, status: "pass", result: output })); + } catch (error) { + failures++; + console.error(JSON.stringify({ file, reducedMotion, status: "fail", error: error instanceof Error ? error.stack : String(error) })); + } finally { + await context.close(); + } + } + } + if (failures) throw new Error(`${failures} browser consumer invocation(s) failed`); +} finally { + try { await browser?.close(); } finally { + try { await server.close(); } finally { await rm(cache, { recursive: true, force: true }); } + } +} diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json index e5834fa7..f3de2a88 100644 --- a/desktop/tsconfig.json +++ b/desktop/tsconfig.json @@ -15,5 +15,5 @@ "skipLibCheck": true, "noEmit": true }, - "include": ["src", "vite.config.ts", "mygo.config.ts"] + "include": ["src", "vite.config.ts", "mygo.config.ts", "test-browser.ts"] } diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md index 6e797076..518840de 100644 --- a/docs/architecture/desktop-app.md +++ b/docs/architecture/desktop-app.md @@ -47,6 +47,8 @@ Windows update-control admission queries the opened directory, marker and token - **Development and builds**: `bun run desktop` builds the CLI and runs `mygo dev` (Beans Dev, `app.beans.dev`, with `~/.beans-dev-v2` and port 4875), which reloads the page on a frontend change and rebuilds the app on a Go change; `cd desktop && bun run dev:web` serves the page alone for a browser, where `?mock=1` runs the demo, `?port=4875` selects the matching Dev CLI, and `?platform=windows` or `linux` previews that system's shortcuts and words (Ctrl, Enter). The browser host loads and validates saved/query ports before any WebSocket construction, including early transport initialization and reconnect; invalid values stay offline without rewriting preferences. `bun run desktop:build [platforms]` builds the CLI for each platform into `desktop/resources/-/bin` (static musl builds for Linux, with cargo-zigbuild, as the CLI releases are) and runs `mygo build -platform`; MyGo needs no cgo, so every platform builds from any computer, and a Mac builds Windows and Linux on x86-64 by default. +Desktop `bun run test` runs the Bun unit checks and then every `src/**/*.browser.tsx` consumer through the existing Solid Vite compiler in isolated Playwright Chromium pages. The browser checks keep real DOM events, CSS and media queries; Reduce Motion runs both settings, and the composer exercises acknowledgement, retained draft and account-transition behavior. Run `bun run generate` for the real host bindings and `bun ./node_modules/playwright/cli.js install chromium` to provision the pinned browser locally. The desktop CI job adds `--with-deps` for Linux libraries before the same test command. Missing consumers, non-callable checks, browser launch failures and rejected checks fail the command; contexts, browser, Vite and temporary caches are closed afterward. `BROWSER_EVIDENCE_DIR` optionally records a mounted composer screenshot. + The Go client's websocket to `127.0.0.1:/ws` sends no `Origin`. A browser tab using `dev:web` connects to that same local socket directly, so its CLI must explicitly allow the Vite page's origin: `BEANS_ALLOWED_ORIGINS=http://localhost:5178,http://127.0.0.1:5178`. `bun run desktop` passes that list to the development app's CLI. When starting `beans serve` by hand for a browser tab, set the same variable on that process; a packaged app leaves the browser allowlist unset. The CLI checks exact `Host` and `Origin` before upgrade. Stable/Dev defaults use `.beans-v2` / `4874` and `.beans-dev-v2` / `4875`. Native preferences are `preferences-v2.json`; browser and disconnected website preview use separate `beans-v2` keys, without old preference reads or saved-port migration. The updater’s independent selected-relay health GET sends `Beans-Protocol: 5` and `Beans-Format: beans-v2` and requires fresh format, sufficient release protocol, supported effective account/roster floors >=5 and `memory_config_version: 1`. Missing, malformed, duplicated or unsupported capability evidence fails closed. Drain/admission/install sequencing and provider/memory/avatar mechanisms remain unchanged. From 7b1fdaab7c69e0d27aa5dd5e8c126fd52c1c36ae Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Wed, 14 Oct 2026 20:21:46 -0300 Subject: [PATCH 09/15] test(desktop): isolate note fixture language (cherry picked from commit ec06d158831077673c5db08b4569090edeae754a) --- desktop/native_memory_note_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/desktop/native_memory_note_test.go b/desktop/native_memory_note_test.go index 726573f7..1480d770 100644 --- a/desktop/native_memory_note_test.go +++ b/desktop/native_memory_note_test.go @@ -69,6 +69,9 @@ func TestNativeMemoryNoteMountedConflict(t *testing.T) { n.authority = client.captureAuthority() n.memoryPanel.Open = true n.memoryPanel.Connections = json.RawMessage(`{"connections":[],"embeddings":[]}`) + oldPrefs := prefs + prefs = &prefsStore{value: Preferences{AppLanguage: "en"}} + defer func() { prefs = oldPrefs }() tt := ui.NewTester(n.memoryView, 1000, 1800) if e = tt.Click("MEMORY.md for Fixture"); e != nil { t.Fatal(e) From fb20dda9aaf456f8c6d1780da4458f9fda778c33 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:13:29 -0300 Subject: [PATCH 10/15] test(desktop): bound setup and clean failed browser startup (cherry picked from commit f827c70ccf7e4e3e39fcfe3f9a29c9f35e4776da) --- desktop/test-browser.ts | 120 +++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 56 deletions(-) diff --git a/desktop/test-browser.ts b/desktop/test-browser.ts index de25a639..b652971a 100644 --- a/desktop/test-browser.ts +++ b/desktop/test-browser.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { chromium } from "playwright"; import type { Browser } from "playwright"; import { createServer } from "vite"; +import type { ViteDevServer } from "vite"; const expected: Record = { "src/ui/chat/cards.browser.tsx": "checkCommandCardInput", @@ -19,23 +20,24 @@ if (Object.keys(expected).some((file) => !files.includes(file))) throw new Error const evidence = process.env.BROWSER_EVIDENCE_DIR; if (evidence) await mkdir(evidence, { recursive: true }); const cache = await mkdtemp(join(tmpdir(), "beans-browser-")); -const server = await createServer({ - cacheDir: cache, - server: { host: "127.0.0.1", port: 0, strictPort: false, open: false }, - plugins: [{ - name: "browser-consumer-fixture", - configureServer(server) { - server.middlewares.use((request, response, next) => { - if (request.url?.split("?")[0] !== "/__browser_check") return next(); - response.setHeader("Content-Type", "text/html"); - response.end(''); - }); - }, - }], -}); +let server: ViteDevServer | undefined; let browser: Browser | undefined; let failures = 0; try { + server = await createServer({ + cacheDir: cache, + server: { host: "127.0.0.1", port: 0, strictPort: false, open: false }, + plugins: [{ + name: "browser-consumer-fixture", + configureServer(server) { + server.middlewares.use((request, response, next) => { + if (request.url?.split("?")[0] !== "/__browser_check") return next(); + response.setHeader("Content-Type", "text/html"); + response.end(''); + }); + }, + }], + }); await server.listen(); const address = server.httpServer?.address(); if (!address || typeof address === "string") throw new Error("Browser fixture has no listening port"); @@ -44,53 +46,59 @@ try { const settings = file.endsWith("/motion.browser.tsx") ? ["reduce", "no-preference"] as const : ["no-preference"] as const; for (const reducedMotion of settings) { const context = await browser.newContext({ reducedMotion, viewport: { width: 1200, height: 900 } }); + let timer: ReturnType | undefined; try { - const page = await context.newPage(); - page.setDefaultTimeout(30_000); - const errors: string[] = []; - page.on("pageerror", (error) => errors.push(error.stack ?? error.message)); - page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); }); - const mock = file.includes("/sheets/skill") ? "0" : "1"; - await page.goto(`http://127.0.0.1:${address.port}/__browser_check?mock=${mock}&platform=linux`); - await page.evaluate(async () => { - for (const href of ["/src/ui/theme.css", "/src/ui/components.css", "/src/ui/layout.css"]) { - await new Promise((resolve, reject) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; link.href = href; - link.onload = () => resolve(); link.onerror = () => reject(new Error(`Stylesheet failed: ${href}`)); - document.head.append(link); - }); + const run = async () => { + const page = await context.newPage(); + page.setDefaultTimeout(30_000); + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.stack ?? error.message)); + page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); }); + const mock = file.includes("/sheets/skill") ? "0" : "1"; + await page.goto(`http://127.0.0.1:${address.port}/__browser_check?mock=${mock}&platform=linux`); + await page.evaluate(async () => { + for (const href of ["/src/ui/theme.css", "/src/ui/components.css", "/src/ui/layout.css"]) { + await new Promise((resolve, reject) => { + const link = document.createElement("link"); + link.rel = "stylesheet"; link.href = href; + link.onload = () => resolve(); link.onerror = () => reject(new Error(`Stylesheet failed: ${href}`)); + document.head.append(link); + }); + } + }); + if (file.endsWith("/palette.browser.tsx")) { + // Browser-only state loads in the isolated page, never in the Bun runner. + await page.evaluate(async (path) => { const { store } = await import(path); store.start(); }, "/src/model/store.ts"); } - }); - if (file.endsWith("/palette.browser.tsx")) { - // Browser-only state loads in the isolated page, never in the Bun runner. - await page.evaluate(async (path) => { const { store } = await import(path); store.start(); }, "/src/model/store.ts"); - } - const result = page.evaluate(async ({ modulePath, required }) => { - const module = await import(`/${modulePath}`); - const checks = Object.entries(module).filter(([name]) => name.startsWith("check")); - if (!checks.length || checks.some(([, check]) => typeof check !== "function")) throw new Error(`Missing callable checks: ${modulePath}`); - if (required && typeof module[required] !== "function") throw new Error(`Missing required export: ${required}`); - const results: Record = {}; - for (const [name, check] of checks) results[name] = (await (check as () => unknown)()) ?? null; - return results; - }, { modulePath: file, required: expected[file] }); - // Observe the real composer while its asynchronous acknowledgement scenarios run. - if (evidence && file.endsWith("/composer.browser.tsx")) { - const mounted = page.locator("textarea").first().waitFor({ state: "visible" }); - await Promise.race([mounted, result]); - if (await page.locator("textarea").count()) await page.screenshot({ path: join(evidence, "composer-mounted.png") }); - } - const output = await Promise.race([ - result, - new Promise((_, reject) => { const timer = setTimeout(() => reject(new Error(`Consumer deadline: ${file}`)), 30_000); timer.unref(); }), - ]); - if (errors.length) throw new Error(errors.join("\n")); - console.log(JSON.stringify({ file, reducedMotion, status: "pass", result: output })); + const result = page.evaluate(async ({ modulePath, required }) => { + const module = await import(`/${modulePath}`); + const checks = Object.entries(module).filter(([name]) => name.startsWith("check")); + if (!checks.length || checks.some(([, check]) => typeof check !== "function")) throw new Error(`Missing callable checks: ${modulePath}`); + if (required && typeof module[required] !== "function") throw new Error(`Missing required export: ${required}`); + const results: Record = {}; + for (const [name, check] of checks) results[name] = (await (check as () => unknown)()) ?? null; + return results; + }, { modulePath: file, required: expected[file] }); + // Observe the real composer while its asynchronous acknowledgement scenarios run. + if (evidence && file.endsWith("/composer.browser.tsx")) { + const mounted = page.locator("textarea").first().waitFor({ state: "visible" }); + await Promise.race([mounted, result]); + if (await page.locator("textarea").count()) await page.screenshot({ path: join(evidence, "composer-mounted.png") }); + } + const output = await result; + if (errors.length) throw new Error(errors.join("\n")); + console.log(JSON.stringify({ file, reducedMotion, status: "pass", result: output })); + }; + // Include page setup and module/style loading in the consumer deadline. + await Promise.race([run(), new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`Consumer deadline: ${file}`)), 30_000); + timer.unref(); + })]); } catch (error) { failures++; console.error(JSON.stringify({ file, reducedMotion, status: "fail", error: error instanceof Error ? error.stack : String(error) })); } finally { + if (timer) clearTimeout(timer); await context.close(); } } @@ -98,6 +106,6 @@ try { if (failures) throw new Error(`${failures} browser consumer invocation(s) failed`); } finally { try { await browser?.close(); } finally { - try { await server.close(); } finally { await rm(cache, { recursive: true, force: true }); } + try { await server?.close(); } finally { await rm(cache, { recursive: true, force: true }); } } } From 9f83055da8d6ea28bd739d9e12c12c22e2d6b512 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:19:06 -0300 Subject: [PATCH 11/15] ci: execute desktop Go fixtures without test-result cache (cherry picked from commit a8a0151ad6f9dcd4b6ad37e9856d409439db1489) --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 09f32efe..a6f910cc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -156,7 +156,7 @@ jobs: - name: Install Chromium for desktop browser checks run: bun ./node_modules/playwright/cli.js install --with-deps chromium - run: bun run test - - run: go test ./... + - run: go test -count=1 ./... mobile: if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository From 2b7cc9aadbd6e3efa661a92951babd417f115fc9 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Mon, 19 Oct 2026 17:46:47 -0300 Subject: [PATCH 12/15] fix(ci): build relay before Unix revocation tests (cherry picked from commit 968e0f66b829f0e54231034ffd4d05e46f26fe05) --- .github/workflows/test.yml | 12 ++++++++++++ docs/architecture/releases.md | 2 ++ scripts/release-pr-gates.test.ts | 16 ++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a6f910cc..c914f1d0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -62,6 +62,12 @@ jobs: fallback: none # Cargo unifies features across the packages of one run, and the phone core takes beans # without the runner, so it is tested on its own. + - name: Build real relay for revocation fixture + run: | + cargo build --locked -p beans-relay --bin beans-relay + relay="$(cargo metadata --locked --no-deps --format-version 1 | python3 -c 'import json, pathlib, sys; print(pathlib.Path(json.load(sys.stdin)["target_directory"]) / "debug" / "beans-relay")')" + test -x "$relay" + printf 'BEANS_REVOCATION_RELAY_BIN=%s\n' "$relay" >> "$GITHUB_ENV" - run: cargo test --locked --workspace --exclude beans-mobile - run: cargo test --locked -p beans-mobile @@ -77,6 +83,12 @@ jobs: with: tool: protoc@3.36.2 fallback: none + - name: Build real relay for revocation fixture + run: | + cargo build --locked -p beans-relay --bin beans-relay + relay="$(cargo metadata --locked --no-deps --format-version 1 | python3 -c 'import json, pathlib, sys; print(pathlib.Path(json.load(sys.stdin)["target_directory"]) / "debug" / "beans-relay")')" + test -x "$relay" + printf 'BEANS_REVOCATION_RELAY_BIN=%s\n' "$relay" >> "$GITHUB_ENV" - run: cargo test --locked --workspace --exclude beans-mobile - run: cargo test --locked -p beans-mobile diff --git a/docs/architecture/releases.md b/docs/architecture/releases.md index c3cc363e..02115299 100644 --- a/docs/architecture/releases.md +++ b/docs/architecture/releases.md @@ -6,6 +6,8 @@ Feature changes run relevant checks locally before integration: the affected Rus [Tests](../../.github/workflows/test.yml) runs the full platform matrix, [Docs](../../.github/workflows/docs.yml) checks architecture budgets and links, and [Catalog](../../.github/workflows/catalog.yml) checks model catalog and marketplace index update timestamps. Jobs accept any same-repository PR head branch; fork PRs are skipped, including fork branches named `release/**`. Manual dispatch does not require a PR. Catalog fetches the PR base branch, falling back to `main` on manual dispatch. Docs and Catalog use distinct `docs` and `catalog` check names. `scripts/release-pr-gates.test.ts` checks triggers, job admission and catalog base selection locally. +Each Rust test job builds the real relay first and exports its executable path through `BEANS_REVOCATION_RELAY_BIN`. The revocation integration fixture starts that binary against isolated temporary storage; it never builds inside the test or uses a live relay. Linux also exercises the relay store against its temporary PostgreSQL service. Local aggregate runs must supply the same prebuilt executable, and PostgreSQL coverage requires `BEANS_RELAY_TEST_POSTGRES`. + Release publication and mobile submission remain manual-only. E2E scripts remain manual/local and are not added to these validation workflows. ## Source and readiness diff --git a/scripts/release-pr-gates.test.ts b/scripts/release-pr-gates.test.ts index a5e055ed..15c0c3f7 100644 --- a/scripts/release-pr-gates.test.ts +++ b/scripts/release-pr-gates.test.ts @@ -70,3 +70,19 @@ test("catalog uses PR base or main for dispatch in both fetch and comparison", ( expect(base).toBe(`origin/${expected}`); } }); + + +test("every Rust aggregate receives a prebuilt real relay for the revocation fixture", () => { + const jobs = workflows.find(({ file }) => file === "test.yml")!.workflow.jobs; + for (const name of ["rust-linux", "rust-macos", "rust-windows"]) { + const steps = jobs[name].steps as { run?: string; if?: string }[]; + const build = steps.findIndex((step) => step.run?.includes("cargo build --locked -p beans-relay --bin beans-relay")); + const aggregate = steps.findIndex((step) => step.run?.includes("cargo test --locked")); + expect(build, `${name}: build relay before tests`).toBeGreaterThanOrEqual(0); + expect(build).toBeLessThan(aggregate); + expect(steps[build].if).toBeUndefined(); + expect(steps[build].run).toContain("BEANS_REVOCATION_RELAY_BIN="); + expect(steps[build].run).toContain("GITHUB_ENV"); + expect(steps[build].run).toContain("cargo metadata --locked --no-deps --format-version 1"); + } +}); From 0c39503f904d63720902f060491d783cc1ea3250 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Fri, 6 Nov 2026 11:51:58 +0000 Subject: [PATCH 13/15] chore(tooling): propagate reviewed Beans AI tooling --- .codegraph-version | 1 + .codegraph/.gitignore | 5 +++ AGENTS.md | 2 + docs/ai-tooling.md | 86 +++++++++++++++++++++++++++++++++++++++++++ scripts/codegraph.sh | 17 +++++++++ 5 files changed, 111 insertions(+) create mode 100644 .codegraph-version create mode 100644 .codegraph/.gitignore create mode 100644 docs/ai-tooling.md create mode 100755 scripts/codegraph.sh diff --git a/.codegraph-version b/.codegraph-version new file mode 100644 index 00000000..fdd3be6d --- /dev/null +++ b/.codegraph-version @@ -0,0 +1 @@ +1.6.2 diff --git a/.codegraph/.gitignore b/.codegraph/.gitignore new file mode 100644 index 00000000..d20c0fe4 --- /dev/null +++ b/.codegraph/.gitignore @@ -0,0 +1,5 @@ +# CodeGraph data files — local to each machine, not for committing. +# Ignore everything in .codegraph/ except this file itself, so transient +# files (the database, daemon.pid, sockets, logs) never show up in git. +* +!.gitignore diff --git a/AGENTS.md b/AGENTS.md index a6f3edd8..e4ffb564 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # Beans +For T3 onboarding, retrieval, command output and model reservations, follow [AI tooling](docs/ai-tooling.md). Product work remains HOLD until Heitor explicitly says OK. + Read [ARCHITECTURE.md](./ARCHITECTURE.md) before writing code, then the subject docs it lists for the parts you change. Identity is a local key pair. Paired Devices sync through an E2E relay. Provider credentials belong to the account: they sync to every paired Device as a blob encrypted with the account key. The AppKit app talks to the local CLI. diff --git a/docs/ai-tooling.md b/docs/ai-tooling.md new file mode 100644 index 00000000..b781f692 --- /dev/null +++ b/docs/ai-tooling.md @@ -0,0 +1,86 @@ +# Prepare and use AI tooling + +Read [AGENTS.md](../AGENTS.md), [BEANS.md](../BEANS.md) and [ARCHITECTURE.md](../ARCHITECTURE.md) before changing Beans. `CLAUDE.md` points to `AGENTS.md`; preserve that link and all existing instructions. + +## Keep product work on HOLD + +This preparation permits onboarding, tooling installation, independently reviewed tooling PRs, normal tooling merges and branch propagation. Product work remains HOLD until Heitor explicitly says OK. Green checks, a tooling merge and completed propagation do not release product work. Do not merge product PRs during this rollout. + +The central coordinator owns global settings and routing. Read `/Users/heitor/.config/ai-tooling/COORDINATION.md` and the current `GLOBAL-ROLLOUT.md` linked there. Report global configuration gaps to that coordinator. Keep one external rollout REPORT with commands, exit codes, receipt hashes, exact heads, resources and blockers. + +Target `bloodf/beans` explicitly for GitHub operations. `origin` is the Beans repository; `upstream` is `egoist/lorca`. T3's upstream canonical identity does not authorize upstream publication or integration. Confirm remotes, branch, HEAD, current base, worktrees and dirty state before writing. Similar source content does not prove ancestry. + +Preserve all refs with a verified Git bundle before propagation. Save staged and unstaged patches, untracked files and their hashes separately. Use an isolated tooling checkout. Preserve existing worktrees and previous work. Do not use automatic stash, `reset --hard`, force push or shared cleanup. + +## Retrieve source with CodeGraph 1.6.2 + +The standalone CLI is pinned by `.codegraph-version`. `scripts/codegraph.sh` checks the installed version, disables telemetry for its process and runs from this checkout's root. Keep CodeGraph outside application dependencies. + +Use the existing installation when it matches the pin. For workstation installation, inspect the installer at `https://raw.githubusercontent.com/colbymchenry/codegraph/f72c9d2efb14454ff4f9fd7b8460abd82f19a287/install.sh`, then run the inspected file with `CODEGRAPH_VERSION=v1.6.2`. Installation and user-specific MCP configuration belong to the central coordinator. + +Run these commands from the repository root: + +```sh +sh scripts/codegraph.sh init --yes +sh scripts/codegraph.sh sync +sh scripts/codegraph.sh status --json +sh scripts/codegraph.sh query dispatch --limit 5 --json +sh scripts/codegraph.sh callers dispatch --file crates/cli/src/api.rs --limit 5 --json +sh scripts/codegraph.sh explore --max-files 3 'api dispatch websocket serve' +``` + +Start with a bounded query before broad source reads. For exact text, missing results or unsupported syntax, use bounded `rg` and exact file ranges. Inspect the actual definition and caller before changing a flow. A graph relationship does not prove runtime behavior or complete dynamic call coverage. + +Each worktree has its own `.codegraph/` index. Do not copy databases between checkouts. Run `sync` and inspect `status --json` after checkout or edits. Check indexed languages, file/node counts, pending changes, worktree mismatch and index completion. Rebuild with `index` after changing include/exclude/extension rules. Version 1.6.2 has no `--strict` flag. + +Track only `.codegraph/.gitignore` inside `.codegraph/`. The ignore file excludes databases, logs, sockets, locks and daemon state. Never commit generated graphs or index data. With a configured CodeGraph MCP, keep the default single `codegraph_explore` tool; otherwise use the same bounded CLI commands. + +## Preserve command status with RTK 1.0.1 + +Read `/Users/heitor/.codex/RTK.md` when present. With a native RTK PreToolUse hook, run normal commands and do not wrap them twice. Without a native hook, use supported explicit commands such as `rtk git status` and `rtk gh pr list --repo bloodf/beans`. MiniMax uses this CLI route. Do not assume one harness's hooks apply to another. + +Preserve the actual exit code and first failure receipt. If condensed output is empty, contradictory or unusable, recover it with `rtk bypass ` or the stored raw receipt. Diagnose the first failure before another attempt. Do not weaken a check, timeout, baseline, security boundary or review requirement to obtain green results. + +## Use Caveman and Ponytail + +Use concise, complete Portuguese sentences with the user. Keep errors, identifiers, numbers and negations exact. Write code, persisted documents and critical instructions in complete language. + +Inspect the affected flow and callers, reuse existing code and standard libraries, and make the smallest complete change. Verify behavior at the relevant boundary. Preserve security, accessibility, approval, encryption and data-loss controls. Installation, synthetic probes, local checks, hosted checks and live behavior are separate evidence. + +## Verify TokenEconomizer per harness + +Reuse the central installation. Preserve the mode without auxiliary paid model calls: `microskills=envfacts`, `loopguard=off`, `repomap=off` and `toolprune=propose`. Do not set a paid model or enable paid proposers. Keep orchestration, review, device and required verification tools available; proposals cannot override project policy. + +From the checkout, inspect effective state without a model call: + +```sh +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" status +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" config show +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" repos list +``` + +Confirm the repository identity is the Beans origin and verify a worktree maps to that same repository. Record the installed adapter's supported events for each harness actually used. Codex's installed hook file declares `SessionStart`, `UserPromptSubmit`, `PostToolUse`, `Stop` and `SessionEnd`; declaration alone does not prove delivery through T3. + +Separate configuration present from fresh-session runtime proof. Loading a skill, starting a process or seeing a zero-session status does not prove the full lifecycle. Record unproved events as UNKNOWN. Do not invent adapters or hook support for Antigravity, MiniMax or another harness. TokenEconomizer learns repository facts and proposes tool pruning; it is not a generic output compressor. No local token savings are claimed without measurement. + +## Reserve every worker through the central dispatcher + +Before each tooling worker, reserve a route: + +```sh +t3-model-route reserve --project beans --purpose tooling --task '' +``` + +Launch only the exact returned provider, model and options through the applicable T3 delegation mechanism. Antigravity accepts Google models only. MiniMax M3.1 Flash requires `m:minimax:MiniMax-M3.1-Flash:v:thinking`. Quota UNKNOWN is not proof of capacity. Never substitute another project, provider or model, retry quota blindly, edit the global helper or implement a local round robin. + +Give each worker exact scope and file ownership. State that concurrent work must be preserved. Record the lease, task/run, provider, model and terminal outcome. Release only the exact lease after terminal evidence. Start no top-level thread for a worker. Use a fresh independent reviewer for each review or re-check, with the exact base/head and applicable risk requirements. No author approves their own change. + +## Verify and propagate tooling + +Keep the existing Beans gates. `bun run check:docs`, `bun run check:catalog` and the same-repository PR test matrix remain applicable. Inspect the current workflow definitions before execution; a local tooling smoke does not replace hosted checks. Product homes, accounts, relays, signing inputs and deployments are not tooling fixtures. + +Create one tooling PR against current Beans `main` and link it immediately to T3. Merge only after independent exact-head review and the real required checks pass. When waiting for hosted checks, use T3's PR watch and end the run; do not poll CI. + +Before propagation, prepare a per-ref plan with original head, target payload, old-head ancestry proof and recovery instructions. Append only tooling to every existing local and origin branch, including historical branches and open PR heads. Preserve each branch's existing instruction and ignore bytes. Do not merge unrelated product history, silently resolve divergence or recreate a branch absent from the server. Push fast-forward with explicit refspecs. Stop on the first remote write failure, re-read remote state and report to central before retry or a strategy change. + +Recheck current remote and PR heads, rescan for new refs, validate indexes in used checkouts and settle owned processes and leases. Record any uncovered ref as BLOCKED with a concrete reason. Product work still waits for Heitor's explicit OK. diff --git a/scripts/codegraph.sh b/scripts/codegraph.sh new file mode 100755 index 00000000..d6aa27fb --- /dev/null +++ b/scripts/codegraph.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Run from any directory with the repository's reviewed CodeGraph version. +set -eu +codegraph_root=$(CDPATH= cd "$(dirname "$0")/.." && pwd) +cd "$codegraph_root" +codegraph_expected=$(cat .codegraph-version) +if ! command -v codegraph >/dev/null 2>&1; then + echo "CodeGraph $codegraph_expected required. See docs/ai-tooling.md." >&2 + exit 1 +fi +codegraph_actual=$(codegraph --version) +if [ "$codegraph_actual" != "$codegraph_expected" ]; then + echo "CodeGraph $codegraph_expected required; found $codegraph_actual. See docs/ai-tooling.md." >&2 + exit 1 +fi +export CODEGRAPH_TELEMETRY=0 +exec codegraph "$@" From 4b4bc24431158d406571f624b12b9713d2d3cac0 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Sat, 7 Nov 2026 15:43:19 -0300 Subject: [PATCH 14/15] fix(l10n): preserve skill comparison count placeholders --- desktop/src/l10n/zh.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/desktop/src/l10n/zh.ts b/desktop/src/l10n/zh.ts index e5035e63..4ff3d435 100644 --- a/desktop/src/l10n/zh.ts +++ b/desktop/src/l10n/zh.ts @@ -1176,8 +1176,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.": "此处未做任何更改,也未启用任何功能。应用差异需要另行确认的操作。", }; From ebeec24240e6515b9ae5942059ffaef574756281 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Sat, 7 Nov 2026 15:47:24 -0300 Subject: [PATCH 15/15] fix(l10n): scan indexed memory health label types --- scripts/l10n-lookups.test.ts | 8 ++++++++ scripts/l10n-lookups.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/scripts/l10n-lookups.test.ts b/scripts/l10n-lookups.test.ts index 1a4c9428..4724322d 100644 --- a/scripts/l10n-lookups.test.ts +++ b/scripts/l10n-lookups.test.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { expect, test } from 'vitest'; import { memoryLookupKeys } from './l10n-lookups.ts'; const model = 'export const MEMORY_OPERATION_LABELS: Record = { queued: "Queued", completed: "Stored" };'; @@ -11,3 +12,10 @@ test('comments, source samples and dynamic maps do not satisfy unused translatio expect([...memoryLookupKeys('/* ' + model + ' */', 'L(MEMORY_OPERATION_LABELS[state])')]).toEqual([]); expect([...memoryLookupKeys(model.replace('"Stored"', 'runtimeLabel'), 'L(MEMORY_OPERATION_LABELS[state])')]).toEqual([]); }); + +test('production indexed health labels are discovered through their real consumer', () => { + const model = readFileSync(new URL('../desktop/src/model/memoryService.ts', import.meta.url), 'utf8'); + const view = readFileSync(new URL('../desktop/src/ui/sheets/memoryService.tsx', import.meta.url), 'utf8'); + const keys = memoryLookupKeys(model, view); + expect([...keys]).toEqual(['Ready', 'Degraded', 'Setup required', 'Queued, not stored', 'Submitted, not stored', 'Processing, not stored', 'Stored', 'Failed, not stored', 'Delivery unknown, not confirmed stored']); +}); diff --git a/scripts/l10n-lookups.ts b/scripts/l10n-lookups.ts index a46913fb..eedbaadf 100644 --- a/scripts/l10n-lookups.ts +++ b/scripts/l10n-lookups.ts @@ -8,7 +8,7 @@ export function memoryLookupKeys(model: string, view: string): Set { const used = new Set([...executable(view).matchAll(/\bL\(\s*(MEMORY_(?:STATUS|OPERATION)_LABELS)\s*\[/g)].map(match => match[1])); const keys = new Set(); const code = executable(model); - for (const match of model.matchAll(/export const (MEMORY_(?:STATUS|OPERATION)_LABELS): Record<\w+, string> = \{([^}]+)\};/g)) { + for (const match of model.matchAll(/export const (MEMORY_(?:STATUS|OPERATION)_LABELS): Record<\w+(?:\["\w+"\])?, string> = \{([^}]+)\};/g)) { if (!used.has(match[1]) || !code.slice(match.index, match.index + 12).startsWith('export const')) continue; // Reject non-literal or incomplete objects instead of guessing runtime values. const body = match[2]!;