Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix: restore retained 1.6.8 behavior and Agent process names (#61)
Orkas1cd3b9d73e1a
diff --git a/docs/audits/2026-09-05-168-parity.md b/docs/audits/2026-09-05-168-parity.mdnew file mode 100644index 00000000..4d596639--- /dev/null+++ b/docs/audits/2026-09-05-168-parity.md@@ -0,0 +1,135 @@+# OrkasOpen 对 Orkas 1.6.8 的逻辑核对与修复++审计日期:2026-09-05。此文记录修复及验证结果;合并状态以对应 PR 为准,合并不代表安装包已发布。++## 结论与边界++不止最初的五项。首轮只深入检查了九个会话与运行时模块,不能据此判断其他功能都正常。本轮把检查扩展到十五个模块类别,按 39 组记录修复:包括同步遗漏、两边共有的问题、开源适配不一致和检查项遗漏。这不是“39 个独立漏同步文件”的统计。++截图中的原始 Agent ID 问题在 168 与 Open 都能复现。因此它不能单独证明漏同步。修复同时补齐了事件中的身份信息和历史记录的名称回退:已知 Agent 显示名字,旧记录可从 Agent 缓存或会话成员找回名字;无法解析的内部 ID 不再冒充名称。外部 Agent 的既有名称处理保留。++实际 Electron 回归截图(测试 Agent 为 ContentWriter):++++本轮没有发现仍缺失的、应同步的生产文件;发现的是已存在文件中的逻辑、调用参数、IPC 和样式遗漏。已确认且属于保留功能的缺口已处理。这个结论不等于所有运行场景都没有缺陷,也不等于 Open 与商业版本具有全部相同能力。++## 固定比较对象++- 来源:Orkas `release_1.6.8`,提交 `99d6e1fa8`,使用 Git 对象读取内容。其 PC 树与原同步来源 `3d92d333da356aec10a2ac3865d4715fb432a1e4` 相同。+- 目标基线:OrkasOpen `b0c86654`。修复分支:`codex/fix-168-parity-20260905`。+- Orkas 工作区保持 `release_1.7.0`。没有 checkout 到 168,没有重置、暂存或清理用户的并行改动。+- 保留后续 Open 修复:流终结的幂等处理、日志脱敏、Codex 登录输入、公开 Orkas API、收窄的失效 CLI 会话匹配和 Linux 支持。没有整体覆盖经过适配的主进程、设置页或媒体服务。++## 覆盖方法++先检查原同步区间的 1,592 个清单项及其排除/适配记录,再独立枚举固定 168 与 Open 的源码、启动脚本、配置及相关核心文件。后者并集为 701 个路径:基线字节相同 407 个、有差异 162 个、Open 独有 14 个、排除 118 个。未出现应保留的 source-only 生产文件。++162 个差异路径按下表检查共享逻辑;明确排除的账号、积分等大块内容按职责和调用边界归类,没有把它们当成待恢复功能。表中数量用于解释文件覆盖范围,不是测试覆盖率,也不是缺陷数量。++| 模块 | 相同 | 差异 | Open 独有 | 排除 | 核对重点 |+| --- | ---: | ---: | ---: | ---: | --- |+| Agent | 1 | 2 | 0 | 1 | 详情入口、返回来源、编辑权限和保存 |+| 应用支持 | 100 | 28 | 4 | 55 | 配置存储、发布回调、生命周期和公共工具 |+| 自动任务与通知 | 5 | 2 | 0 | 1 | 调度、终止通知、持久化与用户归属 |+| Connector | 18 | 13 | 2 | 6 | OAuth、刷新并发、MCP 发现和调用 |+| 会话 | 13 | 10 | 0 | 0 | 流处理、队列、Stop、重开、Agent 交接 |+| 外部 Agent | 24 | 5 | 0 | 0 | CLI 配置、会话恢复、原生模型请求 |+| 文件与保存应用 | 20 | 12 | 0 | 3 | 附件、预览、产物、保存、回收站 |+| 知识库 | 10 | 3 | 0 | 1 | 入库、图片描述、索引与 Office 预览 |+| Marketplace | 7 | 4 | 0 | 3 | 浏览、安装、详情、只读边界 |+| 模型与媒体供应商 | 9 | 17 | 0 | 1 | 凭据、迁移、请求、取消、媒体下载 |+| 原生与启动 | 34 | 17 | 7 | 19 | 代理、原生依赖、启动、退出、打包配置 |+| 项目与任务 | 10 | 5 | 0 | 0 | 项目归属、文件、任务和工作区 |+| 运行时与工具 | 79 | 15 | 0 | 2 | 工具可见性、参数、权限、恢复和结果 |+| 设置与界面 | 54 | 27 | 1 | 24 | 页面生命周期、异步结果、DOM、样式、语言 |+| Skill | 23 | 2 | 0 | 2 | 安装、编辑、系统 Skill 和读取范围 |++计数说明:基线枚举使用当前同步规则记录 Open 的后续能力;另与固定 168 规则逐项复核。只有两个视频生产文件的排除分类不同:168 明确排除商业视频实现,Open 后续新增了自己的公开 API 实现。这两个文件已作为 Open 实现单独检查,没有误判成必须照搬商业适配器。++其他交叉核对:++- IPC:检查静态可识别的 renderer 调用与主进程注册表。补齐五个有效入口后,剩余五个未注册引用属于禁用的开发/上传功能;不是用户可达的缺失入口。动态生成的调用仍由所属功能测试覆盖,静态扫描不声称覆盖所有运行时值。+- renderer 名称绑定:检查新增未声明引用,修复有效路径上的 `trackResult`;剩余诊断属于已禁用的开发/遥测分支、受 `typeof` 保护的可选入口或既有隐式变量,未计为新的可达故障。+- HTML/CSS:比较 DOM ID 与逐个 CSS 选择器,避免把合并选择器、格式化差异或已删功能样式当成遗漏;恢复 117 个共享组件选择器条目及相关声明。这些条目不是 117 个独立缺陷。Library 默认三列样式也对齐到四列,但运行时本来就会按标签数重设列数,因此没有把它计为独立的可见故障。+- 文本:核对 en/zh/ja/pt 四份语言文件。共同删除的 268 个键主要属于已排除功能,附件提示等仍有效的差异已恢复;新增旧视频配置不可用的说明。+- 内置资源:286 个来源文件、7 个 Open 覆盖、1 个排除的系统 Skill,未发现应保留资源缺失。另检查目标 manifest。+- 依赖:锁文件 521 个 package 记录相同、63 个不同、56 个移除、10 个新增;核对商业依赖移除、Linux tokenizer 适配及工具链解析版本差异。保留 Open 的锁文件,没有降级或重新安装依赖。这不是依赖漏洞审计。++## 修复记录++| ID | 问题与处理 | 主要实现/证据所属模块 |+| --- | --- | --- |+| F1 | 委派过程显示内部 ID;补齐事件身份字段和实时/历史名称回退。此问题两边共有 | `event-mapper.ts`、`conversation.js`;事件和重放用例 |+| F2 | 从消息头像/名称、创建结果打开 Agent 详情时返回目标未定义;在导航前捕获来源,查找失败保持当前页 | `agents.js`;详情返回导航用例 |+| F3 | 子 Agent 交接错误复用了展示过滤后的产物列表;交接保留真实文件,页脚仍可隐藏过程文件 | `group_chat/bus.ts`;真实文件交接用例 |+| F4 | 发送未启动或抛错后残留 Stop 恢复快照;按控制器归属清理,保留排队/运行中的快照 | `conversation.js`;发送失败和队列对照用例 |+| F5 | `generate_video` 缺少专用过程文案;恢复实时与历史本地化呈现 | `conversation.js`;过程展示用例 |+| F6 | 知识库图片描述漏设空工具列表 | `library_image_describer.ts`;调用参数用例 |+| F7 | Marketplace Agent 编辑记忆时定义字段未保持只读 | `agents.js`;资源编辑用例 |+| F8 | Agent/Skill 编辑会话漏设仅错误消息操作 | `agents.js`、`skills.js`;控制器创建用例 |+| F9 | 流式 Skill 编辑缺少专用系统 Skill、空普通 Skill 列表和只读目录 | `features/skills.ts`;流式编辑参数用例 |+| F10 | 搜索响应正文、参考图下载缺少完整超时/取消与大小边界 | `search-adapters.ts`、`generation_reference_assets.ts`;正文停滞和下载用例 |+| F11 | PDF 已写入,但产物登记回调抛错使工具整体失败 | `local-tools.ts`;成功落盘后回调失败用例 |+| F12 | OAuth 普通/强制刷新可能并发重复,失败状态不及时,部分 Server grant 不刷新 | Connector manager/OAuth;刷新并发与认证恢复用例 |+| F13 | Agent 保存和 Skill 重命名残留未声明的遥测回调,中断后续状态更新 | Agent/Skill renderer;真实保存与重命名路径 |+| F14 | Connector 目录缺少轻量清单、按名展开与大目录压缩 | `connector-meta-tools.ts`;目录大小和懒加载用例 |+| F15 | Connector 调用丢失取消信号、MCP 错误标记及 schema 限定的参数别名 | `connector-meta-tools.ts`;取消/错误/参数冲突用例 |+| F16 | OAuth 明确错误码被含“取消”的文案掩盖 | `connectors.js`;错误码优先级用例 |+| F17 | 原生 pi provider 缺失推理、请求头、延迟工具和返回详情等处理 | `pi-provider.ts`;恢复对应 provider 行为用例 |+| F18 | 外部 provider 缺少 Moonshot 原生路径及部分推理消息修复 | `external-providers.ts`;实际请求构造用例,保留公开 Orkas API |+| F19 | 主进程未安装全局系统代理路由 | `main/index.ts`;真实 Electron 启动后通过本地代理访问虚构域名 |+| F20 | Office 常驻进程启动/退出清理及重复退出合并遗漏 | `main/index.ts`;保留 Open 生命周期上报,测试启动隔离 |+| F21 | 目录与导入选择器丢失合理默认位置 | 主进程 IPC;实际注册处理器与 dialog 参数用例 |+| F22 | Agent 记忆增改删、知识库/项目 Office HTML 预览五个有效 IPC 未注册;创建 Agent 也补传 profile | 主进程 IPC;记忆落盘、预览所属组件用例 |+| F23 | 图像/视频请求只约束响应头,缺少部分取消、进度和结果校验 | `image_gen.ts`、`video_gen.ts`;四类图像调用、无效字节、响应头后取消/超时 |+| F24 | 图像工具遗漏项目附件路径、引用角色、生产计划、预算/复用/事务及版本化产物 URL;媒体异常需保留未决事务 | 图像/视频工具;生产控制和文件边界用例;不引入商业积分 |+| F25 | 本地默认图像模型和编辑能力字段归一化遗漏 | `client_config.ts`;默认值与两种字段形式用例 |+| F26 | 初始化用户未恢复 uid/未读状态,视图切换过早启动队列 | `boot.js`;用户初始化和队列时序用例 |+| F27 | 工作区选择/重置把失败、取消、持久化后刷新失败混为一谈 | `user-workspace.js`;各结果分支用例 |+| F28 | 设置控件绑定过晚、模型变更事件/缓存刷新遗漏,删除和打开数据目录结果处理不完整 | `settings.js`;延迟 IPC 与设置交互用例 |+| F29 | 回收站恢复后不刷新 Agent/Skill 缓存,刷新失败又被报成恢复失败 | `settings.js`;恢复成功与后续刷新失败用例 |+| F30 | 凭据写入不原子,损坏存储可能被后续操作覆盖;迁移写失败会丢失可读结果 | `auth.ts`;加密存储、原子失败、损坏文件保留用例 |+| F31 | OAuth 过期/刷新失败状态不完整,SDK 连接错误可暴露密钥 | `auth.ts`;刷新恢复和错误脱敏用例 |+| F32 | 模型选择/重排缺少单次原子保存与不可用项稳定顺序,自定义端点模型不应被改写 | `auth.ts`;保存次数、固定模型和排序用例 |+| F33 | 退役模型别名升级、入口去重和持久化迁移遗漏 | `auth.ts`、`provider_catalog.ts`;迁移前后读取与保存用例 |+| F34 | provider 轮转遗漏成功回退后的本轮失败候选抑制、图片省略提示去重与终止类别 | `rotating-provider.ts`;成功/全失败轮转和提示用例 |+| F35 | 语言切换、OAuth 启动 IPC 抛错未恢复界面并明确反馈 | `settings.js`;失败和恢复用例 |+| F36 | 图像设置忽略 IPC 返回的具体模型选项,无法正确选择新增模型 | `settings.js`;选择 Seedream Pro 后实际保存参数用例 |+| F37 | 视频设置允许添加未实现的 Doubao 适配器;限制新增到实际支持的公开 API,旧配置保留并显示不可用 | `video_auth.ts`、IPC、设置页;旧密钥保留/移除与 UI 状态用例 |+| F38 | 队列删除、视频重试/审阅、CLI 设置、Office 自适应、按钮焦点等共享样式丢失;两处 Skill 关闭控件缺少按钮语义 | `style.css`、`index.html`、语言文件;四标签布局与审阅面板端到端检查 |+| F39 | 常规 typecheck 没有执行核心 Agent 的严格配置 | `package.json`;主项目和核心 Agent 两道检查均执行 |++F24 是有意恢复模型可见参数,并非描述清理:新增 `reference_image_urls`、`reference_bindings`、`negative_prompt`、两个视频生产标识和两个 ImageStudio 标识;原必填 `prompt` / `output_path` 不变。所属行为测试通过后更新了工具 schema 指纹,保留参数语义和描述预算检查。++## 保留的产品差异++- Open 不包含商业账号登录、会员/积分、云同步、官方自动更新、服务端语音输入、私有分享/反馈和开发发布面板。这些不列为漏同步。+- Open 使用用户密钥的公开 Orkas API;其视频请求协议和实现由 Open 自己维护。没有补入商业版的 MiniMax、Vidu、Kling、Google、Runway 等视频适配器。Doubao 视频的“可配置但不可执行”矛盾已修复,尚未新增其执行能力。+- 保留开源 Connector bridge、独立数据目录、Linux 源码启动/原生依赖和本地回收站展示。商业管理能力不通过同步恢复。+- 相同源码仍可能共有缺陷,F1 就是实例。对未发生差异的函数没有宣称逐函数重新证明其正确性。++## 验证结果++完整基线在修改前通过:主项目类型检查,8,461 个 JS 用例/15 个跳过,415 个资源用例,E2E 类型检查,142 个桌面 E2E 场景,当前平台原生测试 1,017 个通过/12 个跳过,以及 smoke。++| 检查 | 最终结果 |+| --- | --- |+| 主项目与核心 Agent 严格类型检查 | 通过 |+| 完整 JS 单元测试 | 553 个文件通过;8,605 个用例通过,15 个条件跳过,0 失败 |+| 资源测试 | 415 个通过,0 失败;1 个既有 Python SSL 环境告警 |+| 桌面 E2E 类型检查 | 通过 |+| 桌面 E2E | 144 个不同场景具有通过记录:完整运行 142 通过、1 个夹具时序失败;修正夹具并复验 18 个受影响/新增场景,全部通过 |+| 当前平台原生测试 | macOS:33 个文件通过;1,020 个通过,12 个条件跳过,0 失败 |+| smoke / builtin manifest | 通过 |++最后一轮完整 JS/资源测试在桌面复验结束后串行运行;其启动时记录了所有 `src/` 与 `test/` 文件的哈希,结束时检查没有变化。结构化结果见 [验证记录](2026-09-05-168-verification.json)。++验证过程中修正了旧代理初始化禁止断言,审核并更新图像工具 schema 指纹/描述断言;另外调整了测试夹具:队列编辑要等实际流结束,进程树测试要留出 Electron 子进程启动时间,并原子发布 PID 文件。没有通过跳过失败用例、删除进程清理断言或增加自动重试来取得最终结果。曾在增补测试期间发生的旧模块缓存与新用例混用,已由固定源码的最终串行完整运行排除。+++定向回归覆盖实时与重放、旧数据、异常/取消、落盘后回调失败、并发刷新、provider 回退和真实 IPC。模型请求使用本地协议夹具或测试替身,没有调用用户真实付费模型或使用真实 OAuth 密钥。Electron E2E 使用隔离的临时数据目录,验证实际 renderer/preload/IPC/文件和本地模型协议链路。++限制:本机为 macOS,未在 Windows/Linux 真机重跑;没有执行每一家供应商的真实付费 API、真实账号登录、真实系统通知展示或完整签名安装包发布。平台条件和可选外部资源用例的跳过单列,不算通过。日志中的 Python LibreSSL、Node API 弃用提示及故意触发的错误分支不作为零告警证明。++原始比较快照、差异、红/绿回归日志与全量日志存于本次任务的临时审计目录 `orkas168-compare-pquxtkcw`;本文件及仓库中的行为测试是持续保留的审计入口。diff --git a/docs/audits/2026-09-05-168-verification.json b/docs/audits/2026-09-05-168-verification.jsonnew file mode 100644index 00000000..37a6ca12--- /dev/null+++ b/docs/audits/2026-09-05-168-verification.json@@ -0,0 +1,40 @@+{+ "source_ref": "release_1.6.8",+ "source_commit": "99d6e1fa8",+ "target_base": "b0c86654364700c223b1ed41e729b336d0ba6dcb",+ "target_branch": "codex/fix-168-parity-20260905",+ "source_and_test_files_digest": "d549840edb6496d411b28b13dbeefc68b0e54daf87fe61bf6e781e8951839150",+ "changed_during_final_serial_validation": [],+ "typecheck": {+ "main": "passed",+ "core_agent_strict": "passed",+ "e2e": "passed"+ },+ "unit": {+ "files_passed": 553,+ "passed": 8605,+ "skipped": 15,+ "failed": 0+ },+ "resources": {+ "passed": 415,+ "warnings": 1,+ "failed": 0+ },+ "e2e": {+ "unique_scenarios_with_passing_evidence": 144,+ "full_run_passed": 142,+ "full_run_failed_before_fixture_repair": 1,+ "affected_recheck_passed": 18,+ "affected_recheck_failed": 0+ },+ "native": {+ "platform": "darwin",+ "files_passed": 33,+ "passed": 1020,+ "skipped": 12,+ "failed": 0+ },+ "smoke": "passed",+ "builtin_manifest": "passed"+}diff --git a/docs/audits/assets/168-delegation-agent-name.png b/docs/audits/assets/168-delegation-agent-name.pngnew file mode 100644index 00000000..0d74352eBinary files /dev/null and b/docs/audits/assets/168-delegation-agent-name.png differdiff --git a/package.json b/package.jsonindex 4bc5ef89..dd3ed874 100644--- a/package.json+++ b/package.json@@ -16,7 +16,9 @@"start:electron": "electron .","stop": "pkill -TERM -f \"^$PWD/node_modules/electron/dist/Orkas\\.app/Contents/MacOS/Electron $PWD\" || true","smoke": "tsx src/main/smoke.ts",- "typecheck": "tsc --noEmit",+ "typecheck": "npm run typecheck:main && npm run typecheck:core-agent",+ "typecheck:main": "tsc --noEmit",+ "typecheck:core-agent": "tsc --noEmit -p src/core-agent/tsconfig.json","test": "npm run test:js && npm run test:resources","test:non-model": "npm run typecheck && npm test && npm run test:e2e:typecheck && npm run test:e2e && npm run test:platform-native && npm run smoke","test:js": "node scripts/run-tests.mjs run",diff --git a/src/core-agent/src/providers/pi-provider.ts b/src/core-agent/src/providers/pi-provider.tsindex 148f84c0..881ed132 100644--- a/src/core-agent/src/providers/pi-provider.ts+++ b/src/core-agent/src/providers/pi-provider.ts@@ -168,6 +168,7 @@ function buildPiContext(toolCallId: tr.toolUseId,toolName,content: [{ type: "text", text: tr.content }],+ ...(tr.addedToolNames?.length ? { addedToolNames: tr.addedToolNames } : {}),isError: tr.isError ?? false,timestamp: Date.now(),});@@ -381,22 +382,51 @@ type MapContentOptions = {type LeadingThinkTextFilter = {push(text: string): string;finish(): string;+ takeThinkingActivity(): {+ started: boolean;+ chars: number;+ text: string;+ ended: boolean;+ };};const LEADING_THINK_OPEN = "<think>";const LEADING_THINK_CLOSE = "</think>";/**- * Some user-configured OpenAI-compatible endpoints serialize private- * reasoning as a literal leading `<think>...</think>` text block instead of- * the protocol's structured reasoning field. Hold only the ambiguous prefix- * while streaming, suppress each block in a consecutive leading sequence,- * and pass every non-leading lookalike through unchanged.+ * Some provider endpoints serialize private reasoning as a literal leading+ * `<think>...</think>` text block instead of the protocol's structured+ * reasoning field. Hold only the ambiguous prefix while streaming, suppress+ * each block in a consecutive leading sequence, and pass every non-leading+ * lookalike through unchanged.*/function createLeadingThinkTextFilter(): LeadingThinkTextFilter {let state: "detect" | "suppress" | "pass" = "detect";let pending = "";let suppressedLeadingBlock = false;+ let thinkingActive = false;+ let activityStarted = false;+ let activityChars = 0;+ let activityText = "";+ let activityEnded = false;++ const beginThinking = () => {+ if (thinkingActive) return;+ thinkingActive = true;+ activityStarted = true;+ };++ const recordThinking = (text: string) => {+ if (!text) return;+ activityChars += text.length;+ activityText += text;+ };++ const endThinking = () => {+ if (!thinkingActive) return;+ thinkingActive = false;+ activityEnded = true;+ };return {push(text: string): string {@@ -415,18 +445,33 @@ function createLeadingThinkTextFilter(): LeadingThinkTextFilter {return visible;}state = "suppress";+ beginThinking();pending = candidate.slice(LEADING_THINK_OPEN.length);}if (state === "suppress") {const closeIndex = pending.indexOf(LEADING_THINK_CLOSE);if (closeIndex < 0) {- pending = pending.slice(-(LEADING_THINK_CLOSE.length - 1));+ // Retain only the suffix that could still become a split closing+ // tag. Everything before it is confirmed private reasoning and can+ // be recorded as reasoning without forwarding it as answer text.+ let suffixLength = 0;+ const maxSuffix = Math.min(pending.length, LEADING_THINK_CLOSE.length - 1);+ for (let length = maxSuffix; length > 0; length -= 1) {+ if (LEADING_THINK_CLOSE.startsWith(pending.slice(-length))) {+ suffixLength = length;+ break;+ }+ }+ recordThinking(pending.slice(0, pending.length - suffixLength));+ pending = suffixLength > 0 ? pending.slice(-suffixLength) : "";return "";}+ recordThinking(pending.slice(0, closeIndex));pending = pending.slice(closeIndex + LEADING_THINK_CLOSE.length);suppressedLeadingBlock = true;state = "detect";+ endThinking();}}},@@ -435,10 +480,28 @@ function createLeadingThinkTextFilter(): LeadingThinkTextFilter {const visible = state === "detect"? (suppressedLeadingBlock ? pending.replace(/^\s+/, "") : pending): "";+ if (state === "suppress") {+ recordThinking(pending);+ endThinking();+ }pending = "";state = "pass";return visible;},++ takeThinkingActivity() {+ const activity = {+ started: activityStarted,+ chars: activityChars,+ text: activityText,+ ended: activityEnded,+ };+ activityStarted = false;+ activityChars = 0;+ activityText = "";+ activityEnded = false;+ return activity;+ },};}@@ -493,6 +556,15 @@ export function mapContentForTest(return mapContent(content, options);}+/** Provider-boundary content is never allowed to expose a literal leading+ * private-reasoning block, regardless of whether the route is managed,+ * built-in, or user-configured. */+function mapProviderContent(content: PiAssistantMessage["content"]): MessageContent[] {+ return mapContent(content, { stripLeadingThinkText: true });+}++export const mapProviderContentForTest = mapProviderContent;+export const createLeadingThinkTextFilterForTest = createLeadingThinkTextFilter;export const stripLeadingThinkTextForTest = stripLeadingThinkText;@@ -517,6 +589,119 @@ export function normalizeReasoningForProvider(// ─── Provider creation ────────────────────────────────────────────────────+/**+ * Pi-ai's raw adapters historically turn an omitted reasoning option into an+ * explicit provider-specific "off" value. Omission has a different meaning:+ * the selected model should retain its official thinking toggle and effort.+ * Remove only those synthesized-off controls; explicit caller choices use a+ * separate path and remain untouched.+ */+function restoreOfficialReasoningDefaults(+ payload: unknown,+ model: Model<Api>,+): unknown {+ if (!model.reasoning || !payload || typeof payload !== "object" || Array.isArray(payload)) {+ return payload;+ }++ const next: Record<string, unknown> = { ...(payload as Record<string, unknown>) };+ const compat = model.compat as (Record<string, unknown> & {+ thinkingFormat?: string;+ chatTemplateKwargs?: Record<string, unknown>;+ }) | undefined;+ const thinkingFormat = compat?.thinkingFormat+ || (model.provider === "deepseek" || model.baseUrl?.includes("deepseek.com") ? "deepseek" : undefined);+ const removeSynthesizedReasoningFields = (+ effort: unknown,+ enabled?: unknown,+ ): void => {+ const rawReasoning = next.reasoning;+ if (!rawReasoning || typeof rawReasoning !== "object" || Array.isArray(rawReasoning)) return;+ const reasoning = { ...(rawReasoning as Record<string, unknown>) };+ if (reasoning.effort === effort) delete reasoning.effort;+ if (enabled !== undefined && reasoning.enabled === enabled) delete reasoning.enabled;+ if (Object.keys(reasoning).length > 0) next.reasoning = reasoning;+ else delete next.reasoning;+ };++ if (thinkingFormat === "zai" || thinkingFormat === "deepseek") {+ const thinking = next.thinking as { type?: unknown } | undefined;+ if (thinking?.type === "disabled") delete next.thinking;+ } else if (thinkingFormat === "qwen") {+ if (next.enable_thinking === false) delete next.enable_thinking;+ } else if (thinkingFormat === "qwen-chat-template") {+ delete next.chat_template_kwargs;+ } else if (thinkingFormat === "chat-template") {+ const rawKwargs = next.chat_template_kwargs;+ if (rawKwargs && typeof rawKwargs === "object" && !Array.isArray(rawKwargs)) {+ const kwargs = { ...(rawKwargs as Record<string, unknown>) };+ for (const [key, descriptor] of Object.entries(compat?.chatTemplateKwargs || {})) {+ if (descriptor && typeof descriptor === "object" && "$var" in descriptor) delete kwargs[key];+ }+ if (Object.keys(kwargs).length > 0) next.chat_template_kwargs = kwargs;+ else delete next.chat_template_kwargs;+ }+ } else if (thinkingFormat === "openrouter" || thinkingFormat === "together") {+ const reasoning = next.reasoning as { effort?: unknown; enabled?: unknown } | undefined;+ if (reasoning?.enabled === false || reasoning?.effort === "none") {+ removeSynthesizedReasoningFields("none", false);+ }+ } else if (thinkingFormat === "string-thinking") {+ const offValue = model.thinkingLevelMap?.off;+ if (next.thinking === "none" || (typeof offValue === "string" && next.thinking === offValue)) {+ delete next.thinking;+ }+ }++ // OpenAI Responses and generic OpenAI-compatible reasoners use these+ // shapes rather than a named thinkingFormat.+ const reasoning = next.reasoning as { effort?: unknown } | undefined;+ const mappedOff = model.thinkingLevelMap?.off;+ if (reasoning?.effort === "none" || (typeof mappedOff === "string" && reasoning?.effort === mappedOff)) {+ removeSynthesizedReasoningFields(reasoning.effort);+ }+ if (typeof mappedOff === "string" && next.reasoning_effort === mappedOff) {+ delete next.reasoning_effort;+ }++ return next;+}++export const restoreOfficialReasoningDefaultsForTest = restoreOfficialReasoningDefaults;++/** Read the explicit output ceiling from known provider wire shapes. */+function effectiveMaxTokensFromPayload(payload: unknown): number | undefined {+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined;+ const root = payload as Record<string, unknown>;+ const generationConfig = root.generationConfig && typeof root.generationConfig === "object"+ && !Array.isArray(root.generationConfig)+ ? root.generationConfig as Record<string, unknown>+ : undefined;+ const inferenceConfig = root.inferenceConfig && typeof root.inferenceConfig === "object"+ && !Array.isArray(root.inferenceConfig)+ ? root.inferenceConfig as Record<string, unknown>+ : undefined;+ const options = root.options && typeof root.options === "object" && !Array.isArray(root.options)+ ? root.options as Record<string, unknown>+ : undefined;+ const candidates = [+ root.max_tokens,+ root.max_completion_tokens,+ root.max_output_tokens,+ root.maxTokens,+ generationConfig?.maxOutputTokens,+ inferenceConfig?.maxTokens,+ options?.maxTokens,+ ];+ const limits = candidates+ .map((value) => Number(value))+ .filter((value) => Number.isFinite(value) && value > 0)+ .map((value) => Math.trunc(value));+ return limits.length ? Math.min(...limits) : undefined;+}++export const effectiveMaxTokensFromPayloadForTest = effectiveMaxTokensFromPayload;+/*** Create an LLMProvider backed by pi-ai for the given provider/model.*@@ -557,7 +742,6 @@ export function createPiProvider(config: {supportedReasoning?: ReadonlyArray<"minimal" | "low" | "medium" | "high">;}): LLMProvider {const providerId = config.provider as KnownProvider;- const shouldStripLeadingThinkText = config.provider === "custom";// Resolve the model object. `customModel` shortcuts pi-ai's catalog// lookup for providers pi-ai doesn't know about.@@ -598,8 +782,18 @@ export function createPiProvider(config: {const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);const reasoning = effectiveReasoning(params.reasoning);const sessionId = cacheSafeSessionId(params.sessionId);- const onPayload = config.onPayload- ? ((payload: unknown, hookModel: Model<Api>) => config.onPayload!(payload, hookModel, params.requestMetadata))+ const useOfficialReasoningDefaults = model.reasoning === true+ && params.reasoning === undefined+ && config.defaultReasoning === undefined;+ const onPayload = (useOfficialReasoningDefaults || config.onPayload)+ ? ((payload: unknown, hookModel: Model<Api>) => {+ const normalized = useOfficialReasoningDefaults+ ? restoreOfficialReasoningDefaults(payload, hookModel)+ : payload;+ return config.onPayload+ ? config.onPayload(normalized, hookModel, params.requestMetadata)+ : normalized;+ }): undefined;log.debug(`complete ${providerId}/${model.id}`);@@ -610,6 +804,7 @@ export function createPiProvider(config: {if (reasoning) {result = await piCompleteSimple(model, context, {apiKey: config.apiKey,+ headers: config.headers,transport: CORE_AGENT_TRANSPORT,signal: params.signal,maxTokens: params.maxTokens,@@ -622,6 +817,7 @@ export function createPiProvider(config: {} else {result = await piComplete(model, context, {apiKey: config.apiKey,+ headers: config.headers,transport: CORE_AGENT_TRANSPORT,signal: params.signal,maxTokens: params.maxTokens,@@ -640,9 +836,7 @@ export function createPiProvider(config: {}return {- content: mapContent(result.content, {- stripLeadingThinkText: shouldStripLeadingThinkText,- }),+ content: mapProviderContent(result.content),stopReason: mapStopReason(result.stopReason),usage: mapUsage(result.usage),model: resolvedResponseModel(result, model.id),@@ -657,19 +851,42 @@ export function createPiProvider(config: {const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);const reasoning = effectiveReasoning(params.reasoning);const sessionId = cacheSafeSessionId(params.sessionId);- const onPayload = config.onPayload- ? ((payload: unknown, hookModel: Model<Api>) => config.onPayload!(payload, hookModel, params.requestMetadata))- : undefined;+ const useOfficialReasoningDefaults = model.reasoning === true+ && params.reasoning === undefined+ && config.defaultReasoning === undefined;+ let effectiveMaxTokens: number | undefined;+ const onPayload = async (payload: unknown, hookModel: Model<Api>): Promise<unknown> => {+ const normalized = useOfficialReasoningDefaults+ ? restoreOfficialReasoningDefaults(payload, hookModel)+ : payload;+ const transformed = config.onPayload+ ? await config.onPayload(normalized, hookModel, params.requestMetadata)+ : normalized;+ // pi-ai treats an undefined hook result as "keep the original payload".+ // Observe that exact final shape so this is an on-wire value, not a+ // model-catalog guess made before context and adapter adjustments.+ effectiveMaxTokens = effectiveMaxTokensFromPayload(+ transformed === undefined ? payload : transformed,+ );+ return transformed;+ };log.debug(`stream ${providerId}/${model.id}`);try {- const leadingThinkFilter = shouldStripLeadingThinkText- ? createLeadingThinkTextFilter()- : null;+ const leadingThinkFilter = createLeadingThinkTextFilter();+ const takeLeadingThinkEvents = function* (): Generator<StreamEvent> {+ const activity = leadingThinkFilter.takeThinkingActivity();+ if (activity.started) yield { type: "thinking_start" };+ if (activity.chars > 0) {+ yield { type: "thinking_delta", chars: activity.chars, text: activity.text };+ }+ if (activity.ended) yield { type: "thinking_end" };+ };const eventStream = reasoning? piStreamSimple(model, context, {apiKey: config.apiKey,+ headers: config.headers,transport: CORE_AGENT_TRANSPORT,signal: params.signal,maxTokens: params.maxTokens,@@ -677,17 +894,18 @@ export function createPiProvider(config: {reasoning,cacheRetention: params.cacheRetention,sessionId,- ...(onPayload ? { onPayload: onPayload as any } : {}),+ onPayload: onPayload as any,}): piStream(model, context, {apiKey: config.apiKey,+ headers: config.headers,transport: CORE_AGENT_TRANSPORT,signal: params.signal,maxTokens: params.maxTokens,temperature: params.temperature,cacheRetention: params.cacheRetention,sessionId,- ...(onPayload ? { onPayload: onPayload as any } : {}),+ onPayload: onPayload as any,});for await (const event of eventStream) {@@ -697,13 +915,24 @@ export function createPiProvider(config: {break;case "text_delta":{- const text = leadingThinkFilter?.push(event.delta) ?? event.delta;+ const text = leadingThinkFilter.push(event.delta);+ yield* takeLeadingThinkEvents();if (text) yield { type: "text_delta", text };}break;+ case "thinking_start":+ yield { type: "thinking_start" };+ break;+ case "thinking_delta":+ yield { type: "thinking_delta", chars: event.delta.length, text: event.delta };+ break;+ case "thinking_end":+ yield { type: "thinking_end" };+ break;case "toolcall_start":{- const text = leadingThinkFilter?.finish() ?? "";+ const text = leadingThinkFilter.finish();+ yield* takeLeadingThinkEvents();if (text) yield { type: "text_delta", text };}yield {@@ -724,7 +953,8 @@ export function createPiProvider(config: {break;case "done":{- const text = leadingThinkFilter?.finish() ?? "";+ const text = leadingThinkFilter.finish();+ yield* takeLeadingThinkEvents();if (text) yield { type: "text_delta", text };}const serverFallbackReason = serverFallbackReasonFromResponseId(event.message.responseId);@@ -732,10 +962,9 @@ export function createPiProvider(config: {type: "message_end",stopReason: mapStopReason(event.reason),usage: mapUsage(event.message.usage),- content: mapContent(event.message.content, {- stripLeadingThinkText: shouldStripLeadingThinkText,- }),+ content: mapProviderContent(event.message.content),model: resolvedResponseModel(event.message, model.id),+ ...(effectiveMaxTokens !== undefined ? { effectiveMaxTokens } : {}),...(serverFallbackReason ? { serverFallbackReason } : {}),providerTermination: {category: providerTerminationCategory(@@ -747,7 +976,8 @@ export function createPiProvider(config: {break;case "error":{- const text = leadingThinkFilter?.finish() ?? "";+ const text = leadingThinkFilter.finish();+ yield* takeLeadingThinkEvents();if (text) yield { type: "text_delta", text };}const errorServerFallbackReason = serverFallbackReasonFromResponseId(event.error.responseId);@@ -793,6 +1023,7 @@ export function createPiProvider(config: {messages: [{ role: "user", content: "ping", timestamp: Date.now() }],}, {apiKey: config.apiKey,+ headers: config.headers,transport: CORE_AGENT_TRANSPORT,maxTokens: 1,});diff --git a/src/core-agent/test/providers.test.ts b/src/core-agent/test/providers.test.tsindex ba1b2ab1..e0b50409 100644--- a/src/core-agent/test/providers.test.ts+++ b/src/core-agent/test/providers.test.ts@@ -1,16 +1,9 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import { ProviderRegistry } from "../src/providers/registry.js";-import {- createAnthropicProvider,- createLeadingThinkTextFilterForTest,- createOpenAIProvider,- createPiProvider,- listPiProviders,- listPiModels,- mapContentForTest,- stripLeadingThinkTextForTest,-} from "../src/providers/pi-provider.js";+import { buildPiContextForTest, createAnthropicProvider, createLeadingThinkTextFilterForTest, createOpenAIProvider, createPiProvider, effectiveMaxTokensFromPayloadForTest, listPiProviders, listPiModels, mapContentForTest, mapProviderContentForTest, normalizeReasoningForProvider, providerTerminationCategoryForTest, resolvedResponseModelForTest, restoreOfficialReasoningDefaultsForTest, serverFallbackReasonFromResponseIdForTest, stripLeadingThinkTextForTest } from "../src/providers/pi-provider.js";import { createConfig } from "../src/config/loader.js";+import type { Message, MessageContent } from "../src/shared/types.js";+import type { Model } from "@earendil-works/pi-ai";describe("Providers (pi-ai backed)", () => {describe("createAnthropicProvider", () => {@@ -44,6 +37,25 @@ describe("Providers (pi-ai backed)", () => {});describe("createPiProvider", () => {+ it("reads the effective max-token ceiling from provider wire payloads", () => {+ expect(effectiveMaxTokensFromPayloadForTest({ max_tokens: 8_192 })).toBe(8_192);+ expect(effectiveMaxTokensFromPayloadForTest({ max_completion_tokens: 16_384 })).toBe(16_384);+ expect(effectiveMaxTokensFromPayloadForTest({ max_output_tokens: 32_000 })).toBe(32_000);+ expect(effectiveMaxTokensFromPayloadForTest({ generationConfig: { maxOutputTokens: 4_096 } })).toBe(4_096);+ expect(effectiveMaxTokensFromPayloadForTest({ inferenceConfig: { maxTokens: 2_048 } })).toBe(2_048);+ expect(effectiveMaxTokensFromPayloadForTest({ options: { maxTokens: 1_024 } })).toBe(1_024);+ expect(effectiveMaxTokensFromPayloadForTest({ max_tokens: 8_192, max_completion_tokens: 4_096 })).toBe(4_096);+ expect(effectiveMaxTokensFromPayloadForTest({ model: "server-owned-limit" })).toBeUndefined();+ expect(effectiveMaxTokensFromPayloadForTest({ max_tokens: 0 })).toBeUndefined();+ expect(effectiveMaxTokensFromPayloadForTest({ max_tokens: -1 })).toBeUndefined();+ expect(effectiveMaxTokensFromPayloadForTest({ max_tokens: "invalid" })).toBeUndefined();+ });++ it("clamps unsupported compaction reasoning to the nearest provider level", () => {+ expect(normalizeReasoningForProvider("minimal", ["low", "medium", "high"])).toBe("low");+ expect(normalizeReasoningForProvider("high", ["low", "medium", "high"])).toBe("high");+ });+it("creates a provider for any pi-ai supported provider", () => {const provider = createPiProvider({ provider: "anthropic", model: "claude-opus-4-8" });expect(provider.id).toBe("anthropic");@@ -54,38 +66,773 @@ describe("Providers (pi-ai backed)", () => {expect(provider.id).toBe("google");});- it("removes leading private think blocks from custom-provider content", () => {- const raw = "<think>private chain of thought</think>\n\nUser-facing result";- expect(mapContentForTest([{ type: "text", text: raw }], { stripLeadingThinkText: true }))- .toEqual([{ type: "text", text: "User-facing result" }]);- expect(mapContentForTest([{ type: "text", text: raw }]))- .toEqual([{ type: "text", text: raw }]);+ it("leaves DeepSeek thinking and effort at their official defaults", async () => {+ let capturedPayload: Record<string, unknown> | undefined;+ const model: Model<"openai-completions"> = {+ id: "deepseek-v4-flash",+ name: "DeepSeek V4 Flash",+ api: "openai-completions",+ provider: "deepseek" as any,+ baseUrl: "https://api.deepseek.com/v1",+ reasoning: true,+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 1_048_576,+ maxTokens: 16_384,+ };+ const provider = createPiProvider({+ provider: "deepseek",+ apiKey: "test",+ customModel: model,+ onPayload: (payload) => {+ capturedPayload = payload as Record<string, unknown>;+ throw new Error("payload captured before network");+ },+ });++ await expect(provider.complete({+ model: model.id,+ messages: [{ role: "user", content: [{ type: "text", text: "read the file" }] }],+ tools: [{+ name: "read_file",+ description: "Read a file",+ inputSchema: {+ type: "object",+ properties: { path: { type: "string" } },+ required: ["path"],+ },+ }],+ })).rejects.toThrow(/payload captured before network/);++ expect(capturedPayload).toMatchObject({+ tools: [{+ type: "function",+ function: { name: "read_file" },+ }],+ });+ expect(capturedPayload).not.toHaveProperty("thinking");+ expect(capturedPayload).not.toHaveProperty("reasoning_effort");++ capturedPayload = undefined;+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});+ for await (const _event of provider.stream({+ model: model.id,+ messages: [{ role: "user", content: [{ type: "text", text: "read the file" }] }],+ tools: [{+ name: "read_file",+ description: "Read a file",+ inputSchema: {+ type: "object",+ properties: { path: { type: "string" } },+ required: ["path"],+ },+ }],+ })) {+ // The payload hook intentionally aborts before network I/O.+ }+ const warningText = warning.mock.calls.flat().join(" ");+ warning.mockRestore();+ expect(warningText).toContain("payload captured before network");+ expect(capturedPayload).toMatchObject({+ tools: [{ type: "function", function: { name: "read_file" } }],+ });+ expect(capturedPayload).not.toHaveProperty("thinking");+ expect(capturedPayload).not.toHaveProperty("reasoning_effort");});- it("suppresses consecutive leading think blocks split across deltas", () => {+ it("preserves explicit DeepSeek off and effort choices on complete and stream", async () => {+ const model: Model<"openai-completions"> = {+ id: "deepseek-v4-flash",+ name: "DeepSeek V4 Flash",+ api: "openai-completions",+ provider: "deepseek" as any,+ baseUrl: "https://api.deepseek.com/v1",+ reasoning: true,+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 1_048_576,+ maxTokens: 16_384,+ };+ const payloads: Record<string, unknown>[] = [];+ const provider = createPiProvider({+ provider: "deepseek",+ apiKey: "test",+ customModel: model,+ onPayload: (payload) => {+ payloads.push(payload as Record<string, unknown>);+ throw new Error("payload captured before network");+ },+ });+ const base = {+ model: model.id,+ messages: [{ role: "user" as const, content: [{ type: "text" as const, text: "answer" }] }],+ };++ await expect(provider.complete({ ...base, reasoning: "off" }))+ .rejects.toThrow(/payload captured before network/);+ await expect(provider.complete({ ...base, reasoning: "high" }))+ .rejects.toThrow(/payload captured before network/);++ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});+ for await (const _event of provider.stream({ ...base, reasoning: "off" })) {+ // The payload hook intentionally aborts before network I/O.+ }+ for await (const _event of provider.stream({ ...base, reasoning: "high" })) {+ // The payload hook intentionally aborts before network I/O.+ }+ const warningText = warning.mock.calls.map((call) => call.join(" "));+ warning.mockRestore();+ expect(warningText).toHaveLength(2);+ expect(warningText.every((line) => line.includes("payload captured before network"))).toBe(true);++ expect(payloads[0]).toMatchObject({ thinking: { type: "disabled" } });+ expect(payloads[1]).toMatchObject({+ thinking: { type: "enabled" },+ reasoning_effort: "high",+ });+ expect(payloads[2]).toMatchObject({ thinking: { type: "disabled" } });+ expect(payloads[3]).toMatchObject({+ thinking: { type: "enabled" },+ reasoning_effort: "high",+ });+ });++ it("removes only adapter-synthesized off controls across reasoning protocols", () => {+ const baseModel = {+ id: "reasoner",+ name: "Reasoner",+ api: "openai-completions" as const,+ provider: "test" as any,+ baseUrl: "https://example.test/v1",+ reasoning: true,+ input: ["text" as const],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 100_000,+ maxTokens: 10_000,+ };++ expect(restoreOfficialReasoningDefaultsForTest(+ { thinking: { type: "disabled" }, messages: [] },+ { ...baseModel, compat: { thinkingFormat: "deepseek" } },+ )).toEqual({ messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ { enable_thinking: false, messages: [] },+ { ...baseModel, compat: { thinkingFormat: "qwen" } },+ )).toEqual({ messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ { reasoning: { effort: "none", summary: "auto" }, messages: [] },+ { ...baseModel, compat: { thinkingFormat: "openrouter" } },+ )).toEqual({ reasoning: { summary: "auto" }, messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ { reasoning: { effort: "none", summary: "auto" }, messages: [] },+ { ...baseModel, api: "openai-responses" },+ )).toEqual({ reasoning: { summary: "auto" }, messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ { reasoning: { enabled: false, max_tokens: 512 }, messages: [] },+ { ...baseModel, compat: { thinkingFormat: "together" } },+ )).toEqual({ reasoning: { max_tokens: 512 }, messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ {+ chat_template_kwargs: { enable_reasoning: false, retain_context: true },+ messages: [],+ },+ {+ ...baseModel,+ compat: {+ thinkingFormat: "chat-template",+ chatTemplateKwargs: {+ enable_reasoning: { $var: "thinking.enabled" },+ retain_context: true,+ },+ },+ },+ )).toEqual({ chat_template_kwargs: { retain_context: true }, messages: [] });+ expect(restoreOfficialReasoningDefaultsForTest(+ { thinking: { type: "enabled" }, reasoning_effort: "high" },+ { ...baseModel, compat: { thinkingFormat: "deepseek" } },+ )).toEqual({ thinking: { type: "enabled" }, reasoning_effort: "high" });++ const nonReasoningPayload = { thinking: { type: "disabled" }, messages: [] };+ expect(restoreOfficialReasoningDefaultsForTest(+ nonReasoningPayload,+ { ...baseModel, reasoning: false, compat: { thinkingFormat: "deepseek" } },+ )).toBe(nonReasoningPayload);+ });++ it("does not rewrite payload controls for non-reasoning models", async () => {+ let capturedPayload: Record<string, unknown> | undefined;+ const provider = createPiProvider({+ provider: "openai",+ model: "gpt-4o",+ apiKey: "test",+ onPayload: (payload) => {+ capturedPayload = payload as Record<string, unknown>;+ throw new Error("payload captured before network");+ },+ });++ await expect(provider.complete({+ model: "gpt-4o",+ messages: [{ role: "user", content: [{ type: "text", text: "answer" }] }],+ temperature: 0.25,+ })).rejects.toThrow(/payload captured before network/);++ expect(capturedPayload).toMatchObject({ temperature: 0.25 });+ expect(capturedPayload).not.toHaveProperty("thinking");+ expect(capturedPayload).not.toHaveProperty("reasoning");+ expect(capturedPayload).not.toHaveProperty("reasoning_effort");+ });++ it("preserves official default toggles for built-in reasoning providers", async () => {+ async function capture(providerId: string, modelId: string): Promise<Record<string, any>> {+ let payload: Record<string, any> | undefined;+ const provider = createPiProvider({+ provider: providerId,+ model: modelId,+ apiKey: "test",+ onPayload: (value) => {+ payload = value as Record<string, any>;+ throw new Error("payload captured before network");+ },+ });+ await expect(provider.complete({+ model: modelId,+ messages: [{ role: "user", content: [{ type: "text", text: "answer" }] }],+ })).rejects.toThrow(/payload captured before network/);+ return payload!;+ }++ const openai = await capture("openai", "gpt-5.1");+ const anthropic = await capture("anthropic", "claude-haiku-4-5");+ const google = await capture("google", "gemini-2.5-flash");+ const openrouter = await capture("openrouter", "aion-labs/aion-2.0");+ const zai = await capture("zai", "glm-4.7");+ const qwen = await capture("qwen-token-plan", "deepseek-v4-flash");+ const together = await capture("together", "MiniMaxAI/MiniMax-M3");++ expect(openai).not.toHaveProperty("reasoning");+ expect(anthropic).not.toHaveProperty("thinking");+ expect(google.config).not.toHaveProperty("thinkingConfig");+ expect(openrouter).not.toHaveProperty("reasoning");+ expect(zai).not.toHaveProperty("thinking");+ expect(qwen).not.toHaveProperty("enable_thinking");+ expect(together).not.toHaveProperty("reasoning");+ });++ it("prefers the actual upstream response model over the logical request model", () => {+ expect(resolvedResponseModelForTest(+ { model: "orkas-llm-1.0", responseModel: "deepseek-v4-pro" },+ "orkas-llm-1.0",+ )).toBe("deepseek-v4-pro");+ expect(resolvedResponseModelForTest(+ { model: "orkas-llm-1.0" },+ "fallback",+ )).toBe("orkas-llm-1.0");+ });++ it("decodes only bounded Orkas Server fallback response markers", () => {+ const cases = {+ pro_rate_limited: "rate_limited",+ pro_transport_error: "transport_error",+ pro_configuration_error: "configuration_error",+ pro_not_configured: "not_configured",+ pro_upstream_error: "upstream_error",+ pro_empty_response: "empty_response",+ pro_unavailable: "unavailable",+ } as const;+ for (const [marker, expected] of Object.entries(cases)) {+ expect(serverFallbackReasonFromResponseIdForTest(`orkas-fallback:${marker}`))+ .toBe(expected);+ }+ expect(serverFallbackReasonFromResponseIdForTest("orkas-fallback:future_reason"))+ .toBe("unknown");+ expect(serverFallbackReasonFromResponseIdForTest("chatcmpl-normal-id"))+ .toBeUndefined();+ });++ it("classifies native provider termination markers without leaking raw values", () => {+ expect(providerTerminationCategoryForTest("STOP", "stop")).toBe("normal");+ expect(providerTerminationCategoryForTest("completed", "stop")).toBe("normal");+ expect(providerTerminationCategoryForTest("MAX_TOKENS", "length")).toBe("length");+ expect(providerTerminationCategoryForTest("content_filter", "stop")).toBe("safety");+ expect(providerTerminationCategoryForTest("SAFETY", "stop")).toBe("safety");+ expect(providerTerminationCategoryForTest("sensitive", "stop")).toBe("safety");+ expect(providerTerminationCategoryForTest("future_provider_reason", "stop")).toBe("unknown");+ expect(providerTerminationCategoryForTest(undefined, "stop")).toBe("normal");+ expect(providerTerminationCategoryForTest(undefined, "length")).toBe("length");+ });++ it("does not silently fall back when an explicit model id is unknown", async () => {+ const provider = createPiProvider({ provider: "kimi-coding", apiKey: "test" });+ await expect(async () => {+ for await (const _ of provider.stream({+ model: "not-in-pi-ai-catalog",+ messages: [],+ })) {+ // resolveModel fails before any provider request is made.+ }+ }).rejects.toThrow(/No model found for provider: kimi-coding, model: not-in-pi-ai-catalog/);+ });++ it("replays tool results with the original tool name for Gemini function responses", () => {+ const messages: Message[] = [+ { role: "user", content: [{ type: "text", text: "list files" }] },+ {+ role: "assistant",+ content: [{ type: "tool_use", id: "call_1", name: "list_files", input: { path: "." } }],+ },+ {+ role: "user",+ content: [{ type: "tool_result", toolUseId: "call_1", content: "E_LIST_FAILED", isError: true }],+ },+ ];++ const context = buildPiContextForTest(messages);+ const toolResult = context.messages.find((message) => message.role === "toolResult") as+ | { role: "toolResult"; toolCallId: string; toolName: string; isError?: boolean }+ | undefined;++ expect(toolResult).toMatchObject({+ role: "toolResult",+ toolCallId: "call_1",+ toolName: "list_files",+ isError: true,+ });+ });++ it("passes runtime tool additions to native deferred-tool providers", () => {+ const messages: Message[] = [+ {+ role: "assistant",+ content: [{ type: "tool_use", id: "load-1", name: "tool_load", input: { groups: ["web"] } }],+ },+ {+ role: "user",+ content: [{+ type: "tool_result",+ toolUseId: "load-1",+ content: "loaded",+ addedToolNames: ["web_search"],+ }],+ },+ ];++ const context = buildPiContextForTest(messages);+ const toolResult = context.messages.find((message) => message.role === "toolResult");++ expect(toolResult).toMatchObject({+ role: "toolResult",+ toolCallId: "load-1",+ toolName: "tool_load",+ addedToolNames: ["web_search"],+ });+ });++ it("serializes a loaded GPT tool at the native transcript insertion point", async () => {+ let capturedPayload: Record<string, any> | undefined;+ const model: Model<"openai-responses"> = {+ id: "gpt-5.6",+ name: "GPT-5.6",+ api: "openai-responses",+ provider: "openai" as any,+ baseUrl: "https://api.openai.com/v1",+ reasoning: true,+ compat: { supportsToolSearch: true },+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 1_000_000,+ maxTokens: 128_000,+ };+ const provider = createPiProvider({+ provider: "openai",+ apiKey: "test",+ customModel: model,+ onPayload: (payload) => {+ capturedPayload = payload as Record<string, any>;+ throw new Error("payload captured before network");+ },+ });++ await expect(provider.complete({+ model: model.id,+ messages: [+ {+ role: "assistant",+ content: [{ type: "tool_use", id: "load-1", name: "tool_load", input: { groups: ["web"] } }],+ },+ {+ role: "user",+ content: [{+ type: "tool_result",+ toolUseId: "load-1",+ content: "loaded",+ addedToolNames: ["web_search"],+ }],+ },+ ],+ tools: [+ { name: "tool_load", description: "Load tools", inputSchema: { type: "object" } },+ { name: "web_search", description: "Search", inputSchema: { type: "object" } },+ ],+ })).rejects.toThrow(/payload captured before network/);++ expect(capturedPayload?.tools).toEqual([+ expect.objectContaining({ type: "function", name: "tool_load" }),+ ]);+ const searchOutput = capturedPayload?.input?.find((item: any) => item.type === "tool_search_output");+ expect(searchOutput).toMatchObject({+ execution: "client",+ status: "completed",+ tools: [expect.objectContaining({+ type: "function",+ name: "web_search",+ defer_loading: true,+ })],+ });+ });++ it("preserves structured tool schemas when adapting them to pi-ai", () => {+ const inputSchema = {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["update", "set_status"],+ },+ decision_evidence: {+ type: "object",+ properties: {+ source: { type: "string", enum: ["user_message"] },+ decision: { type: "string", enum: ["approve", "revise", "reject"] },+ },+ required: ["source", "decision"],+ },+ plan: {+ type: "array",+ items: {+ type: "object",+ properties: {+ step: { type: "string" },+ status: { type: "string", enum: ["pending", "in_progress", "completed"] },+ },+ required: ["step", "status"],+ },+ },+ value: {+ description: "A string or numeric value.",+ oneOf: [{ type: "string" }, { type: "number" }],+ },+ },+ required: ["action", "decision_evidence", "plan"],+ };++ const context = buildPiContextForTest([], undefined, [{+ name: "structured_tool",+ description: "Exercise nested tool inputs.",+ inputSchema,+ }]);+ const parameters = context.tools?.[0]?.parameters as Record<string, any>;++ expect(parameters).toMatchObject(inputSchema);+ expect(parameters.properties.decision_evidence).toMatchObject({+ type: "object",+ required: ["source", "decision"],+ });+ expect(parameters.properties.plan.items).toMatchObject({+ type: "object",+ required: ["step", "status"],+ });+ });++ it("round-trips Gemini tool call thought signatures for replay", () => {+ const messages: Message[] = [+ {+ role: "assistant",+ content: [+ {+ type: "tool_use",+ id: "call_1",+ name: "list_files",+ input: { path: "." },+ thoughtSignature: "QUJDRA==",+ },+ ],+ },+ ];++ const context = buildPiContextForTest(+ messages,+ undefined,+ undefined,+ { api: "google-generative-ai", provider: "google", id: "gemini-3.5-flash" },+ );+ const assistant = context.messages.find((message) => message.role === "assistant") as+ | { role: "assistant"; content: Array<{ type: string; thoughtSignature?: string }> }+ | undefined;++ expect(assistant?.content[0]).toMatchObject({+ type: "toolCall",+ thoughtSignature: "QUJDRA==",+ });+ });++ it("preserves Gemini tool call thought signatures from provider responses", () => {+ const content = mapContentForTest([+ {+ type: "toolCall",+ id: "call_1",+ name: "list_files",+ arguments: { path: "." },+ thoughtSignature: "QUJDRA==",+ },+ ]);++ expect(content[0]).toMatchObject({+ type: "tool_use",+ id: "call_1",+ name: "list_files",+ thoughtSignature: "QUJDRA==",+ });+ });++ it("removes a complete leading think block at every provider boundary", () => {+ const providerText = "<think>private chain of thought</think>\n\nUser-facing result";+ const content = mapProviderContentForTest([+ {+ type: "text",+ text: providerText,+ },+ ]);++ expect(content).toEqual([{ type: "text", text: "User-facing result" }]);+ // The low-level mapper remains opt-in for replay and conversion callers;+ // only provider output crosses the mandatory privacy boundary.+ expect(mapContentForTest([{ type: "text", text: providerText }]))+ .toEqual([{ type: "text", text: providerText }]);expect(stripLeadingThinkTextForTest(- "<think>first</think>\n<think>second</think>\nVisible result",+ " <think>private chain of thought</think>\nAnswer",+ )).toBe("Answer");+ expect(stripLeadingThinkTextForTest("<think>unfinished private reasoning"))+ .toBe("");+ });++ it("suppresses a leading think block split across streaming deltas", () => {+ const filter = createLeadingThinkTextFilterForTest();++ expect(filter.push("\n<th")).toBe("");+ expect(filter.push("ink>private reasoning")).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: true,+ chars: "private reasoning".length,+ text: "private reasoning",+ ended: false,+ });+ expect(filter.push(" continues</thi")).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: false,+ chars: " continues".length,+ text: " continues",+ ended: false,+ });+ expect(filter.push("nk>\n\nVisible")).toBe("Visible");+ expect(filter.takeThinkingActivity()).toEqual({+ started: false,+ chars: 0,+ text: "",+ ended: true,+ });+ expect(filter.push(" answer")).toBe(" answer");+ expect(filter.finish()).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: false,+ chars: 0,+ text: "",+ ended: false,+ });+ });++ it("suppresses consecutive leading think blocks, including a split second opening tag", () => {+ expect(stripLeadingThinkTextForTest(+ "<think>first private thought</think>\n<think>second private thought</think>\nVisible result",)).toBe("Visible result");+const filter = createLeadingThinkTextFilterForTest();- expect(filter.push("<think>first</think>\n<th")).toBe("");- expect(filter.push("ink>second</thi")).toBe("");+ expect(filter.push("<think>first private thought</think>\n<th")).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: true,+ chars: "first private thought".length,+ text: "first private thought",+ ended: true,+ });+ expect(filter.push("ink>second private thought</thi")).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: true,+ chars: "second private thought".length,+ text: "second private thought",+ ended: false,+ });expect(filter.push("nk>\nVisible result")).toBe("Visible result");+ expect(filter.takeThinkingActivity()).toEqual({+ started: false,+ chars: 0,+ text: "",+ ended: true,+ });expect(filter.finish()).toBe("");});- it("preserves non-leading and partial think-tag lookalikes", () => {- for (const text of [+ it("preserves a second-tag lookalike after suppressing a real leading think block", () => {+ expect(stripLeadingThinkTextForTest(+ "<think>private thought</think>\n<thinker>visible element</thinker>",+ )).toBe("<thinker>visible element</thinker>");++ const filter = createLeadingThinkTextFilterForTest();+ expect(filter.push("<think>private thought</think>\n<thin")).toBe("");+ expect(filter.finish()).toBe("<thin");+ });++ it("reports an unterminated leading think block through EOF without exposing answer text", () => {+ const filter = createLeadingThinkTextFilterForTest();++ expect(filter.push("<think>unfinished private reasoning")).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: true,+ chars: "unfinished private reasoning".length,+ text: "unfinished private reasoning",+ ended: false,+ });+ expect(filter.finish()).toBe("");+ expect(filter.takeThinkingActivity()).toEqual({+ started: false,+ chars: 0,+ text: "",+ ended: true,+ });+ });++ it("preserves inline, fenced, similar, and partial think-tag lookalikes", () => {+ const lookalikes = ["Answer with an inline <think> example",+ "```xml\n<think>example</think>\n```","<thinker>visible element</thinker>","\n<thin",- ]) {+ ];++ for (const text of lookalikes) {expect(stripLeadingThinkTextForTest(text)).toBe(text);}- const afterBlock = createLeadingThinkTextFilterForTest();- expect(afterBlock.push("<think>private</think>\n<thin")).toBe("");- expect(afterBlock.finish()).toBe("<thin");});+ it("drops a non-JSON reasoning signature when history moves to an OpenAI Responses model", () => {+ const messages: Message[] = [{+ role: "assistant",+ content: [{+ type: "thinking",+ thinking: "private prior-model reasoning",+ thinkingSignature: "reasoning_content",+ }],+ }];++ const context = buildPiContextForTest(+ messages,+ undefined,+ undefined,+ { api: "openai-responses", provider: "openai", id: "gpt-5.5" },+ );+ const assistant = context.messages.find((message) => message.role === "assistant") as+ | { role: "assistant"; content: Array<{ type: string; thinking?: string; thinkingSignature?: string }> }+ | undefined;++ expect(assistant?.content[0]).toMatchObject({+ type: "thinking",+ thinking: "private prior-model reasoning",+ });+ expect(assistant?.content[0]).not.toHaveProperty("thinkingSignature");+ });++ it("preserves a Responses-compatible reasoning signature on the next model turn", () => {+ const signature = JSON.stringify({ type: "reasoning", id: "rs_123" });+ const messages: Message[] = [{+ role: "assistant",+ content: [{+ type: "thinking",+ thinking: "compatible reasoning",+ thinkingSignature: signature,+ }],+ }];++ const context = buildPiContextForTest(+ messages,+ undefined,+ undefined,+ { api: "openai-responses", provider: "openai", id: "gpt-5.5" },+ );+ const assistant = context.messages.find((message) => message.role === "assistant") as+ | { role: "assistant"; content: Array<{ type: string; thinkingSignature?: string }> }+ | undefined;++ expect(assistant?.content[0]).toMatchObject({+ type: "thinking",+ thinkingSignature: signature,+ });+ });++ it("does not emit provider tool results when the matching tool_use is absent", () => {+ const messages: Message[] = [+ {+ role: "user",+ content: [{ type: "tool_result", toolUseId: "missing_call", content: "orphan", isError: true }],+ },+ ];++ const context = buildPiContextForTest(messages);++ expect(context.messages.some((message) => message.role === "toolResult")).toBe(false);+ });++ it("serializes generic visual-analysis intent immediately before each image", () => {+ const messages: Message[] = [{+ role: "user",+ content: [+ { type: "image", data: "page-one", mediaType: "image/png", analysisMode: "quality_review" },+ { type: "image", data: "page-two", mediaType: "image/png", analysisMode: "understand" },+ ],+ }];++ const context = buildPiContextForTest(messages);+ const user = context.messages[0] as {+ role: "user";+ content: Array<{ type: string; text?: string; data?: string }>;+ };++ expect(user.content).toEqual([+ { type: "text", text: '<orkas_visual_analysis mode="quality_review"/>' },+ { type: "image", data: "page-one", mimeType: "image/png" },+ { type: "text", text: '<orkas_visual_analysis mode="understand"/>' },+ { type: "image", data: "page-two", mimeType: "image/png" },+ ]);+ });++ it("omits malformed empty-name tool calls and their tool results", () => {+ const messages: Message[] = [+ {+ role: "assistant",+ content: [{ type: "tool_use", id: "call_1", name: "", input: { path: "." } } as MessageContent],+ },+ {+ role: "user",+ content: [{ type: "tool_result", toolUseId: "call_1", content: "E_LIST_FAILED", isError: true }],+ },+ ];++ const context = buildPiContextForTest(messages);++ expect(context.messages.some((message) => message.role === "assistant")).toBe(false);+ expect(context.messages.some((message) => {+ return message.role === "assistant" && message.content.some((part) => part.type === "toolCall");+ })).toBe(false);+ expect(context.messages.some((message) => message.role === "toolResult")).toBe(false);+ });});describe("listPiProviders / listPiModels", () => {diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex 6e6a422c..5c06c0c8 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -76,6 +76,7 @@ import {curatedModelsFor,isSelectableModel,resolveConfiguredPiModel,+ resolveModelUpgrade,providerLabel,providerLabelKey,providerDocsUrl,@@ -93,6 +94,7 @@ import { isCooledDown, getCooldown, clearCooldown } from '../model/core-agent/primport type { KeyFailureKind } from '../model/core-agent/auth-error';import { createLogger } from '../logger';import { t } from '../i18n';+import { logErrorSummary } from '../util/log-redact';import { sanitizeLogTextForUpload } from '../util/log-sanitize';import {ORKAS_API_BASE_URL,@@ -165,7 +167,6 @@ export async function warmup(): Promise<void> {// ── File paths ───────────────────────────────────────────────────────────function profilesFile(): string { return userAuthProfilesFile(getActiveUserId()); }-function authDir(): string { return userLocalConfigDir(getActiveUserId()); }// Legacy compat for tests/callers that expect this shape.export const FEATURED_PROVIDERS: readonly string[] =@@ -298,8 +299,7 @@ const AUTH_SECRET_RECORD_ID = 'auth-profiles.json';// ── Profiles store IO ────────────────────────────────────────────────────-function ensureAuthDir(): void {- const d = authDir();+function ensureAuthDir(d: string): void {if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });}@@ -357,7 +357,7 @@ function decryptProfilesPayload(raw: string, localId: string): { json: string; nthrow new Error('auth-profiles decrypt failed');}-function loadProfiles(): ProfilesFile {+function loadProfiles(opts: { throwOnInvalidExisting?: boolean } = {}): ProfilesFile {try {const raw = fs.readFileSync(profilesFile(), 'utf-8');// Decrypt current Hosted/Open fallback payloads, or the previous crypto-vault whole-file@@ -389,29 +389,57 @@ function loadProfiles(): ProfilesFile {lastUsed: typeof prof.lastUsed === 'number' ? prof.lastUsed : 0,} as StoredProfile;}- const entries: Entry[] = Array.isArray(data.entries)- ? data.entries- .filter((e: any) => e && e.entryId && e.provider && e.model && e.profileId)- .map((e: any) => ({- entryId: String(e.entryId),- provider: String(e.provider),- model: String(e.model),- profileId: String(e.profileId),- lastUsed: typeof e.lastUsed === 'number' ? e.lastUsed : 0,- createdAt: typeof e.createdAt === 'number' ? e.createdAt : Date.now(),- }))- : [];+ const entries: Entry[] = [];+ const seenEntryKeys = new Set<string>();+ if (Array.isArray(data.entries)) {+ for (const e of data.entries as any[]) {+ if (!e || !e.entryId || !e.provider || !e.model || !e.profileId) continue;+ const provider = String(e.provider);+ const upgraded = resolveModelUpgrade(provider, String(e.model));+ if (upgraded.upgraded) {+ shouldRewrite = true;+ log.info('upgraded saved model entry', {+ provider,+ from: upgraded.previousModelId,+ to: upgraded.modelId,+ });+ }+ const entry: Entry = {+ entryId: String(e.entryId),+ provider,+ model: upgraded.modelId,+ profileId: String(e.profileId),+ lastUsed: typeof e.lastUsed === 'number' ? e.lastUsed : 0,+ createdAt: typeof e.createdAt === 'number' ? e.createdAt : Date.now(),+ };+ const key = `${entry.provider}::${entry.model}::${entry.profileId}`;+ if (seenEntryKeys.has(key)) {+ shouldRewrite = true;+ continue;+ }+ seenEntryKeys.add(key);+ entries.push(entry);+ }+ }const searchProfiles = parseSearchProfilesArray((data as any).searchProfiles);const imageProfiles = parseImageProfilesArray((data as any).imageProfiles);const videoProfiles = parseVideoProfilesArray((data as any).videoProfiles);const ttsProfiles = parseTtsProfilesArray((data as any).ttsProfiles);const store = { version: PROFILES_FILE_VERSION, profiles, entries, searchProfiles, imageProfiles, videoProfiles, ttsProfiles };- if (shouldRewrite || Number((data as any).version) !== PROFILES_FILE_VERSION) saveProfiles(store);+ if (shouldRewrite || Number((data as any).version) !== PROFILES_FILE_VERSION) {+ try { saveProfiles(store); }+ catch (err) {+ // Migration is best-effort: a valid parsed store remains usable when disk writes fail.+ log.warn('auth profiles migration rewrite failed; using parsed store', { error: logErrorSummary(err) });+ }+ }return store;}+ throw new Error('auth-profiles schema invalid');} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {- log.warn('failed to load profiles store:', (err as Error).message);+ log.warn('failed to load profiles store', { error: logErrorSummary(err) });+ if (opts.throwOnInvalidExisting) throw err;}}return { version: PROFILES_FILE_VERSION, profiles: {}, entries: [], searchProfiles: [], imageProfiles: [], videoProfiles: [], ttsProfiles: [] };@@ -478,7 +506,7 @@ function parseTtsProfilesArray(arr: unknown): TtsProfile[] {const out: TtsProfile[] = [];for (const raw of arr) {const p = raw as any;- if (!p || typeof p !== 'object' || !p.id || !p.provider || !p.apiKey) continue;+ if (!p || typeof p !== 'object' || !p.id || !p.apiKey) continue;const provider = String(p.provider || 'custom');if (provider === 'orkas-voice') continue;if (provider !== 'doubao' && !p.baseUrl) continue;@@ -512,7 +540,7 @@ export function loadSearchProfiles(): SearchProfile[] {}export function saveSearchProfiles(list: SearchProfile[]): void {- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });store.searchProfiles = [...list];saveProfiles(store);}@@ -522,7 +550,7 @@ export function loadImageProfiles(): ImageProfile[] {}export function saveImageProfiles(list: ImageProfile[]): void {- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });store.imageProfiles = [...list];saveProfiles(store);}@@ -532,7 +560,7 @@ export function loadVideoProfiles(): VideoProfile[] {}export function saveVideoProfiles(list: VideoProfile[]): void {- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });store.videoProfiles = [...list];saveProfiles(store);}@@ -542,7 +570,7 @@ export function loadTtsProfiles(): TtsProfile[] {}export function saveTtsProfiles(list: TtsProfile[]): void {- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });store.ttsProfiles = [...list];saveProfiles(store);}@@ -574,7 +602,7 @@ export function configureAllOrkasApiServices(rawApiKey: string): { configured: tconst apiKey = String(rawApiKey || '').trim();if (!apiKey) throw new Error('api key required');- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const now = Date.now();const existingProfileEntries = Object.entries(store.profiles).filter(([, profile]) => profile.provider === ORKAS_API_PROVIDER);@@ -675,12 +703,26 @@ export function configureAllOrkasApiServices(rawApiKey: string): { configured: t}function saveProfiles(store: ProfilesFile): void {- ensureAuthDir();- const json = JSON.stringify(store, null, 2);const localId = getActiveUserId();+ const target = userAuthProfilesFile(localId);+ const targetDir = path.dirname(target);+ const tmp = `${target}.tmp`;const ownerId = authSecretOwner(localId);+ const json = JSON.stringify(store, null, 2);const out = ownerId ? localSecrets.encryptLocalSecret(authSecretContext(ownerId), json) : json;- fs.writeFileSync(profilesFile(), out, { encoding: 'utf-8', mode: 0o600 });+ // Capture one account and atomically publish its complete encrypted store.+ // Retry a disappearing directory/temp path once; preserve the original on failure.+ for (let attempt = 0; attempt < 2; attempt += 1) {+ try {+ ensureAuthDir(targetDir);+ fs.writeFileSync(tmp, out, { encoding: 'utf-8', mode: 0o600 });+ fs.renameSync(tmp, target);+ return;+ } catch (err) {+ try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup */ }+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT' || attempt > 0) throw err;+ }+ }}function isStoredProfileBlocked(profile: StoredProfile | undefined): boolean {@@ -900,6 +942,19 @@ export function getConfiguredModelCooldown(): {}export function getConfiguredModelOAuthExpiredMessage(): string | null {+ const store = loadProfiles();+ const now = Date.now();+ for (const entry of store.entries) {+ if (!isEntryAllowed(store, entry)) continue;+ const prof = store.profiles[entry.profileId];+ if (!prof || prof.type !== 'oauth') continue;+ if (now < prof.expires) {+ clearOAuthRefreshFailure(entry.profileId);+ continue;+ }+ if (!oauthRefreshFailures.has(entry.profileId) && prof.refresh) continue;+ return t('errors.model_oauth_expired', { provider: providerLabel(prof.provider) });+ }return null;}@@ -1120,7 +1175,7 @@ export async function addApiKey(if (providerUsesCustomOpenAIConfig(id)) {throw customConfigError('CUSTOM_CONFIG_REQUIRED', 'Use the custom model configuration flow');}- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const chosenLabel = label ? sanitizeLabel(label) : autoLabel(store, id);const profileId = makeProfileId(id, chosenLabel);const now = Date.now();@@ -1150,7 +1205,7 @@ export async function addApiKeyEntry(label?: string,): Promise<{ profileId: string; entryId: string }> {const id = String(providerId || '').trim();- const model = String(modelId || '').trim();+ const model = resolveModelUpgrade(id, String(modelId || '').trim()).modelId;const key = String(apiKey || '').trim();if (!id) throw new Error('provider required');if (!model) throw new Error('model required');@@ -1161,7 +1216,7 @@ export async function addApiKeyEntry(}await assertRuntimeSelectableModel(id, model);- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const chosenLabel = label ? sanitizeLabel(label) : autoLabel(store, id);const profileId = makeProfileId(id, chosenLabel);const now = Date.now();@@ -1254,7 +1309,7 @@ export async function addCustomModelEntry();}- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const chosenLabel = rawLabel? sanitizeCustomLabel(rawLabel): autoLabel(store, CUSTOM_MODEL_PROVIDER);@@ -1303,7 +1358,7 @@ export async function addCustomModelEntry(export async function removeCredential(profileId: string): Promise<{ removed: boolean }> {const id = String(profileId || '').trim();if (!id) throw new Error('profileId required');- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });if (!store.profiles[id]) return { removed: false };delete store.profiles[id];// Cascade: any entry referencing this profile is now dangling; drop those@@ -1321,7 +1376,7 @@ export async function renameProfile(const id = String(profileId || '').trim();const label = sanitizeLabel(newLabel);if (!id) throw new Error('profileId required');- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const prof = store.profiles[id];if (!prof) throw new Error('profile not found');const newId = makeProfileId(prof.provider, label);@@ -1451,12 +1506,12 @@ export async function addEntry({profileId,}: { provider: string; model: string; profileId: string }): Promise<{ entryId: string }> {const p = String(provider || '').trim();- const m = String(model || '').trim();+ const m = resolveModelUpgrade(p, String(model || '').trim()).modelId;const pid = String(profileId || '').trim();if (!p || !m || !pid) throw new Error('provider / model / profileId required');assertModelProviderAllowed(p, m);await assertRuntimeSelectableModel(p, m);- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });if (!store.profiles[pid]) throw new Error('profile not found');if (store.profiles[pid].provider !== p) throw new Error('profile does not belong to provider');@@ -1483,11 +1538,15 @@ export async function addEntry({export async function updateEntryModel(entryId: string, model: string): Promise<{ entryId: string; model: string }> {const id = String(entryId || '').trim();- const m = String(model || '').trim();- if (!id || !m) throw new Error('entryId and model required');- const store = loadProfiles();+ const rawModel = String(model || '').trim();+ if (!id || !rawModel) throw new Error('entryId and model required');+ const store = loadProfiles({ throwOnInvalidExisting: true });const target = store.entries.find((e) => e.entryId === id);if (!target) throw new Error('entry not found');+ const m = resolveModelUpgrade(target.provider, rawModel).modelId;+ if (providerUsesCustomOpenAIConfig(target.provider) && m !== target.model) {+ throw new Error('custom endpoint model is fixed');+ }assertModelProviderAllowed(target.provider, m);await assertRuntimeSelectableModel(target.provider, m);// Deduplicate: if another entry with the same (provider, model, profileId)@@ -1505,7 +1564,7 @@ export async function updateEntryModel(entryId: string, model: string): Promise<export async function removeEntry(entryId: string): Promise<{ removed: boolean }> {const id = String(entryId || '').trim();if (!id) throw new Error('entryId required');- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const before = store.entries.length;store.entries = store.entries.filter((e) => e.entryId !== id);if (store.entries.length === before) return { removed: false };@@ -1516,7 +1575,7 @@ export async function removeEntry(entryId: string): Promise<{ removed: boolean }export async function reorderEntries(orderedIds: string[]): Promise<{ entries: EntryView[] }> {if (!Array.isArray(orderedIds)) throw new Error('orderedIds must be an array');- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const runtimeResolvable = await buildRuntimeModelResolver(store.entries);const byId = new Map(store.entries.map((e) => [e.entryId, e]));const reordered: Entry[] = [];@@ -1545,18 +1604,53 @@ export async function reorderEntries(orderedIds: string[]): Promise<{ entries: E* different model for that same user-owned credential first. */export async function selectEntry(entryId: string,- model?: string,+ requestedModel?: string,): Promise<{ entries: EntryView[] }> {const id = String(entryId || '').trim();if (!id) throw new Error('entryId required');- const requestedModel = String(model || '').trim();- if (requestedModel) await updateEntryModel(id, requestedModel);- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const selected = store.entries.find((entry) => entry.entryId === id);- if (!selected) throw new Error('entry not found');- if (!isEntryAllowed(store, selected)) throw modelNotAvailableError();- await assertRuntimeSelectableModel(selected.provider, selected.model);- return reorderEntries([id]);+ if (!selected) throw modelNotAvailableError();++ const rawModel = String(requestedModel || '').trim();+ if (rawModel && rawModel !== selected.model) {+ if (providerUsesCustomOpenAIConfig(selected.provider)) {+ throw new Error('custom endpoint model is fixed');+ }+ const model = resolveModelUpgrade(selected.provider, rawModel).modelId;+ assertModelProviderAllowed(selected.provider, model);+ await assertRuntimeSelectableModel(selected.provider, model);+ const collision = store.entries.find((entry) => (+ entry.entryId !== id+ && entry.provider === selected.provider+ && entry.model === model+ && entry.profileId === selected.profileId+ ));+ if (collision) throw new Error('same (provider, model, profile) entry already exists');+ selected.model = model;+ }+ const runtimeResolvable = await buildRuntimeModelResolver(store.entries);+ if (+ !isEntryAllowed(store, selected)+ || !runtimeResolvable(selected.provider, selected.model)+ ) throw modelNotAvailableError();++ const runnable = store.entries.filter((entry) => (+ isEntryAllowed(store, entry) && runtimeResolvable(entry.provider, entry.model)+ ));+ const ordered = [selected, ...runnable.filter((entry) => entry.entryId !== id)];+ const runnableIds = new Set(runnable.map((entry) => entry.entryId));+ let orderedIndex = 0;+ store.entries = store.entries.map((entry) => (+ runnableIds.has(entry.entryId) ? ordered[orderedIndex++] : entry+ ));+ saveProfiles(store);+ invalidateCoreAgentRunner();++ const lookup = await buildModelNameLookup();+ return { entries: store.entries.filter((entry) => (+ isEntryAllowed(store, entry) && runtimeResolvable(entry.provider, entry.model)+ )).map((entry) => entryToView(entry, store, lookup, true)) };}// ── OAuth flow orchestration ─────────────────────────────────────────────@@ -1668,7 +1762,7 @@ export async function startOAuth(}const flowId = nextFlowId();- const chosenLabel = label ? sanitizeLabel(label) : autoLabel(loadProfiles(), id);+ const chosenLabel = label ? sanitizeLabel(label) : autoLabel(loadProfiles({ throwOnInvalidExisting: true }), id);// Device-code style flows (MiniMax) don't bind a local port — the UI must// hide its "paste callback URL" input in that case.const usesCallbackServer = provider.usesCallbackServer !== false;@@ -1751,7 +1845,7 @@ export async function startOAuth(},}).then((credentials) => {- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });// Prefer a human-identifiable label from the token if the caller// didn't supply one — email local-part, then accountId prefix —// so multi-account rows don't all read "default".@@ -1872,11 +1966,17 @@ async function resolveEntryApiKey(store: ProfilesFile, entry: Entry): Promise<stconst prof = store.profiles[entry.profileId];if (!prof || !isStoredProfileAllowed(prof)) return undefined;if (prof.type === 'api_key') return prof.key;- if (Date.now() < prof.expires) return prof.access;+ if (Date.now() < prof.expires) {+ clearOAuthRefreshFailure(entry.profileId);+ return prof.access;+ }try {- return await refreshOAuthProfile(entry.profileId);+ const refreshed = await refreshOAuthProfile(entry.profileId);+ if (!refreshed) rememberOAuthRefreshFailure(entry.profileId, prof);+ return refreshed;} catch (err) {- log.warn(`OAuth refresh failed for ${entry.profileId}:`, (err as Error).message);+ rememberOAuthRefreshFailure(entry.profileId, prof);+ log.warn('OAuth refresh failed', { profileId: entry.profileId, error: logErrorSummary(err) });return undefined;}}@@ -1929,11 +2029,17 @@ export function listApiKeyEntries(): ApiKeyEntryChoice[] {* clobbering concurrent writes). Safe no-op if the entry disappeared.*/export function bumpEntryLastUsed(entryId: string): void {- const fresh = loadProfiles();- const target = fresh.entries.find((e) => e.entryId === entryId);- if (target) {- target.lastUsed = Date.now();- saveProfiles(fresh);+ try {+ const fresh = loadProfiles({ throwOnInvalidExisting: true });+ const target = fresh.entries.find((e) => e.entryId === entryId);+ if (target) {+ target.lastUsed = Date.now();+ saveProfiles(fresh);+ }+ } catch (err) {+ // Usage bookkeeping is best-effort. Never overwrite an unreadable store,+ // and never fail an otherwise successful model run for this timestamp.+ log.warn('failed to persist model entry usage', { error: logErrorSummary(err) });}}@@ -2033,7 +2139,7 @@ export async function pickRotationKey(providerId: string): Promise<{const id = String(providerId || '').trim();if (!id) return null;if (!isModelProviderAllowed(id)) return null;- const store = loadProfiles();+ const store = loadProfiles({ throwOnInvalidExisting: true });const candidates = Object.entries(store.profiles).filter(([, p]) => p.provider === id).sort(([, a], [, b]) => (a.lastUsed || 0) - (b.lastUsed || 0));@@ -2049,7 +2155,7 @@ export async function pickRotationKey(providerId: string): Promise<{if (!apiKey) continue;const customConfig = customRuntimeConfigFromProfile(prof);if (providerUsesCustomOpenAIConfig(id) && !customConfig) continue;- const fresh = loadProfiles();+ const fresh = loadProfiles({ throwOnInvalidExisting: true });const target = fresh.profiles[pid];if (target) { target.lastUsed = Date.now(); saveProfiles(fresh); }return {@@ -2068,9 +2174,18 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefineconst prof = store.profiles[profileId];if (!prof || prof.type !== 'oauth') return undefined;- const oauth = await piOauth();+ let oauth: PiOauthModule;+ try {+ oauth = await piOauth();+ } catch (err) {+ rememberOAuthRefreshFailure(profileId, prof);+ throw err;+ }const provider = await oauth.getOAuthProvider(prof.provider);- if (!provider) return undefined;+ if (!provider) {+ rememberOAuthRefreshFailure(profileId, prof);+ return undefined;+ }const creds = {access: prof.access,@@ -2082,8 +2197,14 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefine),),};- const newCreds = await provider.refreshToken(creds as any);- const fresh = loadProfiles();+ let newCreds: any;+ try {+ newCreds = await provider.refreshToken(creds as any);+ } catch (err) {+ rememberOAuthRefreshFailure(profileId, prof);+ throw err;+ }+ const fresh = loadProfiles({ throwOnInvalidExisting: true });const target = fresh.profiles[profileId];if (target && target.type === 'oauth') {target.access = newCreds.access;@@ -2096,6 +2217,7 @@ async function refreshOAuthProfile(profileId: string): Promise<string | undefine}saveProfiles(fresh);}+ clearOAuthRefreshFailure(profileId);return provider.getApiKey(newCreds);}@@ -2131,7 +2253,7 @@ export async function testConnection(): Promise<TestConnectionResult> {const pid = String(providerId || '').trim();if (!pid) return { ok: false, error: 'provider required' };- const selectedModel = String(modelId || '').trim() || curatedModelsFor(pid)[0]?.id || '';+ const selectedModel = resolveModelUpgrade(pid, String(modelId || '').trim()).modelId || curatedModelsFor(pid)[0]?.id || '';if (!isModelProviderAllowed(pid, selectedModel || undefined)) {return { ok: false, error: 'DeepSeek is disabled in this build' };}@@ -2259,7 +2381,7 @@ export async function testConnection(} catch (err) {return {ok: false,- error: (err as Error).message || String(err),+ error: sanitizeConnectionError(err, { apiKey }),durationMs: Date.now() - t0,profileId: chosenProfileId,};@@ -2269,3 +2391,12 @@ export async function testConnection(// ── Legacy aliases ───────────────────────────────────────────────────────export const saveApiKey = (providerId: string, apiKey: string, label?: string) =>addApiKey(providerId, apiKey, label);++const oauthRefreshFailures = new Set<string>();+function rememberOAuthRefreshFailure(profileId: string, prof: OAuthProfile): void {+ if (!profileId || Date.now() < prof.expires) return;+ oauthRefreshFailures.add(profileId);+}+function clearOAuthRefreshFailure(profileId: string): void {+ if (profileId) oauthRefreshFailures.delete(profileId);+}diff --git a/src/main/features/client_config.ts b/src/main/features/client_config.tsindex d5821937..2b661033 100644--- a/src/main/features/client_config.ts+++ b/src/main/features/client_config.ts@@ -579,7 +579,7 @@ export const DEFAULT_PROVIDER_MODELS = PUBLIC_PROVIDER_MODELS;export const DEFAULT_IMAGE_GEN_BY_PROVIDER: Readonly<Record<string, ImageGenCapability>> = {openai: { model: 'gpt-image-2', api: 'openai', supportsEdit: true },google: { model: 'gemini-3.1-flash-image-preview', api: 'gemini', supportsEdit: true },- doubao: { model: 'doubao-seedream-4-5-251128', api: 'doubao', supportsEdit: true },+ doubao: { model: 'doubao-seedream-5-0-lite-260128', api: 'doubao', supportsEdit: true },};/**@@ -710,7 +710,7 @@ function normalizeImageGenCapability(value: unknown): ImageGenCapability | null? r.api as ImageGenCapability['api']: '';if (!model || !api) return null;- return { model, api, supportsEdit: r.supportsEdit === true };+ return { model, api, supportsEdit: (r.supports_edit ?? r.supportsEdit) === true };}function mergeProviderSection(target: Record<string, ProviderModelEntry[]>, value: unknown): void {diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsindex 7253e3fc..8951a386 100644--- a/src/main/features/connectors/manager.ts+++ b/src/main/features/connectors/manager.ts@@ -54,7 +54,12 @@ let _runtimeEpoch = 0;* request; subsequent calls await the same Promise, get the same new grant, and proceed* identically. Lock entries auto-clear in the `finally` block so a failed refresh doesn't* jam the slot. */-const _refreshLocks = new Map<string, Promise<OAuthGrant>>();+interface RefreshLock {+ promise: Promise<OAuthGrant>;+ force: boolean;+ attemptedRemote: boolean;+}+const _refreshLocks = new Map<string, RefreshLock>();function _accountChangedError(): Error & { code: string } {return Object.assign(new Error('connector account changed'), {@@ -482,12 +487,21 @@ async function _refreshGrantIfStale(instId: string,opts: { force?: boolean } = {},): Promise<OAuthGrant> {- const lockKey = opts.force ? `${instId}:force` : instId;+ const lockKey = _runtimeKey(uid, instId);const existing = _refreshLocks.get(lockKey);if (existing) {- log.info('refresh dedupe hit', { id: instId });- return existing;+ log.info('refresh dedupe hit', { id: instId, force: !!opts.force, existing_force: existing.force });+ const grant = await existing.promise;+ if (opts.force && !existing.force && !existing.attemptedRemote) {+ return _refreshGrantIfStale(uid, entry, instId, opts);+ }+ return grant;}+ const lock: RefreshLock = {+ promise: Promise.resolve(null as never),+ force: !!opts.force,+ attemptedRemote: false,+ };let p: Promise<OAuthGrant>;p = Promise.resolve().then(async () => {try {@@ -517,6 +531,7 @@ async function _refreshGrantIfStale(&& inst.oauth_grant.expires_at - Date.now() > REFRESH_BUFFER_MS) {return inst.oauth_grant;}+ lock.attemptedRemote = true;const oldRt = inst.oauth_grant.refresh_token;log.info('refresh attempt', {id: instId,@@ -598,12 +613,13 @@ async function _refreshGrantIfStale(}return next;} finally {- if (_refreshLocks.get(lockKey) === p) {+ if (_refreshLocks.get(lockKey) === lock) {_refreshLocks.delete(lockKey);}}});- _refreshLocks.set(lockKey, p);+ lock.promise = p;+ _refreshLocks.set(lockKey, lock);return p;}@@ -697,7 +713,7 @@ async function _connectAndCacheTools(}const entry = findCatalogEntry(inst.id);if (_isMissingRequiredScopesError(err) || (entry && !_isTransientConnectorFailure(err) && _isGoogleAuthFailure(entry, err))) {- return inst;+ return registry.load(uid).connections[inst.id] || inst;}const degraded = await _markDegradedOnTransientFailure(uid, inst, err, 'resolve_transport', statusPatches,diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.tsindex 21dede0b..785fd2a6 100644--- a/src/main/features/connectors/oauth.ts+++ b/src/main/features/connectors/oauth.ts@@ -397,8 +397,8 @@ export async function refreshIfStale(grant: OAuthGrant,opts: { force?: boolean } = {},): Promise<OAuthGrant> {- if (entry.oauth?.provider_id === 'github') {- return refreshGithubServerManaged(entry, grant, opts);+ if (entry.oauth?.provider_id && ['github', 'bing'].includes(entry.oauth.provider_id)) {+ return refreshServerManaged(entry, grant, opts);}if (!grant.expires_at) return grant;if (grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;@@ -446,7 +446,7 @@ export async function refreshIfStale(return next;}-async function fetchGithubRefresh(body: Record<string, unknown>): Promise<Response> {+async function fetchServerManagedRefresh(body: Record<string, unknown>): Promise<Response> {return postConnectorBridgeJson('connector OAuth refresh',`${accountApiBase()}/connectors/oauth/refresh`,@@ -454,7 +454,7 @@ async function fetchGithubRefresh(body: Record<string, unknown>): Promise<Respon);}-async function refreshGithubServerManaged(+async function refreshServerManaged(entry: CatalogEntry,grant: OAuthGrant,opts: { force?: boolean } = {},@@ -468,12 +468,12 @@ async function refreshGithubServerManaged(// stop racing on GitHub's rotating refresh token.if (!hasServerGrant && !hasLegacyRefresh) {if (!grant.expires_at || !stale) return grant;- throw new Error('github grant expired and has no server grant; reconnect required');+ throw new Error('connector grant expired and has no server grant; reconnect required');}if (hasServerGrant && !stale && !opts.force) return grant;if (!entry.oauth) throw new Error('no oauth config');- const res = await fetchGithubRefresh({+ const res = await fetchServerManagedRefresh({provider: entry.oauth.provider_id,device_id: tokenStore.getDeviceId(),...(opts.force ? { force_refresh: true } : {}),@@ -503,8 +503,8 @@ async function refreshGithubServerManaged(scope?: string;account_label?: string;};- if (body.code !== 0) throw _refreshErrorFromBody(body, 'invalid github refresh response');- if (!body.access_token || !body.grant_id) throw new Error('invalid github refresh response');+ if (body.code !== 0) throw _refreshErrorFromBody(body, 'invalid server-managed refresh response');+ if (!body.access_token || !body.grant_id) throw new Error('invalid server-managed refresh response');const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;return {access_token: body.access_token,diff --git a/src/main/features/generation_reference_assets.ts b/src/main/features/generation_reference_assets.tsindex d7e73822..ef7706a1 100644--- a/src/main/features/generation_reference_assets.ts+++ b/src/main/features/generation_reference_assets.ts@@ -7,11 +7,12 @@ import { spawn } from 'node:child_process';import { createHash } from 'node:crypto';import { prepareFeedbackUploadImage } from '../util/image-transform';-import { fetchWithTimeout, throwIfAborted } from '../util/abort';+import { composeAbortSignal, throwIfAborted } from '../util/abort';import { logPathRef } from '../util/log-redact';import { createLogger } from '../logger';import { killProcessTree } from '../../core-agent/src/sandbox/executor';import { getDeviceId } from './machine_device_id';+import { downloadBinaryWithProxyPolicy } from '../util/proxy-dispatcher';const log = createLogger('generation-reference-assets');@@ -19,7 +20,7 @@ const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;const IMAGE_MAX_BYTES = 12 * 1024 * 1024;const MAX_REFERENCE_DOWNLOAD_BYTES = 100 * 1024 * 1024;const VIDEO_COMPRESS_TRIGGER_BYTES = 8 * 1024 * 1024;-const REFERENCE_UPLOAD_TIMEOUT_MS = 5 * 60 * 1000;+const REFERENCE_TRANSFER_TIMEOUT_MS = 10 * 60 * 1000;const VIDEO_COMPRESS_TIMEOUT_MS = 10 * 60 * 1000;const PROGRESS_HEARTBEAT_MS = 15 * 1000;@@ -145,15 +146,26 @@ export async function loadImageReferenceBuffersWithProgress(index,total,});- const resp = await fetchWithTimeout(- url,- { method: 'GET' },- REFERENCE_UPLOAD_TIMEOUT_MS,- opts.signal,- `reference image download timed out after ${Math.round(REFERENCE_UPLOAD_TIMEOUT_MS / 1000)}s`,- );- if (!resp.ok) throw new Error(`reference image download failed ${resp.status}: ${url}`);- const buf = Buffer.from(await resp.arrayBuffer());+ const timeoutMessage = `reference image download timed out after ${Math.round(REFERENCE_TRANSFER_TIMEOUT_MS / 1000)}s`;+ const composed = composeAbortSignal(opts.signal, REFERENCE_TRANSFER_TIMEOUT_MS, timeoutMessage);+ let buf: Buffer;+ try {+ const downloaded = await downloadBinaryWithProxyPolicy(url, {+ label: 'reference image download',+ signal: composed.signal,+ maxBytes: MAX_REFERENCE_DOWNLOAD_BYTES,+ validate: (body) => {+ if (!body.length) throw new Error('reference image download returned an empty body');+ },+ });+ buf = downloaded.body;+ } catch (err) {+ if (opts.signal?.aborted) throw new Error('operation aborted');+ if (composed.signal.aborted) throw new Error(timeoutMessage);+ throw err;+ } finally {+ composed.cleanup();+ }throwIfAborted(opts.signal);out.push(buf);}diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.tsindex 10df4b43..08ff9329 100644--- a/src/main/features/group_chat/bus.ts+++ b/src/main/features/group_chat/bus.ts@@ -5844,7 +5844,8 @@ async function runActorTurn(return {kind: 'completed',text: workingText,- produced,+ // Handback needs all real outputs; footer filtering is presentation only.+ produced: turnFinalCandidates,outcome,persistedMsg,errText: errText || undefined,diff --git a/src/main/features/image_gen.ts b/src/main/features/image_gen.tsindex 19f1d803..9e53694f 100644--- a/src/main/features/image_gen.ts+++ b/src/main/features/image_gen.ts@@ -27,7 +27,7 @@ import { listApiKeyEntries, loadImageProfiles, type ApiKeyEntryChoice } from './import { findImageGenCapability, type ImageGenCapability } from '../model/provider_catalog';import { createLogger } from '../logger';import { t } from '../i18n';-import { composeAbortSignal, fetchWithTimeout, throwIfAborted } from '../util/abort';+import { composeAbortSignal, fetchAndReadWithTimeout, throwIfAborted } from '../util/abort';import { downloadBinaryWithProxyPolicy } from '../util/proxy-dispatcher';import {ORKAS_API_BASE_URL,@@ -36,7 +36,14 @@ import {type OrkasApiUsageContext,} from './orkas_api';+import { loadImageReferenceBuffersWithProgress, registerGeneratedMediaUrl, type GenerationReferenceProgressReporter } from './generation_reference_assets';+import type { ImageReferenceBinding } from './image_prompt_contract';+const log = createLogger('image-gen');+const DIRECT_IMAGE_HTTP_TIMEOUT_MS = 10 * 60_000;+const IMAGE_DOWNLOAD_TIMEOUT_MS = 10 * 60_000;+const MAX_IMAGE_DOWNLOAD_BYTES = 100 * 1024 * 1024;+type ImageProgressReporter = GenerationReferenceProgressReporter;// ── Picker ───────────────────────────────────────────────────────────────@@ -103,9 +110,13 @@ export interface GenerateImageInput {/** Already-validated absolute paths to reference images for editing /* variations. The picked capability must have `supportsEdit: true`. */referenceImagePaths?: string[];+ referenceImageUrls?: string[];+ referenceBindings?: ImageReferenceBinding[];+ negativePrompt?: string[];/** Provider-side size hint. Default `1024x1024`. */size?: string;signal?: AbortSignal;+ onProgress?: ImageProgressReporter;usageContext?: OrkasApiUsageContext;}@@ -118,6 +129,7 @@ export type GenerateImageResult =bytes: number;provider: string;model: string;+ sourceUrl?: string;}| {ok: false;@@ -131,6 +143,7 @@ export type GenerateImageResult =};export async function generateImage(input: GenerateImageInput): Promise<GenerateImageResult> {+ throwIfAborted(input.signal);if (!input.prompt || !input.prompt.trim()) {return { ok: false, errorCode: 'BAD_INPUT', message: 'prompt is required' };}@@ -146,8 +159,9 @@ export async function generateImage(input: GenerateImageInput): Promise<Generateconst { entry, capability } = picked;const refPaths = input.referenceImagePaths || [];+ const refUrls = input.referenceImageUrls || [];- if (refPaths.length && !capability.supportsEdit) {+ if ((refPaths.length || refUrls.length) && !capability.supportsEdit) {return {ok: false,errorCode: 'EDIT_NOT_SUPPORTED',@@ -156,10 +170,11 @@ export async function generateImage(input: GenerateImageInput): Promise<Generate}let referenceBuffers: Buffer[] | undefined;- if (refPaths.length) {+ if (refPaths.length || refUrls.length) {try {- referenceBuffers = await Promise.all(refPaths.map((p) => fs.readFile(p)));+ referenceBuffers = await loadImageReferenceBuffersWithProgress(refUrls, refPaths, { signal: input.signal, onProgress: input.onProgress });} catch (err) {+ throwIfAborted(input.signal);log.warn(`failed reading reference image: ${(err as Error).message}`);return {ok: false,@@ -175,6 +190,7 @@ export async function generateImage(input: GenerateImageInput): Promise<Generatemodel: capability.model,prompt: input.prompt,size,+ onProgress: input.onProgress,...(input.signal ? { signal: input.signal } : {}),...(input.usageContext ? { usageContext: input.usageContext } : {}),...(referenceBuffers ? { referenceImages: referenceBuffers } : {}),@@ -198,16 +214,23 @@ export async function generateImage(input: GenerateImageInput): Promise<Generate};}} catch (err) {+ if (err instanceof ImageGenerationDeliveryError) throw err;+ throwIfAborted(input.signal);const msg = (err as Error).message;log.error(`image gen API call failed (${entry.provider}/${capability.model}): ${msg}`);return { ok: false, errorCode: 'PROVIDER_API_ERROR', message: msg };}+ throwIfAborted(input.signal);+ adapterRes = validateImageAdapterResult(adapterRes);+ emitProgress(input.onProgress, 'save_image', 'Saving generated image');let finalPath: string;try {finalPath = ensureExtension(input.outputAbsPath, adapterRes.mimeType);await fs.mkdir(path.dirname(finalPath), { recursive: true });+ throwIfAborted(input.signal);await fs.writeFile(finalPath, adapterRes.buffer);+ registerGeneratedMediaUrl(finalPath, adapterRes.sourceUrl);} catch (err) {const msg = (err as Error).message;log.error(`image write failed (${input.outputAbsPath}): ${msg}`);@@ -231,6 +254,7 @@ export async function generateImage(input: GenerateImageInput): Promise<Generatebytes: adapterRes.buffer.length,provider: entry.provider,model: capability.model,+ ...(adapterRes.sourceUrl ? { sourceUrl: adapterRes.sourceUrl } : {}),};}@@ -243,14 +267,15 @@ export interface AdapterRequest {size: string;referenceImages?: Buffer[];signal?: AbortSignal;+ onProgress?: ImageProgressReporter;usageContext?: OrkasApiUsageContext;}export interface AdapterResult {+ sourceUrl?: string;buffer: Buffer;mimeType: string;- /** 0 if dimensions could not be parsed — non-fatal, the file is still- * on disk. */+ /** Dimensions verified from the returned bytes before publication. */width: number;height: number;}@@ -311,7 +336,7 @@ async function waitForOrkasImageTask(let data: any = {};while (!signal.aborted) {await sleepWithSignal(3_000, signal);- const resp = await fetchWithTimeout(+ const { body: statusData } = await fetchAndReadWithTimeout(`${ORKAS_API_BASE_URL}/images/generations/${encodeURIComponent(taskId)}`,{method: 'GET',@@ -323,8 +348,9 @@ async function waitForOrkasImageTask(ORKAS_IMAGE_POLL_TIMEOUT_MS,signal,'Orkas Image status request timed out',+ (resp) => readOrkasImageResponse(resp, 'status'),);- data = await readOrkasImageResponse(resp, 'status');+ data = statusData;const status = String(data?.status || '').toLowerCase();if (['failed', 'cancelled', 'canceled'].includes(status)) {throw new Error(`Orkas Image task ${taskId} ${status}: ${truncate(JSON.stringify(data?.error || data), 500)}`);@@ -357,7 +383,7 @@ export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResult`Orkas Image timed out after ${Math.round(ORKAS_IMAGE_TOTAL_TIMEOUT_MS / 60_000)} minutes`,);try {- const response = await fetchWithTimeout(+ const { body: createdData } = await fetchAndReadWithTimeout(`${ORKAS_API_BASE_URL}/images/generations`,{method: 'POST',@@ -379,14 +405,17 @@ export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResultORKAS_IMAGE_CREATE_TIMEOUT_MS,overall.signal,'Orkas Image create request timed out',+ (resp) => readOrkasImageResponse(resp, 'create'),);- let data = await readOrkasImageResponse(response, 'create');+ let data = createdData;const taskId = String(data?.id || '').trim();if (!data?.data?.[0]?.url && !data?.data?.[0]?.b64_json) {if (!taskId) throw new Error('Orkas Image create returned no task id');data = await waitForOrkasImageTask(taskId, req.apiKey, overall.signal, req.usageContext);}+ emitProgress(req.onProgress, 'decode_image', 'Decoding Orkas image response');+ const sourceUrl = String(data?.data?.[0]?.url || '').trim();const b64 = String(data?.data?.[0]?.b64_json || '');let buffer: Buffer;if (b64) {@@ -405,26 +434,28 @@ export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResultsignal: download.signal,maxBytes: 64 * 1024 * 1024,validate: (body) => {- if (!body.length || !detectMimeType(body)) {- throw new Error('Orkas Image download returned unsupported image bytes');- }+ validateImageAdapterResult({ buffer: body, mimeType: '', width: 0, height: 0 });},});buffer = result.body;+ } catch (err) {+ throw new ImageGenerationDeliveryError(`Orkas Image download failed after generation completed. Do not submit another generation task. ${errorMessage(err)}`, { cause: err });} finally {download.cleanup();}}const mimeType = detectMimeType(buffer) || 'image/png';const dim = parseImageDimensions(buffer, mimeType);- return { buffer, mimeType, width: dim.width, height: dim.height };+ return validateImageAdapterResult({ buffer, mimeType, width: dim.width, height: dim.height, ...(sourceUrl ? { sourceUrl } : {}) });} finally {overall.cleanup();}}export async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResult> {- const hasRefs = !!(req.referenceImages && req.referenceImages.length);+ throwIfAborted(req.signal);+ const referenceImages = (req.referenceImages || []);+ const hasRefs = referenceImages.length > 0;const url = hasRefs? `${OPENAI_BASE}/v1/images/edits`: `${OPENAI_BASE}/v1/images/generations`;@@ -438,7 +469,7 @@ export async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResulform.append('prompt', req.prompt);form.append('size', req.size);form.append('n', '1');- req.referenceImages!.forEach((buf, i) => {+ referenceImages.forEach((buf, i) => {const mime = detectMimeType(buf) || 'image/png';const ext = mime === 'image/png' ? 'png' : mime === 'image/jpeg' ? 'jpg' : 'webp';// OpenAI's edits endpoint expects `image[]` for multi-ref; gpt-image-1@@ -460,25 +491,40 @@ export async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResul};}- const resp = await fetch(url, { method: 'POST', headers, body });- if (!resp.ok) {- const text = await resp.text().catch(() => '');- throw new Error(`OpenAI image API ${resp.status}: ${truncate(text, 500)}`);- }- const data = (await resp.json()) as { data?: Array<{ b64_json?: string; url?: string }> };+ emitProgress(req.onProgress, 'create_image', `Calling OpenAI image ${hasRefs ? 'edit' : 'generation'} API`, {+ provider: 'openai',+ model: req.model,+ });+ const { body: data } = await fetchAndReadWithTimeout<{ data?: Array<{ b64_json?: string; url?: string }> }>(+ url,+ { method: 'POST', headers, body },+ DIRECT_IMAGE_HTTP_TIMEOUT_MS,+ req.signal,+ `OpenAI image API timed out after ${Math.round(DIRECT_IMAGE_HTTP_TIMEOUT_MS / 1000)}s`,+ async (response) => {+ if (!response.ok) {+ const text = await response.text().catch(() => '');+ throw new Error(`OpenAI image API ${response.status}: ${truncate(text, 500)}`);+ }+ return await response.json() as { data?: Array<{ b64_json?: string; url?: string }> };+ },+ );+ emitProgress(req.onProgress, 'decode_image', 'Decoding OpenAI image response', { provider: 'openai' });const b64 = data.data?.[0]?.b64_json;if (!b64) throw new Error('OpenAI image API returned no b64_json data');const buffer = Buffer.from(b64, 'base64');const mimeType = detectMimeType(buffer) || 'image/png';const dim = parseImageDimensions(buffer, mimeType);- return { buffer, mimeType, width: dim.width, height: dim.height };+ return validateImageAdapterResult({ buffer, mimeType, width: dim.width, height: dim.height });}export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResult> {+ throwIfAborted(req.signal);const url = `${GEMINI_BASE}/v1beta/models/${encodeURIComponent(req.model)}:generateContent`;const parts: unknown[] = [{ text: req.prompt }];- if (req.referenceImages?.length) {- for (const buf of req.referenceImages) {+ const referenceImages = (req.referenceImages || []);+ if (referenceImages.length) {+ for (const buf of referenceImages) {parts.push({inline_data: {mime_type: detectMimeType(buf) || 'image/png',@@ -491,19 +537,11 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResulcontents: [{ parts }],generationConfig: { responseModalities: ['IMAGE'] },});- const resp = await fetch(url, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'x-goog-api-key': req.apiKey,- },- body,+ emitProgress(req.onProgress, 'create_image', 'Calling Gemini image API', {+ provider: 'google',+ model: req.model,});- if (!resp.ok) {- const text = await resp.text().catch(() => '');- throw new Error(`Gemini image API ${resp.status}: ${truncate(text, 500)}`);- }- const data = (await resp.json()) as {+ const { body: data } = await fetchAndReadWithTimeout<{candidates?: Array<{content?: {parts?: Array<@@ -512,7 +550,37 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResul>;};}>;- };+ }>(+ url,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-goog-api-key': req.apiKey,+ },+ body,+ },+ DIRECT_IMAGE_HTTP_TIMEOUT_MS,+ req.signal,+ `Gemini image API timed out after ${Math.round(DIRECT_IMAGE_HTTP_TIMEOUT_MS / 1000)}s`,+ async (response) => {+ if (!response.ok) {+ const text = await response.text().catch(() => '');+ throw new Error(`Gemini image API ${response.status}: ${truncate(text, 500)}`);+ }+ return await response.json() as {+ candidates?: Array<{+ content?: {+ parts?: Array<+ | { text?: string }+ | { inline_data?: { mime_type?: string; data?: string }; inlineData?: { mimeType?: string; data?: string } }+ >;+ };+ }>;+ };+ },+ );+ emitProgress(req.onProgress, 'decode_image', 'Decoding Gemini image response', { provider: 'google' });const candParts = data.candidates?.[0]?.content?.parts ?? [];for (const p of candParts) {// Gemini API responses use both snake_case (`inline_data` / `mime_type`)@@ -525,7 +593,7 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResulconst buffer = Buffer.from(inline.data, 'base64');const mimeType = inline.mime_type ?? inline.mimeType ?? detectMimeType(buffer) ?? 'image/png';const dim = parseImageDimensions(buffer, mimeType);- return { buffer, mimeType, width: dim.width, height: dim.height };+ return validateImageAdapterResult({ buffer, mimeType, width: dim.width, height: dim.height });}throw new Error('Gemini image API returned no inline image data');}@@ -579,51 +647,72 @@ function bufferToDataUri(buf: Buffer): string {}export async function callDoubaoImage(req: AdapterRequest): Promise<AdapterResult> {- const refs = req.referenceImages ?? [];+ throwIfAborted(req.signal);+ const refs = (req.referenceImages || []);const isEdit = refs.length > 0;- const size = isEdit && req.size === SEEDREAM_DEFAULT_SIZE- ? 'adaptive'- : normaliseSeedreamSize(req.size);+ const size = isEdit && req.size === SEEDREAM_DEFAULT_SIZE ? 'adaptive' : normaliseSeedreamSize(req.size);const bodyObj: Record<string, unknown> = {model: req.model,prompt: req.prompt,size,- n: 1,- response_format: 'url',+ response_format: 'b64_json',+ output_format: 'jpeg',+ watermark: false,+ sequential_image_generation: 'disabled',};if (isEdit) {const dataUris = refs.map(bufferToDataUri);bodyObj.image = dataUris.length === 1 ? dataUris[0] : dataUris;}const body = JSON.stringify(bodyObj);- const resp = await fetch(`${DOUBAO_BASE}/api/v3/images/generations`, {- method: 'POST',- headers: {- Authorization: `Bearer ${req.apiKey}`,- 'Content-Type': 'application/json',- },- body,+ emitProgress(req.onProgress, 'create_image', `Calling Doubao image ${isEdit ? 'edit' : 'generation'} API`, {+ provider: 'doubao',+ model: req.model,});- if (!resp.ok) {- const text = await resp.text().catch(() => '');- throw new Error(`Doubao image API ${resp.status}: ${truncate(text, 500)}`);- }- const data = (await resp.json()) as {+ const { body: data } = await fetchAndReadWithTimeout<{data?: Array<{ url?: string; b64_json?: string }>;- };+ }>(+ `${DOUBAO_BASE}/api/v3/images/generations`,+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${req.apiKey}`,+ 'Content-Type': 'application/json',+ },+ body,+ },+ DIRECT_IMAGE_HTTP_TIMEOUT_MS,+ req.signal,+ `Doubao image API timed out after ${Math.round(DIRECT_IMAGE_HTTP_TIMEOUT_MS / 1000)}s`,+ async (response) => {+ if (!response.ok) {+ const text = await response.text().catch(() => '');+ throw new Error(`Doubao image API ${response.status}: ${truncate(text, 500)}`);+ }+ return await response.json() as { data?: Array<{ url?: string; b64_json?: string }> };+ },+ );+ emitProgress(req.onProgress, 'decode_image', 'Decoding Doubao image response', { provider: 'doubao' });const item = data.data?.[0];let buffer: Buffer | null = null;+ let sourceUrl = '';if (item?.b64_json) {buffer = Buffer.from(item.b64_json, 'base64');} else if (item?.url) {- const imgResp = await fetch(item.url);- if (!imgResp.ok) throw new Error(`Doubao image fetch failed ${imgResp.status}`);- buffer = Buffer.from(await imgResp.arrayBuffer());+ sourceUrl = item.url;+ emitProgress(req.onProgress, 'download_image', 'Downloading Doubao image output', { provider: 'doubao' });+ buffer = await downloadGeneratedImageBytes(sourceUrl, req, 'Doubao image output download');}if (!buffer) throw new Error('Doubao image API returned no image payload');const mimeType = detectMimeType(buffer) || 'image/png';const dim = parseImageDimensions(buffer, mimeType);- return { buffer, mimeType, width: dim.width, height: dim.height };+ return validateImageAdapterResult({+ buffer,+ mimeType,+ width: dim.width,+ height: dim.height,+ ...(sourceUrl ? { sourceUrl } : {}),+ });}// ── Image format helpers ─────────────────────────────────────────────────@@ -715,3 +804,75 @@ function ensureExtension(p: string, mimeType: string): string {}return p + ext;}++export function validateImageAdapterResult(result: AdapterResult): AdapterResult {+ const mimeType = detectMimeType(result.buffer);+ if (!mimeType) {+ throw new Error('Image provider returned invalid or unsupported image bytes');+ }+ const dimensions = parseImageDimensions(result.buffer, mimeType);+ if (dimensions.width <= 0 || dimensions.height <= 0) {+ throw new Error(`Image provider returned malformed ${mimeType} data`);+ }+ return {+ ...result,+ mimeType,+ width: dimensions.width,+ height: dimensions.height,+ };+}++async function downloadGeneratedImageBytes(+ sourceUrl: string,+ req: AdapterRequest,+ label: string,+): Promise<Buffer> {+ const timeoutMessage = `${label} timed out after ${Math.round(IMAGE_DOWNLOAD_TIMEOUT_MS / 1000)}s`;+ const composed = composeAbortSignal(req.signal, IMAGE_DOWNLOAD_TIMEOUT_MS, timeoutMessage);+ try {+ const downloaded = await downloadBinaryWithProxyPolicy(sourceUrl, {+ label,+ signal: composed.signal,+ maxBytes: MAX_IMAGE_DOWNLOAD_BYTES,+ validate: (body) => {+ validateImageAdapterResult({+ buffer: body,+ mimeType: detectMimeType(body) || 'application/octet-stream',+ width: 0,+ height: 0,+ });+ },+ });+ return downloaded.body;+ } catch (err) {+ const message = req.signal?.aborted+ ? 'operation aborted after the provider completed generation'+ : composed.signal.aborted+ ? timeoutMessage+ : errorMessage(err);+ throw new ImageGenerationDeliveryError(`${label} failed after generation completed and bounded download retries. Do not submit another generation task. ${message}`, { cause: err });+ } finally {+ composed.cleanup();+ }+}++export class ImageGenerationDeliveryError extends Error {+ override readonly name = 'ImageGenerationDeliveryError';++ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ }+}++function emitProgress(+ onProgress: ImageProgressReporter | undefined,+ phase: string,+ message: string,+ data?: Record<string, unknown>,+): void {+ onProgress?.({ phase, message, ...(data ? { data } : {}) });+}++function errorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err || '');+}diff --git a/src/main/features/library_image_describer.ts b/src/main/features/library_image_describer.tsindex cc35f178..96d7d087 100644--- a/src/main/features/library_image_describer.ts+++ b/src/main/features/library_image_describer.ts@@ -56,6 +56,8 @@ export async function describeLibraryImage(message,images: [{ data: compressed.buf.toString('base64'), mediaType: 'image/jpeg' }],skillList: [],+ // This one-shot vision operation must not receive the default tool set.+ toolList: [],idleTimeout: Math.ceil(timeoutMs / 1000),abortSignal: controller.signal,}).catch((err) => ({diff --git a/src/main/features/skills.ts b/src/main/features/skills.tsindex 0c9de7b5..6ad308c7 100644--- a/src/main/features/skills.ts+++ b/src/main/features/skills.ts@@ -3465,17 +3465,13 @@ export async function* streamSendToSkillChat(for await (let event of streamChatWithModel({userId, message: attachmentCtx.message, sessionId, systemPrompt,agentName: 'orkas_chat',+ skillList: [],+ systemSkillList: ['skill-creator', 'package-installer'],cacheRetention: 'short',readOnlyExtraRoots: [- ...(skill.dir ? [skill.dir] : []),- userMarketplaceSkillsDir(getActiveUserId()),- userSkillsDir(userId),- // System skills root so a URL-import chat can read `package-installer`- // before driving `orkas-pkg`; ordinary SkillRegistry no longer loads- // repo-shipped builtin skills.- userSystemSkillsDir(userId),- ...(attachmentCtx.attachmentNames.length ? [chatAttachmentDirForConversation(userId, attachmentCtx.attachmentCid)] : []),- ],+ ...(skill.dir ? [skill.dir] : []),+ ...(attachmentCtx.attachmentNames.length ? [chatAttachmentDirForConversation(userId, attachmentCtx.attachmentCid)] : []),+ ],attachmentMetadata: attachmentCtx.attachmentMetadata,...(attachmentCtx.images.length ? { images: attachmentCtx.images } : {}),...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),diff --git a/src/main/features/video_auth.ts b/src/main/features/video_auth.tsindex cbb4ca48..69a079f9 100644--- a/src/main/features/video_auth.ts+++ b/src/main/features/video_auth.ts@@ -24,9 +24,6 @@ const VIDEO_AUTH_MODELS_BY_PROVIDER: Readonly<Record<string, Array<{ id: string;[ORKAS_API_PROVIDER]: [{ id: ORKAS_API_VIDEO_MODEL, name: 'Video' },],- doubao: [- { id: 'doubao-seedance-2-0-260128', name: 'Seedance 2.0' },- ],};let _idCounter = 0;@@ -110,11 +107,6 @@ export function listVideoProviderOptions(): Array<{ id: string; label: string; dlabel: 'Orkas',docs: ORKAS_API_KEYS_URL,},- {- id: 'doubao',- label: 'DouBao · Seedance',- docs: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey',- },];}@@ -144,6 +136,7 @@ export function flattenVideoProviderOptions(): VideoProviderPickerOption[] {return providers.flatMap((provider) => {const models = listVideoModelOptions(provider.id);+ if (!models.length) return [];if (models.length <= 1) {return [{...provider,diff --git a/src/main/features/video_gen.ts b/src/main/features/video_gen.tsindex 864ac42f..2394c018 100644--- a/src/main/features/video_gen.ts+++ b/src/main/features/video_gen.ts@@ -14,7 +14,7 @@ import {import { prepareReferenceUrls, registerGeneratedMediaUrl } from './generation_reference_assets';import { createLogger } from '../logger';import { t } from '../i18n';-import { composeAbortSignal, fetchWithTimeout, throwIfAborted } from '../util/abort';+import { composeAbortSignal, fetchAndReadWithTimeout, throwIfAborted } from '../util/abort';import { downloadBinaryWithProxyPolicy } from '../util/proxy-dispatcher';import { logErrorSummary, logPathRef } from '../util/log-redact';import { sanitizeLogTextForUpload } from '../util/log-sanitize';@@ -282,7 +282,7 @@ function normalizeVideoInput(input: GenerateVideoInput): NormalizedVideoInput {async function callOrkasApiVideo(req: OrkasVideoRequest): Promise<OrkasVideoResult> {throwIfAborted(req.signal);emitProgress(req.onProgress, 'create_task', 'Creating Orkas API video task');- const create = await fetchWithTimeout(+ const { body: createdData } = await fetchAndReadWithTimeout(`${ORKAS_API_BASE_URL}/videos`,{method: 'POST',@@ -307,8 +307,9 @@ async function callOrkasApiVideo(req: OrkasVideoRequest): Promise<OrkasVideoResuCREATE_TIMEOUT_MS,req.signal,'Orkas API video create request timed out',+ (response) => readOrkasVideoResponse(response, 'create'),);- let data = await readOrkasVideoResponse(create, 'create');+ let data = createdData;const taskId = String(data?.id || '').trim();if (!taskId) throw new Error('Orkas API video create returned no task id');emitProgress(req.onProgress, 'task_created', `Video task created: ${taskId}`, { taskId });@@ -341,7 +342,7 @@ async function callOrkasApiVideo(req: OrkasVideoRequest): Promise<OrkasVideoResuemitProgress(req.onProgress, 'poll_wait', 'Waiting before checking video status', { taskId, attempt: attempts });await sleep(req.pollIntervalMs, req.signal);try {- const poll = await fetchWithTimeout(+ const { body: statusData } = await fetchAndReadWithTimeout(`${ORKAS_API_BASE_URL}/videos/${encodeURIComponent(taskId)}`,{method: 'GET',@@ -353,8 +354,9 @@ async function callOrkasApiVideo(req: OrkasVideoRequest): Promise<OrkasVideoResuPOLL_TIMEOUT_MS,req.signal,'Orkas API video status request timed out',+ (response) => readOrkasVideoResponse(response, 'status'),);- data = await readOrkasVideoResponse(poll, 'status');+ data = statusData;consecutiveTimeouts = 0;emitProgress(req.onProgress, 'poll_result', `Video task status: ${data?.status || 'processing'}`, {taskId,diff --git a/src/main/index.ts b/src/main/index.tsindex 0a9a0454..4236ce4e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -163,8 +163,12 @@ installSdkTimeoutPatch();import { installSseHeaderTimeoutPatch } from './model/core-agent/sse-header-timeout-patch';installSseHeaderTimeoutPatch();-// Provider-fetch diagnostics: dump the real undici cause chain for model-// endpoint failures.+// Install the stable router before diagnostics wrap fetch. Explicit launch+// proxy settings apply now; Electron system routes become available at ready.+import { installEnvProxyDispatcher, installSystemProxyDispatcher } from './util/proxy-dispatcher';+void installEnvProxyDispatcher();++// Provider-fetch diagnostics preserve the router installed above.import { installFetchDiag } from './model/core-agent/fetch-diag';installFetchDiag();@@ -569,7 +573,20 @@ async function runBootSelfCheck(): Promise<void> {}+async function sweepOfficeResidents(reason: 'startup' | 'quit'): Promise<void> {+ // Test profiles may coexist with a real application using the same bundled+ // binary. Only the regular single-instance application owns its residents.+ if (E2E_USER_DATA_DIR || IS_PACKAGED_LAUNCH_SMOKE) return;+ try {+ const office = await import('./features/office/office_engine');+ office.closeAllOfficeResidents();+ } catch (err) {+ createLogger('office-engine').warn(`resident sweep on ${reason} failed`, { error: (err as Error).message });+ }+}+async function runBootMaintenanceSweeps(): Promise<void> {+ await sweepOfficeResidents('startup');// Full cross-user/unindexed recovery stays out of the pre-window self-check.try {const { swept } = await chatsFeature.sweepStaleProcessing();@@ -1223,6 +1240,7 @@ if (!gotLock) {registerConnectorProtocol();app.whenReady().then(async () => {await runBootSelfCheck();+ await installSystemProxyDispatcher();// Publish packaged, local-only content before the first window so the// first task can see every shipped System Skill and Marketplace resource.// The open build has no account bootstrap that can provide this boundary,@@ -1436,22 +1454,28 @@ if (!gotLock) {if (process.platform !== 'darwin') app.quit();});- // Flush pending search-index writes + close KB vector DBs before exit.+ // Repeated quit events share one flush, including the Open lifecycle request.let shutdownFlushed = false;+ let shutdownFlushPromise: Promise<void> | null = null;app.on('before-quit', async (e) => {if (shutdownFlushed) return;e.preventDefault();- // Begin the network request before slower disk cleanup and do not release- // the Electron process until Server has acknowledged the lifecycle request.- const lifecycleFlush = openLifecycleTracking?.flushQuit();- try { await searchFeature.flushAll(); }- catch (err) { createLogger('search').warn('final flush failed', { error: (err as Error).message }); }- try {- const kb = await import('./features/kb_vector');- kb.closeAllKb();- } catch (err) { createLogger('kb_vector').warn('close failed', { error: (err as Error).message }); }- await lifecycleFlush;- shutdownFlushed = true;- app.quit();+ if (shutdownFlushPromise) return;+ shutdownFlushPromise = (async () => {+ const lifecycleFlush = openLifecycleTracking?.flushQuit();+ try { await searchFeature.flushAll(); }+ catch (err) { createLogger('search').warn('final flush failed', { error: (err as Error).message }); }+ try {+ const kb = await import('./features/kb_vector');+ kb.closeAllKb();+ } catch (err) { createLogger('kb_vector').warn('close failed', { error: (err as Error).message }); }+ await sweepOfficeResidents('quit');+ await lifecycleFlush;+ })();+ try { await shutdownFlushPromise; }+ finally {+ shutdownFlushed = true;+ app.quit();+ }});}diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 2bd46e07..788ca1b2 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -1319,7 +1319,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {'projects.files.pickAndUpload': async ({ projectId, targetDir } = {}, ctx) => {if (!safeId(projectId)) throw new Error('invalid projectId');if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');- const picked = await _pickLocalFiles('Choose files', PROJECT_PICK_EXTENSIONS, true);+ const picked = await _pickLocalFiles('Choose files', PROJECT_PICK_EXTENSIONS, true, /* seedWorkspaceOnFirstOpen */ true);if (!picked.length) return { ok: true, cancelled: true, files: [] };const results = [];for (const filePath of picked) {@@ -1396,6 +1396,12 @@ const invokeHandlers: Record<string, InvokeHandler> = {return projectFiles.readProjectDocxHtml(ctx.userId, projectId, name);},+ 'projects.files.officeHtml': async ({ projectId, name }, ctx) => {+ if (!safeId(projectId)) throw new Error('invalid projectId');+ if (typeof name !== 'string' || !name) throw new Error('invalid name');+ return projectFiles.readProjectOfficeHtml(ctx.userId, projectId, name);+ },+'projects.files.status': async ({ projectId, skipReconcile }, ctx) => {if (!safeId(projectId)) throw new Error('invalid projectId');if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');@@ -1807,6 +1813,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];const opts: Electron.OpenDialogOptions = {properties: ['openDirectory'],+ defaultPath: _safeDialogDefaultPath(),title: typeof title === 'string' && title ? title : t('dialog.choose_directory'),};const res = parent@@ -2030,8 +2037,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {return { agent };},- 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime, category, output_format } = {}) => {- return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime, category, output_format }) };+ 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, profile, runtime, category, output_format } = {}) => {+ return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, profile, runtime, category, output_format }) };},@@ -2042,6 +2049,21 @@ const invokeHandlers: Record<string, InvokeHandler> = {return { agent: data };},+ 'agents.memory.add': async ({ agent_id, content }) => {+ if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');+ return agents.addCustomAgentMemory(agent_id, String(content || ''));+ },++ 'agents.memory.remove': async ({ agent_id, old_text }) => {+ if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');+ return agents.removeCustomAgentMemory(agent_id, String(old_text || ''));+ },++ 'agents.memory.update': async ({ agent_id, old_text, content }) => {+ if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');+ return agents.updateCustomAgentMemory(agent_id, String(old_text || ''), String(content || ''));+ },+'agents.delete': async ({ agent_id }, ctx) => {if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');await recycleBin.createAppRecycleBatchForAgent(ctx.userId, agent_id);@@ -2135,6 +2157,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];const opts: Electron.OpenDialogOptions = {properties: ['openDirectory'],+ defaultPath: _safeDialogDefaultPath(),title: t('dialog.choose_skill_source_directory'),};const res = parent@@ -2510,6 +2533,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {},// Read an image file's bytes for inline viewer display.+ 'contexts.officeHtml': async ({ path }) => {+ return contexts.readContextOfficeHtml(path || '');+ },+'contexts.image': async ({ path }) => {return contexts.readContextImage(path || '');},@@ -2735,6 +2762,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {providers: videoAuth.flattenVideoProviderOptions(videoAuth.listVideoProviderOptions()),profiles: videoAuth.listVideoProfiles().map((p) => ({id: p.id, provider: p.provider, model: p.model, label: p.label, createdAt: p.createdAt,+ available: videoAuth.isVideoProviderModelAllowed(p.provider, p.model),apiKeyMasked: auth.maskKey(p.apiKey),})),}),diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.tsindex 5f259185..a1563ee8 100644--- a/src/main/model/core-agent/connector-meta-tools.ts+++ b/src/main/model/core-agent/connector-meta-tools.ts@@ -37,9 +37,10 @@ import {import { validateCustomTransport, validateDisplayName, CustomTransportError } from '../../features/connectors/custom-transport';import { requestInstallConfirm } from '../../features/connectors/install_confirm';import { findCatalogEntry } from '../../features/connectors/catalog';-import { getLanguageForUser } from '../../features/config';+import { resolveLanguageForUser } from '../../features/config';import { descriptionLang } from '../../i18n';import { createLogger } from '../../logger';+import { logErrorRef, maskId } from '../../util/log-redact';import type { ConnectorInstance, ToolSchema } from '../../features/connectors/types';const log = createLogger('connector-meta-tools');@@ -85,7 +86,7 @@ function errResult(code: string, msg: string): ToolResult {function _descriptionLangForUser(uid: string): 'zh' | 'en' {try {- return descriptionLang(getLanguageForUser(uid));+ return descriptionLang(resolveLanguageForUser(uid));} catch {return 'en';}@@ -115,6 +116,58 @@ function _renderConnectorLine(instance: ConnectorInstance, lang: 'zh' | 'en'): s: `- **${instance.id}** — ${instance.display_name}${acct}${warn}`;}+const MAX_INLINE_CONNECTOR_TOOLS_CHARS = 30_000;+function _jsonStringify(value: unknown): string {+ try {+ return JSON.stringify(value ?? {}, null, 2);+ } catch {+ return '{}';+ }+}++function _schemaArgSummary(schema: Record<string, unknown> | undefined): string {+ const props = schema?.properties && typeof schema.properties === 'object' && !Array.isArray(schema.properties)+ ? schema.properties as Record<string, unknown>+ : {};+ const required = Array.isArray(schema?.required) ? new Set(schema.required.map(String)) : new Set<string>();+ const keys = Object.keys(props).slice(0, 12).map((key) => required.has(key) ? key : `${key}?`);+ const suffix = Object.keys(props).length > keys.length ? ', ...' : '';+ return keys.length ? ` args: ${keys.join(', ')}${suffix}` : ' args: {}';+}++function _shortDescription(text: string | undefined): string {+ const compact = String(text || '(no description)').replace(/\s+/g, ' ').trim();+ return compact.length > 220 ? `${compact.slice(0, 217)}...` : compact;+}++function _renderSingleToolSchema(cid: string, tool: ToolSchema): string {+ return [+ `Action on connector "${cid}": ${tool.name}`,+ tool.description || '(no description)',+ '',+ 'Invoke via:',+ `\`call_connector_tool({connector_id: "${cid}", tool_name: "${tool.name}", args: {…}})\``,+ '',+ 'Input schema:',+ '```json',+ _jsonStringify(tool.input_schema ?? {}),+ '```',+ ].join('\n').trimEnd();+}++function _renderCompactToolList(cid: string, tools: ToolSchema[]): string {+ const lines: string[] = [+ `Actions on connector "${cid}" (${tools.length}).`,+ `Call \`list_connector_tools({connector_id: "${cid}", tool_name: "<name>"})\` to expand one action's JSON input schema, then invoke it via ` ++ `\`call_connector_tool({connector_id: "${cid}", tool_name: "<name>", args: {…}})\`.`,+ '',+ ];+ for (const t of tools) {+ lines.push(`- **${t.name}** — ${_shortDescription(t.description)} (${_schemaArgSummary(t.input_schema)})`);+ }+ return lines.join('\n').trimEnd();+}+const MAX_RECOVERY_ACTIONS = 24;const MAX_RECOVERY_ACTION_LIST_CHARS = 3_000;@@ -138,7 +191,11 @@ function _unavailableActionMessage(cid: string, requestedTool: string, tools: To...names.map((name) => `- ${name}`),];if (omitted) lines.push(`- ... ${omitted} more actions omitted`);- lines.push('Choose an exact action name, then inspect its input schema before invoking it.');+ lines.push(+ 'Choose an exact action name. Call ' ++ `list_connector_tools({connector_id: "${cid}", tool_name: "<exact-name>"}) ` ++ 'to obtain its input schema before invoking it.',+ );return lines.join('\n');}@@ -171,11 +228,7 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {// discovery is read-only, aligning with the documented rule avoids a future// side-effectful connector tool inheriting `parallel` by copy-paste.description:- 'Discover the actions available on a specific connector (the system prompt\'s `## Connectors` ' +- 'block lists which connector ids exist for this conversation). Returns each action\'s name, ' +- 'description, and JSON input schema — use the schema verbatim to construct the `args` for ' +- '`call_connector_tool`. Errors when the connector id is not visible to this actor or is ' +- 'currently disconnected.',+ 'List visible connector ids when connector_id is omitted. With a connector_id, list its actions; add tool_name to return one action\'s full input schema before calling call_connector_tool.',inputSchema: {type: 'object',properties: {@@ -183,6 +236,10 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {type: 'string',description: 'Optional visible connector id. Omit to discover valid ids.',},+ tool_name: {+ type: 'string',+ description: 'Optional action name. When provided, returns only that action with its full input schema.',+ },},additionalProperties: false,},@@ -190,9 +247,27 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {const cid = typeof (input as { connector_id?: unknown }).connector_id === 'string'? ((input as { connector_id: string }).connector_id).trim(): '';- if (!cid) return errResult('E_BAD_INPUT', '`connector_id` is required (a non-empty string)');-+ const requestedTool = typeof (input as { tool_name?: unknown }).tool_name === 'string'+ ? ((input as { tool_name: string }).tool_name).trim()+ : '';+ if (!cid && requestedTool) {+ return errResult('E_BAD_INPUT', '`connector_id` is required when `tool_name` is provided');+ }const visible = await resolveVisibleConnectors(opts.userId);+ _recordVisibleConnectorDisplayNames(opts, visible);+ if (!cid) {+ const content = visible.length+ ? [+ 'Visible connectors. Choose an exact id, then call `list_connector_tools` again with `connector_id`.',+ '',+ ...visible.map(({ instance }) => _renderConnectorLine(+ instance,+ _descriptionLangForUser(opts.userId),+ )),+ ].join('\n')+ : 'No connectors are currently visible to this Agent. Ask the user to select or enable one.';+ return { content };+ }const match = visible.find((v) => v.instance.id === cid);if (!match) {// resolveVisibleConnectors already filters to `status.kind === 'connected'`, so a miss@@ -209,11 +284,22 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {content: `Connector "${cid}" reports no actions. Ask the user to refresh it from the Connectors panel.`,};}+ if (requestedTool) {+ const tool = match.tools.find((t) => t.name === requestedTool);+ if (!tool) {+ return errResult(+ 'E_TOOL_NOT_AVAILABLE',+ _unavailableActionMessage(cid, requestedTool, match.tools),+ );+ }+ return { content: _renderSingleToolSchema(cid, tool) };+ }const lines: string[] = [`Actions on connector "${cid}". Invoke any of them via ` +`\`call_connector_tool({connector_id: "${cid}", tool_name: "<name>", args: {…}})\` — ` +- '`args` MUST match the listed input_schema verbatim.',+ '`args` MUST match the listed input_schema verbatim. If this response is compact, call ' ++ `\`list_connector_tools({connector_id: "${cid}", tool_name: "<name>"})\` for one action's schema.`,'',];for (const t of match.tools) {@@ -222,15 +308,14 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {lines.push('');lines.push('Input schema:');lines.push('```json');- try {- lines.push(JSON.stringify(t.input_schema ?? {}, null, 2));- } catch {- lines.push('{}');- }+ lines.push(_jsonStringify(t.input_schema ?? {}));lines.push('```');lines.push('');}- return { content: lines.join('\n').trimEnd() };+ const full = lines.join('\n').trimEnd();+ const compact = full.length > MAX_INLINE_CONNECTOR_TOOLS_CHARS;+ const content = compact ? _renderCompactToolList(cid, match.tools) : full;+ return { content };},};}@@ -258,7 +343,7 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {},required: ['connector_id', 'tool_name', 'args'],},- async execute(input) {+ async execute(input, ctx) {const i = input as { connector_id?: unknown; tool_name?: unknown; args?: unknown };const cid = typeof i.connector_id === 'string' ? i.connector_id.trim() : '';const toolName = typeof i.tool_name === 'string' ? i.tool_name.trim() : '';@@ -308,11 +393,14 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {}try {- const raw = await manager.callTool(opts.userId, cid, toolName, args);- return { content: stringifyMcpResult(raw) };+ const normalizedArgs = normalizeConnectorArgs(args, toolMatch.input_schema);+ const raw = await manager.callTool(opts.userId, cid, toolName, normalizedArgs, { signal: ctx.signal });+ const content = stringifyMcpResult(raw);+ const protocolError = !!raw && typeof raw === 'object' && (raw as { isError?: unknown }).isError === true;+ return protocolError ? { content, isError: true } : { content };} catch (err) {const msg = (err as Error).message;- log.warn(`call_connector_tool failed connector=${cid} tool=${toolName}: ${msg}`);+ log.warn('call_connector_tool failed', { connector_id: maskId(cid), tool: toolName, error: logErrorRef(err) });return {content: `Error calling ${cid}/${toolName}: ${msg}`,isError: true,@@ -322,6 +410,25 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {};}+function normalizeConnectorArgs(+ args: Record<string, unknown>,+ schema: Record<string, unknown> | undefined,+): Record<string, unknown> {+ const properties = schema?.properties && typeof schema.properties === 'object' && !Array.isArray(schema.properties)+ ? schema.properties as Record<string, unknown>+ : {};+ const out: Record<string, unknown> = { ...args };+ for (const key of Object.keys(properties)) {+ if (!key.includes('_') || Object.prototype.hasOwnProperty.call(out, key)) continue;+ const camel = key.replace(/_([a-z])/g, (_m: string, ch: string) => ch.toUpperCase());+ if (Object.prototype.hasOwnProperty.call(out, camel)) {+ out[key] = out[camel];+ delete out[camel];+ }+ }+ return out;+}+/** Task-session tool: install a user-described custom MCP server. The* install ALWAYS requires the user to approve a confirmation dialog* (plan §C2 / §C3) — for stdio that dialog shows the exact command thatdiff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.tsindex bddadab5..a6ae1423 100644--- a/src/main/model/core-agent/event-mapper.ts+++ b/src/main/model/core-agent/event-mapper.ts@@ -619,6 +619,7 @@ export async function* mapCoreAgentEvents(let failureDetails: Pick<StreamEvent, 'failureKind' | 'failureCode' | 'failurePhase'> | null = null;const skillReadByToolId = new Map<string, SkillReadEventMetadata>();const agentReadByToolId = new Map<string, AgentReadEventMetadata>();+ const delegationByToolId = new Map<string, { agent_id: string; agent_name: string }>();const connectorByToolId = new Map<string, ConnectorEventMetadata>();const earlyToolStarts = new Set<string>();const toolDeltaNames = new Map<string, string>();@@ -859,6 +860,13 @@ export async function* mapCoreAgentEvents(toolDeltaNames.delete(ev.id);const skillMeta = skillReadMetadataForToolStart(ev.name, ev.input, opts);if (skillMeta) skillReadByToolId.set(ev.id, skillMeta);+ // Persist UI identity separately from agent.json read metadata so+ // replay does not depend on the currently selected conversation.+ if ((ev.name === 'dispatch_to' || ev.name === 'hand_off_to') && ev.input && typeof ev.input === 'object') {+ const id = String((ev.input as { to?: unknown }).to || '').trim();+ const name = opts.agentDisplayNameById?.get(id);+ if (id && name) delegationByToolId.set(ev.id, { agent_id: id, agent_name: name });+ }const agentMeta = agentReadMetadataForToolStart(ev.name, ev.input, opts);if (agentMeta) agentReadByToolId.set(ev.id, agentMeta);const connectorMeta = connectorMetadataForToolStart(ev.name, ev.input);@@ -880,6 +888,7 @@ export async function* mapCoreAgentEvents(...(resourceScope ? { resource_scope: resourceScope } : {}),...skillReadEventFields(skillMeta),...agentReadEventFields(agentMeta),+ ...delegationByToolId.get(ev.id),...connectorEventFields(connectorMeta, opts.connectorDisplayNameById),},},@@ -905,6 +914,7 @@ export async function* mapCoreAgentEvents(message: ev.message,...(ev.phase ? { progress_phase: ev.phase } : {}),...(ev.data ? { progress_data: ev.data } : {}),+ ...delegationByToolId.get(ev.id),},},};@@ -934,6 +944,8 @@ export async function* mapCoreAgentEvents(skillReadByToolId.delete(ev.id);const agentMeta = agentReadByToolId.get(ev.id) || null;agentReadByToolId.delete(ev.id);+ const delegationMeta = delegationByToolId.get(ev.id);+ delegationByToolId.delete(ev.id);const connectorMeta = connectorByToolId.get(ev.id) || null;connectorByToolId.delete(ev.id);// Two click-to-expand storage paths, decided here:@@ -962,6 +974,7 @@ export async function* mapCoreAgentEvents(...(ev.errorSeverity ? { errorSeverity: ev.errorSeverity } : {}),...skillReadEventFields(skillMeta),...agentReadEventFields(agentMeta),+ ...delegationMeta,...connectorEventFields(connectorMeta, opts.connectorDisplayNameById),};if (spill) {diff --git a/src/main/model/core-agent/external-providers.ts b/src/main/model/core-agent/external-providers.tsindex cac298cd..ef9f7f91 100644--- a/src/main/model/core-agent/external-providers.ts+++ b/src/main/model/core-agent/external-providers.ts@@ -1,6 +1,6 @@/**- * External providers — factories for chat providers that pi-ai 0.68.1- * doesn't ship out of the box.+ * External providers — factories for chat providers with app-specific ids+ * and endpoint configuration.** Each factory hand-builds a pi-ai `Model<TApi>` object and passes it to* `createPiProvider({ customModel })`. That route bypasses pi-ai's@@ -102,6 +102,31 @@ function configuredModelVisionDeclaration(model: {return undefined;}+function alignDeepSeekReasoningPayload(params: unknown): unknown {+ try {+ const p = params as { reasoning_effort?: string; messages?: Array<{ role?: string; reasoning_content?: unknown; reasoning?: unknown }> };+ const priorAssistants = (p.messages || []).filter((m) => m && m.role === 'assistant');+ if (priorAssistants.length === 0) {+ // No prior turns — nothing to be inconsistent with. Preserve an+ // explicitly requested reasoning_effort; an omitted control remains+ // omitted so DeepSeek applies the selected model's official defaults.+ return params;+ }+ const allHaveReasoning = priorAssistants.every(+ (m) => (typeof m.reasoning_content === 'string' && m.reasoning_content.length > 0)+ || (typeof m.reasoning === 'string' && (m.reasoning as string).length > 0),+ );+ if (!allHaveReasoning && p.reasoning_effort !== undefined) {+ delete p.reasoning_effort;+ }+ } catch { /* never let onPayload throw — pi-ai treats throw as fatal */ }+ return params;+}++export function repairDeepSeekPayload(params: unknown): unknown {+ return repairOpenAIToolMessageOrder(alignDeepSeekReasoningPayload(params));+}+export function repairOpenAICompatiblePayload(params: unknown): unknown {return repairOpenAIToolMessageOrder(params);}@@ -145,6 +170,7 @@ export async function createOrkasApiProvider(config: {customModel: buildOrkasApiModel(config.modelId),defaultReasoning: 'low',headers: orkasApiUsageHeaders(config.usageContext),+ onPayload: repairOpenAICompatiblePayload,});}@@ -156,12 +182,13 @@ const MOONSHOT_BASE_URL = 'https://api.moonshot.cn/v1';* Context windows by Moonshot model id. Numbers come from* platform.kimi.com/docs/models (checked 2026-06). Fallback 131072 for* ids we haven't catalogued — safe lower bound given every current kimi- * model is at least 128k. Legacy ids still resolve via fallback if a stale- * credential references them.+ * model is at least 128k. Legacy K2 preview ids still resolve via fallback+ * if a stale credential references them.*/const MOONSHOT_CONTEXT_WINDOW: Record<string, number> = {'kimi-k3': 1048576,'kimi-k2.7-code': 262144,+ 'kimi-k2.7-code-highspeed': 262144,'kimi-k2.6': 262144,'kimi-k2.5': 262144,};@@ -172,8 +199,8 @@ function moonshotContextWindow(modelId: string): number {// Per-model max output tokens. Why this needs a per-model table: pi-ai's// `simple-options.buildBaseOptions` reads `model.maxTokens` as the default-// `max_tokens` request param (clamped at 32000 ceiling); a single hard-coded-// value caps every model at the lowest common denominator and complex+// `max_tokens` request param and fits it to the remaining context; a single+// hard-coded value caps every model at the lowest common denominator and complex// structured replies get cut mid-stream with `stopReason: "length"` while// the renderer just shows whatever streamed before the cap. Numbers from// platform.kimi.com/docs/models (2026-06). Unknown ids fall back to 8192@@ -181,7 +208,8 @@ function moonshotContextWindow(modelId: string): number {const MOONSHOT_MAX_OUTPUT_TOKENS: Record<string, number> = {'kimi-k3': 131072,'kimi-k2.7-code': 32768,- 'kimi-k2.6': 16384,+ 'kimi-k2.7-code-highspeed': 32768,+ 'kimi-k2.6': 32768,'kimi-k2.5': 16384,};@@ -189,6 +217,10 @@ function moonshotMaxOutputTokens(modelId: string): number {return MOONSHOT_MAX_OUTPUT_TOKENS[modelId] ?? 8192;}+// K3 was added to pi-ai in 0.80.9. Keep this small local fallback so the+// synchronous catalog/window path remains accurate, but use pi-ai's native+// model at runtime (see buildRuntimeMoonshotModel) so future protocol changes+// do not have to be mirrored here before requests can work.const MOONSHOT_K3_PROTOCOL_FALLBACK: Pick<Model<'openai-completions'>,'reasoning' | 'thinkingLevelMap' | 'input' | 'compat'@@ -201,6 +233,7 @@ const MOONSHOT_K3_PROTOCOL_FALLBACK: Pick<medium: null,high: null,xhigh: null,+ max: 'max',},input: ['text', 'image'],compat: {@@ -211,17 +244,33 @@ const MOONSHOT_K3_PROTOCOL_FALLBACK: Pick<supportsStrictMode: false,thinkingFormat: 'deepseek',requiresReasoningContentOnAssistantMessages: true,+ deferredToolsMode: 'kimi',},};+type PiBuiltinCatalog = typeof import('@earendil-works/pi-ai/providers/all');+let _piBuiltinCatalogPromise: Promise<PiBuiltinCatalog> | null = null;+function piBuiltinCatalog(): Promise<PiBuiltinCatalog> {+ if (!_piBuiltinCatalogPromise) {+ _piBuiltinCatalogPromise = import('@earendil-works/pi-ai/providers/all');+ }+ return _piBuiltinCatalogPromise;+}+/*** Build a `Model<"openai-completions">` object for a Moonshot model.* Exported for tests — production code usually goes through* `createMoonshotProvider()`.*/-export function buildMoonshotModel(modelId: string): Model<'openai-completions'> {+export function buildMoonshotModel(+ modelId: string,+ nativeModel?: Model<'openai-completions'>,+): Model<'openai-completions'> {+ // Server model_catalog metadata is authoritative when present. The local+ // tables remain conservative fallbacks for offline/stale configurations.const curated = curatedModelsFor('moonshot').find((m) => m.id === modelId);- const protocol = modelId === 'kimi-k3' ? MOONSHOT_K3_PROTOCOL_FALLBACK : null;+ const fallbackProtocol = modelId === 'kimi-k3' ? MOONSHOT_K3_PROTOCOL_FALLBACK : null;+ const protocol = nativeModel || fallbackProtocol;return {id: modelId,name: curated?.name || modelId,@@ -231,7 +280,9 @@ export function buildMoonshotModel(modelId: string): Model<'openai-completions'>provider: 'moonshot' as any,baseUrl: MOONSHOT_BASE_URL,reasoning: protocol?.reasoning ?? false,- ...(protocol?.thinkingLevelMap ? { thinkingLevelMap: { ...protocol.thinkingLevelMap } } : {}),+ ...(protocol?.thinkingLevelMap+ ? { thinkingLevelMap: { ...protocol.thinkingLevelMap } }+ : {}),input: modelInputFromConfiguredCapabilities(protocol ? [...protocol.input] : ['text', 'image'],curated,@@ -243,10 +294,21 @@ export function buildMoonshotModel(modelId: string): Model<'openai-completions'>cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },contextWindow: configuredPositiveInteger(curated?.contextWindow, moonshotContextWindow(modelId)),maxTokens: configuredPositiveInteger(curated?.maxTokens, moonshotMaxOutputTokens(modelId)),+ ...(nativeModel?.headers ? { headers: { ...nativeModel.headers } } : {}),...(protocol?.compat ? { compat: { ...protocol.compat } } : {}),};}+/** Build the request-time model with pi-ai's native Moonshot protocol data. */+export async function buildRuntimeMoonshotModel(modelId: string): Promise<Model<'openai-completions'>> {+ const catalog = await piBuiltinCatalog();+ const nativeModel = (catalog.getBuiltinModel as (+ providerId: string,+ requestedModelId: string,+ ) => Model<'openai-completions'> | undefined)('moonshotai-cn', modelId);+ return buildMoonshotModel(modelId, nativeModel);+}+export interface CreateMoonshotProviderConfig {apiKey: string;modelId: string;@@ -264,12 +326,15 @@ export interface CreateMoonshotProviderConfig {export async function createMoonshotProvider(config: CreateMoonshotProviderConfig): Promise<LLMProvider> {if (!config.apiKey) throw new Error('moonshot: apiKey required');if (!config.modelId) throw new Error('moonshot: modelId required');- const mod = await ca();- const model = buildMoonshotModel(config.modelId);+ const [mod, model] = await Promise.all([+ ca(),+ buildRuntimeMoonshotModel(config.modelId),+ ]);return mod.createPiProvider({provider: 'moonshot',apiKey: config.apiKey,customModel: model,+ onPayload: repairOpenAICompatiblePayload,});}@@ -372,29 +437,9 @@ export async function createDeepSeekProvider(config: CreateDeepSeekProviderConfi// Fix: `onPayload` decides reasoning_effort dynamically — inspect// every prior assistant turn for reasoning_content// ("reasoning consistent"):- // - all have → keep reasoning_effort (covers A in reverse)- // - not all → drop reasoning_effort (covers B)- onPayload: (params) => {- try {- const p = params as { reasoning_effort?: string; messages?: Array<{ role?: string; reasoning_content?: unknown; reasoning?: unknown }> };- const priorAssistants = (p.messages || []).filter((m) => m && m.role === 'assistant');- if (priorAssistants.length === 0) {- // No prior turns — nothing to be inconsistent with. Default- // direction: keep reasoning_effort if model.reasoning=true so a- // fresh thinking-mode session works.- return params;- }- const allHaveReasoning = priorAssistants.every(- (m) => (typeof m.reasoning_content === 'string' && m.reasoning_content.length > 0)- || (typeof m.reasoning === 'string' && (m.reasoning as string).length > 0),- );- if (!allHaveReasoning && p.reasoning_effort !== undefined) {- delete p.reasoning_effort;- }- } catch { /* never let onPayload throw — pi-ai treats throw as fatal */ }- return params;- },- ...(model.reasoning ? { defaultReasoning: 'low' as const } : {}),+ // - all have → keep an explicitly requested reasoning_effort+ // - not all → drop only that explicit effort+ onPayload: repairDeepSeekPayload,});}@@ -468,6 +513,7 @@ export async function createDoubaoProvider(config: CreateDoubaoProviderConfig):provider: 'doubao',apiKey: config.apiKey,customModel: model,+ onPayload: repairOpenAICompatiblePayload,});}diff --git a/src/main/model/core-agent/image-gen-tool.ts b/src/main/model/core-agent/image-gen-tool.tsindex d8af9430..b45a794a 100644--- a/src/main/model/core-agent/image-gen-tool.ts+++ b/src/main/model/core-agent/image-gen-tool.ts@@ -2,10 +2,10 @@* `generate_image` tool — produces an image with whatever image-gen-capable* api_key entry sits highest in the user's auth-profiles priority list.*- * Permission gating: same as `bash` / `write_file` (`localExec.granted`).- * Reuses `localExec` rather than introducing a parallel switch — the user's- * mental model is "let this app touch my machine" and writing image bytes- * to a workspace path is the same blast radius as `write_file`.+ * Permission posture: shares the `localExec` local-access mode with `bash` /+ * `write_file` rather than introducing a parallel switch. The user's mental+ * model is "let this app touch my machine", and writing image bytes to a+ * workspace path is the same blast radius as `write_file`.** Path scope: same sandbox as `read_file` / `write_file`* (active workspace ∪ current cid's attachment dir). `output_path` and every@@ -21,11 +21,39 @@ import * as fs from 'node:fs';import type { AgentTool, ToolContext, ToolResult } from '#core-agent';import { generateImage } from '../../features/image_gen';+import {+ IMAGE_REFERENCE_ROLES,+ compileImagePromptContract,+ normalizeImageReferenceBindings,+ normalizeImageStringList,+ type ImageReferenceBinding,+} from '../../features/image_prompt_contract';import { isPathAllowed } from '../../util/path-sandbox';import { uniquifyPath, renderRenameSignal } from '../../util/uniquify-path';+import { noteGeneration, regenerationWarning } from '../../util/generation-guard';import { getWorkspacePath } from '../../features/user_workspace';-import { chatAttachmentDir } from '../../paths';+import { chatAttachmentDirForConversation } from '../../util/project-layout';import { createLogger } from '../../logger';+import { logErrorRef, logPathRef, maskId } from '../../util/log-redact';+import { versionedChatMediaLocalUrl } from '../../util/chat-media-url';+import {+ beginVideoProductionGeneration,+ finishVideoProductionGeneration,+ videoProductionControlStatePath,+ type VideoProductionGenerationTransaction,+} from '../../features/video_production_control';+import {+ beginImageStudioGeneration,+ findReusableImageStudioGeneration,+ finishImageStudioGeneration,+ imageGenerationControlStatePath,+ type ImageGenerationTransaction,+} from '../../features/image_production_control';+import {+ estimateImageProductionCredits,+ type ImageProductionCreditQuote,+} from '../../features/image_production_credits';+import { IMAGE_STUDIO_AGENT_ID, VIDEO_STUDIO_AGENT_ID } from './tool-catalog';const log = createLogger('image-gen-tool');@@ -34,13 +62,17 @@ export interface ImageGenToolOpts {/** Conversation id — extends the path sandbox to allow writing into* the conv's attachment dir (and reading reference images from it). */cid?: string;- turnId?: string;+ conversationTitle?: string;+ conversationTitleUpdatedAt?: number;/** Project id of the current conversation, when it belongs to one.* Threaded through from group_chat so workspace resolution picks up* the project-scoped selection (per CLAUDE.md projects feature). */projectId?: string;+ turnId?: string;+ agentId?: string;+ agentName?: string;/** Same contract as `local-tools.LocalToolsOpts.onFileWritten`. */- onFileWritten?: (absPath: string) => void;+ onFileWritten?: (absPath: string) => void | Promise<void>;/** Same contract as `local-tools.LocalToolsOpts.hasProducedPath`:* caller-supplied predicate that returns true when this path was* already written by the same caller this turn (refinement → overwrite@@ -53,10 +85,10 @@ function allowedRoots(opts: ImageGenToolOpts): string[] {try {const ws = getWorkspacePath(opts.userId, opts.projectId);if (ws) roots.push(ws);- } catch (err) { log.warn(`resolve workspace: ${(err as Error).message}`); }+ } catch (err) { log.warn('resolve workspace failed', { user_id: maskId(opts.userId), project_id: maskId(opts.projectId), error: logErrorRef(err) }); }if (opts.cid) {- try { roots.push(chatAttachmentDir(opts.userId, opts.cid)); }- catch (err) { log.warn(`resolve attachment dir: ${(err as Error).message}`); }+ try { roots.push(chatAttachmentDirForConversation(opts.userId, opts.cid)); }+ catch (err) { log.warn('resolve attachment dir failed', { user_id: maskId(opts.userId), cid: maskId(opts.cid), error: logErrorRef(err) }); }}return roots;}@@ -65,6 +97,14 @@ function resolveAbs(ctx: ToolContext, p: string): string {return path.resolve(ctx.workingDir ?? '.', p);}+function possibleImageOutputPaths(p: string): string[] {+ const lower = p.toLowerCase();+ if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.webp')) {+ return [p];+ }+ return [`${p}.png`, `${p}.jpg`, `${p}.webp`];+}+export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {return {name: 'generate_image',@@ -80,24 +120,59 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {output_path: {type: 'string',description:- 'Where to write the image. Absolute path or relative to the workspace. '- + 'Must fall inside the workspace or the current conversation\'s attachment dir. '- + 'Extension (.png/.jpg/.webp) is optional — added automatically based on the returned format. '- + 'If the target already exists and was not written by you this turn, the basename is '- + 'automatically suffixed (`-2 / -3 / ...`); the rename is surfaced in a `<file-renamed>` '- + 'block in the tool result. Always use the saved path verbatim for any follow-up reads '- + 'or markdown image links.',+ 'Where to write the image. Absolute or workspace-relative; must be in workspace/attachments. Extension optional; collisions auto-suffix and return <file-renamed>.',},reference_images: {type: 'array',items: { type: 'string' },- description:- 'Optional absolute paths to reference images for editing/variations. '- + 'Each must fall inside the same scope as `output_path`. Up to 4.',+ description: 'Optional local reference image paths for editing/variations in the same scope as output_path. Up to 4 references total, including reference_image_urls.',+ },+ reference_image_urls: {+ type: 'array',+ items: { type: 'string' },+ description: 'Optional HTTPS reference image URLs for editing/variations.',+ },+ reference_bindings: {+ type: 'array',+ description: 'Optional role contract for references. Indices use reference_images first, then reference_image_urls. Use this to distinguish identity, style, composition, structure, content, mask, and edit-source references.',+ items: {+ type: 'object',+ properties: {+ index: { type: 'number' },+ role: { type: 'string', enum: IMAGE_REFERENCE_ROLES },+ strength: { type: 'number', description: 'Reference influence from 0 to 1.' },+ preserve: { type: 'array', items: { type: 'string' } },+ may_change: { type: 'array', items: { type: 'string' } },+ region: { type: 'string' },+ },+ required: ['index', 'role'],+ },+ },+ negative_prompt: {+ type: 'array',+ items: { type: 'string' },+ description: 'Explicit unwanted objects, artifacts, text failures, or style properties.',},size: {type: 'string',- description: 'Provider size hint. One of: 1024x1024 (default), 1536x1024, 1024x1536, auto.',+ description:+ 'Provider size hint. Seedream supports 2K (default after normalization), 3K, 4K, or a valid WIDTHxHEIGHT; other providers commonly use 1024x1024, 1536x1024, 1024x1536, or auto.',+ },+ production_plan_path: {+ type: 'string',+ description: 'VideoStudio only: approved project/plan.json that owns this billable segment.',+ },+ production_segment_id: {+ type: 'string',+ description: 'VideoStudio only: approved image-generate segment id in production_plan_path.',+ },+ image_project_path: {+ type: 'string',+ description: 'ImageStudio only: image project directory whose image-manifest.json owns the route and durable per-turn generation budget.',+ },+ image_request_id: {+ type: 'string',+ description: 'ImageStudio only: stable unique id for this billable generation intent within the current user turn. Reusing a completed id in the same turn reuses its output; every new id consumes one current-turn project budget slot.',},},required: ['prompt', 'output_path'],@@ -116,7 +191,12 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {const isMine: (p: string) => boolean = opts.hasProducedPath? (p) => opts.hasProducedPath!(p): () => false;- const { finalPath: outputAbs, renamed } = await uniquifyPath(requestedAbs, isMine);+ const videoStudioControlled = opts.agentId === VIDEO_STUDIO_AGENT_ID;+ const imageStudioControlled = opts.agentId === IMAGE_STUDIO_AGENT_ID;+ const unique = videoStudioControlled+ ? { finalPath: requestedAbs, renamed: false }+ : await uniquifyPath(requestedAbs, isMine);+ const { finalPath: outputAbs, renamed } = unique;const roots = allowedRoots(opts);if (!isPathAllowed(outputAbs, roots)) {return {@@ -124,11 +204,21 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {isError: true,} as ToolResult;}+ const escapedSuffixedOutput = possibleImageOutputPaths(outputAbs).find((p) => !isPathAllowed(p, roots));+ if (escapedSuffixedOutput) {+ return {+ content: `E_PATH_OUT_OF_SCOPE: output_path with generated image extension is outside the current scope (workspace + attachments): ${escapedSuffixedOutput}`,+ isError: true,+ } as ToolResult;+ }const referenceImages: string[] = Array.isArray(input.reference_images)? (input.reference_images as unknown[]).map(String).filter(Boolean): [];- if (referenceImages.length > 4) {+ const referenceImageUrls: string[] = Array.isArray(input.reference_image_urls)+ ? (input.reference_image_urls as unknown[]).map(String).map((s) => s.trim()).filter(Boolean)+ : [];+ if (referenceImages.length + referenceImageUrls.length > 4) {return { content: 'reference_images: at most 4 entries allowed', isError: true } as ToolResult;}const refAbs: string[] = [];@@ -146,33 +236,236 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {refAbs.push(abs);}+ let referenceBindings: ImageReferenceBinding[] = [];+ let negativePrompt: string[] = [];+ try {+ referenceBindings = normalizeImageReferenceBindings(input.reference_bindings, refAbs.length + referenceImageUrls.length);+ negativePrompt = normalizeImageStringList(input.negative_prompt, 'negative_prompt');+ } catch (error) {+ return { content: (error as Error).message, isError: true } as ToolResult;+ }+ const providerPrompt = compileImagePromptContract(prompt, referenceBindings, negativePrompt);+const sizeRaw = typeof input.size === 'string' ? input.size : undefined;- const result = await generateImage({- prompt,- outputAbsPath: outputAbs,- ...(refAbs.length ? { referenceImagePaths: refAbs } : {}),- ...(sizeRaw ? { size: sizeRaw } : {}),- ...(ctx.signal ? { signal: ctx.signal } : {}),- usageContext: {- conversationId: opts.cid,- turnId: opts.turnId,- },- });+ let productionPlanAbs = '';+ let productionStatePath = '';+ let productionTransaction: VideoProductionGenerationTransaction | undefined;+ if (videoStudioControlled) {+ const planRaw = String(input.production_plan_path ?? '').trim();+ const segmentId = String(input.production_segment_id ?? '').trim();+ if (!planRaw || !segmentId) {+ return {+ content: 'E_VIDEO_PRODUCTION_CONTEXT_REQUIRED: VideoStudio generate_image requires production_plan_path and production_segment_id.',+ isError: true,+ } as ToolResult;+ }+ productionPlanAbs = resolveAbs(ctx, planRaw);+ if (!isPathAllowed(productionPlanAbs, roots)) {+ return { content: `E_PATH_OUT_OF_SCOPE: production_plan_path is outside scope: ${productionPlanAbs}`, isError: true } as ToolResult;+ }+ if (!fs.statSync(productionPlanAbs, { throwIfNoEntry: false })?.isFile()) {+ return { content: 'E_VIDEO_PRODUCTION_PLAN_MISSING: production_plan_path is not a file', isError: true } as ToolResult;+ }+ productionStatePath = videoProductionControlStatePath({+ userId: opts.userId,+ ...(opts.projectId ? { projectId: opts.projectId } : {}),+ planPath: productionPlanAbs,+ });+ try {+ const begun = await beginVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ segmentId,+ kind: 'image',+ outputPath: outputAbs,+ candidateOutputPaths: possibleImageOutputPaths(outputAbs),+ request: {+ prompt: providerPrompt,+ reference_images: referenceImages,+ reference_image_urls: referenceImageUrls,+ ...(referenceBindings.length ? { reference_bindings: referenceBindings } : {}),+ ...(negativePrompt.length ? { negative_prompt: negativePrompt } : {}),+ ...(sizeRaw ? { size: sizeRaw } : {}),+ },+ });+ if (begun.status === 'reused') {+ if (opts.onFileWritten) await opts.onFileWritten(begun.transaction.output_path);+ return {+ content: `VideoStudio reused the completed billable transaction for segment ${segmentId}: ${begun.transaction.output_path}. Show it with: })`,+ } as ToolResult;+ }+ productionTransaction = begun.transaction;+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }+ }++ let imageProjectAbs = '';+ let imageStatePath = '';+ let imageTransaction: ImageGenerationTransaction | undefined;+ let imageCreditQuote: ImageProductionCreditQuote | undefined;+ if (imageStudioControlled) {+ const projectRaw = String(input.image_project_path ?? '').trim();+ const requestId = String(input.image_request_id ?? '').trim();+ if (!projectRaw || !requestId) {+ return {+ content: 'E_IMAGE_GENERATION_CONTEXT_REQUIRED: ImageStudio generate_image requires image_project_path and image_request_id.',+ isError: true,+ } as ToolResult;+ }+ imageProjectAbs = resolveAbs(ctx, projectRaw);+ if (!isPathAllowed(imageProjectAbs, roots)) {+ return { content: `E_PATH_OUT_OF_SCOPE: image_project_path is outside scope: ${imageProjectAbs}`, isError: true } as ToolResult;+ }+ if (!fs.statSync(imageProjectAbs, { throwIfNoEntry: false })?.isDirectory()) {+ return { content: 'E_IMAGE_GENERATION_PROJECT_MISSING: image_project_path is not a directory', isError: true } as ToolResult;+ }+ imageStatePath = imageGenerationControlStatePath(opts.userId, imageProjectAbs);+ try {+ const reusable = await findReusableImageStudioGeneration(imageStatePath, requestId, opts.turnId);+ if (reusable?.output_path) {+ if (opts.onFileWritten) await opts.onFileWritten(reusable.output_path);+ return {+ content: `ImageStudio reused completed generation ${requestId}: ${reusable.output_path}. Show it with: })`,+ } as ToolResult;+ }+ imageCreditQuote = await estimateImageProductionCredits({+ requestId,+ ...(sizeRaw ? { size: sizeRaw } : {}),+ referenceCount: refAbs.length + referenceImageUrls.length,+ }, ctx.signal);+ if (imageCreditQuote.unavailable_segment_ids.length) {+ return {+ content: `E_IMAGE_PRODUCTION_PROVIDER_UNAVAILABLE: no configured image-generation provider for request ${requestId}. No generation transaction was started.`,+ isError: true,+ } as ToolResult;+ }+ const begun = await beginImageStudioGeneration({+ stateAbsPath: imageStatePath,+ projectDirAbs: imageProjectAbs,+ requestId,+ outputAbsPath: outputAbs,+ ...(opts.turnId ? { turnId: opts.turnId } : {}),+ });+ if (begun.status === 'reused') {+ const reusedPath = begun.transaction.output_path!;+ if (opts.onFileWritten) await opts.onFileWritten(reusedPath);+ return {+ content: `ImageStudio reused completed generation ${requestId}: ${reusedPath}. Show it with: })`,+ } as ToolResult;+ }+ imageTransaction = begun.transaction;+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }+ }++ let result: Awaited<ReturnType<typeof generateImage>>;+ try {+ result = await generateImage({+ prompt: providerPrompt,+ outputAbsPath: outputAbs,+ ...(refAbs.length ? { referenceImagePaths: refAbs } : {}),+ ...(referenceImageUrls.length ? { referenceImageUrls } : {}),+ ...(referenceBindings.length ? { referenceBindings } : {}),+ ...(negativePrompt.length ? { negativePrompt } : {}),+ ...(sizeRaw ? { size: sizeRaw } : {}),+ ...(ctx.signal ? { signal: ctx.signal } : {}),+ onProgress: (event) => {+ ctx.emitProgress?.({+ phase: event.phase,+ message: event.message,+ ...(event.data ? { data: event.data } : {}),+ });+ },+ usageContext: { conversationId: opts.cid, turnId: opts.turnId },+ });+ } catch (err) {+ return {+ content: productionTransaction+ ? `E_VIDEO_PRODUCTION_GENERATION_UNCERTAIN: provider dispatch ended without a terminal result (${(err as Error).message || String(err)}); keep the pending transaction and do not retry without a new explicit Gate C approval.`+ : imageTransaction+ ? `E_IMAGE_GENERATION_UNCERTAIN: provider dispatch ended without a terminal result (${(err as Error).message || String(err)}); the request remains pending and still counts toward the current turn's project budget.`+ : `[PROVIDER_EXCEPTION] ${(err as Error).message || String(err)}`,+ isError: true,+ } as ToolResult;+ }if (result.ok === false) {+ if (productionTransaction) {+ try {+ await finishVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'image',+ ok: false,+ errorCode: result.errorCode,+ });+ } catch (err) {+ return { content: `${(err as Error).message}; provider error=[${result.errorCode}] ${result.message}`, isError: true } as ToolResult;+ }+ }+ if (imageTransaction) {+ try {+ await finishImageStudioGeneration({+ stateAbsPath: imageStatePath,+ transactionId: imageTransaction.transaction_id,+ ok: false,+ errorCode: result.errorCode,+ });+ } catch (err) {+ return { content: `${(err as Error).message}; provider error=[${result.errorCode}] ${result.message}`, isError: true } as ToolResult;+ }+ }return { content: `[${result.errorCode}] ${result.message}`, isError: true } as ToolResult;}+ if (productionTransaction) {+ try {+ await finishVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'image',+ ok: true,+ outputPath: result.path,+ });+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }+ }+ if (imageTransaction) {+ try {+ await finishImageStudioGeneration({+ stateAbsPath: imageStatePath,+ transactionId: imageTransaction.transaction_id,+ ok: true,+ outputPath: result.path,+ });+ } catch (err) {+ return { content: (err as Error).message, isError: true } as ToolResult;+ }+ }+if (opts.onFileWritten) {- try { opts.onFileWritten(result.path); }- catch (err) { log.warn(`onFileWritten callback failed: ${(err as Error).message}`); }+ try { await opts.onFileWritten(result.path); }+ catch (err) { log.warn('onFileWritten callback failed', { path: logPathRef(result.path), error: logErrorRef(err) }); }}+ // Soft guard: count (re)generations of THIS requested deliverable and+ // surface a one-line warning past the threshold — billable, never blocked.+ const guardNote = regenerationWarning(noteGeneration(opts.cid, requestedAbs), 'image');const summary =`Image written to ${result.path} `+ `(${result.width}x${result.height}, ${result.bytes} bytes, ${result.provider}/${result.model}). `- + `Show it to the user with: `;+ + (result.sourceUrl ? `Source URL: ${result.sourceUrl}. ` : '')+ + `Show it to the user with: })`+ + (imageCreditQuote ? `\nImageStudio local provider availability before dispatch: ${JSON.stringify(imageCreditQuote)}` : '')+ + (guardNote ? `\n${guardNote}` : '');const content = renamed ? `${summary}${renderRenameSignal(requestedAbs, result.path)}` : summary;return { content } as ToolResult;},diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex bd8aa7a1..813585dd 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -4800,7 +4800,8 @@ function createMarkdownToPdfTool(opts: LocalToolsOpts): AgentTool {}if (outcome.kind === 'render') return { content: outcome.err, isError: true };const { finalPath, renamed } = outcome;- if (opts.onFileWritten) await opts.onFileWritten(finalPath);+ try { await opts.onFileWritten?.(finalPath); }+ catch (err) { log.warn('PDF publication callback failed', { error: logErrorRef(err) }); }const base = `PDF written: ${finalPath}`;return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };},@@ -4870,7 +4871,8 @@ function createHtmlToPdfTool(opts: LocalToolsOpts): AgentTool {}if (outcome.kind === 'render') return { content: outcome.err, isError: true };const { finalPath, renamed } = outcome;- if (opts.onFileWritten) await opts.onFileWritten(finalPath);+ try { await opts.onFileWritten?.(finalPath); }+ catch (err) { log.warn('PDF publication callback failed', { error: logErrorRef(err) }); }const base = `PDF written: ${finalPath}`;return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };},diff --git a/src/main/model/core-agent/rotating-provider.ts b/src/main/model/core-agent/rotating-provider.tsindex b94d096f..21c0cb8f 100644--- a/src/main/model/core-agent/rotating-provider.ts+++ b/src/main/model/core-agent/rotating-provider.ts@@ -42,7 +42,12 @@** On a credential/account rotatable failure: `markCooldown(profileId, kind, reason)`.* Network failures are never cooled down; each new user request starts from- * the configured entries list again.+ * the configured entries list again. Within one run, though, a candidate whose+ * network failure exhausted its retry budget while a LATER candidate committed+ * is latched out of the remaining model rounds (run-local only) — otherwise+ * every tool-loop round re-pays the dead candidate's full timeout/retry+ * ladder. A sweep where every candidate fails network-class latches nothing,+ * so a transient machine-local outage keeps full retry on the next call.* On a successful first-event-yield: `onSuccess(profileId)` fires so* callers can clear any prior cooldown + bump lastUsed.*/@@ -183,8 +188,8 @@ export function boundMessagesForImageLimit(}const omittedImages = totalImages - limit;const notice = limit > 0- ? `<model-image-limit max_images="${limit}" omitted_images="${omittedImages}">Only the retained image blocks in this request are visually available. Use attachment manifest paths with read_file one image at a time for omitted images; do not claim visual processing from a listed path alone.</model-image-limit>`- : `<model-image-limit max_images="0" omitted_images="${omittedImages}" vision_supported="false">This model cannot receive image blocks, including read_file image previews. Do not claim visual analysis. When ocr_file is available it may extract text; otherwise explain that a vision-capable model is required.</model-image-limit>`;+ ? `<model-image-limit max_images="${limit}" omitted_images="${omittedImages}">Only the retained image blocks in this request are visually available. Use attachment manifest paths with read_files one image at a time for omitted images; do not claim visual processing from a listed path alone.</model-image-limit>`+ : `<model-image-limit max_images="0" omitted_images="${omittedImages}" vision_supported="false">This model cannot receive image blocks, including read_files image previews. Do not claim visual analysis. When ocr_file is available it may extract text; otherwise explain that a vision-capable model is required.</model-image-limit>`;projected.push({role: 'user',content: [{ type: 'text', text: notice }],@@ -245,10 +250,16 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LL0,Math.trunc(config.normalEmptyRetryAttempts ?? NORMAL_EMPTY_RETRY_ATTEMPTS),);- // A credential/account failure or a provider that never produced its first- // usable event is kept out of later model rounds in this agent run. This is- // run-local only; only credential failures enter the persisted cooldown.+ // A credential/account failure, a provider that never produced its first+ // usable event, or a network-exhausted candidate that a later candidate+ // outlived (see the per-call networkFailedThisCall sets) is kept out of+ // later model rounds in this agent run. This is run-local only; only+ // credential failures enter the persisted cooldown.const unavailableProfiles = new Set<string>();+ // W4-2: stream() runs once per tool-loop round with the full history, so+ // without this run-local latch the same "images omitted" notice repeats on+ // every remaining round of the turn.+ let imagesOmittedAnnounced = false;const cooldownIdFor = (candidate: RotatingCandidate): string => (candidate.cooldownId || candidate.profileId@@ -293,6 +304,23 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLconst next = { ...params, model: cand.modelId };if (typeof cand.maxInputImages === 'number' && Number.isFinite(cand.maxInputImages)) {next.messages = boundMessagesForImageLimit(params.messages, cand.maxInputImages);+ // W4-2 evidence: a text-only model silently loses every attached image+ // here, and the visible symptom is the model "admitting" it cannot see+ // — sampled users debugged that as their own mistake. Log the drop so+ // diagnosis has a recorded fact; the user-facing notice needs the+ // provider_fallback-style event plumbing (recorded in the plan doc).+ if (cand.maxInputImages === 0) {+ const dropped = params.messages.reduce(+ (sum, message) => sum + message.content.filter((content) => content.type === 'image').length,+ 0,+ );+ if (dropped > 0) {+ log.warn('image attachments dropped for text-only model', {+ provider_id: cand.providerId,+ dropped_images: dropped,+ });+ }+ }}const metadata = params.requestMetadata;const usesModelDefault = !!metadata@@ -411,6 +439,7 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLtype EmptyObservation = {kind: ProviderEmptyKind;terminalEventSeen: boolean;+ terminationCategory?: ProviderTerminationCategory;usage?: Partial<Usage>;};@@ -594,6 +623,7 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLempty: {kind,terminalEventSeen: true,+ terminationCategory: category ?? 'unknown',...((ev as Extract<StreamEvent, { type: 'message_end' }>).usage? { usage: (ev as Extract<StreamEvent, { type: 'message_end' }>).usage }: {}),@@ -619,6 +649,9 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLlet lastFailure: PreCommitFailure | null = null;let exhaustedNetwork = false;const retryAttempts = retryAttemptsFor(params);+ // Deferred network latch — same contract as stream(); see the comment+ // there for why promotion only happens after a later candidate succeeds.+ const networkFailedThisCall = new Set<string>();reportCandidates();if (params.signal?.aborted) {throw abortError(params.signal);@@ -640,6 +673,7 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLthrowIfAborted((params as { signal?: AbortSignal }).signal);config.onCandidateChosen?.({ profileId: cand.profileId, providerId: cand.providerId, modelId: cand.modelId });config.onSuccess?.(cand.profileId, cand);+ for (const id of networkFailedThisCall) unavailableProfiles.add(id);return result;} catch (err) {const signal = (params as { signal?: AbortSignal }).signal;@@ -671,6 +705,8 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLif (failure.cooldownKind && failure.cooldownKind !== 'network') {markCooldown(cooldownIdFor(cand), failure.cooldownKind, reason);unavailableProfiles.add(cooldownIdFor(cand));+ } else if (failure.kind === 'network') {+ networkFailedThisCall.add(cooldownIdFor(cand));}exhaustedNetwork = !failure.cooldownKind || failure.kind === 'network';log.warn('complete trying next candidate', {@@ -697,6 +733,14 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLlet exhaustedNetwork = false;const retryAttempts = retryAttemptsFor(params);const allowedNormalEmptyRetries = normalEmptyRetriesFor(params);+ // Candidates whose network-class failure exhausted the same-candidate+ // retry budget in THIS call. Promoted into `unavailableProfiles` only at+ // the commit point — a later candidate working is the proof the failure+ // was candidate-specific rather than a machine-local outage. An+ // exhausted sweep latches nothing: compaction shares this instance and+ // swallows the terminal error, so a full-network blip must leave the+ // next call free to retry every candidate.+ const networkFailedThisCall = new Set<string>();reportCandidates();for (let i = 0; i < candidates.length; i++) {@@ -721,6 +765,9 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLcandidateIndex: i + 1,candidateCount: candidates.length,terminalEventSeen: attempt.empty.terminalEventSeen,+ ...(attempt.empty.terminationCategory+ ? { terminationCategory: attempt.empty.terminationCategory }+ : {}),...(attempt.empty.usage ? { usage: attempt.empty.usage } : {}),};@@ -819,6 +866,8 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LL};} else if (isProviderNoFirstEventTimeout(attempt.err)) {unavailableProfiles.add(cooldownIdFor(cand));+ } else if (failure.kind === 'network') {+ networkFailedThisCall.add(cooldownIdFor(cand));}exhaustedNetwork = !failure.cooldownKind || failure.kind === 'network';log.warn('stream trying next candidate', {@@ -836,6 +885,26 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LLconst { iterator, buffered, cleanup } = attempt;config.onCandidateChosen?.({ profileId: cand.profileId, providerId: cand.providerId, modelId: cand.modelId });config.onSuccess?.(cand.profileId, cand);+ // This candidate works, so the network failures collected above were+ // candidate-specific: keep those candidates out of the remaining+ // model rounds of this run. Deliberately no markCooldown — the next+ // run starts from the full candidate list again.+ for (const id of networkFailedThisCall) unavailableProfiles.add(id);++ // W4-2: the committed candidate is text-only, so paramsFor stripped+ // every attached image. Say so — the visible alternative is the model+ // "admitting" it cannot see, which sampled users debugged as their+ // own mistake.+ if (cand.maxInputImages === 0 && !imagesOmittedAnnounced) {+ const omitted = params.messages.reduce(+ (sum, message) => sum + message.content.filter((content) => content.type === 'image').length,+ 0,+ );+ if (omitted > 0) {+ imagesOmittedAnnounced = true;+ yield { type: 'images_omitted', count: omitted, providerId: cand.providerId } as StreamEvent;+ }+ }for (const ev of buffered) yield ev;diff --git a/src/main/model/core-agent/search-adapters.ts b/src/main/model/core-agent/search-adapters.tsindex 20b4b432..fd75abf3 100644--- a/src/main/model/core-agent/search-adapters.ts+++ b/src/main/model/core-agent/search-adapters.ts@@ -14,6 +14,7 @@import type { SearchProfile } from '../../features/auth';import { createLogger } from '../../logger';+import { fetchAndReadWithTimeout } from '../../util/abort';import {ORKAS_API_BASE_URL,ORKAS_API_KEYS_URL,@@ -43,16 +44,26 @@ export class SearchAccountError extends Error {}}-const REQUEST_TIMEOUT_MS = 15_000;+const REQUEST_TIMEOUT_MS = 30_000;-async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number = REQUEST_TIMEOUT_MS): Promise<Response> {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);- try {- return await fetch(url, { ...init, signal: controller.signal });- } finally {- clearTimeout(timer);- }+async function fetchTextWithTimeout(+ url: string,+ init: RequestInit,+ timeoutMs: number = REQUEST_TIMEOUT_MS,+): Promise<{ response: Response; text: string }> {+ const { response, body } = await fetchAndReadWithTimeout(+ url,+ init,+ timeoutMs,+ null,+ `Search request timed out after ${timeoutMs}ms`,+ (resp) => resp.text(),+ );+ return { response, text: body };+}++function parseJson<T>(text: string): T {+ return (text ? JSON.parse(text) : {}) as T;}function clamp(n: number, min: number, max: number): number {@@ -67,7 +78,7 @@ async function orkasApiSearch(count: number,context?: OrkasApiUsageContext,): Promise<SearchAdapterResult> {- const resp = await fetchWithTimeout(`${ORKAS_API_BASE_URL}/search`, {+ const { response: resp, text } = await fetchTextWithTimeout(`${ORKAS_API_BASE_URL}/search`, {method: 'POST',headers: {Authorization: `Bearer ${profile.apiKey}`,@@ -77,10 +88,9 @@ async function orkasApiSearch(body: JSON.stringify({ query, max_results: clamp(count, 1, 20) }),});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Orkas Search ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as {+ const data = parseJson(text) as {results?: Array<{ title?: string; url?: string; snippet?: string }>;};return {@@ -102,16 +112,15 @@ async function tavilySearch(profile: SearchProfile, query: string, count: numbermax_results: clamp(count, 1, 20),search_depth: 'basic',});- const resp = await fetchWithTimeout('https://api.tavily.com/search', {+ const { response: resp, text } = await fetchTextWithTimeout('https://api.tavily.com/search', {method: 'POST',headers: { 'Content-Type': 'application/json' },body,});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Tavily ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as { results?: Array<{ title?: string; url?: string; content?: string }> };+ const data = parseJson(text) as { results?: Array<{ title?: string; url?: string; content?: string }> };return {provider: 'tavily',results: (data.results || []).map((r) => ({@@ -126,7 +135,7 @@ async function tavilySearch(profile: SearchProfile, query: string, count: numberasync function serperSearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {const body = JSON.stringify({ q: query, num: clamp(count, 1, 20) });- const resp = await fetchWithTimeout('https://google.serper.dev/search', {+ const { response: resp, text } = await fetchTextWithTimeout('https://google.serper.dev/search', {method: 'POST',headers: {'X-API-KEY': profile.apiKey,@@ -135,10 +144,9 @@ async function serperSearch(profile: SearchProfile, query: string, count: numberbody,});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Serper ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as {+ const data = parseJson(text) as {organic?: Array<{ title?: string; link?: string; snippet?: string }>;};return {@@ -158,7 +166,7 @@ async function braveApiSearch(profile: SearchProfile, query: string, count: numbq: query,count: String(clamp(count, 1, 20)),}).toString()}`;- const resp = await fetchWithTimeout(url, {+ const { response: resp, text } = await fetchTextWithTimeout(url, {method: 'GET',headers: {Accept: 'application/json',@@ -166,10 +174,9 @@ async function braveApiSearch(profile: SearchProfile, query: string, count: numb},});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Brave Search ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as {+ const data = parseJson(text) as {web?: { results?: Array<{ title?: string; url?: string; description?: string }> };};return {@@ -200,7 +207,7 @@ async function baiduAiSearch(profile: SearchProfile, query: string, count: numbemessages: [{ role: 'user', content: query }],resource_type_filter: [{ type: 'web', top_k: clamp(count, 1, 20) }],});- const resp = await fetchWithTimeout('https://qianfan.baidubce.com/v2/ai_search', {+ const { response: resp, text } = await fetchTextWithTimeout('https://qianfan.baidubce.com/v2/ai_search', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -209,10 +216,9 @@ async function baiduAiSearch(profile: SearchProfile, query: string, count: numbebody,});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Baidu AI Search ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as {+ const data = parseJson(text) as {references?: Array<{ title?: string; url?: string; web_anchor?: string; snippet?: string; content?: string }>;};return {@@ -252,7 +258,7 @@ async function metasoSearch(profile: SearchProfile, query: string, count: numbersize: clamp(count, 1, 20),includeSummary: false,});- const resp = await fetchWithTimeout('https://api.metaso.cn/search', {+ const { response: resp, text } = await fetchTextWithTimeout('https://api.metaso.cn/search', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -261,10 +267,9 @@ async function metasoSearch(profile: SearchProfile, query: string, count: numberbody,});if (!resp.ok) {- const text = await resp.text().catch(() => '');throw new Error(`Metaso ${resp.status}: ${text.slice(0, 300)}`);}- const data = (await resp.json()) as Record<string, unknown>;+ const data = parseJson(text) as Record<string, unknown>;const list: any[] = Array.isArray((data as any).references) ? (data as any).references: Array.isArray((data as any).results) ? (data as any).results: Array.isArray((data as any).data) ? (data as any).datadiff --git a/src/main/model/core-agent/video-gen-tool.ts b/src/main/model/core-agent/video-gen-tool.tsindex 02b6f1aa..895ea17d 100644--- a/src/main/model/core-agent/video-gen-tool.ts+++ b/src/main/model/core-agent/video-gen-tool.ts@@ -267,7 +267,9 @@ export function createVideoGenTool(opts: VideoGenToolOpts): AgentTool {}}- const result = await generateVideo({+ let result: Awaited<ReturnType<typeof generateVideo>>;+ try {+ result = await generateVideo({prompt,outputAbsPath: outputAbs,...(referenceImageUrls.length ? { referenceImageUrls } : {}),@@ -291,6 +293,15 @@ export function createVideoGenTool(opts: VideoGenToolOpts): AgentTool {...(event.data ? { data: event.data } : {}),}),});+ } catch (err) {+ const safeError = sanitizeLogTextForUpload((err as Error).message || String(err));+ return {+ content: productionTransaction+ ? `E_VIDEO_PRODUCTION_GENERATION_UNCERTAIN: provider dispatch ended without a terminal result (${safeError}); keep the pending transaction and do not retry without a new explicit Gate C approval.`+ : `[PROVIDER_EXCEPTION] ${safeError}`,+ isError: true,+ } as ToolResult;+ }if (result.ok === false) {if (productionTransaction) {diff --git a/src/main/model/provider_catalog.ts b/src/main/model/provider_catalog.tsindex 27e5cfdf..81fb1f3b 100644--- a/src/main/model/provider_catalog.ts+++ b/src/main/model/provider_catalog.ts@@ -207,6 +207,9 @@ const PI_MODEL_TEMPLATE_ALIAS_LABEL: Readonly<Record<string, Readonly<Record<str};const MODEL_UPGRADE_ALIAS: Readonly<Record<string, Readonly<Record<string, string>>>> = {+ zai: {+ 'glm-5.1': 'glm-5.2',+ },anthropic: {'claude-opus-4-7': 'claude-opus-5','claude-opus-4-8': 'claude-opus-5',diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 7d3faff8..0b4581ce 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -260,7 +260,9 @@the recipient chip — see initUserWorkspace(). --><div class="chat-skill-chip" id="chat-skill-chip" data-target="conversation" style="display:none"><span class="chip-label"></span>- <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>+ <button type="button" class="chip-close" data-i18n-title="chat.chip_remove_title" data-i18n-aria-label="chat.chip_remove_title" title="Remove" aria-label="Remove">+ <span data-ui-icon="x" data-ui-icon-class="chip-close-icon"></span>+ </button></div><button type="button" class="chat-queue-edit-delete-btn" id="chat-queue-edit-delete-btn"data-i18n-title="chat.queue_delete_editing" data-i18n-aria-label="chat.queue_delete_editing"@@ -662,7 +664,9 @@the recipient chip — see initUserWorkspace(). --><div class="chat-skill-chip" id="project-chat-skill-chip" data-target="project" style="display:none"><span class="chip-label"></span>- <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>+ <button type="button" class="chip-close" data-i18n-title="chat.chip_remove_title" data-i18n-aria-label="chat.chip_remove_title" title="Remove" aria-label="Remove">+ <span data-ui-icon="x" data-ui-icon-class="chip-close-icon"></span>+ </button></div><button type="button" class="chat-send-btn" id="project-chat-send-btn" data-i18n-title="chat.send_title" title="Send"><span data-ui-icon="send" data-ui-icon-class="send-icon"></span>diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex cd3beac8..9a2557fb 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -318,7 +318,7 @@"chat.recipient_commander_hint": "Default recipient, no @ needed","chat.recipient_picker_title": "Choose agent, skill, or connector","chat.recipient_picker_title_with_library": "Choose agent, skill, connector, or Library file",- "chat.attach_title": "Upload attachment (text / PDF / Word / image / video)",+ "chat.attach_title": "Upload attachment (documents, spreadsheets, presentations, archives, images, audio, and video)","chat.chip_remove_title": "Remove","chat.send_title": "Send","chat.attach_uploading": "Uploading",@@ -2096,5 +2096,6 @@"skills.source_global": "Global","settings.commander_avatar.title": "Commander avatar","settings.commander_avatar.sub": "Click the avatar to pick a new color.",- "settings.commander_avatar.hint": "Click the avatar on the left to change it"+ "settings.commander_avatar.hint": "Click the avatar on the left to change it",+ "settings.video.provider_unavailable": "This video provider is not supported in this build. The saved key is retained and can be removed. Configure Orkas API to generate videos."}diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex 114fbd23..a9ac11e7 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -306,7 +306,7 @@"chat.recipient_commander_hint": "デフォルトの宛先です。@ は不要です","chat.recipient_picker_title": "エージェント、スキル、コネクターを選択","chat.recipient_picker_title_with_library": "エージェント、スキル、コネクター、ライブラリファイルを選択",- "chat.attach_title": "添付ファイルをアップロード(テキスト / PDF / Word / 画像 / 動画)",+ "chat.attach_title": "添付ファイルをアップロード(文書 / 表計算 / プレゼンテーション / 圧縮ファイル / 画像 / 音声 / 動画)","chat.chip_remove_title": "削除","chat.send_title": "送信","chat.attach_uploading": "アップロード中",@@ -2096,5 +2096,6 @@"skills.source_global": "グローバル","settings.commander_avatar.title": "コマンダーのアバター","settings.commander_avatar.sub": "アバターをクリックして色を変更できます。",- "settings.commander_avatar.hint": "左のアバターをクリックして変更"+ "settings.commander_avatar.hint": "左のアバターをクリックして変更",+ "settings.video.provider_unavailable": "このビルドではこの動画プロバイダーは利用できません。保存済みのキーは保持され、削除できます。動画を生成するには Orkas API を設定してください。"}diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.jsonindex 59382c4a..23877cbf 100644--- a/src/renderer/locales/pt.json+++ b/src/renderer/locales/pt.json@@ -314,7 +314,7 @@"chat.recipient_commander_hint": "Destinatário padrão, não é necessário @","chat.recipient_picker_title": "Escolha agente, habilidade ou conector","chat.recipient_picker_title_with_library": "Escolha agente, habilidade, conector ou arquivo de biblioteca",- "chat.attach_title": "Carregar anexo (texto/PDF/Word/imagem/vídeo)",+ "chat.attach_title": "Carregar anexo (documentos, planilhas, apresentações, arquivos compactados, imagens, áudio e vídeo)","chat.chip_remove_title": "Remover","chat.send_title": "Enviar","chat.attach_uploading": "Enviando",@@ -2096,5 +2096,6 @@"bash.permission.reason_sep": ", ","settings.commander_avatar.title": "Avatar do comandante","settings.commander_avatar.sub": "Clique no avatar para escolher uma nova cor.",- "settings.commander_avatar.hint": "Clique no avatar à esquerda para alterar"+ "settings.commander_avatar.hint": "Clique no avatar à esquerda para alterar",+ "settings.video.provider_unavailable": "Este provedor de vídeo não está disponível nesta versão. A chave salva foi mantida e pode ser removida. Configure a API Orkas para gerar vídeos."}diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex b4c3a34c..466a8e25 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -318,7 +318,7 @@"chat.recipient_commander_hint": "默认接收者,无需 @","chat.recipient_picker_title": "选择智能体、技能或连接器","chat.recipient_picker_title_with_library": "选择智能体、技能、连接器或资料库文件",- "chat.attach_title": "上传附件(文本/PDF/Word/图片/视频)",+ "chat.attach_title": "上传附件(文档、表格、演示文稿、压缩包、图片、音频、视频)","chat.chip_remove_title": "移除","chat.send_title": "发送","chat.attach_uploading": "上传中",@@ -2096,5 +2096,6 @@"skills.source_global": "全局","settings.commander_avatar.title": "指挥官头像","settings.commander_avatar.sub": "点击头像可更换颜色。",- "settings.commander_avatar.hint": "点击左侧头像进行更换"+ "settings.commander_avatar.hint": "点击左侧头像进行更换",+ "settings.video.provider_unavailable": "此版本不支持该视频供应商。已保存的密钥会保留,可自行删除;生成视频请配置 Orkas API。"}diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex ad54053f..c86c9a80 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -1772,6 +1772,7 @@ function _renderAgentDetailKnowhow(agent, editing = false) {function _renderAgentDetail(agent, editing, { refreshCliOptions = false } = {}) {agent = { ...agent, source: _agentSource(agent.source) };const isCommander = _isCommanderAgent(agent);+ const canEditDefinition = _canEditAgentDefinition(agent);document.getElementById('agents-detail-content').style.display = '';const nameEl = document.getElementById('agents-detail-name');@@ -1817,7 +1818,7 @@ function _renderAgentDetail(agent, editing, { refreshCliOptions = false } = {})const unsetHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset'))}</span>`;// Workflow renders markdown in readonly mode; raw text in edit mode so user// can edit source directly.- if (editing && !isCommander) {+ if (editing && !isCommander && canEditDefinition) {workflowEl.textContent = agent.workflow || '';} else {const workflowMarkdown = structuredWorkflow.length@@ -1837,7 +1838,6 @@ function _renderAgentDetail(agent, editing, { refreshCliOptions = false } = {})const delBtn = document.getElementById('agent-delete-btn');const isMock = _isAgentProfileMock(agent);const isCustom = agent.source === 'custom' && !isMock;- const canEditDefinition = !isMock && isCustom;const canEdit = isCommander || canEditDefinition || _canEditAgentMemory(agent);if (useBtn) {useBtn.style.display = editing ? 'none' : '';@@ -1876,7 +1876,7 @@ function _renderAgentDetail(agent, editing, { refreshCliOptions = false } = {})_renderAgentOutputFormatSection(agent, editing);- _toggleAgentFieldEditable(editing && !isCommander);+ _toggleAgentFieldEditable(editing && !isCommander && canEditDefinition);}/** Render the output-format preference dropdown (auto / text /@@ -2861,7 +2861,6 @@ async function _flushAgentFieldSave({ validate = false } = {}) {const localised = _agentCreateErrorMessage(data);throw new Error(localised || data.error || 'save failed');}- trackResult('success');if (field === 'name') {const nextName = data.agent?.name || String(value || '').trim();_selectedAgent = { ..._selectedAgent, name: nextName };@@ -3594,7 +3593,7 @@ function _ensureAgentChatController() {historyEndpoint: (id) => `/api/agents/${encodeURIComponent(id)}/chat`,streamEndpoint: (id) => `/api/agents/${encodeURIComponent(id)}/chat/send/stream`,clearEndpoint: (id) => `/api/agents/${encodeURIComponent(id)}/chat`,- features: { archive: false, scrollPin: true, queue: true },+ features: { archive: false, scrollPin: true, queue: true, messageActions: 'errors-only' },queue: {keyPrefix: 'agent',panelId: 'agents-chat-queue',diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.jsindex 5ed7a35c..7c1fcf0e 100644--- a/src/renderer/modules/boot.js+++ b/src/renderer/modules/boot.js@@ -352,14 +352,13 @@ async function initUser() {const data = await res.json();if (data.ok && data.user_id) {currentUserId = data.user_id;+ try { globalThis.currentUserId = currentUserId; } catch (_) {}+ if (typeof _restoreUnreadTaskState === 'function') _restoreUnreadTaskState();_bootLog.info('user init', { user_id: currentUserId });- // Bind the telemetry identity as soon as we have a user_id;- // Monitor handles dedupe + queueing internally, so no need to- // check whether umami has finished initializing.- }+ }} catch (e) {_bootLog.error('init user failed', { error: (e && e.message) || String(e) });- }+ }}// ─── View routing ───@@ -463,11 +462,7 @@ function setView(view, cid, opts = {}) {if (!opts.skipLoad && typeof _chatAttachRefreshFromServer === 'function') {_chatAttachRefreshFromServer(cid);}- // If we returned to a conversation with queued items and nothing is- // streaming, kick off the next one automatically.- if (!isConvPending(cid) && (messageQueues.get(cid) || []).length) {- _dispatchNextQueued(cid);- }+ // History hydration owns queue dispatch after restoring active_recipient._updateConvSendUI(cid);setTimeout(() => focusChatComposerIfIdle('chat-input'), 50);} else if (view === 'new-chat') {diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex d3efee7e..04ef0643 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -77,6 +77,7 @@ const CONNECT_CANCEL_CODES = new Set(['user_cancelled', 'superseded']);function _isConnectCancel(errLike) {const code = errLike && typeof errLike.code === 'string' ? errLike.code : '';if (code && CONNECT_CANCEL_CODES.has(code)) return true;+ if (code && code !== 'unknown' && code !== 'E_UNKNOWN') return false;const msg = String((errLike && (errLike.error || errLike.message)) || '').toLowerCase();return msg.includes('superseded') || msg.includes('cancelled') || msg.includes('canceled');}@@ -1255,6 +1256,7 @@ function _formatConnectError(errLike) {if (code === 'connector_unsupported' || /connector_unsupported/i.test(String(msg))) {return t('connectors.toast.unsupported');}+ if (code === 'storage_unavailable') return t('connectors.errors.storage_unavailable');if (code === 'missing_required_scopes' || /missing_required_scopes|missing required scopes/i.test(String(msg))) {return t('connectors.errors.missing_required_scopes');}diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex d7ee55e8..8395c5bc 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -883,6 +883,9 @@ function _processToolPresentation(name, data, input) {const skillName = _processFirstText(input, ['skill_name', 'skillName', 'skill', 'name']);return { actionKey: 'chat.process.action_use_skill', target: skillName };}+ if (key === 'generate_video') {+ return { actionKey: 'chat.process.action_generate_video', target };+ }if (['generate_image', 'image_generation'].includes(key)) {return { actionKey: 'chat.process.action_generate_image', target };}@@ -917,12 +920,22 @@ function _processToolPresentation(name, data, input) {if (key.startsWith('collaboration:') || ['agent', 'task', 'background_agent', 'dispatch_to', 'hand_off_to', 'run_worker',].includes(key)) {+ const persistedName = _processFirstText(data, ['agent_name', 'agentName']);+ if (persistedName) return { actionKey: 'chat.process.action_call_agent', target: persistedName };const agentName = _processFirstText(input, ['agent_name', 'agentName', 'recipient_name', 'recipientName','subagent_type', 'subagentType', 'agent_type', 'agentType','to', 'recipient', 'agent', 'name',]);- return { actionKey: 'chat.process.action_call_agent', target: agentName };+ // New events persist the display name; older history can resolve its id+ // through the existing Agent cache. Never present opaque local ids as names.+ const localAgent = typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)+ ? _agentsCache.find((agent) => agent.agent_id === agentName || agent.id === agentName)+ : null;+ const label = localAgent?.name || (/^[a-f0-9]{12}$/i.test(agentName)+ ? _groupActorLabel(agentName)+ : agentName);+ return { actionKey: 'chat.process.action_call_agent', target: label };}if (_isOrkasBridgeToolName(name)) {// Future bridge tools must remain internal actions rather than silently@@ -3983,8 +3996,9 @@ function _actorLinkAttrs(fromId) {async function _openActorAgentDetail(actorId) {const aid = String(actorId || '').trim();if (!_isActorDetailTarget(aid)) return;+ const returnTarget = typeof _captureAgentDetailReturnTarget === 'function'+ ? _captureAgentDetailReturnTarget() : null;if (window.Monitor) (() => {})('message_actor_open', { agent_id: aid });- setView('agents');if (aid === 'commander') {if (typeof openAgentDetail === 'function') await openAgentDetail('commander', { returnTarget });else if (typeof selectAgent === 'function') await selectAgent('commander');@@ -5132,7 +5146,8 @@ function _hydrateMessageCreatedAgentChip(msgDiv) {const aid = chip.dataset.agentId;if (!aid) return;if (window.Monitor) (() => {})('created_agent_chip_open', { agent_id: aid });- setView('agents');+ const returnTarget = typeof _captureAgentDetailReturnTarget === 'function'+ ? _captureAgentDetailReturnTarget() : null;// Pre-check the agent is still loadable; if it was deleted (or its// record is broken) the detail view would render an empty shell. Keep// the user on the entry page instead.@@ -10400,7 +10415,10 @@ async function sendInConversation(cid, content, extra, options = {}) {success: !aborted && !errored,});}- if (!started && _convChatCtrls.get(cid) === ctrl) _convChatCtrls.delete(cid);+ if (!started && _convChatCtrls.get(cid) === ctrl) {+ _clearSentComposerSnapshot(cid);+ _convChatCtrls.delete(cid);+ }return { ...terminal, started, aborted, errored, result };} catch (err) {const durationMs = Math.round(performance.now() - startedAt);@@ -10434,7 +10452,10 @@ async function sendInConversation(cid, content, extra, options = {}) {if (taskStarted && _convChatCtrls.get(cid) === ctrl) {_finishStreamingMsg(cid);}- if (_convChatCtrls.get(cid) === ctrl) _convChatCtrls.delete(cid);+ if (_convChatCtrls.get(cid) === ctrl) {+ if (!taskStarted) _clearSentComposerSnapshot(cid);+ _convChatCtrls.delete(cid);+ }throw err;}}diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.jsindex ec12dfd7..cbac8dff 100644--- a/src/renderer/modules/settings.js+++ b/src/renderer/modules/settings.js@@ -118,6 +118,9 @@ async function loadSettings() {_settingsBindClientConfigOnce();_settingsBindRecycleBinOnce();_settingsBindOrkasApiOnce();+ _settingsBindMetacognitionOnce();+ _settingsRenderTaskNotifications();+ _settingsRenderLocalExec();_settingsSyncLanguageRadio();await Promise.all([_settingsSafeCall('settings providers refresh', _settingsRefreshProviders),@@ -385,7 +388,22 @@ function _settingsRenderTaskNotifications() {}}-function _settingsBindClientConfigOnce() {}+function _settingsBindClientConfigOnce() {+ if (_settingsState.clientConfigBound || typeof window.orkas?.onPushEvent !== 'function') return;+ _settingsState.clientConfigBound = true;+ window.orkas.onPushEvent('client-config:changed', (payload) => {+ const keys = Array.isArray(payload?.keys) ? payload.keys : [];+ if (!keys.includes('model_catalog') && !keys.includes('model.deepseek.enabled')) return;+ _settingsState.modelsCache = {};+ if (typeof refreshModelGuard === 'function') void refreshModelGuard().catch(() => {});+ if (currentView !== 'settings') return;+ void _settingsSafeCall('client config model refresh', async () => {+ await Promise.all([_settingsRefreshProviders(), _settingsRefreshEntries()]);+ await _settingsRenderPicker();+ _settingsRenderEntries();+ });+ });+}// ── Local recycle bin ──@@ -644,8 +662,13 @@ function _settingsBindRecycleBinOnce() {_settingsRecycleExpandedIds.delete(id);} else {await window.orkas.recycleBin.restore(id);- if (typeof loadProjects === 'function') await loadProjects(true);- if (typeof loadConversations === 'function') await loadConversations();+ // The restore has committed; refresh failures must not report that it failed.+ await Promise.all([+ _settingsSafeCall('restored Agents refresh', typeof loadAgents === 'function' ? () => loadAgents(true) : null),+ _settingsSafeCall('restored Skills refresh', typeof loadSkills === 'function' ? () => loadSkills(true) : null),+ _settingsSafeCall('restored projects refresh', typeof loadProjects === 'function' ? () => loadProjects(true) : null),+ _settingsSafeCall('restored conversations refresh', typeof loadConversations === 'function' ? () => loadConversations() : null),+ ]);}} catch (err) {_settingsLog.warn(`recycle bin ${deleting ? 'delete' : 'restore'} failed`, {@@ -849,36 +872,7 @@ function _settingsRenderMetacognition() {if (status) {status.textContent = s.envForcedOff ? t('settings.metacognition.env_forced_off') : '';}- if (!cb.dataset.bound) {- cb.addEventListener('change', async () => {- if (cb.disabled) return;- const next = !!cb.checked;- try {- const res = await window.orkas.invoke('prefs.setMetacognition', { enabled: next });- if (res && res.ok) {- _settingsState.metacognition = { ..._settingsState.metacognition, enabled: !!res.enabled };- } else {- // Roll back the UI on write failure.- cb.checked = !next;- _settingsLog.warn('setMetacognition rejected', res);- _settingsTrackEvent('metacognition_toggle_result', { result: 'failure', enabled: !next });- _settingsTrackError('metacognition_toggle', {- error_type: 'operation',- error_message: 'metacognition_toggle_rejected',- });- }- } catch (err) {- cb.checked = !next;- _settingsLog.warn('setMetacognition failed', err);- _settingsTrackEvent('metacognition_toggle_result', { result: 'failure', enabled: !next });- _settingsTrackError('metacognition_toggle', {- error_type: 'operation',- error_message: 'metacognition_toggle_failed',- });- }- });- cb.dataset.bound = '1';- }+ _settingsBindMetacognitionOnce();}// ── Data root row ──@@ -904,7 +898,7 @@ function _settingsRenderDataRoot() {const startedAt = Date.now();let res;try {- await window.orkas.invoke('app.openDataRoot');+ res = await window.orkas.invoke('app.openDataRoot');} catch (err) {_settingsLog.warn('open data root failed', {error_type: err && typeof err.name === 'string' ? err.name : 'unknown',@@ -967,10 +961,13 @@ function _settingsBindLanguageOnce() {_settingsLanguageSel.onChange(async (next) => {if (typeof isSupportedLang === 'function' && !isSupportedLang(next)) return;try {- await setLang(next);- _settingsLog.info('language changed', { lang: next });- } catch (err) {- _settingsLog.warn('setLang failed', { error: (err && err.message) || String(err) });+ const applied = await setLang(next);+ if (applied !== next) return; // superseded by a newer user choice+ _settingsLog.info('language changed', { lang: applied });+ } catch {+ _settingsSyncLanguageRadio();+ _settingsLog.warn('language change failed');+ await uiAlert(t('settings.language.change_failed'));}});}@@ -1010,6 +1007,7 @@ async function _settingsRefreshEntries() {_settingsState.entries = (res && res.ok && Array.isArray(res.entries)) ? res.entries : [];if (typeof trackModelConfigSnapshot === 'function') trackModelConfigSnapshot(_settingsState.entries);_settingsRenderOrkasApiCard();+ _settingsEmitModelEntriesChanged();}function _settingsRenderOrkasApiCard() {@@ -1665,7 +1663,9 @@ async function _settingsStartOAuthFlow(provider, modelId) {document.addEventListener('keydown', onKey, true);_settingsLog.info('oauth start', { provider: oauthProviderId });- const startRes = await window.orkas.invoke('auth.startOAuth', { provider: oauthProviderId });+ let startRes;+ try { startRes = await window.orkas.invoke('auth.startOAuth', { provider: oauthProviderId }); }+ catch (_) { startRes = { ok: false, code: 'invoke_failed' }; }if (!startRes || !startRes.ok) {body.innerHTML = `<div class="oauth-flow-stage error">${escapeHtml((startRes && startRes.error) || t('settings.oauth.start_failed'))}</div>`;_settingsLog.warn('oauth start failed', { provider: oauthProviderId, error: startRes && startRes.error });@@ -2062,6 +2062,7 @@ function _settingsRenderEntryRow(entry, priorityIdx) {ipcName: 'auth.reorderEntries',onSuccess: (res) => {_settingsState.entries = Array.isArray(res.entries) ? res.entries : _settingsState.entries;+ _settingsEmitModelEntriesChanged();_settingsRenderEntries();},});@@ -2158,7 +2159,9 @@ async function _settingsRemoveEntry(entry) {provider: entry.provider,model: entry.model,});- const res = await window.orkas.invoke('auth.removeEntry', { entryId: entry.entryId });+ let res;+ try { res = await window.orkas.invoke('auth.removeEntry', { entryId: entry.entryId }); }+ catch (_) { res = { ok: false, code: 'invoke_failed' }; }if (!res || !res.ok) {_settingsLog.warn('remove entry failed', { entry_id: entry.entryId, error: res && res.error });_settingsTrackModelConfigResult(@@ -2378,14 +2381,19 @@ const _IMAGE_PROVIDER_OPTIONS = [{ id: 'doubao', label: 'DouBao · Seedream', docs: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey' },];-function _imageProviderLabel(id) {- const hit = _IMAGE_PROVIDER_OPTIONS.find((p) => p.id === id);- return hit ? hit.label : id;+function _imageProviderLabel(provider, model) {+ if (provider === 'orkas-image') return 'Orkas · Image';+ const hit = _settingsImageProviderOptions().find((option) => (+ (option.provider || option.id) === provider+ && (!model || !option.model || option.model === model)+ ));+ return hit ? hit.label : provider;}async function _settingsRefreshImageProfiles() {const res = await window.orkas.invoke('imageAuth.list');_settingsState.imageProfiles = (res && res.ok && Array.isArray(res.profiles)) ? res.profiles : [];+ _settingsState.imageProviderOptions = res?.ok && res.providers?.length ? res.providers : _IMAGE_PROVIDER_OPTIONS;_settingsRenderOrkasApiCard();}@@ -2404,7 +2412,7 @@ function _settingsRenderImagePicker() {}const prev = _settingsState.imageProviderSel.getValue();_settingsState.imageProviderSel.setOptions(- _IMAGE_PROVIDER_OPTIONS.map((p) => ({ value: p.id, label: p.label, hint: p.docs })),+ _settingsImageProviderOptions().map((p) => ({ value: p.id, label: p.label, hint: p.docs })),{ value: prev || '', placeholder: t('settings.image.pick_provider') },);const addBtn = document.getElementById('settings-image-add-btn');@@ -2415,14 +2423,16 @@ function _settingsRenderImagePicker() {}async function _settingsClickAddImageKey() {- const provider = _settingsState.imageProviderSel?.getValue() || '';+ const providerOpt = _imageProviderOption(_settingsSelectedImageOptionId());+ const provider = providerOpt?.provider || providerOpt?.id || '';+ const model = providerOpt?.model || '';const input = document.getElementById('settings-image-key-input');const apiKey = (input?.value || '').trim();if (!provider) { _settingsSetStatus('settings-image-status', 'error', t('settings.image.error_provider_needed')); return; }if (!apiKey) { _settingsSetStatus('settings-image-status', 'error', t('settings.image.error_key_needed')); return; }_settingsSetStatus('settings-image-status', 'busy', t('settings.image.adding'));try {- const res = await window.orkas.invoke('imageAuth.add', { provider, apiKey, label: 'default' });+ const res = await window.orkas.invoke('imageAuth.add', { provider, model, apiKey, label: 'default' });if (!res || !res.ok) {_settingsSetStatus('settings-image-status', 'error', (res && res.error) || t('settings.image.add_failed'));return;@@ -2462,7 +2472,7 @@ function _settingsRenderImageEntries() {const isOrkasApi = p.provider === _ORKAS_API_PROVIDER_ID;const providerLabel = isOrkasApi? _settingsOrkasServiceLabel('Image')- : _imageProviderLabel(p.provider);+ : _imageProviderLabel(p.provider, p.model);primary.innerHTML = `<span class="entry-provider">${escapeHtml(providerLabel)}</span><span class="entry-sep">·</span>@@ -2511,7 +2521,6 @@ function _settingsRenderImageEntries() {const _VIDEO_AUTH_PROVIDER_OPTIONS = [{ id: 'orkas-api', label: _settingsOrkasServiceLabel('Video'), docs: _ORKAS_API_KEYS_URL },- { id: 'doubao', label: 'DouBao · Seedance', docs: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey' },];function _settingsVideoProviderOptions() {@@ -2606,12 +2615,15 @@ function _settingsRenderVideoEntries() {}list.forEach((p, idx) => {const row = document.createElement('div');- row.className = 'entry-row' + (idx === 0 ? ' is-default' : '');+ const available = p.available !== false;+ const isDefault = available && list.find((profile) => profile.available !== false)?.id === p.id;+ row.className = 'entry-row' + (isDefault ? ' is-default' : '');row.dataset.profileId = p.id;const rank = document.createElement('div');rank.className = 'entry-rank';- rank.textContent = idx === 0 ? t('settings.video.active_tag') : `#${idx + 1}`;+ rank.textContent = !available ? t('new_chat.model_picker.unavailable')+ : isDefault ? t('settings.video.active_tag') : `#${idx + 1}`;row.appendChild(rank);const main = document.createElement('div');@@ -2629,6 +2641,12 @@ function _settingsRenderVideoEntries() {${p.apiKeyMasked ? `<span class="account-mask">${escapeHtml(p.apiKeyMasked)}</span>` : ''}`;main.appendChild(primary);+ if (!available) {+ const reason = document.createElement('div');+ reason.className = 'form-hint';+ reason.textContent = t('settings.video.provider_unavailable');+ main.appendChild(reason);+ }row.appendChild(main);const actions = document.createElement('div');@@ -2861,3 +2879,27 @@ function _settingsRenderTtsEntries() {container.appendChild(row);});}++function _settingsEmitModelEntriesChanged() {+ try {+ window.dispatchEvent(new CustomEvent('orkas:model-entries-changed', {+ detail: {},+ }));+ } catch (_) { /* renderer may be tearing down */ }+}++function _settingsImageProviderOptions() {+ return Array.isArray(_settingsState.imageProviderOptions) && _settingsState.imageProviderOptions.length+ ? _settingsState.imageProviderOptions+ : _IMAGE_PROVIDER_OPTIONS;+}++function _imageProviderOption(id) {+ return _settingsImageProviderOptions().find((p) => p.id === id) || null;+}++function _settingsSelectedImageOptionId() {+ return _settingsState.imageProviderSel?.getValue()+ || document.getElementById('settings-image-provider')?.dataset?.value+ || '';+}diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.jsindex 2ab6f1e0..1d65e735 100644--- a/src/renderer/modules/skills.js+++ b/src/renderer/modules/skills.js@@ -2048,7 +2048,6 @@ async function _flushSkillFieldSave({ validate = false } = {}) {if (!data || data.ok === false) {throw new Error(data?.error || 'save failed');}- trackResult('success');if (field === 'name') {const nextName = data.skill?.name || newName || currentId;_skillsCache = null;@@ -2083,7 +2082,6 @@ async function _flushSkillFieldSave({ validate = false } = {}) {if (!data.ok) {throw new Error(data.error || 'save failed');}- trackResult('success');if (validate && field === 'name' && !skipRename) {// Directory was renamed — refresh caches + update _selectedSkill.id// so subsequent calls (selectSkillFile / chat dir lookup) hit the@@ -2309,7 +2307,7 @@ function _ensureSkillChatController() {historyEndpoint: (id) => `/api/skills/${encodeURIComponent(id)}/chat`,streamEndpoint: (id) => `/api/skills/${encodeURIComponent(id)}/chat/send/stream`,clearEndpoint: (id) => `/api/skills/${encodeURIComponent(id)}/chat`,- features: { archive: false, scrollPin: true, queue: true },+ features: { archive: false, scrollPin: true, queue: true, messageActions: 'errors-only' },queue: {keyPrefix: 'skill',panelId: 'skills-chat-queue',diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.jsindex 3712149c..d0cbb0b6 100644--- a/src/renderer/modules/user-workspace.js+++ b/src/renderer/modules/user-workspace.js@@ -164,13 +164,29 @@ async function _selectAndSetWorkspace(target, dirPath) {let selectedPath = dirPath;if (!selectedPath) {const dirResult = await window.orkas.invoke('workspace.selectDirectory', {});- if (!dirResult || !dirResult.ok || !dirResult.path) return;+ if (!dirResult || dirResult.ok === false) {+ _showWorkspaceSetFailure(t('workspace.set_failed'));+ return;+ }+ if (!dirResult.path) {+ return;+ }selectedPath = dirResult.path;}const setResult = await window.orkas.invoke('workspace.set', { path: selectedPath, ...hint });if (setResult && setResult.ok && setResult.path) {- await _refreshAllWorkspaceInfo();- _wsLog.info('workspace selected', { target, path: setResult.path });+ // The authoritative mutation has already completed. Keep the terminal+ // row independent from the follow-up chip refresh: a slow or failed+ // read-back must not hide success or append a contradictory failure.+ _wsLog.info('workspace selected', { target });+ try {+ await _refreshAllWorkspaceInfo();+ } catch (err) {+ _wsLog.warn('workspace refresh after selection failed', {+ target,+ error_type: err && typeof err.name === 'string' ? err.name : 'unknown',+ });+ }} else {_showWorkspaceSetFailure((setResult && setResult.error) || t('workspace.set_failed'));_wsLog.warn('workspace selection rejected', { target, error_code: 'set_failed' });@@ -189,11 +205,25 @@ async function _resetWorkspace(target) {try {const result = await window.orkas.invoke('workspace.reset', hint);if (result && result.ok && result.path) {- await _refreshAllWorkspaceInfo();- _wsLog.info('workspace reset', { target, path: result.path });+ // Reset persistence is the terminal boundary; UI read-back is a+ // separate best-effort refresh and cannot change that result.+ _wsLog.info('workspace reset', { target });+ try {+ await _refreshAllWorkspaceInfo();+ } catch (err) {+ _wsLog.warn('workspace refresh after reset failed', {+ target,+ error_type: err && typeof err.name === 'string' ? err.name : 'unknown',+ });+ }+ } else {+ _wsLog.warn('workspace reset rejected', { target, error_code: 'reset_failed' });}} catch (err) {- _wsLog.error('workspace reset failed', err);+ _wsLog.error('workspace reset failed', {+ target,+ error_type: err && typeof err.name === 'string' ? err.name : 'unknown',+ });}}diff --git a/src/renderer/style.css b/src/renderer/style.cssindex 5ef71af0..bffc6ee8 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -9267,21 +9267,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }/* Composer chips share P3's border, radius, and type. Menu triggers(recipient / workspace / model) stay transparent at rest; selected-contentchips such as Skill retain a surface fill. Open states use primary-soft. */-.chat-skill-chip {- flex-shrink: 0;- display: inline-flex;- align-items: center;- gap: 5px;- padding: 4px 9px;- background: var(--surface-2);- border: 1px solid var(--border);- color: var(--text-2);- border-radius: 7px;- font-size: 12px;- font-weight: 500;- line-height: 1.4;- align-self: center;-}.chat-recipient-chip {flex-shrink: 0;@@ -9321,13 +9306,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }color: var(--text);}-.chat-skill-chip .chip-label {- display: inline-flex;- align-items: center;- min-width: 0;- max-width: 160px;-}-.chat-skill-chip .chip-label-prefix {flex-shrink: 0;color: var(--muted);@@ -9342,27 +9320,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }color: var(--primary);}-.chat-skill-chip .chip-close {- width: 16px;- height: 16px;- border-radius: 50%;- display: inline-flex;- align-items: center;- justify-content: center;- font-size: 13px;- font-weight: 600;- cursor: pointer;- color: var(--primary);- opacity: 0.65;- transition: all 0.12s;-}--.chat-skill-chip .chip-close:hover {- background: rgba(220, 38, 38, 0.15);- color: var(--danger);- opacity: 1;-}-/* ─── Workspace chip (user working directory selector) ─── *//* Workspace chip — P3 chrome, same family as recipient / project / skill.@@ -9495,14 +9452,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }overflow: hidden;}-.skill-picker-tabs {- display: grid;- grid-template-columns: repeat(3, minmax(0, 1fr));- gap: 4px;- padding: 8px 8px 0;- background: #fff;-}-.skill-picker-tab {border: 1px solid transparent;background: transparent;@@ -13714,10 +13663,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }/* :disabled — the shared .btn already carries padding / radius / color fromline 3100 block; keep only the semantic state here. */-.btn-primary:disabled {- opacity: 0.6;- cursor: not-allowed;-}/* ─── Devtools (仅开发环境) ─────────────────────────────────────────────── */.devtools-container {@@ -14662,8 +14607,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }owns padding + scroll, so the marketplace preview lines up pixel-for-pixel with thein-app detail page. */.marketplace-detail-body { flex: 1; min-height: 0; overflow: hidden; display: flex; padding: 0; }-.marketplace-detail-body > .agents-detail-body,-.marketplace-detail-body > .skills-detail-content { flex: 1; min-height: 0; }.marketplace-detail-loading {flex: 1;min-height: 100%;@@ -16731,3 +16674,450 @@ body.is-sidebar-resizing iframe { pointer-events: none; }justify-self: start;}}+.chat-queue-edit-delete-btn {+ width: 30px;+ height: 30px;+ margin-left: auto;+ padding: 0;+ border: 1px solid #fecaca;+ border-radius: 7px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: #fff;+ color: #dc2626;+ cursor: pointer;+ flex-shrink: 0;+}+.chat-queue-edit-delete-btn:hover {+ border-color: #fca5a5;+ background: #fef2f2;+ color: #b91c1c;+}+.chat-queue-edit-delete-btn:focus-visible {+ outline: 2px solid rgba(220, 38, 38, 0.28);+ outline-offset: 2px;+}+.chat-queue-edit-delete-btn[hidden] {+ display: none;+}+.queue-delete-icon {+ width: 15px;+ height: 15px;+}+.chat-bottom-bar .chat-queue-edit-delete-btn:not([hidden]) + .chat-send-btn {+ margin-left: 0;+}+.composer-model-menu-item.is-version-open {+ background: var(--surface-2);+}+.chat-md-video-shell.is-load-failed .chat-md-video {+ opacity: 0.35;+}+.chat-md-video-shell.is-load-failed .chat-md-video-float {+ display: none;+}+.chat-md-video-load-failure {+ position: absolute;+ inset: 0;+ z-index: 2;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ padding: 20px;+ box-sizing: border-box;+ color: #e2e8f0;+ background: rgba(15, 23, 42, 0.58);+ cursor: default;+}+.chat-md-video-load-failure-text {+ font-size: 13px;+ font-weight: 500;+ line-height: 1.4;+ text-align: center;+}+.chat-md-video-retry {+ min-height: 30px;+ padding: 4px 12px;+ border: 1px solid rgba(255, 255, 255, 0.4);+ border-radius: 6px;+ background: rgba(15, 23, 42, 0.82);+ color: #fff;+ font: inherit;+ font-size: 12px;+ cursor: pointer;+}+.chat-md-video-retry:hover,+.chat-md-video-retry:focus-visible {+ border-color: rgba(255, 255, 255, 0.72);+ background: rgba(30, 41, 59, 0.96);+}+.chat-file-viewer.is-office-fit .chat-file-viewer-stage {+ height: auto;+ max-height: 92vh;+}+.chat-file-viewer.is-office-fit .chat-file-viewer-body {+ flex: 0 1 auto;+ max-height: calc(92vh - 50px);+ overflow: hidden;+}+.chat-skill-chip {+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-height: 26px;+ padding: 3px 6px 3px 9px;+ background: var(--surface-2);+ border: 1px solid var(--border);+ color: var(--text-2);+ border-radius: 7px;+ font-size: 12px;+ font-weight: 500;+ line-height: 1.4;+ align-self: center;+}++.chat-skill-chip .chip-label {+ display: inline-flex;+ align-items: center;+ min-width: 0;+ max-width: 160px;+ line-height: 18px;+}++.chat-skill-chip .chip-close {+ appearance: none;+ flex: 0 0 18px;+ width: 18px;+ height: 18px;+ margin: 0 -1px 0 0;+ padding: 0;+ border: 0;+ border-radius: 50%;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ color: var(--muted);+ cursor: pointer;+ font: inherit;+ line-height: 1;+ opacity: 0.78;+ transition: background 0.12s, color 0.12s, opacity 0.12s;+}++.chat-skill-chip .chip-close:hover {+ background: rgba(220, 38, 38, 0.1);+ color: var(--danger);+ opacity: 1;+}++.chat-skill-chip .chip-close:focus-visible {+ outline: 2px solid rgba(220, 38, 38, 0.18);+ outline-offset: 1px;+}++.skill-picker-tabs {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: 4px;+ padding: 8px 8px 0;+ background: #fff;+}++.btn:disabled {+ cursor: default;+ opacity: 0.55;+}++.btn:disabled:hover { background: #fff; }+.btn-primary:disabled,+.btn-primary:disabled:hover {+ background: var(--primary);+ color: #fff;+ border-color: var(--primary);+}+.btn-danger:disabled:hover { background: #fff; }+.custom-model-intro {+ margin-left: 0;+ margin-bottom: 12px;+}+.btn-primary:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}+.agents-detail-runtime-select .ai-select-trigger { background: #fff; }++.agents-detail-cli-settings { max-width: 560px; }+.agents-detail-cli-grid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px;+}+.agents-detail-cli-field { min-width: 0; }+.agents-detail-cli-field-label {+ margin-bottom: 5px;+ color: var(--muted);+ font-size: 11px;+ font-weight: 600;+}+.agents-detail-cli-select { width: 100%; min-width: 0; }+.agents-detail-cli-select .ai-select-trigger { background: #fff; }+.agents-detail-cli-note,+.agents-detail-cli-loading {+ margin-top: 7px;+ color: var(--muted);+ font-size: 11px;+ line-height: 1.4;+}+.agents-detail-cli-note.is-warning { color: #a16207; }+@media (max-width: 720px) {+ .agents-detail-cli-grid { grid-template-columns: 1fr; }+}+.marketplace-detail-body > .agents-detail-body,+.marketplace-detail-body > .skills-detail-content {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+}+.marketplace-detail-body > .skills-detail-content.marketplace-detail-body-inner {+ padding-top: 24px;+}+.video-review-panel .chat-md-drawer-header { padding: 14px 14px 12px; }+.video-review-panel .chat-md-drawer-body { padding: 0; }+.video-review-summary {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 9px 16px;+ background: #fbfcfe;+ border-bottom: 1px solid var(--border);+ font-size: 11.5px;+ color: var(--muted);+}+.video-review-summary b { font-size: 12px; font-weight: 600; color: var(--text); }+.video-review-panel .chat-md-drawer-body > * { flex: 0 0 auto; }+.video-review-composition + .video-review-composition { border-top: 1px solid var(--border); }+.video-review-comp-head { display: flex; flex-direction: column; gap: 10px; padding: 14px 16px 12px; }+.video-review-comp-name {+ font-size: 14.5px;+ font-weight: 650;+ line-height: 1.4;+ letter-spacing: -0.01em;+ color: var(--text);+ text-wrap: pretty;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.video-review-comp-meta { display: flex; flex-wrap: wrap; gap: 6px; font-size: 11.5px; color: var(--muted); }+.video-review-meta-sep { font-style: normal; color: #c2c7d3; }+.video-review-rail { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; }+.video-review-step {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 7px 9px;+ border: 1px solid var(--border-strong);+ border-radius: 9px;+ background: #fcfdff;+}+.video-review-step-name {+ display: flex;+ align-items: center;+ gap: 5px;+ font-size: 11.5px;+ font-weight: 600;+ color: var(--text-2);+}+.video-review-step-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: #d4d8e2; }+.video-review-step-state { font-size: 11px; color: var(--muted); }+.video-review-step.is-done { border-color: rgba(22, 163, 74, 0.35); background: rgba(22, 163, 74, 0.05); }+.video-review-step.is-done .video-review-step-dot { background: var(--success); }+.video-review-step.is-done .video-review-step-state { color: var(--success); }+.video-review-step.is-wait { border-color: rgba(217, 119, 6, 0.4); background: rgba(217, 119, 6, 0.05); }+.video-review-step.is-wait .video-review-step-dot { background: var(--warn); }+.video-review-step.is-wait .video-review-step-state { color: var(--warn); font-weight: 600; }+.video-review-step.is-partial .video-review-step-dot { background: var(--warn); }+.video-review-step.is-partial .video-review-step-state { color: var(--muted); }+.video-review-step.is-todo { border-style: dashed; background: #fff; }+.video-review-step.is-todo .video-review-step-name { color: #a8aebd; }+.video-review-step.is-todo .video-review-step-state { color: #c2c7d3; }+.video-review-section { border-top: 1px solid var(--border); }+.video-review-section-head {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 11px 16px;+ border: 0;+ background: transparent;+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.video-review-section-head:hover { background: #fafbfe; }+.video-review-section-title { font-size: 12px; font-weight: 650; color: var(--text); }+.video-review-section-sub { flex: 1 1 auto; min-width: 0; font-size: 11px; color: var(--muted); }+.video-review-chevron { flex: 0 0 auto; display: inline-flex; color: #a8aebd; }+.video-review-chevron-icon { width: 14px; height: 14px; transition: transform 0.16s ease; }+.video-review-composition.is-open > .video-review-comp-fold .video-review-chevron-icon,+.video-review-section.is-open .video-review-chevron-icon { transform: rotate(90deg); }+.video-review-section-body { padding: 0 16px 14px; }+.video-review-hint { margin: 0 0 8px; font-size: 11.5px; line-height: 1.6; color: var(--muted); }+.video-review-narration {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 9px 10px;+ border: 1px solid var(--border);+ border-radius: 10px;+ background: #fcfdff;+}+.video-review-narration audio { flex: 1 1 auto; min-width: 0; height: 30px; }+.video-review-narration-meta { font-family: var(--font-mono); font-size: 11px; color: var(--muted); white-space: nowrap; }+.video-review-scenes { border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }+.video-review-scene {+ display: grid;+ grid-template-columns: 104px 1fr;+ gap: 11px;+ padding: 10px 11px;+ background: #fff;+}+.video-review-scene + .video-review-scene { border-top: 1px solid var(--border); }+.video-review-scene:hover { background: #fafbfe; }+.video-review-final-video {+ width: 100%;+ max-height: 320px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: #000;+}+.video-review-scene-frame.is-expandable,+.video-review-final-video.is-expandable { cursor: zoom-in; }+.video-review-scene-frame.is-expandable:hover,+.video-review-final-video.is-expandable:hover { filter: brightness(1.06); }+.video-review-scene-frame {+ width: 100%;+ aspect-ratio: 16 / 9;+ object-fit: cover;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: #eceef3;+}+.video-review-scene-frame.is-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 10px;+ color: #a8aebd;+ background: repeating-linear-gradient(45deg, #f2f3f7 0 6px, #eaecf2 6px 12px);+}+.video-review-scene-body { min-width: 0; display: flex; flex-direction: column; gap: 4px; }+.video-review-scene-id {+ align-self: flex-start;+ padding: 1px 6px;+ border-radius: 5px;+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--primary-text);+ background: var(--primary-soft);+}+.video-review-scene-copy { font-size: 12.5px; font-weight: 550; line-height: 1.4; color: var(--text); text-wrap: pretty; }+.video-review-scene-narration {+ font-size: 11.5px;+ line-height: 1.5;+ color: var(--muted);+ text-wrap: pretty;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.video-review-scene-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 3px; }+.video-review-action.btn-sm {+ padding: 3px 9px;+ border-color: var(--border-strong);+ font-size: 11.5px;+ font-weight: 400;+ color: var(--text-2);+ border-radius: 7px;+}+.video-review-action.btn-sm:hover {+ border-color: var(--primary);+ color: var(--primary-text);+ background: var(--primary-soft);+}+.video-review-comp-fold {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 12px 16px;+ border: 0;+ background: #fbfcfe;+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.video-review-comp-fold:hover { background: #f5f7fc; }+.video-review-composition.is-open > .video-review-comp-fold {+ background: #f5f7fc;+ border-bottom: 1px solid var(--border);+}+.video-review-fold-name {+ flex: 1 1 auto;+ min-width: 0;+ font-size: 12.5px;+ font-weight: 600;+ color: var(--text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.video-review-pill {+ flex: 0 0 auto;+ padding: 1px 7px;+ border: 1px solid;+ border-radius: 999px;+ font-size: 10.5px;+ white-space: nowrap;+}+.video-review-pill.is-ok { color: var(--success); border-color: rgba(22, 163, 74, 0.4); background: var(--success-soft); }+.video-review-pill.is-wait { color: var(--warn); border-color: rgba(217, 119, 6, 0.4); background: rgba(217, 119, 6, 0.08); }+.video-review-composition.is-folded > .video-review-fold-body > .video-review-comp-head { padding-top: 12px; }+.video-review-empty {+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 34px 24px;+ text-align: center;+ font-size: 12.5px;+ line-height: 1.7;+ color: var(--muted);+}+.video-review-empty b { font-size: 13px; font-weight: 600; color: var(--text-2); }+.context-menu-item:focus-visible { background: var(--primary-soft); }+.context-menu-item:focus-visible {+ outline: 2px solid var(--primary);+ outline-offset: -2px;+}++.composer-model-menu-item.is-disabled {+ cursor: not-allowed;+ opacity: 0.52;+ background: transparent;+}++.composer-model-menu-select:disabled {+ cursor: not-allowed;+}++.composer-model-menu-item.is-disabled:hover,+.composer-model-menu-select:disabled:hover {+ background: transparent;+}diff --git a/test/e2e/chat_e2e_model_stream.spec.ts b/test/e2e/chat_e2e_model_stream.spec.tsindex 978ecece..9ee956e0 100644--- a/test/e2e/chat_e2e_model_stream.spec.ts+++ b/test/e2e/chat_e2e_model_stream.spec.ts@@ -706,7 +706,9 @@ test.describe('real chat pipeline with a local model', () => {});test('deletes a queued message from composer edit without ever sending it', async ({ modelOrkas }) => {- modelOrkas.setModelMode('slow');+ // Establish the edit lock before the local response ends, including on a+ // loaded runner. The ordinary 2.4s fixture can drain the row during click.+ modelOrkas.setModelMode('very-slow');const page = await sendNewChat(modelOrkas, 'E2E active turn while deleting a queue edit.');await expect.poll(() => modelOrkas.modelRequests.length,@@ -733,7 +735,7 @@ test.describe('real chat pipeline with a local model', () => {// Let the active slow turn settle while the edit lock is held. If the// regression returns, the queued text would already reach the model here.- await page.waitForTimeout(2_800);+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toBeVisible({ timeout: 30_000 });expect(modelOrkas.modelRequests).toHaveLength(1);await page.locator('#chat-queue-edit-delete-btn').click();diff --git a/test/e2e/commander_e2e_orchestration.spec.ts b/test/e2e/commander_e2e_orchestration.spec.tsindex 7b666c9e..3784294b 100644--- a/test/e2e/commander_e2e_orchestration.spec.ts+++ b/test/e2e/commander_e2e_orchestration.spec.ts@@ -25,7 +25,7 @@ test.describe('Commander orchestration', () => {test('hands a finished deliverable to a shipped agent without an empty Commander tail', async ({modelOrkas,- }) => {+ }, testInfo) => {if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');let page = modelOrkas.page;const delegatedTask = 'Write the final launch announcement with a concise title and two paragraphs.';@@ -64,6 +64,14 @@ test.describe('Commander orchestration', () => {// narrated segment is the only Commander bubble. A process replay or// active-turn snapshot must not recreate the duplicate live placeholder.await expect(commanderBubbles).toHaveCount(1);+ await expect(commanderBubbles.locator('.stream-process-body')).toContainText('ContentWriter');+ await expect(commanderBubbles.locator('.stream-process-body')).not.toContainText(CONTENT_WRITER_ID);+ const process = commanderBubbles.locator('.stream-process');+ if (!(await process.evaluate((element) => (element as HTMLDetailsElement).open))) {+ await process.locator('summary').click();+ }+ await expect(commanderBubbles.locator('.stream-process-body')).toBeVisible();+ await commanderBubbles.screenshot({ path: testInfo.outputPath('delegation-agent-name.png') });const runningConversationId = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');@@ -131,6 +139,8 @@ test.describe('Commander orchestration', () => {);await expect(restoredCommanderBubble).toHaveCount(1);await expect(restoredCommanderBubble).toContainText(commanderNarration);+ await expect(restoredCommanderBubble.locator('.stream-process-body')).toContainText('ContentWriter');+ await expect(restoredCommanderBubble.locator('.stream-process-body')).not.toContainText(CONTENT_WRITER_ID);expect(modelOrkas.modelRequests).toHaveLength(requestsBeforeRelaunch);});diff --git a/test/e2e/composer_e2e_interactions.spec.ts b/test/e2e/composer_e2e_interactions.spec.tsindex cd6a0f66..676ae9a0 100644--- a/test/e2e/composer_e2e_interactions.spec.ts+++ b/test/e2e/composer_e2e_interactions.spec.ts@@ -854,3 +854,17 @@ test.describe('new chat composer', () => {);});});++test('keeps all four recipient tabs on one row, including Library', async ({ appPage }) => {+ await appPage.locator('#new-chat-recipient-chip').click();+ const tabs = appPage.locator('.skill-picker-tabs [data-agent-picker-tab]');+ await expect(tabs).toHaveCount(4);+ const boxes = await tabs.evaluateAll((elements) => elements.map((element) => {+ const rect = element.getBoundingClientRect();+ return { top: rect.top, width: rect.width, height: rect.height };+ }));+ expect(boxes.every((box) => box.width > 0 && box.height > 0)).toBe(true);+ expect(Math.max(...boxes.map((box) => box.top)) - Math.min(...boxes.map((box) => box.top))).toBeLessThan(2);+ await tabs.filter({ hasText: 'Library' }).click();+ await expect(appPage.locator('[data-agent-picker-tab="library"]')).toHaveClass(/\bactive\b/);+});diff --git a/test/e2e/fixtures/orkas.ts b/test/e2e/fixtures/orkas.tsindex 73f9c474..1a564e18 100644--- a/test/e2e/fixtures/orkas.ts+++ b/test/e2e/fixtures/orkas.ts@@ -53,6 +53,7 @@ type OrkasOptions = {updateStub?: boolean;voiceStub?: boolean;metacognitionEnabled?: boolean;+ enableSystemProxy?: boolean;};export type CliStubInvocation = {@@ -788,6 +789,7 @@ export class OrkasTestApp {readonly updateStub: boolean;readonly voiceStub: boolean;readonly metacognitionEnabled: boolean;+ readonly enableSystemProxy: boolean;readonly cliStatePath: string;readonly fakeOpenCodePath: string | null;readonly fakeHermesPath: string | null;@@ -872,6 +874,7 @@ export class OrkasTestApp {this.updateStub = options.updateStub === true;this.voiceStub = options.voiceStub === true;this.metacognitionEnabled = options.metacognitionEnabled === true;+ this.enableSystemProxy = options.enableSystemProxy === true;this.root = mkdtempSync(path.join(tmpdir(), 'orkas-e2e-'));this.workspaceRoot = path.join(this.root, 'workspace');this.userWorkspaceRoot = path.join(this.root, 'userWorkSpace');@@ -955,7 +958,7 @@ export class OrkasTestApp {ORKAS_ACCOUNT_API_BASE: this.apiBaseUrl,ORKAS_E2E_MARKETPLACE_API_BASE: this.marketplaceStub ? this.apiBaseUrl : '',ORKAS_METACOGNITION: this.metacognitionEnabled ? '1' : '0',- ORKAS_NO_AUTO_PROXY: '1',+ ORKAS_NO_AUTO_PROXY: this.enableSystemProxy ? '0' : '1',ORKAS_PROFILE: 'global',NO_PROXY: 'localhost,127.0.0.1,::1',no_proxy: 'localhost,127.0.0.1,::1',diff --git a/test/e2e/proxy_e2e_routing.spec.ts b/test/e2e/proxy_e2e_routing.spec.tsnew file mode 100644index 00000000..86972b31--- /dev/null+++ b/test/e2e/proxy_e2e_routing.spec.ts@@ -0,0 +1,30 @@+import { createServer } from 'node:http';+import { expect, test } from '@playwright/test';+import { OrkasTestApp } from './fixtures/orkas';++test('main-process fetch follows the system proxy after normal app startup', async ({}, testInfo) => {+ const requests: string[] = [];+ const server = createServer((request, response) => {+ requests.push(request.url || '');+ response.end('local proxy response');+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Proxy fixture has no port');+ const app = new OrkasTestApp(testInfo, { enableSystemProxy: true });+ try {+ await app.launch();+ const result = await app.electronApp!.evaluate(async ({ session }, port) => {+ await session.defaultSession.setProxy({ proxyRules: `http=127.0.0.1:${port}` });+ try {+ return await (await fetch('http://orkas-proxy-parity.invalid/probe', { signal: AbortSignal.timeout(5000) })).text();+ } catch { return 'proxy was bypassed'; }+ }, address.port);+ expect(result).toBe('local proxy response');+ expect(requests).toContain('http://orkas-proxy-parity.invalid/probe');+ } finally {+ await app.dispose();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});diff --git a/test/e2e/video_review_e2e_panel.spec.ts b/test/e2e/video_review_e2e_panel.spec.tsindex 4daa3efb..1a0d5f60 100644--- a/test/e2e/video_review_e2e_panel.spec.ts+++ b/test/e2e/video_review_e2e_panel.spec.ts@@ -156,6 +156,8 @@ test.describe('video review panel', () => {await expect(page.locator('.video-review-comp-name')).toHaveText('A 60-second Orkas product film');await expect(page.locator('.video-review-comp-name')).not.toContainText('project/composition');await expect(page.locator('.video-review-step')).toHaveCount(4);+ await expect(page.locator('.video-review-rail')).toHaveCSS('display', 'grid');+ await expect(page.locator('.video-review-scene').first()).toHaveCSS('display', 'grid');await expect(page.locator('.video-review-step').nth(1)).toHaveClass(/\bis-done\b/);await expect(page.locator('.video-review-step').nth(3)).toHaveClass(/\bis-wait\b/);// A standalone final-confirmation stop stores its playable artifact indiff --git a/test/main/features/auth-recovery-parity.test.ts b/test/main/features/auth-recovery-parity.test.tsnew file mode 100644index 00000000..af638f96--- /dev/null+++ b/test/main/features/auth-recovery-parity.test.ts@@ -0,0 +1,118 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++let root: string;+let previousRoot: string | undefined;+const uid = 'authParityRecovery';+beforeEach(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-auth-parity-'));+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = root;+ vi.resetModules();+ (await import('../../../src/main/features/users')).activateUser(uid);+});+afterEach(() => {+ vi.doUnmock('node:fs');+ vi.doUnmock('#core-agent');+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ fs.rmSync(root, { recursive: true, force: true });+});++async function writeStore(store: unknown) {+ const { userAuthProfilesFile } = await import('../../../src/main/paths');+ const { encryptLocalSecret } = await import('../../../src/main/util/local-secret-store');+ const file = userAuthProfilesFile(uid);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, encryptLocalSecret({ namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json' }, JSON.stringify(store)));+ return file;+}++describe('auth retained recovery boundaries', () => {+ it('reports expired OAuth only after refresh fails, then clears it after successful refresh', async () => {+ const refreshToken = vi.fn().mockRejectedValueOnce(new Error('expired grant'))+ .mockResolvedValueOnce({ access: 'fixture-new-access', refresh: 'fixture-new-refresh', expires: Date.now() + 60_000 });+ const oauth = await import('../../../src/core-agent/src/auth/oauth-compat');+ oauth.registerOAuthProvider({ id: 'openai-codex', name: 'Codex', login: vi.fn(), refreshToken, getApiKey: (credentials) => credentials.access });+ await writeStore({ version: 6, profiles: {+ 'openai-codex:default': { type: 'oauth', provider: 'openai-codex', label: 'default', access: 'fixture-old', refresh: 'fixture-refresh', expires: 1, createdAt: 1, lastUsed: 0 },+ }, entries: [{ entryId: 'fixture-entry', provider: 'openai-codex', profileId: 'openai-codex:default', model: 'gpt-5.5', createdAt: 1, lastUsed: 0 }] });+ const auth = await import('../../../src/main/features/auth');+ expect(auth.getConfiguredModelOAuthExpiredMessage()).toBeNull();+ expect(await auth.pickChatEntryGroup()).toEqual([]);+ expect(auth.getConfiguredModelOAuthExpiredMessage()).toBeTruthy();+ expect(await auth.pickChatEntryGroup()).toEqual([expect.objectContaining({ apiKey: 'fixture-new-access' })]);+ expect(auth.getConfiguredModelOAuthExpiredMessage()).toBeNull();+ expect(refreshToken).toHaveBeenCalledTimes(2);+ });++ it('publishes selection and model change together in one write', async () => {+ const { userAuthProfilesFile } = await import('../../../src/main/paths');+ const file = userAuthProfilesFile(uid);+ let publishes = 0;+ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return { ...actual, renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ if (String(to) === file) publishes++;+ return actual.renameSync(from, to);+ } };+ });+ const auth = await import('../../../src/main/features/auth');+ const target = await auth.addApiKeyEntry('openai', 'gpt-5.6-sol', 'fixture-key-one');+ await auth.addApiKeyEntry('anthropic', 'claude-opus-5', 'fixture-key-two');+ publishes = 0;+ const selected = await auth.selectEntry(target.entryId, 'gpt-5.6-terra');+ expect(publishes).toBe(1);+ expect(selected.entries[0]).toMatchObject({ entryId: target.entryId, model: 'gpt-5.6-terra' });+ });++ it('does not mutate a custom endpoint model through Composer selection', async () => {+ const auth = await import('../../../src/main/features/auth');+ const entry = await auth.addCustomModelEntry({ baseUrl: 'https://fixture.example/v1', model: 'fixed-model', apiKey: 'fixture-key' });+ await expect(auth.selectEntry(entry.entryId, 'other-model')).rejects.toThrow('fixed');+ expect((await auth.listEntries()).entries[0].model).toBe('fixed-model');+ });++ it.each(['saveSearchProfiles', 'saveImageProfiles', 'saveVideoProfiles', 'saveTtsProfiles', 'configureAllOrkasApiServices'] as const)+ ('preserves an invalid existing schema during %s', async (operation) => {+ const file = await writeStore({ version: 6, unexpected: 'preserve' });+ const original = fs.readFileSync(file, 'utf8');+ const auth = await import('../../../src/main/features/auth');+ expect(() => operation === 'configureAllOrkasApiServices'+ ? auth[operation]('fixture-new-key') : auth[operation]([])).toThrow('schema invalid');+ expect(fs.readFileSync(file, 'utf8')).toBe(original);+ });++ it('keeps legacy custom speech profiles that did not record a provider', async () => {+ await writeStore({ version: 6, profiles: {}, entries: [], ttsProfiles: [{ id: 'legacy-speech', baseUrl: 'https://fixture.example/v1', model: 'speech', apiKey: 'fixture-key' }] });+ const auth = await import('../../../src/main/features/auth');+ expect(auth.loadTtsProfiles()).toEqual([expect.objectContaining({ id: 'legacy-speech', provider: 'custom' })]);+ });++ it('does not fail a healthy model choice when last-used persistence fails', async () => {+ const auth = await import('../../../src/main/features/auth');+ const entry = await auth.addApiKeyEntry('openai', 'gpt-5.5', 'fixture-key');+ const { userAuthProfilesFile } = await import('../../../src/main/paths');+ const file = userAuthProfilesFile(uid);+ fs.writeFileSync(file, 'fixture-corrupt-store');+ expect(() => auth.bumpEntryLastUsed(entry.entryId)).not.toThrow();+ expect(fs.readFileSync(file, 'utf8')).toBe('fixture-corrupt-store');+ });++ it('redacts SDK connection errors before returning them to the renderer', async () => {+ const key = 'fixture-opaque-secret-123456';+ vi.doMock('#core-agent', async (importOriginal) => ({+ ...await importOriginal<typeof import('#core-agent')>(),+ createPiProvider: () => ({ complete: async () => { throw new Error(`Rejected ${key} at https://private.fixture.example/v1?signature=secret`); } }),+ }));+ const auth = await import('../../../src/main/features/auth');+ const profile = await auth.addApiKey('openai', key);+ const result = await auth.testConnection('openai', 'gpt-5.5', profile.profileId);+ expect(result.ok).toBe(false);+ expect(result.error).toContain('Rejected');+ expect(result.error).not.toContain(key);+ expect(result.error).not.toContain('signature=secret');+ });+});diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.tsindex 9a71316f..bdbcd6b9 100644--- a/test/main/features/auth.test.ts+++ b/test/main/features/auth.test.ts@@ -337,10 +337,10 @@ describe('auth › multi-profile store (addApiKey / removeCredential / renameProconst a = await import('../../../src/main/features/auth');const { entries } = await a.listEntries();expect(entries).toHaveLength(1);- expect(entries[0].model).toBe('k2p6');+ expect(entries[0].model).toBe('k2p7');const rewritten = JSON.parse(localSecrets.decryptLocalSecret(ctx, fs.readFileSync(file, 'utf8')));- expect(rewritten.entries[0].model).toBe('k2p6');+ expect(rewritten.entries[0].model).toBe('k2p7');});it('removeCredential drops the profile', async () => {@@ -772,7 +772,7 @@ describe('auth › entries (priority list)', () => {await a.addEntry({ provider: 'kimi-coding', model: 'k2p6', profileId: p.profileId });const { entries } = await a.listEntries();expect(entries).toHaveLength(1);- expect(entries[0].model).toBe('k2p6');+ expect(entries[0].model).toBe('k2p7');});it('addEntry rejects a profileId belonging to a different provider', async () => {@@ -1153,3 +1153,332 @@ describe('auth › getConfig', () => {expect(await a.getConfig()).toEqual({ provider: 'anthropic', model: 'claude-opus-5' });});});++describe('auth › durable shared profile contracts', () => {+ it('keeps a successfully parsed profile available when its migration rewrite fails', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, localSecrets.encryptLocalSecret({+ namespace: 'auth.profiles',+ ownerId: TEST_UID,+ recordId: 'auth-profiles.json',+ }, JSON.stringify({+ version: 4,+ profiles: {+ 'openai:default': {+ type: 'api_key',+ provider: 'openai',+ label: 'default',+ key: 'sk-readable-during-migration-xxxxxxxx',+ createdAt: 1,+ lastUsed: 0,+ },+ },+ entries: [],+ searchProfiles: [],+ imageProfiles: [],+ })), 'utf8');++ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return {+ ...actual,+ renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ if (String(from) === `${file}.tmp` && String(to) === file) {+ throw Object.assign(new Error('migration rename denied'), { code: 'EACCES' });+ }+ return actual.renameSync(from, to);+ },+ };+ });++ const a = await import('../../../src/main/features/auth');+ const { providers } = await a.listProviders();++ expect(providers.find((provider) => provider.id === 'openai')?.profiles)+ .toEqual([expect.objectContaining({ masked: 'sk-r…xxxx' })]);+ expect(localSecrets.isEncryptedSecret(fs.readFileSync(file, 'utf8'))).toBe(true);+ });++ it('recreates a missing credentials directory before the first profile write', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };+ fs.rmSync(path.dirname(file), { recursive: true, force: true });++ const a = await import('../../../src/main/features/auth');+ await a.addApiKey('openai', 'sk-created-after-missing-dir-xxxxxxxx');++ expect(fs.statSync(path.dirname(file)).isDirectory()).toBe(true);+ expect(localSecrets.decryptLocalSecret(ctx, fs.readFileSync(file, 'utf8')))+ .toContain('sk-created-after-missing-dir-xxxxxxxx');+ });++ it('recovers one transient ENOENT while writing the temporary profile file', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };+ let writeAttempts = 0;+ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return {+ ...actual,+ writeFileSync: (target: fs.PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions) => {+ if (String(target) === `${file}.tmp`) {+ writeAttempts += 1;+ if (writeAttempts === 1) {+ actual.rmSync(path.dirname(file), { recursive: true, force: true });+ throw Object.assign(new Error('transient missing profile directory'), { code: 'ENOENT' });+ }+ }+ return actual.writeFileSync(target, data, options);+ },+ };+ });++ const a = await import('../../../src/main/features/auth');+ await a.addApiKey('openai', 'sk-new-after-write-retry-xxxxxxxx');++ expect(writeAttempts).toBe(2);+ expect(localSecrets.decryptLocalSecret(ctx, fs.readFileSync(file, 'utf8')))+ .toContain('sk-new-after-write-retry-xxxxxxxx');+ });++ it('recovers one transient ENOENT while atomically publishing auth profiles', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, localSecrets.encryptLocalSecret(ctx, JSON.stringify({+ version: 6,+ profiles: {+ 'openai:default': {+ type: 'api_key',+ provider: 'openai',+ label: 'default',+ key: 'sk-existing-must-survive-xxxxxxxx',+ createdAt: 1,+ lastUsed: 0,+ },+ },+ entries: [],+ searchProfiles: [],+ imageProfiles: [],+ videoProfiles: [],+ ttsProfiles: [],+ disabledManagedProviders: [],+ disabledManagedModels: [],+ })), 'utf8');++ let publishAttempts = 0;+ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return {+ ...actual,+ renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ if (String(from) === `${file}.tmp` && String(to) === file) {+ publishAttempts += 1;+ if (publishAttempts === 1) {+ actual.rmSync(from, { force: true });+ throw Object.assign(new Error('transient missing temp file'), { code: 'ENOENT' });+ }+ }+ return actual.renameSync(from, to);+ },+ };+ });++ const a = await import('../../../src/main/features/auth');++ await a.addApiKey('anthropic', 'sk-new-after-retry-xxxxxxxx');++ expect(publishAttempts).toBe(2);+ const saved = localSecrets.decryptLocalSecret(ctx, fs.readFileSync(file, 'utf8'));+ expect(saved).toContain('sk-existing-must-survive-xxxxxxxx');+ expect(saved).toContain('sk-new-after-retry-xxxxxxxx');+ });++ it('rethrows repeated ENOENT without replacing the existing auth profiles', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const original = localSecrets.encryptLocalSecret(ctx, JSON.stringify({+ version: 6,+ profiles: {+ 'openai:default': {+ type: 'api_key',+ provider: 'openai',+ label: 'default',+ key: 'sk-existing-must-remain-xxxxxxxx',+ createdAt: 1,+ lastUsed: 0,+ },+ },+ entries: [],+ searchProfiles: [],+ imageProfiles: [],+ videoProfiles: [],+ ttsProfiles: [],+ disabledManagedProviders: [],+ disabledManagedModels: [],+ }));+ fs.writeFileSync(file, original, 'utf8');++ let publishAttempts = 0;+ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return {+ ...actual,+ renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ if (String(from) === `${file}.tmp` && String(to) === file) {+ publishAttempts += 1;+ actual.rmSync(from, { force: true });+ throw Object.assign(new Error('persistent missing temp file'), { code: 'ENOENT' });+ }+ return actual.renameSync(from, to);+ },+ };+ });++ const a = await import('../../../src/main/features/auth');+ await expect(a.addApiKey('anthropic', 'sk-must-not-persist-xxxxxxxx'))+ .rejects.toMatchObject({ code: 'ENOENT' });++ expect(publishAttempts).toBe(2);+ expect(fs.readFileSync(file, 'utf8')).toBe(original);+ expect(fs.existsSync(`${file}.tmp`)).toBe(false);+ });++ it('does not retry a non-ENOENT publish failure or replace existing profiles', async () => {+ const paths = await import('../../../src/main/paths');+ const localSecrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const original = localSecrets.encryptLocalSecret(ctx, JSON.stringify({+ version: 6,+ profiles: {+ 'openai:default': {+ type: 'api_key', provider: 'openai', label: 'default',+ key: 'sk-existing-before-eacces-xxxxxxxx', createdAt: 1, lastUsed: 0,+ },+ },+ entries: [], searchProfiles: [], imageProfiles: [], videoProfiles: [], ttsProfiles: [],+ disabledManagedProviders: [], disabledManagedModels: [],+ }));+ fs.writeFileSync(file, original, 'utf8');+ let publishAttempts = 0;+ vi.doMock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs')>();+ return {+ ...actual,+ renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ if (String(from) === `${file}.tmp` && String(to) === file) {+ publishAttempts += 1;+ throw Object.assign(new Error('profile publish denied'), { code: 'EACCES' });+ }+ return actual.renameSync(from, to);+ },+ };+ });++ const a = await import('../../../src/main/features/auth');+ await expect(a.addApiKey('anthropic', 'sk-must-not-persist-xxxxxxxx'))+ .rejects.toMatchObject({ code: 'EACCES' });++ expect(publishAttempts).toBe(1);+ expect(fs.readFileSync(file, 'utf8')).toBe(original);+ expect(fs.existsSync(`${file}.tmp`)).toBe(false);+ });++ it.each([+ ['addApiKeyEntry', async (a: typeof import('../../../src/main/features/auth')) => {+ await a.addApiKeyEntry('openai', 'gpt-5.5', 'sk-must-not-overwrite-xxxxxxxx');+ }],+ ['addCustomModelEntry', async (a: typeof import('../../../src/main/features/auth')) => {+ await a.addCustomModelEntry({+ baseUrl: 'https://example.com/v1',+ model: 'private-model',+ apiKey: 'sk-must-not-overwrite-xxxxxxxx',+ });+ }],+ ['reorderEntries', async (a: typeof import('../../../src/main/features/auth')) => {+ await a.reorderEntries([]);+ }],+ ])('refuses %s when the existing credential store is unreadable', async (_name, mutate) => {+ const paths = await import('../../../src/main/paths');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const corrupt = 'credential-store-must-be-preserved';+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, corrupt, 'utf8');+ const a = await import('../../../src/main/features/auth');++ await expect(mutate(a)).rejects.toThrow();+ expect(fs.readFileSync(file, 'utf8')).toBe(corrupt);+ expect(loggerMocks.warn).toHaveBeenCalledWith(+ 'failed to load profiles store',+ expect.objectContaining({+ error: expect.objectContaining({+ name: 'SyntaxError',+ message_hash: expect.any(String),+ message_chars: expect.any(Number),+ }),+ }),+ );+ expect(JSON.stringify(loggerMocks.warn.mock.calls)).not.toContain(corrupt);+ });+ it('atomically changes a Composer model version and promotes that entry', async () => {+ const a = await import('../../../src/main/features/auth');+ const openai = await a.addApiKey('openai', 'sk-composer-version-xxxxxxxx', 'versioned');+ const target = await a.addEntry({+ provider: 'openai', model: 'gpt-5.6-sol', profileId: openai.profileId,+ });+ const anthropic = await a.addApiKey('anthropic', 'sk-composer-priority-xxxxxxxx', 'priority');+ const first = await a.addEntry({+ provider: 'anthropic', model: 'claude-opus-5', profileId: anthropic.profileId,+ });++ expect((await a.listEntries()).entries.map((entry) => entry.entryId))+ .toEqual([first.entryId, target.entryId]);+ const selected = await a.selectEntry(target.entryId, 'gpt-5.6-terra');+ expect(selected.entries).toMatchObject([{+ entryId: target.entryId,+ model: 'gpt-5.6-terra',+ modelName: 'GPT-5.6 Terra',+ }, {+ entryId: first.entryId,+ }]);+ expect((await a.listEntries()).entries[0]).toMatchObject({+ entryId: target.entryId,+ model: 'gpt-5.6-terra',+ });+ });++ it('does not partially change or promote an invalid Composer model version', async () => {+ const a = await import('../../../src/main/features/auth');+ const openai = await a.addApiKey('openai', 'sk-composer-invalid-xxxxxxxx', 'versioned');+ const target = await a.addEntry({+ provider: 'openai', model: 'gpt-5.6-sol', profileId: openai.profileId,+ });+ const anthropic = await a.addApiKey('anthropic', 'sk-composer-first-xxxxxxxx', 'priority');+ const first = await a.addEntry({+ provider: 'anthropic', model: 'claude-opus-5', profileId: anthropic.profileId,+ });++ await expect(a.selectEntry(target.entryId, 'gpt-not-listed'))+ .rejects.toMatchObject({ code: 'MODEL_NOT_AVAILABLE' });+ expect((await a.listEntries()).entries.map((entry) => [entry.entryId, entry.model]))+ .toEqual([+ [first.entryId, 'claude-opus-5'],+ [target.entryId, 'gpt-5.6-sol'],+ ]);+ });++});diff --git a/test/main/features/client_config.test.ts b/test/main/features/client_config.test.tsindex a0e0bfb1..3b4d87b3 100644--- a/test/main/features/client_config.test.ts+++ b/test/main/features/client_config.test.ts@@ -71,6 +71,19 @@ describe('client_config', () => {expect(manager.get('feature.local-default')).toBe(true);});+ it('preserves the wire-format image editing flag through normalization and cache reads', async () => {+ const { clientConfig, getConfiguredImageGenCapability, DEFAULT_IMAGE_GEN_BY_PROVIDER } = await import('../../../src/main/features/client_config');+ const users = await import('../../../src/main/features/users');+ users.activateUser('clientconfigimageparity');+ clientConfig.applyServerPayload({ immediate: { model_catalog: { image_generation: {+ google: { model: 'fixture-image', api: 'gemini', supports_edit: true },+ } } }, restart: {}, config_hash: 'fixture-image-edit' }, 'fixture-image-edit');+ expect(getConfiguredImageGenCapability('google')).toMatchObject({ model: 'fixture-image', supportsEdit: true });+ expect(DEFAULT_IMAGE_GEN_BY_PROVIDER.doubao.model).toBe('doubao-seedream-5-0-lite-260128');+ // The normalized camelCase form is read again through the same catalog path.+ expect(getConfiguredImageGenCapability('google')).toMatchObject({ supportsEdit: true });+ });+it('ships the synchronized public model catalog with compatibility metadata', () => {expect(DEFAULT_PROVIDER_MODELS['openai-codex']).toEqual([{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol', template: 'gpt-5.5', contextWindow: 372000, maxTokens: 128000, maxInputImages: 20 },diff --git a/test/main/features/connectors/manager.test.ts b/test/main/features/connectors/manager.test.tsindex 1021cf6a..8d2d1f3f 100644--- a/test/main/features/connectors/manager.test.ts+++ b/test/main/features/connectors/manager.test.ts@@ -1300,3 +1300,58 @@ describe('features/connectors/manager authorization recovery', () => {});});++describe('OAuth refresh ownership', () => {+ it('shares one rotating grant between an ordinary refresh and a forced retry', async () => {+ const registry = await import('../../../../src/main/features/connectors/registry');+ const manager = await import('../../../../src/main/features/connectors/manager');+ const instance = notionInstance();+ instance.oauth_grant.expires_at = Date.now() + 3_600_000;+ instance.dcr_client = { client_id: 'local-client', token_endpoint: 'https://example.test/token' } as any;+ await registry.upsert(TEST_UID, instance);+ let rejectFirstConnect!: (error: Error) => void;+ let firstConnectStarted!: () => void;+ const firstConnect = new Promise<void>((resolve) => { firstConnectStarted = resolve; });+ mocks.mcp.connect = vi.fn().mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {+ rejectFirstConnect = reject;+ firstConnectStarted();+ })).mockResolvedValue(undefined);+ let releaseRefresh!: () => void;+ let refreshStarted!: () => void;+ const refreshGate = new Promise<void>((resolve) => { releaseRefresh = resolve; });+ const refreshing = new Promise<void>((resolve) => { refreshStarted = resolve; });+ mocks.dcr.refreshDcrIfStale = vi.fn(async (_client, grant) => {+ refreshStarted();+ await refreshGate;+ return { ...grant, access_token: 'rotated-access', refresh_token: 'rotated-once', expires_at: Date.now() + 3_600_000 };+ });+ const first = manager.refreshTools(TEST_UID, 'notion');+ await firstConnect;+ await registry.update(TEST_UID, 'notion', (current) => ({ ...current, oauth_grant: { ...current.oauth_grant!, expires_at: 1 } }));+ const second = manager.refreshTools(TEST_UID, 'notion');+ await refreshing;+ rejectFirstConnect(new Error('401 Unauthorized'));+ // Allow the rejected connect to enter its forced-refresh path while the+ // ordinary remote request remains held at the explicit fixture gate.+ await new Promise<void>((resolve) => setImmediate(resolve));+ releaseRefresh();+ await Promise.all([first, second]);+ expect(mocks.dcr.refreshDcrIfStale).toHaveBeenCalledTimes(1);+ expect(registry.load(TEST_UID).connections.notion.oauth_grant?.refresh_token).toBe('rotated-once');+ expect(registry.load(TEST_UID).connections.notion.status.kind).toBe('connected');+ });++ it('does not count a Google grant rejected during verification as connected', async () => {+ await writeGoogleConnectorsConfig(true);+ const registry = await import('../../../../src/main/features/connectors/registry');+ const manager = await import('../../../../src/main/features/connectors/manager');+ const instance = googleInstance('gmail', ['https://www.googleapis.com/auth/gmail.modify']);+ instance.oauth_grant.expires_at = 1;+ instance.tools_cache = [{ name: 'search', description: '', input_schema: {} }] as any;+ await registry.upsert(TEST_UID, instance);+ mocks.oauth.refreshIfStale = vi.fn(async () => { throw Object.assign(new Error('connector_reconnect_required'), { code: 'connector_reconnect_required' }); });+ expect(await manager.verifyUsableConnectors(TEST_UID)).toBe(0);+ expect(registry.load(TEST_UID).connections.gmail.status.kind).toBe('error');+ expect(mocks.mcp.connect).not.toHaveBeenCalled();+ });+});diff --git a/test/main/features/connectors/oauth.test.ts b/test/main/features/connectors/oauth.test.tsindex 753a156e..c8265abf 100644--- a/test/main/features/connectors/oauth.test.ts+++ b/test/main/features/connectors/oauth.test.ts@@ -338,3 +338,18 @@ describe('features/connectors/oauth', () => {expect(err.message).toMatch(/refresh HTTP 503/);});});++describe('server-managed Bing grants', () => {+ it('refreshes an expired grant by its server id without a local refresh token', async () => {+ const request = vi.fn(async () => ({ ok: true, json: async () => ({ code: 0, access_token: 'new-access', grant_id: 'bing-grant', expires_in: 3600 }) }));+ vi.stubGlobal('fetch', request);+ const oauth = await import('../../../../src/main/features/connectors/oauth');+ const catalog = await import('../../../../src/main/features/connectors/catalog');+ const result = await oauth.refreshIfStale('u1', catalog.findCatalogEntry('bing-webmaster')!, {+ access_token: 'expired', refresh_token: null, server_managed: true, server_grant_id: 'bing-grant', expires_at: 1,+ scopes: ['webmaster.read'], token_type: 'Bearer',+ });+ expect(result).toMatchObject({ access_token: 'new-access', refresh_token: null, server_grant_id: 'bing-grant' });+ expect(JSON.parse(String(request.mock.calls[0]?.[1]?.body))).toMatchObject({ provider: 'bing', grant_id: 'bing-grant', device_id: 'device-1' });+ });+});diff --git a/test/main/features/generation_reference_assets.test.ts b/test/main/features/generation_reference_assets.test.tsindex 4557dee5..b84ee82d 100644--- a/test/main/features/generation_reference_assets.test.ts+++ b/test/main/features/generation_reference_assets.test.ts@@ -239,3 +239,11 @@ describe('generation reference assets', () => {}});});++describe('reference image transfer guards', () => {+ it('rejects an empty successful response', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array(0))));+ const { loadImageReferenceBuffersWithProgress } = await import('../../../src/main/features/generation_reference_assets');+ await expect(loadImageReferenceBuffersWithProgress(['https://cdn.example/empty.png'], [], {})).rejects.toThrow(/empty body/);+ });+});diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.tsindex 7701a89b..d1275cfd 100644--- a/test/main/features/group_chat/bus.test.ts+++ b/test/main/features/group_chat/bus.test.ts@@ -1613,11 +1613,12 @@ describe('group_chat bus › enqueue routing + persistence', () => {expect(fs.existsSync(shotlistPath)).toBe(true);});- it('hides process-dispatch files while keeping their paths in the commander handback', async () => {+ it.each(['shotlist.json', 'metadata.json', 'working/shotlist.json'])(+ 'hides process-dispatch file %s while keeping its path in the commander handback', async (filename) => {const bus = await import('../../../../src/main/features/group_chat/bus');const paths = await import('../../../../src/main/paths');const cid = 'cid-process-output-hidden';- const processPath = path.join(tmpDir, 'workspace', 'shotlist.json');+ const processPath = path.join(tmpDir, 'workspace', filename);fs.mkdirSync(path.dirname(processPath), { recursive: true });fs.writeFileSync(processPath, '{}');diff --git a/test/main/features/image_gen.test.ts b/test/main/features/image_gen.test.tsindex 23201716..1d95f864 100644--- a/test/main/features/image_gen.test.ts+++ b/test/main/features/image_gen.test.ts@@ -360,3 +360,60 @@ describe('image_gen › callGeminiImage', () => {}});});++// Keep the body pending after headers so cancellation/deadline tests exercise+// the actual adapter's response consumption, not merely fetch dispatch.+describe('image generation transfer and artifact boundaries', () => {+ const names = ['callOpenAIImage', 'callGeminiImage', 'callDoubaoImage', 'callOrkasImage'] as const;+ it.each(names)('%s cancels a response body after headers have arrived', async (name) => {+ const m = await import('../../../src/main/features/image_gen');+ const controller = new AbortController();+ let release!: (value: string) => void;+ let reading!: () => void;+ const bodyStarted = new Promise<void>((resolve) => { reading = resolve; });+ const fetchStub = vi.fn(async (_url, init) => {+ const body = new Promise<string>((resolve, reject) => {+ release = resolve;+ init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });+ });+ return { ok: true, status: 200, text: () => { reading(); return body; }, json: () => { reading(); return body.then(JSON.parse); } };+ });+ vi.stubGlobal('fetch', fetchStub);+ const result = m[name]({ apiKey: 'fixture-key', model: 'fixture', prompt: 'a circle', size: '1024x1024', signal: controller.signal })+ .then(() => 'success', (error) => error.message);+ try {+ await bodyStarted;+ controller.abort();+ await new Promise((resolve) => setImmediate(resolve));+ release('{}');+ expect(await result).toMatch(/aborted/i);+ expect(fetchStub).toHaveBeenCalledTimes(1);+ } finally { release?.('{}'); vi.unstubAllGlobals(); }+ });++ it.each(names)('%s rejects invalid decoded bytes despite an HTTP success', async (name) => {+ const m = await import('../../../src/main/features/image_gen');+ const invalid = Buffer.from('<html>upstream error</html>').toString('base64');+ vi.stubGlobal('fetch', async () => new Response(JSON.stringify(name === 'callGeminiImage'+ ? { candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: invalid } }] } }] }+ : { data: [{ b64_json: invalid }] }), { status: 200 }));+ try {+ await expect(m[name]({ apiKey: 'fixture-key', model: 'fixture', prompt: 'a circle', size: '1024x1024' }))+ .rejects.toThrow(/invalid|unsupported|malformed/i);+ } finally { vi.unstubAllGlobals(); }+ });++ it('does not submit or write an already cancelled image generation', async () => {+ writeProfilesFile({ 'openai:default': apiKeyProfile('openai', 'fixture-key') }, [entry('openai', 'gpt-5.4', 'openai:default', 'e1')]);+ const m = await import('../../../src/main/features/image_gen');+ const fetchStub = vi.fn(async () => new Response('{}', { status: 200 }));+ vi.stubGlobal('fetch', fetchStub);+ const controller = new AbortController(); controller.abort();+ try {+ await expect(m.generateImage({ prompt: 'a circle', outputAbsPath: path.join(tmpDir, 'cancelled.png'), signal: controller.signal }))+ .rejects.toThrow(/aborted/i);+ expect(fetchStub).not.toHaveBeenCalled();+ expect(fs.existsSync(path.join(tmpDir, 'cancelled.png'))).toBe(false);+ } finally { vi.unstubAllGlobals(); }+ });+});diff --git a/test/main/features/library-image-describer.test.ts b/test/main/features/library-image-describer.test.tsindex ff407826..0f5ff65f 100644--- a/test/main/features/library-image-describer.test.ts+++ b/test/main/features/library-image-describer.test.ts@@ -86,6 +86,7 @@ describe('Library image describer', () => {mediaType: 'image/jpeg',}],skillList: [],+ toolList: [],idleTimeout: 240,abortSignal: expect.any(AbortSignal),}));diff --git a/test/main/features/local_agents/bridge_skill_runner.test.ts b/test/main/features/local_agents/bridge_skill_runner.test.tsindex f772d7fa..6f021379 100644--- a/test/main/features/local_agents/bridge_skill_runner.test.ts+++ b/test/main/features/local_agents/bridge_skill_runner.test.ts@@ -223,15 +223,16 @@ describe('CLI bridge Skill runner', () => {const child = spawn(process.execPath, ['-e', ${JSON.stringify(grandchild)}], {stdio: ['ignore', 'inherit', 'inherit'],});- fs.writeFileSync(- path.join(process.env.ORKAS_RUN_SKILL_DIR, 'timeout-pids.json'),- JSON.stringify({ parent: process.pid, child: child.pid }),- );+ const marker = path.join(process.env.ORKAS_RUN_SKILL_DIR, 'timeout-pids.json');+ fs.writeFileSync(marker + '.tmp', JSON.stringify({ parent: process.pid, child: child.pid }));+ fs.renameSync(marker + '.tmp', marker);process.stdout.write('started');setInterval(() => {}, 1000);`;const runner = fixture(source, {- timeoutMs: 500,+ // Electron-as-Node plus the grandchild must finish starting before the+ // timeout can exercise a TERM-resistant process tree on a loaded host.+ timeoutMs: 2000,previewBytes: 100,hardOutputBytes: 4096,killGraceMs: 60,@@ -255,7 +256,7 @@ describe('CLI bridge Skill runner', () => {expect(result.status).toBe('timed_out');expect(result.timedOut).toBe(true);expect(result.stdout.text).toContain('started');- expect(Date.now() - startedAt).toBeLessThan(2500);+ expect(Date.now() - startedAt).toBeLessThan(4000);await waitFor(() => processTree !== null&& !processIsAlive(processTree.parent)&& !processIsAlive(processTree.child));@@ -280,10 +281,9 @@ describe('CLI bridge Skill runner', () => {const child = spawn(process.execPath, ['-e', ${JSON.stringify(grandchild)}], {stdio: 'ignore',});- fs.writeFileSync(- path.join(process.env.ORKAS_RUN_SKILL_DIR, 'active-pids-' + label + '.json'),- JSON.stringify({ parent: process.pid, child: child.pid }),- );+ const marker = path.join(process.env.ORKAS_RUN_SKILL_DIR, 'active-pids-' + label + '.json');+ fs.writeFileSync(marker + '.tmp', JSON.stringify({ parent: process.pid, child: child.pid }));+ fs.renameSync(marker + '.tmp', marker);process.on('SIGTERM', () => {});setInterval(() => {}, 1000);`;diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.tsindex c0a9c741..4e192e20 100644--- a/test/main/features/skills.test.ts+++ b/test/main/features/skills.test.ts@@ -2572,6 +2572,9 @@ describe('skills › streamSendToSkillChat synthesized progress', () => {}expect(seenOpts.message).toBe('请读取 SKILL.md 和导入资料,并直接整理完整技能。');+ expect(seenOpts.skillList).toEqual([]);+ expect(seenOpts.systemSkillList).toEqual(['skill-creator', 'package-installer']);+ expect(seenOpts.readOnlyExtraRoots).toEqual([path.join(customSkillsDir(), 'alpha')]);const chatPath = path.join(tmpDir, TEST_UID, 'cloud', 'chats', 'skill', 'alpha', 'chat.jsonl');const first = JSON.parse(fs.readFileSync(chatPath, 'utf8').trim().split('\n')[0]);expect(first.role).toBe('user');diff --git a/test/main/features/video_auth.test.ts b/test/main/features/video_auth.test.tsindex 001cce1c..f1480d57 100644--- a/test/main/features/video_auth.test.ts+++ b/test/main/features/video_auth.test.ts@@ -33,6 +33,7 @@ import {listVideoProfiles,removeVideoProfile,reorderVideoProfiles,+ listVideoProviderOptions,} from '../../../src/main/features/video_auth';beforeEach(() => {@@ -50,8 +51,8 @@ describe('video auth profiles', () => {error: 'unsupported video model "doubao/retired-model"',});expect(addVideoProfile({- provider: 'doubao',- model: 'doubao-seedance-2-0-260128',+ provider: 'orkas-api',+ model: 'orkas-video',apiKey: '',})).toEqual({ ok: false, error: 'apiKey required' });expect(mocks.profiles).toEqual([]);@@ -59,14 +60,14 @@ describe('video auth profiles', () => {it('keeps explicit ordering and bounded labels deterministic', () => {const first = addVideoProfile({- provider: 'doubao',- model: 'doubao-seedance-2-0-260128',+ provider: 'orkas-api',+ model: 'orkas-video',apiKey: 'first',label: ` ${'x'.repeat(60)} `,});const second = addVideoProfile({- provider: 'doubao',- model: 'doubao-seedance-2-0-260128',+ provider: 'orkas-api',+ model: 'orkas-video',apiKey: 'second',label: 'second',});@@ -96,10 +97,16 @@ describe('video auth profiles', () => {model: 'orkas-video',label: 'Orkas · Video',});- expect(options[1]).toMatchObject({- id: 'doubao',- provider: 'doubao',- model: 'doubao-seedance-2-0-260128',- });+ expect(options).toHaveLength(1);+ expect(listVideoProviderOptions().map((option) => option.id)).toEqual(['orkas-api']);});});++ it('retains legacy credentials for removal but refuses new unsupported video profiles', () => {+ mocks.profiles = [{ id: 'legacy', provider: 'doubao', model: 'doubao-seedance-2-0-260128', apiKey: 'legacy-key', label: 'Legacy', createdAt: 1 }];+ expect(addVideoProfile({ provider: 'doubao', model: 'doubao-seedance-2-0-260128', apiKey: 'new-key' })).toMatchObject({ ok: false });+ expect(listVideoProfiles()).toEqual(mocks.profiles);+ expect(listVideoProfiles()).toHaveLength(1);+ expect(removeVideoProfile('legacy')).toEqual({ ok: true });+ expect(listVideoProfiles()).toEqual([]);+ });diff --git a/test/main/features/video_gen.test.ts b/test/main/features/video_gen.test.tsindex 6b640ca3..e9806635 100644--- a/test/main/features/video_gen.test.ts+++ b/test/main/features/video_gen.test.ts@@ -153,3 +153,31 @@ describe('video_gen › Orkas public API', () => {expect(() => validateDownloadedVideo(Buffer.from('not a video'))).toThrow(/invalid or unsupported MP4/);});});++describe('video request body lifetime', () => {+ it.each(['cancel', 'deadline'] as const)('keeps %s active after create response headers arrive', async (mode) => {+ vi.useFakeTimers();+ const controller = new AbortController();+ let bodyRead!: () => void;+ const reading = new Promise<void>((resolve) => { bodyRead = resolve; });+ const fetchStub = vi.fn(async (_url, init) => ({+ ok: true,+ status: 202,+ text: () => new Promise<string>((_resolve, reject) => {+ init.signal.addEventListener('abort', () => reject(init.signal.reason), { once: true });+ bodyRead();+ }),+ }));+ vi.stubGlobal('fetch', fetchStub);+ try {+ const pending = generateVideo({ prompt: 'test', outputAbsPath: path.join(tmpDir, 'pending.mp4'), signal: controller.signal });+ await reading;+ if (mode === 'cancel') controller.abort();+ else await vi.advanceTimersByTimeAsync(60_001);+ expect(await pending).toMatchObject({ ok: false, message: expect.stringMatching(mode === 'cancel' ? /abort/i : /timed out/i) });+ expect(fetchStub).toHaveBeenCalledTimes(1);+ expect(mocks.downloadBinaryWithProxyPolicy).not.toHaveBeenCalled();+ expect(fs.existsSync(path.join(tmpDir, 'pending.mp4'))).toBe(false);+ } finally { vi.useRealTimers(); }+ });+});diff --git a/test/main/ipc/retained-feature-parity.test.ts b/test/main/ipc/retained-feature-parity.test.tsnew file mode 100644index 00000000..ceed2f98--- /dev/null+++ b/test/main/ipc/retained-feature-parity.test.ts@@ -0,0 +1,122 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { trustedIpcSender } from '../../helpers/trusted-ipc-sender';++vi.mock('electron', () => ({+ app: { isPackaged: false },+ ipcMain: { handle: vi.fn(), on: vi.fn() },+ dialog: { showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] })) },+ BrowserWindow: { getAllWindows: vi.fn(() => []), getFocusedWindow: vi.fn(() => null) },+ shell: { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') },+ systemPreferences: {+ getMediaAccessStatus: vi.fn(() => 'granted'),+ askForMediaAccess: vi.fn(async () => true),+ },+}));++vi.mock('../../../src/main/features/kb_indexer', () => ({+ enqueue: vi.fn(),+ kbEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+}));++vi.mock('../../../src/main/features/search', () => ({+ upsertContext: vi.fn(),+ dropContext: vi.fn(),+}));++vi.mock('../../../src/main/features/kb_vector', () => ({+ findBySha1: vi.fn(() => null),+}));++let tmpDir: string;+let prevWs: string | undefined;+const TEST_UID = 'uRetainedIpc';++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-retained-ipc-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ vi.clearAllMocks();+ const users = await import('../../../src/main/features/users');+ users.activateUser(TEST_UID);+});++afterEach(() => {+ if (prevWs === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function contextsRoot(): string {+ return path.join(tmpDir, TEST_UID, 'cloud', 'contexts');+}++async function invoke(channel: string, payload: any): Promise<any> {+ const electron = await import('electron') as any;+ const { register } = await import('../../../src/main/ipc/index');+ register();+ const call = electron.ipcMain.handle.mock.calls.find(([name]: [string]) => name === 'orkas.invoke');+ expect(call).toBeTruthy();+ const handler = call[1];+ return handler({ sender: trustedIpcSender() }, { channel, payload });+}++describe('retained Agent memory and Office preview IPC', () => {+ it('round-trips Agent memory through the registered renderer endpoint', async () => {+ const created = await invoke('agents.create', { name: 'MemoryOwner', workflow: 'Help with notes' });+ const agent_id = created.agent.agent_id;+ expect(await invoke('agents.memory.add', { agent_id, content: 'Use metric units.' }))+ .toMatchObject({ ok: true, entries: ['Use metric units.'] });+ expect(await invoke('agents.memory.update', { agent_id, old_text: 'Use metric units.', content: 'Use SI units.' }))+ .toMatchObject({ ok: true, entries: ['Use SI units.'] });+ expect(await invoke('agents.memory.remove', { agent_id, old_text: 'Use SI units.' }))+ .toMatchObject({ ok: true, entries: [] });+ });++ it.each(['contexts.officeHtml', 'projects.files.officeHtml'])('%s reaches the owned Office renderer', async (channel) => {+ const previews = await import('../../../src/main/util/office-preview');+ const render = vi.spyOn(previews, 'officeFileToPreviewHtml').mockResolvedValue({+ html: '<html>quarterly results</html>', kind: 'spreadsheet', layoutRendered: true,+ });+ const payload: Record<string, string> = {};+ let root = contextsRoot();+ if (channel.startsWith('projects.')) {+ const projects = await import('../../../src/main/features/projects');+ const created = await projects.createProject(TEST_UID, 'Preview owner');+ if (!created.ok) throw new Error('project setup failed');+ payload.projectId = created.project.project_id;+ payload.name = 'results.xlsx';+ const paths = await import('../../../src/main/paths');+ root = paths.projectFilesDir(TEST_UID, payload.projectId);+ } else payload.path = 'results.xlsx';+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(path.join(root, 'results.xlsx'), 'office fixture bytes');+ expect(await invoke(channel, payload)).toMatchObject({+ ok: true, html: '<html>quarterly results</html>', kind: 'spreadsheet', layoutRendered: true,+ });+ expect(render).toHaveBeenCalledWith('spreadsheet', 'results.xlsx', path.join(root, 'results.xlsx'), expect.any(Buffer));+ render.mockRestore();+ });++ it.each(['common.pickDirectory', 'skills.pickImportDir'])('%s opens in an explicit usable workspace', async (channel) => {+ await invoke(channel, {});+ const electron = await import('electron') as any;+ const opts = electron.dialog.showOpenDialog.mock.calls[0]?.[0];+ expect(typeof opts.defaultPath).toBe('string');+ expect(path.isAbsolute(opts.defaultPath)).toBe(true);+ expect(fs.statSync(opts.defaultPath).isDirectory()).toBe(true);+ });+});++it('reports unsupported legacy video credentials without exposing them as an active provider', async () => {+ const auth = await import('../../../src/main/features/auth');+ auth.saveVideoProfiles([{ id: 'legacy', provider: 'doubao', model: 'doubao-seedance-2-0-260128', apiKey: 'legacy-private-key', label: 'Legacy', createdAt: 1 }]);+ const result = await invoke('videoAuth.list', {});+ expect(result.providers.map((provider: any) => provider.provider)).toEqual(['orkas-api']);+ expect(result.profiles).toEqual([expect.objectContaining({ id: 'legacy', available: false })]);+ expect(result.profiles[0]).not.toHaveProperty('apiKey');+ expect(auth.loadVideoProfiles()[0]?.apiKey).toBe('legacy-private-key');+});diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.tsindex c8012ce9..4874c9b6 100644--- a/test/main/model/core-agent/connector-meta-tools.test.ts+++ b/test/main/model/core-agent/connector-meta-tools.test.ts@@ -20,7 +20,7 @@ const fixtures: {instances: ConnectorInstance[];agents: Record<string, AgentMock>;analyticsEvents: { event: string; payload: Record<string, unknown> }[];- callTool: (uid: string, id: string, name: string, args: Record<string, unknown>) => Promise<unknown>;+ callTool: (uid: string, id: string, name: string, args: Record<string, unknown>, opts?: { signal?: AbortSignal }) => Promise<unknown>;} = {instances: [],agents: {},@@ -32,8 +32,8 @@ vi.mock('../../../../src/main/features/connectors/manager', () => ({listInstances: (uid: string) => (uid ? fixtures.instances : []),restoreComposioConnectionsFromServer: async () => 0,refreshStaleToolCaches: async () => 0,- callTool: (uid: string, id: string, name: string, args: Record<string, unknown>) =>- fixtures.callTool(uid, id, name, args),+ callTool: (uid: string, id: string, name: string, args: Record<string, unknown>, opts?: { signal?: AbortSignal }) =>+ fixtures.callTool(uid, id, name, args, opts),}));vi.mock('../../../../src/main/features/analytics/connectors', () => ({@@ -428,13 +428,13 @@ describe('list_connector_tools', () => {expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');});- it('missing connector_id → E_BAD_INPUT', async () => {+ it('discovers valid connector ids without requiring a prior id', async () => {fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];const { createConnectorMetaTools } = await loadModule();const [listTools] = await createConnectorMetaTools({ userId: UID });const r = await runTool(listTools, {});- expect(r.isError).toBe(true);- expect(r.content).toContain('E_BAD_INPUT');+ expect(r.isError).toBeFalsy();+ expect(r.content).toContain('**notion**');});it('does not apply diagnostic actor metadata as an execution-time filter', async () => {@@ -630,3 +630,74 @@ describe('stringifyMcpResult (via call_connector_tool)', () => {expect(r.content).toContain('"type":"image"');});});++describe('connector lazy discovery and invocation parity', () => {+ it('compacts a large catalog and expands only the requested schema', async () => {+ const tools = Array.from({ length: 40 }, (_, index) => ({+ name: `action_${index}`, description: 'Search an indexed collection',+ input_schema: { type: 'object', properties: { query: { type: 'string', description: 'detail '.repeat(200) } } },+ }));+ fixtures.instances = [makeInstance({ id: 'notion', tools })];+ const { createConnectorMetaTools } = await loadModule();+ const [list] = await createConnectorMetaTools({ userId: UID });+ const catalog = await runTool(list, { connector_id: 'notion' });+ expect(catalog.isError).toBeFalsy();+ expect(catalog.content.length).toBeLessThan(30_000);+ expect(catalog.content).toContain('action_39');+ expect(catalog.content).not.toContain('detail '.repeat(200));+ const expanded = await runTool(list, { connector_id: 'notion', tool_name: 'action_3' });+ expect(expanded.content).toContain('detail '.repeat(200));+ expect(expanded.content).not.toContain('action_39');+ const unknown = await runTool(list, { connector_id: 'notion', tool_name: 'missing' });+ expect(unknown.isError).toBe(true);+ expect(unknown.content).toContain('E_TOOL_NOT_AVAILABLE');+ });++ it('refreshes display identity during live discovery after a connector is added', async () => {+ const names = new Map<string, string>();+ const { createConnectorMetaTools } = await loadModule();+ const [list] = await createConnectorMetaTools({ userId: UID, allowRuntimeRefresh: true, connectorDisplayNameById: names });+ expect((await runTool(list)).isError).toBeFalsy();+ fixtures.instances = [makeInstance({ id: 'notion', display_name: 'Notes', tools: NOTION_TOOLS })];+ expect((await runTool(list)).content).toContain('Notes');+ expect(names.get('notion')).toBe('Notes');+ });++ it('preserves a returned MCP failure instead of announcing success', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.callTool = async () => ({ isError: true, content: [{ type: 'text', text: 'Permission denied' }] });+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ expect(await runTool(call, { connector_id: 'notion', tool_name: 'search', args: {} })).toMatchObject({ isError: true, content: expect.stringContaining('Permission denied') });+ });++ it('forwards Stop cancellation to the active connector request', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const controller = new AbortController();+ fixtures.callTool = async (_uid, _id, _name, _args, opts) => {+ expect(opts?.signal).toBe(controller.signal);+ controller.abort();+ if (opts?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');+ return 'unexpected success';+ };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const result = await call.execute({ connector_id: 'notion', tool_name: 'search', args: {} }, { signal: controller.signal, workingDir: '.' } as any);+ expect(controller.signal.aborted).toBe(true);+ expect(result.isError).toBe(true);+ });++ it('maps only schema-declared camelCase aliases while preserving explicit values and the input object', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: [{ name: 'search', description: '', input_schema: { properties: { page_size: {}, user_id: {} } } }] })];+ const args = { pageSize: 10, user_id: 'explicit', userId: 'alias', unknownKey: 'keep' };+ fixtures.callTool = async (_uid, _id, _name, actual) => {+ expect(actual).toEqual({ page_size: 10, user_id: 'explicit', userId: 'alias', unknownKey: 'keep' });+ return 'OK';+ };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ expect((await runTool(call, { connector_id: 'notion', tool_name: 'search', args })).isError).toBeFalsy();+ expect(args.pageSize).toBe(10);+ expect(args).not.toHaveProperty('page_size');+ });+});diff --git a/test/main/model/core-agent/external-provider-request-parity.test.ts b/test/main/model/core-agent/external-provider-request-parity.test.tsnew file mode 100644index 00000000..a76de41e--- /dev/null+++ b/test/main/model/core-agent/external-provider-request-parity.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from 'vitest';++const configs = vi.hoisted(() => [] as any[]);+vi.mock('#core-agent', () => ({ createPiProvider: (config: any) => { configs.push(config); return { id: config.provider }; } }));++import { createDeepSeekProvider, createDoubaoProvider, createMoonshotProvider, createOrkasApiProvider } from '../../../../src/main/model/core-agent/external-providers';++describe('external provider request policy', () => {+ it.each([+ ['deepseek', createDeepSeekProvider, 'deepseek-v4-flash'],+ ['doubao', createDoubaoProvider, 'doubao-seed-2-0-lite-260428'],+ ['moonshot', createMoonshotProvider, 'kimi-k3'],+ ['orkas-api', createOrkasApiProvider, 'orkas-llm-1.5-pro'],+ ] as const)('preserves detached tool results without sending invalid %s message order', async (_provider, create, modelId) => {+ await create({ apiKey: 'fixture', modelId });+ const config = configs.at(-1);+ const request = { messages: [{ role: 'user', content: 'Continue' }, { role: 'tool', tool_call_id: 'lost-call', content: 'Persisted evidence' }] };+ const payload = config.onPayload ? config.onPayload(request) : request;+ expect(payload.messages[1]).toMatchObject({ role: 'user', content: expect.stringContaining('Persisted evidence') });+ expect(payload.messages[1]).not.toHaveProperty('tool_call_id');+ });++ it('does not silently choose low reasoning for a direct DeepSeek request', async () => {+ await createDeepSeekProvider({ apiKey: 'fixture', modelId: 'deepseek-v4-flash' });+ expect(configs.at(-1).defaultReasoning).toBeUndefined();+ });+});diff --git a/test/main/model/core-agent/image-gen-tool.test.ts b/test/main/model/core-agent/image-gen-tool.test.tsindex 3729aa50..708b504f 100644--- a/test/main/model/core-agent/image-gen-tool.test.ts+++ b/test/main/model/core-agent/image-gen-tool.test.ts@@ -18,8 +18,8 @@ vi.mock('../../../../src/main/features/image_gen', () => ({vi.mock('../../../../src/main/features/user_workspace', () => ({getWorkspacePath: () => h.workspace,}));-vi.mock('../../../../src/main/paths', () => ({- chatAttachmentDir: () => path.join(h.workspace, 'attachments'),+vi.mock('../../../../src/main/util/project-layout', () => ({+ chatAttachmentDirForConversation: () => path.join(h.workspace, 'attachments'),}));vi.mock('../../../../src/main/logger', () => ({createLogger: () => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }),diff --git a/test/main/model/core-agent/image-production-parity.test.ts b/test/main/model/core-agent/image-production-parity.test.tsnew file mode 100644index 00000000..6b78bed9--- /dev/null+++ b/test/main/model/core-agent/image-production-parity.test.ts@@ -0,0 +1,371 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ pathAllowed: true,+ generateImage: vi.fn(),+ estimateImageCredits: vi.fn(),+ findReusableImageGeneration: vi.fn(),+ beginImageGeneration: vi.fn(),+ finishImageGeneration: vi.fn(),+ noteGeneration: vi.fn(),+ regenerationWarning: vi.fn(),+}));++vi.mock('../../../../src/main/features/image_gen', () => ({+ generateImage: (...args: unknown[]) => h.generateImage(...args),+}));+vi.mock('../../../../src/main/features/image_production_credits', () => ({+ estimateImageProductionCredits: (...args: unknown[]) => h.estimateImageCredits(...args),+}));+vi.mock('../../../../src/main/features/image_production_control', () => ({+ findReusableImageStudioGeneration: (...args: unknown[]) => h.findReusableImageGeneration(...args),+ beginImageStudioGeneration: (...args: unknown[]) => h.beginImageGeneration(...args),+ finishImageStudioGeneration: (...args: unknown[]) => h.finishImageGeneration(...args),+ imageGenerationControlStatePath: () => '/tmp/image-generation-state.json',+}));+vi.mock('../../../../src/main/util/path-sandbox', () => ({+ isPathAllowed: () => h.pathAllowed,+}));+vi.mock('../../../../src/main/util/uniquify-path', () => ({+ uniquifyPath: async (p: string) => ({ finalPath: p, renamed: false }),+ renderRenameSignal: () => '',+}));+vi.mock('../../../../src/main/util/generation-guard', () => ({+ noteGeneration: (...args: unknown[]) => h.noteGeneration(...args),+ regenerationWarning: (...args: unknown[]) => h.regenerationWarning(...args),+}));+vi.mock('../../../../src/main/features/user_workspace', () => ({+ getWorkspacePath: () => '/ws',+}));+vi.mock('../../../../src/main/util/project-layout', () => ({+ chatAttachmentDirForConversation: () => '/ws/attachments',+}));+vi.mock('../../../../src/main/util/chat-media-url', () => ({+ versionedChatMediaLocalUrl: (p: string) => `chat-media://test/${encodeURIComponent(p)}`,+}));+vi.mock('../../../../src/main/features/video_production_control', () => ({+ beginVideoProductionGeneration: vi.fn(),+ finishVideoProductionGeneration: vi.fn(),+ videoProductionControlStatePath: () => '/ws/production-state.json',+}));+vi.mock('../../../../src/main/logger', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+}));+vi.mock('../../../../src/main/util/log-redact', () => ({+ logErrorRef: (e: unknown) => String(e),+ logPathRef: (p: unknown) => String(p),+ maskId: (s: unknown) => String(s),+}));++beforeEach(() => {+ h.pathAllowed = true;+ h.generateImage.mockReset();+ h.estimateImageCredits.mockReset();+ h.findReusableImageGeneration.mockReset();+ h.beginImageGeneration.mockReset();+ h.finishImageGeneration.mockReset();+ h.noteGeneration.mockReset().mockReturnValue(1);+ h.regenerationWarning.mockReset().mockReturnValue(null);+ h.estimateImageCredits.mockResolvedValue({+ in_app_credits_required_milli: 0,+ external_billing_estimate_available: false,+ sufficient: true,++ externally_billed_segment_ids: [],++ unavailable_segment_ids: [],+ segments: [{ segment_id: 'hero-initial', billing_mode: 'external' }],+ });+ h.findReusableImageGeneration.mockResolvedValue(null);+ h.beginImageGeneration.mockResolvedValue({+ status: 'started',+ transaction: {+ transaction_id: 'image-tx-1',+ request_id: 'hero-initial',+ status: 'pending',+ },+ callCount: 1,+ maxCalls: 2,+ });+ h.finishImageGeneration.mockResolvedValue({});+ h.generateImage.mockImplementation(async (request: any) => {+ request.onProgress?.({ phase: 'generating', message: 'halfway', data: { progress: 50 } });+ return {+ ok: true,+ path: request.outputAbsPath,+ width: 1024,+ height: 1024,+ bytes: 128,+ provider: 'test-provider',+ model: 'test-model',+ };+ });+});++function ctx() {+ return {+ workingDir: path.resolve('/ws'),+ emitProgress: vi.fn(),+ } as any;+}++describe('generate_image tool', () => {+ it('dispatches generation with the requested inputs and publishes the output', async () => {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const onFileWritten = vi.fn();+ const tool = createImageGenTool({+ userId: 'u1',+ cid: 'c1',+ turnId: 't1',+ agentId: 'a1',+ agentName: 'Designer',+ conversationTitle: 'Bird concept',+ conversationTitleUpdatedAt: 1_234,+ onFileWritten,+ });+ const context = ctx();+ const outputPath = path.resolve('/ws/out/image.png');++ const res = await tool.execute!({+ prompt: ' a blue bird ',+ output_path: 'out/image.png',+ reference_image_urls: [' https://example.com/reference.png '],+ size: '1024x1024',+ }, context);++ expect(res.isError).toBeFalsy();+ expect(h.generateImage).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a blue bird',+ outputAbsPath: outputPath,+ referenceImageUrls: ['https://example.com/reference.png'],+ size: '1024x1024',+ usageContext: { conversationId: 'c1', turnId: 't1' },+ }));+ expect(context.emitProgress).toHaveBeenCalledWith({+ phase: 'generating',+ message: 'halfway',+ data: { progress: 50 },+ });+ expect(onFileWritten).toHaveBeenCalledWith(outputPath);+ expect(String(res.content)).toContain(`Image written to ${outputPath}`);+ expect(String(res.content)).toContain('1024x1024, 128 bytes, test-provider/test-model');+ expect(h.estimateImageCredits).not.toHaveBeenCalled();+ });++ it('surfaces repeated billable-generation warnings in the successful tool result', async () => {+ h.noteGeneration.mockReturnValueOnce(3);+ h.regenerationWarning.mockReturnValueOnce('generation #3 is billable');+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'cost-aware-chat' });++ const res = await tool.execute!({+ prompt: 'a blue bird',+ output_path: 'out/image.png',+ }, ctx());++ expect(res.isError).toBeFalsy();+ expect(h.noteGeneration).toHaveBeenCalledWith(+ 'cost-aware-chat',+ path.resolve('/ws/out/image.png'),+ );+ expect(h.regenerationWarning).toHaveBeenCalledWith(3, 'image');+ expect(String(res.content)).toContain('generation #3 is billable');+ });++ it('compiles structured reference roles and negative constraints for every provider', async () => {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1' });++ const res = await tool.execute!({+ prompt: 'Editorial portrait',+ output_path: 'portrait.png',+ reference_image_urls: ['https://example.com/person.png'],+ reference_bindings: [{+ index: 0,+ role: 'identity',+ strength: 0.9,+ preserve: ['facial identity', 'hair shape'],+ may_change: ['background'],+ region: 'hero',+ }],+ negative_prompt: ['garbled text', 'duplicated face'],+ }, ctx());++ expect(res.isError).toBeFalsy();+ const request = h.generateImage.mock.calls[0][0];+ expect(request.prompt).toContain('Reference 1: role=identity; strength=0.90');+ expect(request.prompt).toContain('preserve=facial identity, hair shape');+ expect(request.prompt).toContain('Avoid: garbled text; duplicated face.');+ expect(request.referenceBindings).toEqual([expect.objectContaining({ role: 'identity', strength: 0.9, region: 'hero' })]);+ expect(request.negativePrompt).toEqual(['garbled text', 'duplicated face']);+ });++ it('requires durable project generation context for ImageStudio', async () => {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '814b61b027f0' });++ const res = await tool.execute!({ prompt: 'a bird', output_path: 'bird.png' }, ctx());++ expect(res.isError).toBe(true);+ expect(String(res.content)).toContain('E_IMAGE_GENERATION_CONTEXT_REQUIRED');+ expect(h.generateImage).not.toHaveBeenCalled();+ });++ it('checks configured ImageStudio provider availability before starting its durable transaction', async () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-quote-'));+ try {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', turnId: 'turn-image-1', agentId: '814b61b027f0' });+ const outputPath = path.join(projectDir, 'hero.png');++ const res = await tool.execute!({+ prompt: 'a bird',+ output_path: outputPath,+ image_project_path: projectDir,+ image_request_id: 'hero-initial',+ reference_image_urls: ['https://example.com/guide.png'],+ size: '2048x2048',+ }, ctx());++ expect(res.isError).toBeFalsy();+ expect(h.estimateImageCredits).toHaveBeenCalledWith({+ requestId: 'hero-initial',+ size: '2048x2048',+ referenceCount: 1,+ }, undefined);+ expect(h.estimateImageCredits.mock.invocationCallOrder[0])+ .toBeLessThan(h.beginImageGeneration.mock.invocationCallOrder[0]);+ expect(h.beginImageGeneration.mock.invocationCallOrder[0])+ .toBeLessThan(h.generateImage.mock.invocationCallOrder[0]);+ expect(h.findReusableImageGeneration).toHaveBeenCalledWith(+ '/tmp/image-generation-state.json',+ 'hero-initial',+ 'turn-image-1',+ );+ expect(h.beginImageGeneration).toHaveBeenCalledWith(expect.objectContaining({+ requestId: 'hero-initial',+ turnId: 'turn-image-1',+ }));+ expect(String(res.content)).toContain('ImageStudio local provider availability before dispatch');+ expect(String(res.content)).toContain('"external_billing_estimate_available":false');+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });++ it('blocks an unavailable ImageStudio route before consuming a call slot', async () => {+ h.estimateImageCredits.mockResolvedValueOnce({+ expected_credits_milli: 0,+ required_credits_milli: 0,+ available_credits_milli: 100_000,+ sufficient: false,+ fallback_fully_covered: true,+ orkas_credit_estimate_exact: true,+ externally_billed_segment_ids: [],++ unavailable_segment_ids: ['hero-initial'],+ segments: [{ segment_id: 'hero-initial', billing_mode: 'unavailable' }],+ });+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-unavailable-'));+ try {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '814b61b027f0' });++ const res = await tool.execute!({+ prompt: 'a bird',+ output_path: path.join(projectDir, 'bird.png'),+ image_project_path: projectDir,+ image_request_id: 'hero-initial',+ }, ctx());++ expect(res.isError).toBe(true);+ expect(String(res.content)).toContain('E_IMAGE_PRODUCTION_PROVIDER_UNAVAILABLE');+ expect(h.beginImageGeneration).not.toHaveBeenCalled();+ expect(h.generateImage).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });++ it('reuses a completed ImageStudio request without a new quote or provider call', async () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-reuse-'));+ const outputPath = path.join(projectDir, 'bird.png');+ fs.writeFileSync(outputPath, 'existing');+ h.findReusableImageGeneration.mockResolvedValueOnce({+ transaction_id: 'old-tx',+ request_id: 'hero-initial',+ status: 'completed',+ output_path: outputPath,+ });+ try {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '814b61b027f0' });++ const res = await tool.execute!({+ prompt: 'a bird',+ output_path: outputPath,+ image_project_path: projectDir,+ image_request_id: 'hero-initial',+ }, ctx());++ expect(res.isError).toBeFalsy();+ expect(String(res.content)).toContain('reused completed generation hero-initial');+ expect(h.estimateImageCredits).not.toHaveBeenCalled();+ expect(h.beginImageGeneration).not.toHaveBeenCalled();+ expect(h.generateImage).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });++ it('rejects an output outside the active workspace before provider dispatch', async () => {+ h.pathAllowed = false;+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1' });++ const res = await tool.execute!({ prompt: 'a bird', output_path: '../bird.png' }, ctx());++ expect(res.isError).toBe(true);+ expect(String(res.content)).toContain('E_PATH_OUT_OF_SCOPE');+ expect(h.generateImage).not.toHaveBeenCalled();+ });++ it('surfaces a thrown provider exception as a tool result', async () => {+ h.generateImage.mockRejectedValueOnce(new Error('connection closed'));+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1' });++ const res = await tool.execute!({ prompt: 'a bird', output_path: 'bird.png' }, ctx());++ expect(res.isError).toBe(true);+ expect(String(res.content)).toBe('[PROVIDER_EXCEPTION] connection closed');+ });++ it('keeps an ImageStudio transaction pending when delivery ends without a terminal result', async () => {+ h.generateImage.mockRejectedValueOnce(new Error('generated output delivery failed'));+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-uncertain-'));+ try {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '814b61b027f0' });++ const res = await tool.execute!({+ prompt: 'a bird',+ output_path: path.join(projectDir, 'bird.png'),+ image_project_path: projectDir,+ image_request_id: 'hero-initial',+ }, ctx());++ expect(res.isError).toBe(true);+ expect(String(res.content)).toContain('E_IMAGE_GENERATION_UNCERTAIN');+ expect(String(res.content)).toContain('request remains pending');+ expect(h.beginImageGeneration).toHaveBeenCalledOnce();+ expect(h.generateImage).toHaveBeenCalledOnce();+ expect(h.finishImageGeneration).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });+});diff --git a/test/main/model/core-agent/local-tools.test.ts b/test/main/model/core-agent/local-tools.test.tsindex d775d35c..47cc34e3 100644--- a/test/main/model/core-agent/local-tools.test.ts+++ b/test/main/model/core-agent/local-tools.test.ts@@ -1960,3 +1960,32 @@ describe('local-tools › markdown_to_pdf › locked probe+render wiring', () =>}});});++describe('PDF output publication', () => {+ it.each(['markdown', 'html'])('keeps a successfully rendered %s PDF successful when the publication callback fails', async (sourceType) => {+ vi.resetModules();+ const render = vi.fn(async (_content: string, outPath: string) => { fs.writeFileSync(outPath, '%PDF-fixture'); });+ vi.doMock('../../../../src/main/util/md-to-pdf', () => ({ markdownToPdf: render, htmlToPdf: render }));+ try {+ const users = await import('../../../../src/main/features/users');+ users.activateUser(UID);+ await allFilesAuto();+ const ws = await import('../../../../src/main/features/user_workspace');+ const wsDir = path.join(tmpDir, 'ws');+ fs.mkdirSync(wsDir, { recursive: true });+ expect(ws.setWorkspacePath(UID, wsDir).ok).toBe(true);+ const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');+ const onFileWritten = vi.fn(async () => { throw new Error('publication fixture failed'); });+ const tool = createLocalTools({ userId: UID, cid: CID, onFileWritten }).find((item) => item.name === 'create_pdf')!;+ const target = path.join(wsDir, 'report.pdf');+ const result = await tool.execute({ source_type: sourceType, path: target, content: '<h1>Report</h1>' }, { workingDir: wsDir, state: {} } as any);+ expect(result.isError).toBeFalsy();+ expect(String(result.content)).toContain('PDF written:');+ expect(fs.readFileSync(target, 'utf8')).toBe('%PDF-fixture');+ expect(onFileWritten).toHaveBeenCalledWith(target);+ } finally {+ vi.doUnmock('../../../../src/main/util/md-to-pdf');+ vi.resetModules();+ }+ });+});diff --git a/test/main/model/core-agent/rotating-provider.test.ts b/test/main/model/core-agent/rotating-provider.test.tsindex 53db87a7..4f5c69e7 100644--- a/test/main/model/core-agent/rotating-provider.test.ts+++ b/test/main/model/core-agent/rotating-provider.test.ts@@ -1944,3 +1944,253 @@ describe('rotating-provider › complete calls and per-call stream policy', () =expect(fallbackBuilds).toBe(0);});});++describe("rotation shared run lifecycle", () => {+it('commits on reasoning activity before answer text and clears the first-event deadline', async () => {+ let fallbackBuilds = 0;+ const p = createRotatingProvider({+ providerId: 'test',+ firstEventTimeoutMs: 20,+ candidates: [+ {+ profileId: 'reasoner',+ providerId: 'reasoner',+ modelId: 'reasoner-model',+ build: async () => ({+ id: 'reasoner',+ name: 'reasoner',+ async *stream(): AsyncIterable<StreamEvent> {+ yield { type: 'message_start' };+ yield { type: 'thinking_start' };+ await new Promise((resolve) => setTimeout(resolve, 50));+ yield { type: 'thinking_delta', chars: 12 };+ yield { type: 'thinking_end' };+ yield { type: 'text_delta', text: 'answer' };+ },+ async complete() { throw new Error('unused'); },+ async validateAuth() { return true; },+ }),+ },+ {+ profileId: 'fallback',+ providerId: 'fallback',+ modelId: 'fallback-model',+ build: async () => {+ fallbackBuilds += 1;+ return fakeProvider('fallback', { streamEvents: [{ type: 'text_delta', text: 'wrong' }] });+ },+ },+ ],+ });++ const events = await collect(p.stream(PARAMS));+ expect(events.map((event) => event.type)).toEqual([+ 'message_start', 'thinking_start', 'thinking_delta', 'thinking_end', 'text_delta',+ ]);+ expect(fallbackBuilds).toBe(0);+ });+it('latches a network-exhausted candidate out of later model rounds once a fallback commits, without cooldown', async () => {+ // 2026-08-16 latency review P0-1: stream() runs once per tool-loop round.+ // Without the run-local latch, a candidate whose endpoint is dead in a+ // candidate-specific way (e.g. its fetch path ignores the proxy) re-pays+ // the full timeout/retry ladder on every remaining round of the turn+ // before reaching the fallback that actually serves the reply.+ const netErr = new TypeError('fetch failed');+ let p1Builds = 0;+ let p2Builds = 0;+ const p = createRotatingProvider({+ providerId: 'test',+ networkRetryDelayMs: () => 0,+ candidates: [+ {+ profileId: 'p1',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p1Builds += 1;+ return fakeProvider('p1', { throwBefore: netErr });+ },+ },+ {+ profileId: 'p2',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p2Builds += 1;+ return fakeProvider('p2', { streamEvents: [{ type: 'text_delta', text: 'ok' } as any] });+ },+ },+ ],+ });++ const firstRound = await collect(p.stream(PARAMS));+ const secondRound = await collect(p.stream(PARAMS));++ expect(p1Builds).toBe(4); // round 1 keeps the full same-candidate retry ladder+ expect(p2Builds).toBe(2);+ expect((firstRound.at(-1) as any).text).toBe('ok');+ expect(secondRound.some((ev: any) => ev.type === 'retry')).toBe(false); // round 2 skips p1 entirely+ expect((secondRound.at(-1) as any).text).toBe('ok');+ // Run-local only: a fresh run (new provider instance) must retry p1, so+ // the network failure must not enter the persisted cooldown.+ expect(getCooldown('p1')).toBeUndefined();+ });+it('does not latch anything when every candidate fails network-class, so recovery after a full blip retries them all', async () => {+ // Counterexample guarding the deferred-latch design: compaction shares+ // this provider instance and swallows the exhausted error, so a transient+ // machine-local outage must leave the next call free to retry every+ // candidate. Only a sweep where a later candidate commits may latch.+ const netErr = new TypeError('fetch failed');+ let p1Builds = 0;+ let p2Builds = 0;+ let blip = true;+ const p = createRotatingProvider({+ providerId: 'test',+ networkRetryDelayMs: () => 0,+ candidates: [+ {+ profileId: 'p1',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p1Builds += 1;+ return blip+ ? fakeProvider('p1', { throwBefore: netErr })+ : fakeProvider('p1', { streamEvents: [{ type: 'text_delta', text: 'back' } as any] });+ },+ },+ {+ profileId: 'p2',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p2Builds += 1;+ return fakeProvider('p2', { throwBefore: netErr });+ },+ },+ ],+ });++ await expect(collect(p.stream(PARAMS))).rejects.toMatchObject({ code: 'PROVIDER_NETWORK_EXHAUSTED' });+ blip = false;+ const events = await collect(p.stream(PARAMS));++ expect(p1Builds).toBe(5); // 4 during the blip + 1 recovered attempt+ expect(p2Builds).toBe(4); // only the blip round+ expect((events.at(-1) as any).text).toBe('back');+ });+it('announces omitted images when the committed candidate is text-only', async () => {+ // W4-2: a text-only model silently lost every attached image and the+ // only visible symptom was the model claiming it cannot see. The commit+ // must be preceded by an images_omitted event naming the count.+ const messages: CompletionParams['messages'] = [{+ role: 'user',+ content: [+ { type: 'text', text: 'read this screenshot' },+ { type: 'image', data: 'shot-1', mediaType: 'image/jpeg' },+ { type: 'image', data: 'shot-2', mediaType: 'image/jpeg' },+ ],+ }];+ const provider = createRotatingProvider({+ providerId: 'custom',+ candidates: [{+ profileId: 'text-only',+ providerId: 'custom',+ modelId: 'tiny-8b',+ maxInputImages: 0,+ build: async () => ({+ id: 'custom',+ name: 'custom',+ async *stream() {+ yield { type: 'text_delta', text: 'I cannot see any image.' } as any;+ },+ async complete() { throw new Error('unused'); },+ async validateAuth() { return true; },+ }),+ }],+ });++ const events = await collect(provider.stream({ ...PARAMS, messages }));+ const omitted = events.find((ev: any) => ev.type === 'images_omitted');+ expect(omitted).toMatchObject({ count: 2, providerId: 'custom' });+ expect(events.findIndex((ev: any) => ev.type === 'images_omitted'))+ .toBeLessThan(events.findIndex((ev: any) => ev.type === 'text_delta'));+ });+it('announces omitted images once per run, not on every tool-loop round', async () => {+ // The agent runner calls stream() once per tool-loop round with the full+ // history; a per-call announcement repeated the same notice ten times in+ // a ten-round turn and persisted every copy into the process rail.+ const messages: CompletionParams['messages'] = [{+ role: 'user',+ content: [+ { type: 'text', text: 'read this screenshot' },+ { type: 'image', data: 'shot-1', mediaType: 'image/jpeg' },+ ],+ }];+ const provider = createRotatingProvider({+ providerId: 'custom',+ candidates: [{+ profileId: 'text-only',+ providerId: 'custom',+ modelId: 'tiny-8b',+ maxInputImages: 0,+ build: async () => ({+ id: 'custom',+ name: 'custom',+ async *stream() {+ yield { type: 'text_delta', text: 'round output' } as any;+ },+ async complete() { throw new Error('unused'); },+ async validateAuth() { return true; },+ }),+ }],+ });++ const round1 = await collect(provider.stream({ ...PARAMS, messages }));+ const round2 = await collect(provider.stream({ ...PARAMS, messages }));+ expect(round1.filter((ev: any) => ev.type === 'images_omitted')).toHaveLength(1);+ expect(round2.filter((ev: any) => ev.type === 'images_omitted')).toHaveLength(0);+ });+it('complete() latches a network-exhausted candidate after a fallback succeeds, without cooldown', async () => {+ // Equivalent-path invariant with stream(): auxiliary complete() callers+ // repeat within one run too, and must not re-pay a dead candidate's+ // retry ladder once a fallback has proven the failure candidate-specific.+ const netErr = new TypeError('fetch failed');+ let p1Builds = 0;+ let p2Builds = 0;+ const okResult = { content: [{ type: 'text', text: 'ok' }], stopReason: 'end_turn', usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, model: 'test' };+ const p = createRotatingProvider({+ providerId: 'test',+ networkRetryDelayMs: () => 0,+ candidates: [+ {+ profileId: 'p1',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p1Builds += 1;+ return fakeProvider('p1', { completeError: netErr });+ },+ },+ {+ profileId: 'p2',+ providerId: 'test',+ modelId: 'test-model',+ build: async () => {+ p2Builds += 1;+ return fakeProvider('p2', { completeResult: okResult });+ },+ },+ ],+ });++ const first = await p.complete(PARAMS);+ const second = await p.complete(PARAMS);++ expect((first.content[0] as any).text).toBe('ok');+ expect((second.content[0] as any).text).toBe('ok');+ expect(p1Builds).toBe(4); // full retry ladder in call 1, skipped in call 2+ expect(p2Builds).toBe(2);+ expect(getCooldown('p1')).toBeUndefined();+ });+});diff --git a/test/main/model/core-agent/search-adapters.test.ts b/test/main/model/core-agent/search-adapters.test.tsindex 53bb2100..b8fe6034 100644--- a/test/main/model/core-agent/search-adapters.test.ts+++ b/test/main/model/core-agent/search-adapters.test.ts@@ -128,3 +128,24 @@ describe('open-source BYO search adapters', () => {]);});});++describe('search transfer deadlines', () => {+ it.each(['orkas-api', 'tavily', 'serper', 'brave-search', 'baidu-ai-search', 'metaso'])('keeps the %s deadline active while reading the response body', async (provider) => {+ vi.useFakeTimers();+ try {+ let responseSignal: AbortSignal | undefined;+ const readBody = () => new Promise<string>((_resolve, reject) => {+ responseSignal!.addEventListener('abort', () => reject(new Error('body aborted')), { once: true });+ });+ vi.stubGlobal('fetch', vi.fn(async (_url, init) => {+ responseSignal = init.signal;+ return { ok: true, status: 200, text: readBody, json: readBody };+ }));+ const pending = runSearchAdapter({ id: 'test', provider, apiKey: 'fixture', label: '', createdAt: 0 } as any, 'query', 1);+ const outcome = pending.then(() => 'success', () => 'failed');+ await vi.advanceTimersByTimeAsync(30_001);+ expect(responseSignal?.aborted).toBe(true);+ expect(await outcome).toBe('failed');+ } finally { vi.useRealTimers(); }+ });+});diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.tsindex 33e64910..df5f85d3 100644--- a/test/main/model/core-agent/tool-catalog.test.ts+++ b/test/main/model/core-agent/tool-catalog.test.ts@@ -453,7 +453,10 @@ describe('tool-catalog', () => {expect(fingerprint,'A model-visible field, enum, bound, default, or required rule changed; review it as a schema change, not description cleanup.',- ).toBe('03aebb7d2ce9f2b428830abcdc07d5898f409d455d540b1ed5b6d3e6cac0026b');+ // Reviewed 168 parity additions: image URL/role/negative-prompt inputs and+ // ImageStudio/VideoStudio production transaction identifiers. Existing+ // required inputs and tool visibility remain unchanged.+ ).toBe('68660ba57a038f6c2ad728e822af5ae70abe13d2b1410a9e8a5d2443b84ed05e');});it('keeps the reviewed stable tool corpus within the description budgets', () => {diff --git a/test/main/model/event-mapper.test.ts b/test/main/model/event-mapper.test.tsindex 879202ee..5b068d4e 100644--- a/test/main/model/event-mapper.test.ts+++ b/test/main/model/event-mapper.test.ts@@ -598,6 +598,24 @@ describe('event-mapper › tool_start / tool_end emit a single structured event'expect(endEvent.event.data.agent_file).toBe('agent.json');});+ it.each(['dispatch_to', 'hand_off_to'])(+ '%s persists the delegated Agent identity after an early tool announcement', async (name) => {+ const agentId = 'd76b91de8c7b';+ const out = await collect([+ { type: 'tool_delta', id: 'delegate-1', name, inputDelta: '' } as AgentRunEvent,+ { type: 'tool_start', id: 'delegate-1', name, input: { to: agentId, message: 'Build a game' } },+ { type: 'tool_progress', id: 'delegate-1', name, message: 'Agent running' },+ { type: 'tool_end', id: 'delegate-1', name, result: 'done' },+ ], { agentDisplayNameById: new Map([[agentId, 'ProductDemoBuilder']]) });+ const events = out.filter((event) => event.type === 'event').map((event) => event.event.data);+ expect(events.map((event) => event.phase)).toEqual(['start', 'progress', 'progress', 'end']);+ for (const event of events.slice(1)) {+ expect(event).toMatchObject({ agent_id: agentId, agent_name: 'ProductDemoBuilder' });+ expect(event).not.toHaveProperty('agent_file');+ }+ },+ );+it.each([['list_connector_tools', { connector_id: 'connector-instance-91f0' }],['call_connector_tool', {diff --git a/test/main/util/proxy-dispatcher.test.ts b/test/main/util/proxy-dispatcher.test.tsindex 76c0c26b..76983609 100644--- a/test/main/util/proxy-dispatcher.test.ts+++ b/test/main/util/proxy-dispatcher.test.ts@@ -480,11 +480,12 @@ describe('util/proxy-dispatcher per-request system routing', () => {});describe('util/proxy-dispatcher startup ordering', () => {- it('uses Electron network routing without a hosted account bootstrap', () => {+ it('installs system routing before opening the window without a hosted account bootstrap', () => {const source = fs.readFileSync(new URL('../../../src/main/index.ts', import.meta.url), 'utf8');expect(source).toContain('setFetchImplementation((input, init) => net.fetch');expect(source).not.toContain('const accountBoot = account.bootstrap();');- expect(source).not.toContain('await installSystemProxyDispatcher();');+ expect(source.indexOf('await installSystemProxyDispatcher();')).toBeGreaterThan(0);+ expect(source.indexOf('await installSystemProxyDispatcher();')).toBeLessThan(source.lastIndexOf(' createWindow();'));expect(source).not.toContain("registerImmediate('net:system-proxy'");});});diff --git a/test/renderer/agent-detail-return-navigation.test.ts b/test/renderer/agent-detail-return-navigation.test.tsindex 3aca3bb1..a35a6eeb 100644--- a/test/renderer/agent-detail-return-navigation.test.ts+++ b/test/renderer/agent-detail-return-navigation.test.ts@@ -77,6 +77,12 @@ function loadNavigation(initialView: string, initialId = '') {_selectedAgent: null,_exitAgentEditMode: vi.fn(async () => {}),_closeAgentRowMenu: vi.fn(),+ GROUP_RESERVED: new Set(['user', 'commander']),+ window: {},+ _convLog: { warn: vi.fn() },+ uiAlert: vi.fn(),+ t: (key: string) => key,+ apiFetch: vi.fn(async () => ({ json: async () => ({ ok: true, agent: { agent_id: 'agent-a' } }) })),document: {getElementById: (id: string) => element(id),},@@ -93,11 +99,52 @@ function loadNavigation(initialView: string, initialId = '') {extractFunction(agentsSource, '_isAgentDetailReturnTargetCurrent'),extractFunction(agentsSource, '_returnFromAgentsDetailView'),extractFunction(agentsSource, '_resetAgentsDetailForNavigation'),+ extractFunction(conversationSource, '_isAgentActor'),+ extractFunction(conversationSource, '_isActorDetailTarget'),+ extractFunction(conversationSource, '_openActorAgentDetail'),+ extractFunction(conversationSource, '_hydrateMessageCreatedAgentChip'),].join('\n'), context);return { context, element, selectAgent, setView };}describe('agent detail return navigation', () => {+ async function openConversationEntry(context: any, entry: string) {+ if (entry !== 'created-chip') return context._openActorAgentDetail(entry);+ let click: (() => Promise<void>) | undefined;+ const chip = {+ dataset: { agentId: 'agent-a' },+ addEventListener: (_event: string, handler: () => Promise<void>) => { click = handler; },+ };+ context._hydrateMessageCreatedAgentChip({ querySelectorAll: () => [chip] });+ await click!();+ }++ it.each(['commander', 'agent-a', 'created-chip'])(+ 'opens the real conversation %s entry and dismisses back to the same conversation', async (entry) => {+ const { context, element, selectAgent, setView } = loadNavigation('conversation', 'conversation-a');+ await openConversationEntry(context, entry);+ expect(selectAgent).toHaveBeenCalledWith(entry === 'commander' ? 'commander' : 'agent-a', { refreshCliOptions: true });+ expect(element('panel-agents').classList.contains('resource-detail-overlay')).toBe(true);+ expect(context.currentCid).toBe('conversation-a');+ context._returnFromAgentsDetailView();+ expect(element('panel-agents').classList.contains('resource-detail-overlay')).toBe(false);+ expect(context.currentView).toBe('conversation');+ expect(context.currentCid).toBe('conversation-a');+ expect(setView).not.toHaveBeenCalled();+ },+ );++ it.each(['agent-a', 'created-chip'])(+ 'keeps the conversation visible when %s refers to an unavailable Agent', async (entry) => {+ const { context, selectAgent, setView } = loadNavigation('conversation', 'conversation-a');+ context.apiFetch.mockResolvedValue({ json: async () => ({ ok: false }) });+ await openConversationEntry(context, entry);+ expect(selectAgent).not.toHaveBeenCalled();+ expect(setView).not.toHaveBeenCalled();+ expect(context.currentCid).toBe('conversation-a');+ },+ );+it('returns a viewed agent to the conversation that opened it', async () => {const { context, element, selectAgent, setView } = loadNavigation('conversation', 'conversation-a');@@ -155,9 +202,6 @@ describe('agent detail return navigation', () => {});it('routes every cross-page entry and both back gestures through the shared helpers', () => {- expect(conversationSource).toContain("await openAgentDetail('commander', { returnTarget })");- expect(conversationSource).toContain('await openAgentDetail(aid, { returnTarget })');- expect(conversationSource).toContain('openAgentDetail(aid, { returnTarget })');expect(projectDetailSource).toContain('await openAgentDetail(agentId)');expect(searchSource).toContain('await openAgentDetail(r.id, { returnTarget: agentReturnTarget })');expect(stateSource).toContain(diff --git a/test/renderer/connectors-degraded-card.test.ts b/test/renderer/connectors-degraded-card.test.tsindex b31def89..e4599c19 100644--- a/test/renderer/connectors-degraded-card.test.ts+++ b/test/renderer/connectors-degraded-card.test.ts@@ -613,3 +613,18 @@ describe('connectors panel — degraded cards never claim 已连接', () => {expect(ctx._renderCatalogCard(entry, null).innerHTML).not.toContain('is-loading');});});++describe('explicit connector failure codes', () => {+ it.each([+ [{ code: 'user_cancelled', error: 'User cancelled' }, false],+ [{ code: 'superseded', error: 'A newer request replaced it' }, false],+ [{ code: 'E_UNKNOWN', error: 'Operation canceled' }, false],+ [{ code: 'storage_unavailable', error: 'Storage failed after another request was cancelled' }, true],+ [{ code: 'invalid_grant', error: 'Previous operation canceled; grant invalid' }, true],+ ])('shows hard failures without mistaking incidental cancel text for user cancellation: %j', (error, shouldAlert) => {+ const context = loadConnectorsRenderer();+ context._handleConnectFailure({}, 0, error);+ expect(context.__alerts.length).toBe(shouldAlert ? 1 : 0);+ if (error.code === 'storage_unavailable') expect(context.__alerts[0]).toBe(context.t('connectors.errors.storage_unavailable'));+ });+});diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.tsindex 0f01fd70..6404d19c 100644--- a/test/renderer/conversation-sidebar.test.ts+++ b/test/renderer/conversation-sidebar.test.ts@@ -127,6 +127,8 @@ function loadConversationRenderer() {'chat.process.action_search_conversation': 'Search conversation','chat.process.action_run_command': 'Run command','chat.process.action_generate_image': 'Generate image',+ 'chat.process.action_generate_video': 'Generate video',+ 'chat.from_agent_unknown': 'Agent','chat.process.action_generate_audio': 'Generate audio','chat.process.action_create_plan': 'Create plan','chat.process.action_execute_plan': 'Execute plan',@@ -228,6 +230,62 @@ function loadConversationRenderer() {return context;}+describe('delegation and video process presentation', () => {+ it.each(['dispatch_to', 'hand_off_to'])(+ 'renders persisted %s identity in live progress and history without the registry cache', (name) => {+ const context = loadConversationRenderer();+ const events = [+ { stream: 'tool', data: { phase: 'start', id: 'delegate-1', name } },+ { stream: 'tool', data: { phase: 'progress', id: 'delegate-1', name,+ arguments: { to: 'd76b91de8c7b' }, agent_name: 'ProductDemoBuilder' } },+ { stream: 'tool', data: { phase: 'end', id: 'delegate-1', name,+ agent_name: 'ProductDemoBuilder', duration_ms: 8000 } },+ ];+ const lines: string[] = [];+ context._streamingAppendProgress = (_msg: unknown, line: string) => lines.push(line);+ const message = {};+ for (const event of events) context._renderAgentEvent(message, event);+ expect(lines.slice(1).every((line) => line.includes('Call agent · ProductDemoBuilder'))).toBe(true);+ expect(lines.join('\n')).not.toContain('d76b91de8c7b');+ const replay = context._createProcessDisplayContext();+ for (const event of JSON.parse(JSON.stringify(events)).slice(1)) {+ expect(context._formatEventLine(event, replay)).toContain('Call agent · ProductDemoBuilder');+ }+ expect(context._formatEventLine(events[2])).toContain('Call agent · ProductDemoBuilder');+ },+ );++ it.each(['registry', 'members', 'unknown', 'explicit'])(+ 'resolves legacy delegation ids using %s identity information', (source) => {+ const context = loadConversationRenderer();+ context.currentCid = 'c1';+ if (source === 'registry') context._agentsCache = [{ agent_id: 'd76b91de8c7b', name: 'ProductDemoBuilder' }];+ if (source === 'members') vm.runInContext(+ '_groupMembersCache.set("c1", [{ id: "d76b91de8c7b", name: "ProductDemoBuilder" }])', context,+ );+ const line = context._formatEventLine({ stream: 'tool', data: {+ phase: 'start', name: 'dispatch_to', arguments: { to: 'd76b91de8c7b' },+ ...(source === 'explicit' ? { agent_name: 'aabbccddeeff' } : {}),+ } });+ const expectedName = source === 'explicit' ? 'aabbccddeeff' : source === 'unknown' ? 'Agent' : 'ProductDemoBuilder';+ expect(line).toContain(`Call agent · ${expectedName}`);+ expect(line).not.toContain('d76b91de8c7b');+ },+ );++ it('preserves the video action through terminal events and a fresh replay', () => {+ const context = loadConversationRenderer();+ const events = [+ { stream: 'tool', data: { phase: 'start', id: 'video-1', name: 'generate_video', arguments: { output_path: 'demo.mp4' } } },+ { stream: 'tool', data: { phase: 'end', id: 'video-1', name: 'generate_video' } },+ ];+ for (let pass = 0; pass < 2; pass += 1) {+ const display = context._createProcessDisplayContext();+ for (const event of events) expect(context._formatEventLine(event, display)).toContain('Generate video · demo.mp4');+ }+ });+});+describe('conversation form submission boundary', () => {it('rejects a failed form mark with the backend error so the widget can retry', async () => {const context = loadConversationRenderer();@@ -3566,6 +3624,7 @@ describe('conversation process metadata formatting', () => {['office_render', { path: 'reports/summary.docx' }, 'Render file · reports/summary.docx'],['pdf_render', { path: 'reports/summary.pdf' }, 'View file · reports/summary.pdf'],['generate_image', { output_path: 'images/cover.png' }, 'Generate image · images/cover.png'],+ ['generate_video', { output_path: 'video/demo.mp4' }, 'Generate video · video/demo.mp4'],['generate_speech', { output_path: 'audio/voice.mp3' }, 'Generate audio · audio/voice.mp3'],['call_connector_tool', { connector_id: 'Notion' }, 'Use connector · Notion'],['add_custom_connector', { display_name: 'Internal Docs' }, 'Add connector · Internal Docs'],@@ -6160,7 +6219,7 @@ describe('conversation controller settlement', () => {]);});- it('retries a failed edit reply through its owning controller with the original request metadata', async () => {+ it.each(['agent', 'skill'])('retries a failed %s edit reply through its owning controller with the original request metadata', async (owner) => {const context = loadConversationRenderer();const historyEl: any = { innerHTML: '', dataset: {} };const capturedRequests: Array<{ url: string; body: any }> = [];@@ -6197,15 +6256,16 @@ describe('conversation controller settlement', () => {};};- const controller = context.createChatController({- historyEl,- getCurrentId: () => 'skill-a1',- historyEndpoint: () => '/skill/history',- streamEndpoint: () => '/skill/send',- telemetrySurface: 'skill_edit',- features: { bindInput: false, scrollPin: false, queue: true, messageActions: 'errors-only' },- queue: { keyPrefix: 'skill' },- });+ context.window.addEventListener = () => {};+ context.document.getElementById = (id: string) => id === `${owner}s-chat-messages` ? historyEl : null;+ context._setChatScrollOffset = () => {};+ context._pinMessageToTopWithDynamicSpacer = () => {};+ context._chatAttachList = () => [];+ vm.runInContext(fs.readFileSync(path.join(process.cwd(), `src/renderer/modules/${owner}s.js`), 'utf8'), context);+ vm.runInContext(owner === 'agent'+ ? "_selectedAgent = { id: 'resource-a1', source: 'custom' }; _bindAgentEditAttachments = () => {};"+ : "_skillEditSkillId = 'resource-a1'; _bindSkillEditAttachments = () => {};", context);+ const controller = owner === 'agent' ? context._ensureAgentChatController() : context._ensureSkillChatController();await controller.loadHistory();const userMessage = {@@ -6225,7 +6285,7 @@ describe('conversation controller settlement', () => {expect(capturedRequests).toHaveLength(1);expect(capturedRequests[0]).toEqual({- url: '/skill/send',+ url: `/api/${owner}s/resource-a1/chat/send/stream`,body: expect.objectContaining({content: 'Refine this skill',attachments: ['brief.md'],@@ -6412,19 +6472,39 @@ describe('conversation controller settlement', () => {expect(result.result).toBe(expected);});- it('returns failure for a controller preflight rejection', async () => {+ it.each(['rejected', 'thrown'])(+ 'discards a sent composer snapshot when preflight is %s', async (failure) => {const context = loadConversationRenderer();+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/queue-draft.js'), 'utf8'), context);+ context._rememberSentComposerSnapshot('c1', { text: 'old unsent attempt' });context.performance = performance;context._makeConvChatController = () => ({abort() {},async send() {+ if (failure === 'thrown') throw new Error('preflight failed');return { started: false, aborted: false, errored: false, reason: 'model_not_configured' };},});- const result = await context.sendInConversation('c1', 'hello');+ if (failure === 'thrown') {+ await expect(context.sendInConversation('c1', 'hello')).rejects.toThrow('preflight failed');+ } else {+ expect((await context.sendInConversation('c1', 'hello')).result).toBe('failure');+ }+ expect(vm.runInContext('_sentComposerSnapshots.has("c1")', context)).toBe(false);+ expect(context._restoreSentComposerSnapshot('c1')).toBe(false);+ });++ it('keeps the active turn snapshot when a new message is queued', async () => {+ const context = loadConversationRenderer();+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/queue-draft.js'), 'utf8'), context);+ context.performance = performance;+ context._rememberSentComposerSnapshot('c1', { text: 'active turn' });+ context.pendingConvs.set('c1', {});+ context.enqueueMessage = vi.fn();- expect(result.result).toBe('failure');+ expect(await context.sendInConversation('c1', 'queued turn')).toMatchObject({ queued: true });+ expect(vm.runInContext('_sentComposerSnapshots.get("c1").text', context)).toBe('active turn');});});diff --git a/test/renderer/resource-edit-parity.test.ts b/test/renderer/resource-edit-parity.test.tsnew file mode 100644index 00000000..f98c3c4a--- /dev/null+++ b/test/renderer/resource-edit-parity.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import path from 'node:path';+import vm from 'node:vm';++function loadRenderer(module: 'agents' | 'skills') {+ const elements = new Map<string, any>();+ const element = (id: string) => {+ if (!elements.has(id)) elements.set(id, {+ style: {}, dataset: {}, attrs: {}, hidden: false, readOnly: false,+ textContent: '', innerHTML: '', innerText: '', value: '',+ classList: { add() {}, remove() {}, toggle() {} },+ setAttribute(name: string, value: string) { this.attrs[name] = value; },+ addEventListener() {}, querySelector() { return null; },+ });+ return elements.get(id);+ };+ const context: any = {+ console, setTimeout, clearTimeout,+ createLogger: () => ({ info() {}, warn() {}, error() {} }),+ window: { addEventListener() {} },+ document: { getElementById: element, querySelector: () => null },+ t: (key: string) => key, getLang: () => 'en',+ escapeHtml: (s: string) => s, renderMarkdownFull: (s: string) => `<p>${s}</p>`,+ normalizeDisplayText: (s: string) => s, pickDesc: (agent: any) => agent.description,+ uiAlert: vi.fn(),+ };+ vm.createContext(context);+ vm.runInContext(fs.readFileSync(path.join(process.cwd(), `src/renderer/modules/${module}.js`), 'utf8'), context);+ return { context, element };+}++describe('resource editing integration', () => {+ it.each(['marketplace', 'custom'])('keeps %s Agent definition permissions when entering memory edit mode', (source) => {+ const { context, element } = loadRenderer('agents');+ // These independent detail panels are outside the definition editor.+ for (const name of ['HeaderCategory', 'Runtime', 'CliSettings', 'ProjectDir', 'Avatar', 'Stats', 'Knowhow', 'OutputFormatSection']) {+ context[`_renderAgentDetail${name}`] = () => {};+ }+ context._renderAgentHeaderCategory = () => {};+ context._renderAgentEnabledButton = () => {};+ context._renderAgentOutputFormatSection = () => {};+ context._renderSourceMetaHtml = () => '';+ context._renderAgentDetailMemory = vi.fn();+ const agent = { agent_id: 'a1', name: 'Writer', source, description: 'Writes drafts', workflow: 'Draft the answer' };+ expect(context._canEnterAgentEditMode(agent)).toBe(true);+ context._renderAgentDetail(agent, true);+ expect(context._renderAgentDetailMemory).toHaveBeenCalledWith(expect.objectContaining({ agent_id: 'a1' }), true);+ const editable = source === 'custom';+ expect(element('agents-detail-name-input').readOnly).toBe(!editable);+ expect(element('agents-detail-desc').attrs.contenteditable).toBe(editable ? 'plaintext-only' : 'false');+ expect(element('agents-detail-workflow').attrs.contenteditable).toBe(editable ? 'plaintext-only' : 'false');+ if (!editable) expect(element('agents-detail-workflow').innerHTML).toBe('<p>Draft the answer</p>');+ });++ it('finishes an Agent rename by refreshing its selected name, cache and recipient chip', async () => {+ const { context, element } = loadRenderer('agents');+ context.apiFetch = vi.fn(async () => ({ json: async () => ({ ok: true, agent: { name: 'NewName' } }) }));+ context.loadAgents = vi.fn(async () => {});+ context._renderRecipientChip = vi.fn();+ vm.runInContext("_selectedAgent = { id: 'a1', name: 'OldName', source: 'custom' }; _pendingAgentField = { field: 'name', value: 'NewName' };", context);+ await context._flushAgentFieldSave({ validate: true });+ expect(context.apiFetch).toHaveBeenCalledWith('/api/agents/a1/update', expect.objectContaining({ method: 'PUT' }));+ expect(context.uiAlert).not.toHaveBeenCalled();+ expect(vm.runInContext('_selectedAgent.name', context)).toBe('NewName');+ expect(element('agents-detail-name-input').value).toBe('NewName');+ expect(context.loadAgents).toHaveBeenCalledWith(true);+ expect(context._renderRecipientChip).toHaveBeenCalledOnce();+ });++ it('uses the renamed Skill directory for subsequent saves and edit chat', async () => {+ const { context } = loadRenderer('skills');+ context.apiFetch = vi.fn(async () => ({ json: async () => ({ ok: true, skill: { id: 'beta' } }) }));+ context.loadSkills = vi.fn(async () => {});+ vm.runInContext("_selectedSkill = { id: 'alpha', name: 'alpha', source: 'custom', filepath: 'SKILL.md' }; _skillEditSkillId = 'alpha'; _skillTreeCache.set('custom:alpha', []); _expandedDirs.add('custom:alpha'); _pendingSkillField = { field: 'name', value: 'beta' };", context);+ expect(await context._flushSkillFieldSave({ validate: true })).toBe(true);+ expect(context.uiAlert).not.toHaveBeenCalled();+ expect(vm.runInContext('[_selectedSkill.id, _skillEditSkillId, _skillTreeCache.size, _expandedDirs.has("custom:alpha")]', context)).toEqual(['beta', 'beta', 0, false]);+ vm.runInContext("_pendingSkillField = { field: 'description', value: 'Updated' };", context);+ expect(await context._flushSkillFieldSave()).toBe(true);+ expect(context.apiFetch.mock.calls.map((call: any[]) => call[0])).toEqual(['/api/skills/alpha/update', '/api/skills/beta/update?skipRename=1']);+ });+});diff --git a/test/renderer/settings-add-account.test.ts b/test/renderer/settings-add-account.test.tsindex db8b228f..e15497a7 100644--- a/test/renderer/settings-add-account.test.ts+++ b/test/renderer/settings-add-account.test.ts@@ -132,6 +132,7 @@ function loadSettingsClickHarness(},getValue: () => value,getOptions: () => options,+ setAriaLabel() {},setValue(next: string) {value = next || '';element.dataset.value = value;@@ -190,6 +191,47 @@ function loadSettingsClickHarness(}describe('settings model authorization add account', () => {+ it('uses the model options returned by imageAuth and preserves the selected model on save', async () => {+ const model = 'doubao-seedream-5-0-pro-260628';+ const option = { id: `doubao:${model}`, provider: 'doubao', model, label: 'DouBao · Seedream 5.0 Pro' };+ const { context, elements, invoke } = loadSettingsClickHarness(async (channel) => (+ channel === 'imageAuth.list' ? { ok: true, profiles: [], providers: [option] } : { ok: true }+ ));+ const key = new FakeElement();+ key.value = 'fixture-image-key';+ elements.set('settings-image-key-input', key);+ elements.set('settings-image-provider', new FakeElement());+ elements.set('settings-image-status', new FakeElement());+ await context._settingsRefreshImageProfiles();+ context._settingsRenderImagePicker();+ expect(vm.runInContext('_settingsState.imageProviderSel.getOptions()', context)).toEqual([+ expect.objectContaining({ value: option.id, label: option.label }),+ ]);+ context.__selected = option.id;+ vm.runInContext('_settingsState.imageProviderSel.setValue(__selected)', context);+ await context._settingsClickAddImageKey();+ expect(invoke).toHaveBeenCalledWith('imageAuth.add', { provider: 'doubao', model, apiKey: 'fixture-image-key', label: 'default' });+ });++ it('turns a rejected OAuth start IPC into the visible error state', async () => {+ const { context, elements } = loadSettingsClickHarness(async () => { throw new Error('fixture IPC failure'); });+ await expect(context._settingsStartOAuthFlow({ id: 'openai-codex', label: 'Codex' }, 'gpt-5.5')).resolves.toBeUndefined();+ expect(elements.get('oauth-flow-body')!.innerHTML).toContain('settings.oauth.start_failed');+ });++ it('resets the language picker and explains a failed language change', async () => {+ const { context, elements } = loadSettingsClickHarness();+ elements.set('settings-language-select', new FakeElement());+ context.getLang = () => 'en';+ context.isSupportedLang = () => true;+ context.setLang = vi.fn(async () => { throw new Error('fixture preference failure'); });+ context.getSupportedLangs = () => ['en', 'zh'];+ context._settingsBindLanguageOnce();+ await vm.runInContext("_settingsLanguageSel.emitChange('zh')", context);+ expect(context.uiAlert).toHaveBeenCalledWith('settings.language.change_failed');+ expect(vm.runInContext('_settingsLanguageSel.getValue()', context)).toBe('en');+ });+it('updates existing-entry models and reverts failed selections', async () => {const success = loadSettingsClickHarness();vm.runInContext('window.__settingsReloaded = false; _settingsReload = async () => { window.__settingsReloaded = true; };', success.context);@@ -675,3 +717,20 @@ describe('settings model authorization add account', () => {expect(context.__closeFlow).not.toHaveBeenCalled();});});++it('shows legacy unsupported video profiles as unavailable instead of active', async () => {+ const { context, elements } = loadSettingsClickHarness(async (channel) => (+ channel === 'videoAuth.list' ? {+ ok: true,+ providers: [{ id: 'orkas-api', provider: 'orkas-api', model: 'orkas-video', label: 'Orkas · Video' }],+ profiles: [{ id: 'legacy', provider: 'doubao', model: 'doubao-seedance-2-0-260128', available: false, label: 'Legacy', apiKeyMasked: '***' }],+ } : { ok: true }+ ));+ await context._settingsRefreshVideoProfiles();+ context._settingsRenderVideoEntries();+ const row = elements.get('settings-video-entries')!.children[0];+ expect(row.className).not.toContain('is-default');+ expect(row.children.find((child) => child.className === 'entry-rank')?.textContent).toBe('new_chat.model_picker.unavailable');+ const main = row.children.find((child) => child.className === 'entry-main');+ expect(main?.children.find((child) => child.className === 'form-hint')?.textContent).toBe('settings.video.provider_unavailable');+});diff --git a/test/renderer/settings-open.test.ts b/test/renderer/settings-open.test.tsindex aec8fb89..df0f2eb7 100644--- a/test/renderer/settings-open.test.ts+++ b/test/renderer/settings-open.test.ts@@ -134,3 +134,30 @@ describe('settings sidebar navigation', () => {expect(loadSettings).toHaveBeenCalledOnce();});});++it('restores unread state after the real user initialization boundary', async () => {+ const { context } = loadRendererNavigation();+ context.apiFetch = vi.fn(async () => ({ json: async () => ({ ok: true, user_id: 'local-owner' }) }));+ const owners: string[] = [];+ context._restoreUnreadTaskState = () => { owners.push(vm.runInContext('currentUserId', context)); };+ await context.initUser();+ expect(owners).toEqual(['local-owner']);+ expect(context.currentUserId).toBe('local-owner');+});++it('does not drain restored queues before conversation history resolves', () => {+ const { context } = loadRendererNavigation();+ const history = Promise.withResolvers<void>();+ context.loadConversationHistory = vi.fn(() => history.promise);+ context._restoreDraft = vi.fn();+ context.renderMessageQueue = vi.fn();+ context.isConvPending = () => false;+ context._dispatchNextQueued = vi.fn();+ context._updateConvSendUI = vi.fn();+ context.focusChatComposerIfIdle = vi.fn();+ vm.runInContext("messageQueues.set('queued-task', [{ id: 'q1', content: 'follow up' }]);", context);+ context.setView('conversation', 'queued-task');+ expect(context.loadConversationHistory).toHaveBeenCalledWith('queued-task', undefined);+ expect(context._dispatchNextQueued).not.toHaveBeenCalled();+ history.resolve();+});diff --git a/test/renderer/settings-recycle.test.ts b/test/renderer/settings-recycle.test.tsindex ebcfa873..1eff6eb7 100644--- a/test/renderer/settings-recycle.test.ts+++ b/test/renderer/settings-recycle.test.ts@@ -73,6 +73,23 @@ function loadHarness(batches: Array<Record<string, unknown>>) {}describe('Settings recycle bin', () => {+ it('refreshes Agent and Skill caches after a successful restore', async () => {+ const { sandbox, getClickListener, recycleBin } = loadHarness([]);+ sandbox.uiAlert = vi.fn();+ sandbox.uiConfirm = vi.fn(async () => true);+ sandbox.loadAgents = vi.fn(async () => {});+ sandbox.loadSkills = vi.fn(async () => {});+ sandbox._settingsBindRecycleBinOnce();+ const button = { disabled: false, getAttribute: () => 'fixture-batch', hasAttribute: () => false };+ await getClickListener()!({ target: { closest: (selector: string) => selector === '[data-recycle-restore], [data-recycle-delete]' ? button : null } });+ expect(recycleBin.restore).toHaveBeenCalled();+ expect(sandbox.loadAgents).toHaveBeenCalledWith(true);+ expect(sandbox.loadSkills).toHaveBeenCalledWith(true);+ sandbox.loadAgents.mockRejectedValueOnce(new Error('fixture refresh failure'));+ await getClickListener()!({ target: { closest: (selector: string) => selector === '[data-recycle-restore], [data-recycle-delete]' ? button : null } });+ expect(sandbox.uiAlert).not.toHaveBeenCalled();+ });+const repeatedTitle = '@ContentWriter 最近关于模型即应用';const batch = {id: 'batch-1',diff --git a/test/renderer/settings-task-notifications.test.ts b/test/renderer/settings-task-notifications.test.tsindex bb443b9f..e29200b4 100644--- a/test/renderer/settings-task-notifications.test.ts+++ b/test/renderer/settings-task-notifications.test.ts@@ -403,3 +403,19 @@ describe('Settings → General task notification toggle', () => {expect(event).not.toHaveBeenCalled();});});++it('binds the visible notification toggle before slow settings reads finish', async () => {+ const pending = Promise.withResolvers<any>();+ const h = loadHarness({ ok: true }, undefined, true, pending.promise);+ const opening = h.sandbox.loadSettings();+ try {+ expect(h.listeners.has('change')).toBe(true);+ h.checkbox.checked = false;+ await h.listeners.get('change')!();+ expect(h.invoke).toHaveBeenCalledWith('prefs.setTaskNotifications', { enabled: false });+ } finally {+ pending.resolve({ ok: true, enabled: true });+ await opening;+ }+ expect(h.checkbox.checked).toBe(false);+});diff --git a/test/renderer/workspace-outcome-parity.test.ts b/test/renderer/workspace-outcome-parity.test.tsnew file mode 100644index 00000000..f84f5047--- /dev/null+++ b/test/renderer/workspace-outcome-parity.test.ts@@ -0,0 +1,46 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++function harness(invoke: ReturnType<typeof vi.fn>) {+ const context: any = {+ document: { addEventListener: vi.fn(), querySelectorAll: () => [] },+ window: { addEventListener: vi.fn(), orkas: { invoke } },+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+ t: (key: string) => key,+ uiToast: vi.fn(),+ };+ vm.createContext(context);+ vm.runInContext(readFileSync(resolve(__dirname, '../../src/renderer/modules/user-workspace.js'), 'utf8'), context);+ return context;+}++describe('workspace mutation outcome', () => {+ it('distinguishes picker failure from user cancellation', async () => {+ const invoke = vi.fn().mockResolvedValueOnce({ ok: false }).mockResolvedValueOnce({ ok: true, path: '' });+ const context = harness(invoke);+ await context._selectAndSetWorkspace('new-chat');+ expect(context.uiToast).toHaveBeenCalledOnce();+ context.uiToast.mockClear();+ await context._selectAndSetWorkspace('new-chat');+ expect(context.uiToast).not.toHaveBeenCalled();+ expect(invoke.mock.calls.map(([channel]) => channel)).toEqual(['workspace.selectDirectory', 'workspace.selectDirectory']);+ });++ it('keeps a successful workspace mutation successful when UI refresh rejects', async () => {+ const invoke = vi.fn(async () => ({ ok: true, path: '/fixture/workspace' }));+ const context = harness(invoke);+ context._refreshAllWorkspaceInfo = vi.fn(async () => { throw new Error('fixture refresh failure'); });+ await context._selectAndSetWorkspace('new-chat', '/fixture/workspace');+ expect(invoke).toHaveBeenCalledWith('workspace.set', { path: '/fixture/workspace' });+ expect(context.uiToast).not.toHaveBeenCalled();+ });++ it('opens the selected folder without an undefined timing variable', async () => {+ const invoke = vi.fn(async () => ({ ok: false }));+ const context = harness(invoke);+ await expect(context._openWorkspaceFolder('new-chat')).resolves.toBeUndefined();+ expect(invoke).toHaveBeenCalledWith('workspace.openPath', {});+ });+});