Skip to content

armgit / Orkas

Public Imported from GitHub
0

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.

Refresh local task and project workflows

wytecd0fd5a7c20
diff --git a/docs/test/conversations-regression.md b/docs/test/conversations-regression.md
new file mode 100644
index 00000000..9accf206
--- /dev/null
+++ b/docs/test/conversations-regression.md
@@ -0,0 +1,367 @@
+# 对话、附件与 Artifact 模块人工回归 Case
+
+## 评测原则与证据矩阵
+
+对话是所有 Agent 与项目任务的持久化底座。Case 必须同时证明成功路径和失败恢复,
+不能把“侧边栏消失”当作删除成功,也不能把“模型回复过”当作消息已可靠落盘。
+
+| 核心场景 | 用户预期结果 | 单测/契约 | Electron E2E | Benchmark |
+|---|---|---|---|---|
+| 创建、重命名、置顶、删除 | UI、索引、消息和资源状态一致,重启后不反转 | `features/chats.test.ts` 的索引、tombstone、清理与并发更新 | `conversations_e2e_lifecycle.spec.ts` | 确定性状态,不进入 benchmark |
+| 重复点击当前任务 | 已挂载的消息、滚动位置、草稿、附件和焦点保持不变;点击其他任务仍正常切换 | `conversation-sidebar.test.ts` 的当前任务 no-op 与其他任务切换反例 | “对话列表与切换”人工回归 | 确定性交互,不进入 benchmark |
+| 直达智能体的新任务标题 | `@Agent` 仅参与消息路由,首次显示、刷新及持久化标题均只保留任务正文 | `features/chats.test.ts` 与 sendStream IPC 契约 | `conversations_e2e_lifecycle.spec.ts` | 确定性传输契约,不进入 benchmark |
+| 指挥官分段气泡耗时 | 每个已结束的指挥官气泡显示各自执行耗时;终止式与非终止式交接、实时与刷新后均一致,且不生成空尾消息 | `group_chat/bus-integration.test.ts` 与 renderer process metadata 契约 | 聊天主链路回归 | 确定性持久化/渲染契约,不进入 benchmark |
+| Office 过程动作语义 | 结构检查显示“检查文件”,像素渲染显示“渲染文件”;PDF/HTML 预览继续显示“查看文件”;恢复旧任务时旧 `office_check`/`office_render`、PDF 和进程工具事件保持相同业务标签且不展示 session id,四种语言一致 | `conversation-sidebar.test.ts` 的新旧事件差分与 renderer locale parity | 运行一次 Office 生成任务并核对过程轨道顺序 | 确定性标签,不进入 benchmark |
+| 匿名与具名调度边界 | `run_worker` 只创建不可见匿名 helper;带旧版 `to` 的调用明确提示改用 `dispatch_to`,且不得启动匿名或具名 worker、加入 roster 或写入 Agent 回复 | `group_chat/bus-integration.test.ts` 的真实 bus、session、roster 与消息 JSONL 负控 | Commander 分别执行匿名辅助与具名 Agent 调度 | 语义质量另由 Commander regression 评估;边界本身为确定性契约 |
+| 删除失败与恢复 | 后端未确认删除时会话保持可见并显示原因,用户可重试 | 后端删除/清理单测 | 注入 IPC 500,验证不假成功且恢复后可删除 | 确定性状态,不进入 benchmark |
+| 草稿切换与消息排队 | 每个会话只恢复自己的草稿;用户点击停止时,触发该轮的消息按用户书写的原样(含内联 Skill/Connector token、接收 Agent、引用与复用附件)回到输入框,已发送消息仍留在对话中,输入框已有内容或队列项正在编辑时一律不覆盖,正常结束的轮次不得再被回填;队列消息编辑时完整恢复正文、附件、引用、Skill/Connector 与接收 Agent,保存后回到原位置,也可直接删除且永不发送该项;编辑期间不出队;目标与当前 Actor 相同且主进程标记该 CoreAgent/Codex/Claude turn 可 steer 时显示“发送”,文本、附件/图片、引用文件、Skill 与 Connector 均可同轮插入;不同 Agent、nested turn 与不支持 ingress 的 CLI 保留为后续轮次;立即发送的用户消息落入活动 AI 气泡之后时,该气泡下一次产生可见输出即移到用户消息之后,后续 token 不重复移动 DOM,最终再以服务端时间校准;未打开该会话时,上一条结束仍自动发送队首且不污染当前 tab | `queue-draft.test.ts` 覆盖按钮/点击双重准入及所有 sidecar;`composer-abort-restore.test.ts` 覆盖停止回填的内容、raw/派发文本差分、未发送输入与编辑锁保护、终态清理与非用户中断;`conversation-sidebar.test.ts` 覆盖活动气泡跨越新用户消息且每个边界只移动一次;`group_chat/bus-steer.test.ts` 覆盖 CoreAgent/CLI 富消息 hydration、ACK 后出队及 FIFO/Actor 边界;Codex/Claude backend 与 runner 单测覆盖 native ingress 生命周期、ID、图片、串行 writer 和失败回退;`agent-runner.test.ts` 覆盖 CoreAgent 结构化模型请求、持久化、去重与 ACK 重试 | `chat_e2e_model_stream.spec.ts` 覆盖 CoreAgent 引用与真实附件同轮转向,以及最终落盘前的实时消息换位;`chat_e2e_cli_recovery.spec.ts` 覆盖 Codex 同轮插入只运行一个进程,以及 OpenCode 不显示按钮并在当前进程结束后自动续跑;另保留真实附件编辑、编辑态删除和后台自动出队 | 确定性状态,不进入 benchmark |
+| 后台消息与会话排序 | 后台任务按消息的真实时间排序;打开任务回放缓存事件时不得把查看时间当作新活动时间 | `conversation-sidebar.test.ts` 的后台消息回放与排序负例 | 两个先后结束的自动任务来回切换,顺序保持不变 | 确定性状态,不进入 benchmark |
+| 自动任务执行状态 | 自动任务执行中同时显示呼吸状态点和自动化时钟,状态点固定在时钟左侧;结束后移除状态点,不显示静态圆点 | `conversation-sidebar.test.ts` 的运行态图标顺序与静止态无标记 | 启动自动任务后检查侧边栏和项目对话列表 | 确定性 DOM 状态,不进入 benchmark |
+| 后台任务未读提示 | Orkas 在后台或用户正在查看其他任务时,任务完成、失败或等待输入后,任务标题及所属 Tasks/Projects 层级显示红点;打开该任务后清除,重启和账号切换不串线 | `task-unread-indicators.test.ts` 覆盖前后台、持久化、父级聚合和账号隔离;`preload.test.ts` 自动发现真实 Renderer 推送消费者并覆盖精确 `conversation:task_terminal` 通道、动态通道及近似通道拒绝 | `task_notifications_e2e_navigation.spec.ts` 显式隐藏 Electron 窗口后通过生产终态通道验证任务与项目标题红点 | 确定性 IPC/状态/DOM 契约,不进入 benchmark |
+| 任务最终状态标签 | 已完成、等待输入或已取消的任务不显示“失败”;只有真实失败显示。成功回复、任务终态、流关闭、历史恢复与回放乱序时,最新的权威任务结果必须胜出 | `conversation-sidebar.test.ts` 的状态旅程矩阵与 `conversation-task-turn-capture.test.ts` 的桥接契约 | `chat_e2e_model_stream.spec.ts` 验证真实失败、重启保留、重试成功清除,以及普通成功重启后不误标 | 确定性状态,不进入 benchmark |
+| 消息底部操作可见性 | 普通消息操作在悬停或键盘聚焦时显示,所有按钮直接外露,反馈位于末尾,其余按钮保留原顺序;失败或中断回复的恢复操作始终可用;Agent、Skill、文件等结果 chip 不受影响 | `conversation-failed-retry.test.ts` 的共享操作容器 CSS 契约及结果行反例 | 普通与项目任务分别复验用户消息、成功回复、失败回复和刷新恢复 | 确定性视觉交互,不进入 benchmark |
+| 流式中断、排队与重启 | 仅本机登记的执行中任务随应用退出时显示中断;同步自其他进程/设备的 `running` 不得被本机恢复扫描误判,已持久化完整回复只清理陈旧运行态 | chats local-journal stale-state sweep、sendStream IPC、bus abort、failed-turn retry | `chat_e2e_model_stream.spec.ts` | CLI/模型恢复质量由 the separately authorized model canary 单独评测 |
+| 流式期间消息列表滚动 | 新建任务即使跳过历史加载,也必须在启用发送时置顶占位前绑定消息列表手势;滚轮、触摸或滚动条移动应立即解除占位,允许继续查看下方内容 | `conversation-sidebar.test.ts` 的 fresh-history 绑定、滚轮、触摸与裸 scroll 契约 | `chat_e2e_scroll.spec.ts` 分别从普通新任务页和项目页创建任务,在首轮完成后的慢速第二轮中验证消息区滚轮解除占位 | 确定性交互,不进入 benchmark |
+| 长对话轮次定位 | 对话达到 5 个用户轮次后显示轻量定位轨道;点位索引与正文独立并按 15 轮分页,轨道最多显示 12 个点;发送新轮次后当前点立即随对话前进,选中点尽量保持居中,上下仍有点位时对应边缘点渐缩渐隐;轨道内上滑加载更早的完整点位;悬浮/聚焦显示两行用户摘要和五行 AI 摘要,点击未挂载轮次时直接精确寻址且不串行加载中间正文页 | `conversation-turn-navigation.test.ts` 与 `features/chats.test.ts` 覆盖阈值、完整分页、新轮次自动跟随、选中点居中与边界夹取、双向溢出状态、可见点上限、摘要上限、旧对话懒构建、程序化滚动和缓存失效 | 视觉、轨道滚动与旧对话首次构建按“长对话首屏与历史窗口”人工复验 | 确定性索引/DOM/分页边界,不进入 benchmark |
+| 对话历史连续性 | Commander 与具名 Agent 共享同一 canonical 已完成对话投影,各自保留私有执行 session 与独立压缩;CLI 接收有界完整历史或成功游标后的 diff;任何 actor 都不应收到内部 JSON/宿主标记 | canonical history 投影、Agent checkpoint、CLI history compiler/cursor、chat-history scope/边界契约 | 当前任务指代续做、项目旧会话续做与重启 | shared-conversation-context Regression、Commander project-history Regression、Claude/Codex current-history benchmark |
+| 文件预览与编辑 | Markdown/文本编辑不丢草稿、不重复写、不绕过只读权限;PPT 预览首次选中第 1 页,滚动时只选中视口中心页;抽屉异常不留空壳,保存后重启仍一致 | `md-view-edit.test.ts`、`text-view-edit.test.ts`、`chat-md-drawer.test.ts`、`office-preview-rendered.test.ts` | `composer_e2e_interactions.spec.ts`;PPT 滚动保留真实浏览器手工复验 | 确定性编辑、布局与 IPC,不进入 benchmark |
+| 内联 HTML 离线预览 | 自包含 HTML 的内联脚本、本地及内嵌图片正常工作;远程脚本、资源、连接和框架导航不得自动联网 | `window-security.test.ts` 的 CSP/URL/导航边界 | `html_preview_e2e_offline_policy.spec.ts` 的真实 Chromium 请求负控 | 确定性安全边界,不进入 benchmark |
+| 多文件 HTML 预览 | 文件预览打开页面前先登记其所在文件夹:同文件夹及子文件夹的 CSS、JS、ES 模块、JSON、字体按正确类型加载,隐藏路径、其他文件夹、主目录及以上的文件夹一律不放行;本地存储仍被沙箱禁止。Agent 的 `html_preview` 检查按同一沙箱加载交付页面,生成应用的冒烟检查保持原方式 | `chat_attachments.test.ts` 的授权/隐藏/越界/过期;`produced-html-preview-assets.test.ts` 的真实 IPC 范围;`html_preview.test.ts` 的文件预览检查;`window-security.test.ts` 的沙箱参数一致性 | `html_preview_e2e_offline_policy.spec.ts` 的多文件站点在预览窗口与 `html_preview` 中的对照 | 确定性安全边界,不进入 benchmark |
+| 任务详情文件树 | 后台文件刷新更新列表,但不折叠用户已展开的目录 | `conversation-info.test.ts` 的目录状态与刷新竞态 | 按“长对话首屏与历史窗口”人工复验 | 确定性 DOM 状态,不进入 benchmark |
+
+### 任务最终状态标签场景矩阵(2026-08-08)
+
+| 用户目标 / 场景 | 起始状态与变化 | 可观察结果 | 严重失败与恢复 | 层级与独立判据 | 当前风险 / 覆盖 |
+|---|---|---|---|---|---|
+| 查看正常完成或内部故障后已恢复的任务 | 最终回复已落盘;生命周期流随后异常关闭 | 任务行没有“失败”,回复仍可见 | 成功任务被误报失败,用户重复执行已经完成的工作 | Renderer 状态旅程;断言最终任务行状态,不断言内部调用次数 | 历史实况;覆盖“回复先到、流错误后到” |
+| 从早到的传输错误恢复 | 流错误先显示失败;稍后收到同一任务的 `completed` 终态 | 失败标签自动消失,无需重新打开任务 | 状态永久停在失败 | Renderer 乱序旅程 + E2E 成功重试;最终任务行和持久化回复为判据 | 覆盖反向竞态与恢复 |
+| 识别真实失败 | 无成功回复;权威任务终态为 `failed` | 当前任务行显示“失败”,重启后从失败历史恢复,成功重试后清除 | 真实失败被静默隐藏,用户失去重试线索 | Renderer + Electron E2E;可见标签、失败气泡和重试后状态是相互独立的判据 | 覆盖失败、重启、重试闭环 |
+| 区分等待、取消和失败 | 终态分别为 `waiting_input`、`cancelled`、`failed` | 前两者不显示失败,只有后者显示 | 等待用户操作或主动停止被误报成系统失败 | 参数化 Renderer 状态旅程;任务行状态为判据 | 覆盖相邻状态反例 |
+| 重启或打开已有任务 | 最新历史分别为成功回复、结构化失败回复、待回复用户消息;索引可带陈旧失败状态 | 仅最新结构化失败显示失败;成功和待回复状态覆盖陈旧标记 | 旧内存/索引状态压过持久化事实 | Renderer 历史恢复;以最新持久化消息和任务行状态作差分判据 | 覆盖冷恢复与兼容数据 |
+| 接收重复、乱序或恶意终态 | 新任务结果已到;随后重放旧任务终态,或收到缺 cid/未知 status 的载荷 | 新结果不反转;其他任务不受影响;无效载荷不清除真实失败 | 回放把成功改成失败,或跨任务串线 | Renderer 负控;比较目标与旁路任务最终状态 | 主动问题发现:旧终态跨来源乱序、无效输入、跨 cid 隔离 |
+
+未在自动化中伪造 Electron 主进程在成功终态之后崩溃的 IPC 通道;该精确故障由
+Renderer 的双向乱序测试确定性覆盖。Electron E2E 负责独立证明真实状态能穿过
+模型、总线、持久化和侧边栏,并覆盖失败重启及成功重试,不复制宿主崩溃注入。
+
+## 自动化覆盖
+
+`test/e2e/chat_e2e_model_stream.spec.ts` 已通过本地隔离 SSE 模型覆盖创建会话、流式回复、停止生成、失败重试、截断流不得伪完成、流式期间消息排队/顺序消费、活动轮富消息转向、消息落盘和完整重启恢复;`test/e2e/chat_e2e_scroll.spec.ts` 另从普通新任务页和项目页覆盖流式期间的滚轮、触摸与裸 `scroll` 契约。引用立即发送 case 证明结构化引用和新增文本能进入相同 CoreAgent turn,并保留完整 `<referenced-messages>`;真实附件 case 证明附件行同样显示“发送”,用户消息先落入时间线而不启动竞争流,CoreAgent 的下一次模型请求再获得新的 attachment manifest。`chat_e2e_cli_recovery.spec.ts` 用 Codex App Server stub 证明 `turn/steer` 在同一 CLI run 内生效,并用慢速 OpenCode stub 证明无 ingress 的 CLI 不显示“发送”、当前进程结束后再自动以原生 follow-up 续跑。Codex backend 进程测试固定 `expectedTurnId`、`clientUserMessageId`、`localImage`、拒绝回退和 terminal 注销;Claude Code 进程测试固定第二条 user JSONL 与 control response 的串行写入。带真实附件的队列编辑、编辑态删除、切换 tab 后后台自动出队、停止、失败恢复与重启仍分别校验无丢失、晚到重放或重复派发。
+
+“立即发送”使用明确的执行控制:Renderer 只有在按钮通过活动 Actor/ingress 双重准入后才发送显式 `steer_active_turn: true`,IPC 仅接受严格布尔值并映射到主进程 `steerActiveTurn`;显式 `false` 或字符串伪值均不得授权介入。测试验证显式控制才允许介入;缺少控制时仍按 FIFO。按钮显示与点击之间还要重新校验活动 Actor;资格失效时不得请求后端、不得从本地队列移除,也不得降级成普通发送。任何队列侧旧元数据都不能把一次通过校验的“立即发送”覆盖成 `false`。`queue-draft.test.ts`、send IPC 契约、`group_chat/bus.test.ts` 和底层 steer 测试分别覆盖按钮载荷与竞态、跨 IPC 边界的 fail-closed 传递、真实活动 CLI 会话的同轮介入/FIFO 表现,以及未授权消息持续留在 durable FIFO 的不变量。
+
+`test/main/features/group_chat/visibility.test.ts` 以生产中出现过的内部历史回显形状覆盖 canonical history 投影:保留用户请求、角色名、dispatch、失败代码和产物路径,但不得再生成 `[Historical group conversation …]`/整条记录 JSON;已污染的旧 Assistant 回复不得继续传播,用户主动提到的相似普通文本仍须保留。
+
+`src/core-agent/test/session.test.ts` 还固定了 checkpoint、history exact facts、turn context、workspace ledger、completed-work ledger 与 execution-plan anchor 的模型投影边界:这些块必须保留任务续接所需事实,同时显式标记为私有运行时上下文,禁止在用户可见回复中引用、概括或确认;completed-work 投影加标记后仍不得突破原有 6000 字符上限。
+
+## 准备
+
+1. 准备一个普通对话、一个项目对话、一个绑定智能体/技能的对话。
+2. 准备 PDF、DOCX、图片、Markdown、CSV、代码文件、较大文本文件和包含中文/空格/特殊字符的文件名。
+3. 准备一个会生成 Artifact 和多个文件产物的真实模型任务。
+
+## 对话列表与切换
+
+1. 新建、重命名、删除、归档或恢复对话后,侧边栏、对话标题、任务详情和搜索结果应一致刷新。
+2. 快速切换多个对话时,消息、附件 chip、文件 tab 和输入草稿不应串线。
+3. 长标题、长摘要、多语言标题在宽屏和窄屏下不应遮挡按钮或撑开布局。
+4. 准备大量历史对话后重启应用:首次列表仍应正确显示指挥官/智能体头像;后续启动应复用已持久化的参与者摘要,不再逐个扫描消息日志。
+5. 将一个仍在执行且已进入本机 `running-conversations.json` 的对话强制退出并重启:仅该对话应恢复为 idle 并出现一次中断提示;若主消息末尾已经持久化同一轮的完整终局回复,即使 `state.json` 错误残留为 `running` 也只能静默清理状态,不得追加或继续显示中断气泡。另准备一个仅由同步落入、未进入本机运行日志的 `running` 状态,启动维护扫描必须原样保留且不得写中断消息。
+6. 在大量会话均已带记录同步版本后重启:列表应以各项目的 `_index.json` 为主数据源,不应逐个打开重复的 `meta.json`;旧版无同步版本记录和索引缺失记录仍应自动恢复。
+7. 在两个项目内分别准备多个对话,重命名或置顶其中一个:只应更新该对话的 `meta.json` 和所属项目 `_index.json`,其他对话 metadata 与其他项目索引的文件时间/内容应保持不变;删除、恢复和跨项目移动后索引仍应正确。
+8. 在一个项目持续收发消息,同时在另一项目准备大量对话:activity、重命名、置顶和删除只能读取/改写目标项目索引;并发执行两个不同字段更新后两个结果都必须保留,不能发生后写覆盖先写。
+9. 新任务首条消息包含中英文逗号、句号、问号等标点,或包含 `https://orkas.ai`、带查询参数的 URL、`www.` 地址时,自动标题应保留标点及后续文本,仅在超过 100 个半角显示宽度(约 50 个汉字或 100 个英文字符)时截断并追加省略号,存储与重命名时省略号不得被再次截掉;项目详情的任务列表应显示完整的截断标题。带引用消息的新任务只能用用户输入的正文生成标题,不得使用引用内容;只有引用而无正文时保留默认标题。首次乐观显示、刷新后的持久化标题和回收站恢复标题应一致。
+10. 新任务通过接收者选择器直达智能体时,用户消息应保留路由所需的 `@Agent`,但首次标题、列表刷新后的标题及重启恢复标题都只能使用任务正文,不得带 `@Agent`。
+11. 指挥官产生多个气泡时,每个已结束气泡的“过程信息”右侧都应显示该气泡自身的执行耗时:`hand_off_to` 前的说明气泡不得计入智能体执行时间,`dispatch_to` 后的总结气泡应独立计时;刷新或重启后耗时仍应保留,终止式交接不得产生空尾消息。
+12. 让两个自动任务在后台先后产生消息并结束,再打开较早结束的任务:侧边栏排序必须继续使用消息的持久化时间,不得因缓存事件在查看时回放而刷新为当前时间、跳到较晚任务之前;重复切换结果相同。
+13. 打开一个已有多条消息的任务,滚动到中间并保留未发送草稿或附件,然后再次点击侧边栏中已选中的同一任务:消息区不得出现加载态或重建,滚动位置、草稿、附件、右侧详情和输入焦点均保持原状,也不得重复记录“打开任务”;随后点击另一个任务,仍应正常切换并加载目标内容。
+
+## 长对话首屏与历史窗口
+
+1. 准备超过 10 条消息且包含中文、多行 Markdown、附件、产物、表单和 malformed JSONL 行的对话:打开时应优先显示最新 10 条,顺序、角色、附件和状态应正确,不能长时间白屏或卡住。
+2. 向上滚动到消息区顶部时,应出现内嵌“加载中”状态并自动增加紧邻的更早一页,已有消息不得重复或缺失,阅读位置不得跳动;包含整页内部 dispatch/路由记录时应自动跨过空白页,继续滚动可持续加载直至文件开头,此后不再显示 loading。
+3. 对话总用户轮次少于 5 个时不显示左侧定位轨道;达到 5 个后立即加载最新 15 个短横点,即使对应正文尚未分页挂载。定位轨道最多同时显示 12 个点,单点高度 18px,因此最大高度固定为 216px,并在自身范围内滚动;选中任一点后,该点应位于轨道中央,只有最前或最后等已无法继续滚动的边界位置允许偏离中央。轨道上方或下方仍有点位(包括尚未加载的更早分页)时,对应边缘的三个实际定位点应保持原有 18px 间距和 2px 可见高度,只向外逐渐缩短、变淡,不得增加额外轨道高度;到达真实边界后所有实际定位点恢复正常样式。普通、悬浮与选中态必须围绕同一中心线改变宽度,不得横向偏移。在轨道顶部继续向上滚动时每次前置 15 个更早点位,阅读位置不跳动,直至所有轮次均可达,不得采样或合并。悬浮或键盘聚焦任一点时,用户摘要最多两行/100 个 Unicode 字符,AI 摘要最多五行/240 个 Unicode 字符;点击未挂载轮次直接读取目标锚点并居中高亮,不得串行补载中间正文页。窗口宽度小于 760px 时隐藏轨道,不遮挡消息和输入框。
+ 正文定位按优先级判断:真正滚到对话顶部时选第一轮;否则最后一条消息进入可视区或滚到真正底部时选最后一轮;中间按视口高度 25% 处所在的轮次定位,AI 回复属于前面的用户提问。首尾同时可见时顶部优先。历史窗口的首尾不能冒充整段对话的首尾;窗口以回复开头时仍归属其原轮次。点击点位后保持选中,直到用户继续滚动或再次跳转;消息高度变化后重新计算位置,不主动移动正文。`chat_e2e_turn_navigation.spec.ts` 覆盖上述界面行为、定位索引分页失败后的重试与阅读位置保留。
+4. 准备一个在本版本之前创建且没有本地轮次索引的长对话:打开后最新正文仍先显示,主进程只为当前对话异步建立本地派生索引;索引完成后加载最新 15 个点,轨道内最多可见 12 个,第二次打开直接复用。追加消息、删除消息、同步替换源 JSONL 或移动对话归属后,旧索引必须失效并从当前源重建;由更早版本建立的索引(摘要预算不同)在升级后首次打开时同样重建一次,之后复用;删除对话时同时清除派生索引。
+5. 在已加载多页后切换对话再切回:正文应重新从最新 10 条开始,定位轨道则重新加载最新 15 个点并最多显示 12 个;全局搜索定位较早消息时,不应错误高亮当前页面的其他消息。
+6. 全局搜索命中首屏 10 条之外的早期消息时,点击结果应根据整份 JSONL 的消息下标计算目标页起点,一次读取“目标页起点到当前最新消息”的完整尾段,并把源下标映射到每个气泡后直接定位;目标消息之后的所有消息必须保留,更早内容仍可向上分页。旧消息即使缺少稳定 ID/时间也必须命中;定位应为瞬时跳转,且该程序化滚动不得触发“加载更早消息”继续逐页补载。
+7. 打开右侧任务详情的文件 tab 并展开一个目录后,让模型生成或删除文件:文件列表应更新,已展开目录不应因静默刷新自行折叠;同一次文件刷新不应重新读取整段对话历史,附件和已有产物信息仍应保留。
+8. 在包含大量项目和会话的数据集上分别打开普通对话、项目对话并继续翻页:请求应携带侧边栏已知的项目/全局归属提示,主进程只整理目标会话;模拟同步把对话移入另一项目后,旧提示仍应回退并打开正确记录。
+
+## 输入框与 @ 选择
+
+1. 在新建对话、普通对话、项目对话输入框中输入 `@`,分别选择多个 Skill 与 Connector 后,应在正文中以内联 chip 展示,并能与中英文/日文/葡文普通文字混排。
+2. 发送后,历史用户消息和实际模型输入应把这些 chip 展开为当前语言的普通文本(如“XX 技能”“XX 连接器”),不应残留内部 token 或旧底栏单选 chip。
+3. 回复 streaming 期间继续输入并排队时,队列预览应展示可读的 Skill / Connector 标签,实际派发时仍应按正文 token 展开。
+4. 旧草稿或旧队列中保存的单个 `use`/`skill` 字段应能恢复为正文 chip 或按旧前缀发送,不应丢失用户输入。
+5. 从资料库选择文件附加到聊天草稿时,选择器高亮不单独上报;每次真实附加只上报一次 `event_chat_library_attach_result`。失败时再配对一条 `error_chat_library_attach`,且两者都不得包含文件名或路径。
+6. 在项目详情的指挥官输入框粘贴截图或图片文件时,应在当前项目的草稿区显示附件 chip,图片不得直接嵌入输入框正文;发送后附件应随新建项目对话一并迁移。
+7. 回复 streaming 期间排队三条消息,让中间一条同时带附件、引用、Skill、Connector 和接收 Agent 后点击编辑:正文及所有 chip 应完整进入主输入框,队列列表仍保留该项及其取消入口,当前回复结束也不得发送任何队列项;修改后发送只把整份消息放回原顺序,不能创建额外消息。重复测试空内容、附件上传中和 Esc 取消:前两者保持编辑锁,Esc 恢复原消息及先前未发送草稿的全部内容后才继续队列。
+8. 在会话 A 回复 streaming 时排队一条消息,然后切到会话 B 且不要再打开 A:A 的当前回复结束后应自动发送队首,侧边栏运行态应跟随 A;B 的输入框、发送按钮和消息历史不得出现 A 的正文或流式占位。待 A 完成后再打开它,应看到两轮用户消息和两轮回复均按原顺序落盘,队列为空。
+9. 发送一条同时带附件、引用、Skill/Connector chip 和接收 Agent 的消息,执行中点击停止:输入框应还原为用户书写的原文(chip 与接收 Agent 一并复原,不得出现 `@Agent` 前缀或已展开的“XX 技能”正文),附件以复用形态回来且删除不影响已发送消息,光标落在末尾;已发送的那条消息仍留在对话中。修改后再次发送只产生一条新消息,Skill 不得被重复展开。重复以下三种情况,输入框内容都不得被覆盖:停止前已在输入框输入新内容、停止时正在编辑队列项、以及在上一轮正常结束之后才点击停止(此时不应回填任何内容)。从新建任务页和项目页发出的首条消息同样适用。
+
+## Agent capability handback, including CLI bridge transfer
+
+1. Directly address an in-process Agent with a primary deliverable outside its declared workflow. The Agent should briefly name the exact capability boundary and emit `<handback reason="capability_boundary" />`; the marker must stay hidden while the commander automatically continues with the original goal and attachments. Then directly give the Agent an in-scope task that it completes successfully: it must return the result without a handback marker or Commander continuation.
+2. Repeat with missing user input, a recoverable tool failure, a difficult in-scope task, and a task another Agent could merely perform better. These cases must stay with the current Agent and use its normal form/recovery path instead of handing back.
+3. Make a malformed Agent reply contain both `<handback reason="capability_boundary" />` and an input form. The form must win: control stays with the Agent and no commander continuation is queued.
+4. From the resumed commander turn, deliberately send the unchanged task back to the same Agent. Its second handback may return as the current dispatch result, but it must not enqueue another commander turn or create an automatic loop.
+5. Exercise an existing interactive `hand_off_to(..., resume)` ledger. Its handback must keep using the ledger resume path exactly once and must not also create a direct-handback continuation.
+6. Address multiple Agents in one user message and have each emit handback. The original message must wake commander at most once. If that same user message already addressed commander, handback must not enqueue an extra commander turn. Under D29, a plan that gives Commander a part (for example "最后你汇总一下") counts as addressing it: Commander runs only its planned part, with the hand-back as its predecessor result.
+7. Exercise a direct legacy bare `<handback />`, an unknown/conflicting reason, and an explicit capability-boundary reply followed by a runtime error. Every marker must stay hidden. Bare, unknown, or conflicting direct markers must not fabricate a capability boundary or wake Commander; the failed runtime must surface its failure without creating a continuation. Repeat the bare marker under an existing orchestration ledger to verify backward-compatible resume exactly once.
+8. Directly address an external CLI Agent with `@Agent` or the recipient chip and inspect its prompt: it must not receive capability-mismatch or lifecycle-completion handback guidance. After its reply completes, the recipient chip must stay on that Agent; send a no-mention follow-up and verify it routes to the same Agent and remains sticky. Then switch explicitly to Commander and verify the floor changes only from that user action.
+9. Inspect a CLI run when the ordinary group-chat Agent connector resolver has no visible connector: `orkas_list_connector_tools` and `orkas_call_connector_tool` must be absent from MCP discovery and direct host RPC must reject them. Connect and enable one connector for the user and repeat: both methods may appear through the same user-scoped visibility used by an in-process group-chat Agent, while every CLI call still requires the existing approval gate.
+10. Directly ask a user-selected CLI Agent for a Commander-only operation such as automation, Agent, or Skill creation. The CLI must call `orkas_handoff_to_commander` instead of emitting `<auto-task>`, `<agent>`, or `<skill>`. The run accepts only its first bounded reason/context request, then normalizes it into the ordinary Agent handback path: form priority, ledger resume, direct-origin dedupe, loop guards, floor reset, and original goal/attachment preservation must be identical. Have Commander emit the valid mutation container and verify the automation/object is actually created once; a form, failed/aborted CLI run, duplicate request, or user message already addressed to Commander must not create a second continuation. The live Claude/Codex model regression must additionally prove that an available custom Skill is read directly without transfer, while the combined automation/Agent/Skill mutation request produces exactly one structured handoff with all requirements preserved.
+11. Have Commander `hand_off_to` an interactive external CLI Agent, then complete that handed-off interaction with a visible result plus `<handback reason="completed_handoff" />`. Unlike direct user selection, the marker must stay hidden, the Agent result must remain the only user-facing completion, the conversation floor must return to Commander, and no extra Commander model turn or stale duplicate reply may appear. A ledger-backed `hand_off_to(..., resume)` must still wake Commander exactly once, and the legacy bare marker remains accepted only for ledger/floor lifecycle compatibility.
+12. After a Commander-only discussion, directly address an Agent for the first time. In-process and CLI contexts use the same scoped canonical dialogue source and latest-five-user-turn policy, excluding the current inbound task until it is added separately. CLI recovery/deltas are bounded to 30K estimated tokens without per-message byte clipping. Native CLI session history remains CLI-owned; another actor's private execution session must never be copied as canonical history.
+13. Have Commander `hand_off_to` an Agent that returns a distinctive blocker, then send a follow-up such as “fix that issue.” The Agent bubble must remain the only user-facing delivery in the hand-off turn and `hand_off_to` may still return only its acknowledgement. On the follow-up, Commander's ordinary model history must be synchronized from the canonical conversation log and contain the earlier user request, the Agent identity/name, and the exact blocker text; Commander must continue from that evidence without claiming the dispatch never happened or blindly repeating it. Verify no Commander visibility-slice file is created, while private execution state remains restricted to its owning Agent/session.
+14. After the first Commander synchronization, send several more turns in a long conversation and verify later turns use the persisted canonical-history checkpoint: only the tail beginning at the previous mutable user turn is read and replaced, while the older Session JSONL prefix is untouched. Replace/tombstone the canonical log, rename an already-observed actor, or reload a Session whose raw indexes were trimmed and verify the checkpoint fails closed into one full rebuild. A full rebuild first keeps at most the latest five completed user turns under 30K estimated tokens, including framing and omission notes. Before inference the core additionally applies 20% of allocatable turn-start room; current input is separate. Drop oldest whole turns without backfilling around an oversized newest turn. Omitted history remains retrievable through `chat_history`; historical summaries and fact ledgers are not injected. Same-turn tools do not move the frozen history allowance; a smaller resolved model can tighten it, retries/restarts preserve it, and a new user turn recomputes it. Active-process checkpointing retains its separate owner.
+15. Seed a prior Commander/Agent reply with the exact leaked production markers `[Historical group conversation — actor responses]` and `[History retained facts — host-persisted model extraction]`, then send a short follow-up. Canonical history must omit that contaminated reply body while retaining its actor attribution and produced-file metadata. A user message containing the look-alike phrase `[Historical conversation]` must remain verbatim. New projected turns must contain readable actor headers and exact blocker text, but no host marker or whole-record JSON for the model to echo.
+16. Force same-turn compaction after several successful tool calls, then continue with a checkpoint, workspace observations, completed-work ledger, and execution-plan anchor. The model must use those facts to continue without repeating completed calls, while the final user-visible answer contains none of the private context labels, bookkeeping IDs, control instructions, or acknowledgement that such blocks exist. Repeat with a near-limit completed-work ledger and verify the final marked projection remains at or below 6000 characters.
+17. Run a CLI Agent Skill that keeps both a parent process and a descendant alive, then end the Orkas run, close MCP stdin, and cancel the CLI process. Every path must terminate the complete Skill process tree, settle any in-flight tool call without a timeout, emit no unexpected MCP stderr/protocol output, and remove the run-scoped output directory. Repeat with two concurrent Skill calls so shutdown cannot silently clean up only one run; use the Windows native process lane to verify the corresponding task-tree termination.
+18. Directly address an in-process Agent and an external CLI Agent, and have each reply name `@指挥官`, `@commander`, `@用户`, and `@user` in ordinary prose, including inside a Markdown table cell and mid-sentence (2026-10-04 regression: a CLI reply that only described the rule woke Commander twice). Each reply must stay addressed to the user, keep the commander mention visible as display text, and create no Commander task, turn, or bubble. Then verify escalation still works only through its structured paths: an in-process `<handback reason="capability_boundary" />` and a CLI `orkas_handoff_to_commander` call each wake Commander exactly once.
+
+## Planned dispatch (D29)
+
+Planner calls are visible in Orkas logs as `planned dispatch cid=… tasks=… edges=… references=…`, and fallbacks as `planned dispatch fell back to commander` with a reason. Check board rows, the inputs each actor receives, and the log line for every case.
+
+1. Classification. `@A 写初稿` creates one task for A without a planner call. Bare `@A` and `@A @B`, without references or attachments, are rejected as empty: keep the draft and leave history, board tasks and floor unchanged. `先看一下现状 @指挥官 再定计划` goes straight to Commander without a planner call. `帮我翻译这段 @Translator` is planned: Translator gets the translation task and Commander gets nothing (before D29, only Commander received it). Mentions inside code spans, code blocks, or quote lines do not count toward any of these decisions.
+2. Parallel, then merge. `让 @A 和 @B 分别写初稿,最后汇总成一份` starts A and B together. The Commander row shows "Waiting on A and B" and starts only after both are done. Its input contains one `<predecessor-task-result>` block for each draft, and the summary uses both.
+3. Chain. `@A 写一篇介绍,然后 @B 做成 PPT` starts B only after A is done. B's input contains A's reply and produced file paths, and B's `<task-assignment>` says its result goes to the user while A's says it goes to B.
+4. Reference only. `把 @A 的报告发给 @B 改一下` creates a task for B only. A gets no task or turn, and the floor moves to B.
+5. Failure and run anyway. In case 2, stop A while it runs. The Commander row becomes blocked with Run anyway and Cancel. Run anyway starts it with B's result plus a `<missing-predecessor-results>` note that names A as stopped. It must never start silently or be cancelled silently.
+6. Fallback. Make the planner fail (offline, or invalid output in a test build). The whole message goes to Commander with the "could not split this user message" note and the named actors, and no partial agent task is created. A planner clarifying question reaches Commander verbatim.
+7. Stop while planning. On a slow network, send a planned message. Its bubble appears at once and the send button shows Stop while it is being split. Stop leaves the bubble in history and creates no task and no agent turn.
+8. Send order while planning. While a planned message for a single assignee is still being planned, send a follow-up without a mention. The follow-up queues after the planned task and routes to that assignee (the new floor), never to the floor from before the plan.
+9. Composer. None of the three composers (conversation, new chat, project) shows an order toggle. The mention preview lists the named actors only. A planned send to an external CLI Agent keeps the model picker enabled; a direct send to a single external CLI Agent still disables it. Text that carries a routing mention gets no injected recipient prefix.
+10. User's own steps. `@Codex 先把接口写好,我来部署,部署完 @Tester 跑一遍冒烟测试` creates tasks for Codex and Tester only. No task, including a Commander task, is about the deploy, and Tester's part says it follows the deploy. Tester starts when Codex is done, because the board cannot wait for the user.
+11. Choosing and sharing. `@Codex @ClaudeCode 你们俩选一个来做这个重构就行` gives the task to Codex and lists ClaudeCode as a reference. `@Codex @ClaudeCode 这两个方案哪个更好?` gives both the same question in parallel, without a clarifying question.
+12. Restart. Restart Orkas while a planned successor waits or is blocked. The successor is reconciled to cancelled with the rest of the queue, and old single-value dependencies in saved boards still load.
+
+## Waiting agents (D30)
+
+An Agent that stops to ask the user takes a free floor (the composer chip) and keeps the user's reply in its own turn. Check the chip, board rows, the Agent's input and Commander's `<orchestration-resume>` turns for every case.
+
+1. 09-20 replay. Without a mention, ask for one map video plus three map images. Commander dispatches VideoStudio, which stops on its plan with a question. The chip switches to VideoStudio, Commander's dispatch result ends with `<blocked-on-user agent_id="…" />`, and a second dispatch or hand-off to VideoStudio in that turn is refused as waiting for the user's reply. Reply `同意` without a mention: VideoStudio receives it as the user's own message and its plan gate accepts it on the first try. Its board row continues; no new row is created and none is cancelled.
+2. Completion. VideoStudio ends the routed interaction with `<handback reason="completed_handoff" />` after delivering the final video; Commander then resumes exactly once with its `resume` steps and the chip returns to Commander. A question without the open marker (common after a gate refusal) must keep the chip on VideoStudio and must not resume Commander. A gate refusal that asks for the user (`outcome: need_user`) counts as waiting even without the marker. A reply that asks the user and also ends with `<handback />` keeps the chip and the `resume`; Commander resumes only after the real delivery.
+3. Two waiting Agents. Dispatch two interactive Agents that both ask. The first to ask holds the chip; the other's question stays visible and can be answered by mentioning it. When the first finishes, the chip moves to the second. Commander resumes once per Agent, each with its own `resume`.
+4. Hand-off without resume. Hand VideoStudio a single video with no `resume`. Commander is not woken. If VideoStudio hands back after delivery the chip returns to Commander (as with external CLI Agents); without a handback it stays on VideoStudio and a later "字幕再大一点" reaches it directly.
+5. Planned tasks (D29). `@A 做视频 @B 做三张图,最后你合成一页` where A asks to confirm. The chip moves from Commander to A, replying continues A's row, and after A finishes the chip returns to Commander and the merge task starts with both results. A's later replies still carry its split note: A reports only its own video and never combines B's images; only Commander's merge does.
+6. User speaks to Commander meanwhile. While an Agent waits, `@指挥官 换个方向` lets Commander call that Agent again; the waiting row is superseded as before. A Commander turn started by an Agent result or a resume may not call it.
+7. Forms unchanged. An Agent that asks through a form does not take the chip; submitting the form resumes its task and Commander as before, and a plain reply instead of submitting still starts a new row.
+8. Reminder. While an in-process Agent holds the chip because of Commander (a hand-off or its own question), its input starts with "Return control to commander"; when the user picked the Agent, it does not.
+9. Restart. Restart Orkas while an Agent waits. The chip stays with it, a new message to Commander may call it again, and a resume turn may not.
+10. Draft stop. With a model that tries to confirm or export the draft in the turn that rendered it, the refusal ends the turn with the draft shown and one question, the board row stays waiting, the next reply continues that row, and in a D29 request the merge task waits for the final video. A draft from an earlier turn is still confirmed and exported by the reply that approves it.
+11. Managed-route failures. With the Orkas official model, a request rejection, a safety block and a provider-side failure each show their own localized next step, never "The model could not process this request"; a bring-your-own provider still shows its own text, and running out of Orkas credits still offers the purchase entry.
+12. No recap. Ask for a video plus two posters without asking for a summary. Each Agent's delivery is the last word on its part: Commander does not end with a message that lists the delivered files again. Ask for a combined release note instead, and Commander still builds it.
+13. Waiting specialist. When a dispatched VideoStudio stops to ask the user, Commander finishes only independent work in that turn and never renders the video itself.
+
+## 待发送消息编辑与删除
+
+1. 在回复进行中排入一条带附件、引用、Skill、Connector 和接收 Agent 的消息,输入另一份未发送草稿后点击队列“编辑”。主输入框必须还原队列项全部内容,纸飞机应变为保存对勾;输入框中没有垃圾桶,队列项及其“取消”仍可见。
+2. 保持编辑态直到上一条回复自然结束。该队列项不得发送,侧边栏仍显示待发送状态。
+3. 点击保存对勾。队列项应回到原索引,先前草稿及其附件/引用/资源选择全部恢复,之后按 FIFO 自动发送。
+4. 重复进入编辑态,等上一条回复结束后点击该消息队列行的“取消”。当前队列项应立即从持久化队列移除,先前草稿完整恢复;等待超过正常 drain 时间,模型请求中也不得出现被删正文或附件。
+5. 普通输入和编辑状态均不得出现输入框垃圾桶;按 Escape 只取消本次修改并保留原队列项,不能等价为删除。
+
+## Multiple message quotes
+
+1. Quote three different assistant messages in one task. The composer must show all three in selection order; quoting the same message again must not duplicate it.
+2. Remove the middle quote. The first and third quotes must remain, keep their order, and preserve their own produced-file chips.
+3. Switch to another task and quote a message there, then switch back. Each task must restore only its own pending quote collection.
+4. Send multiple quotes both with and without typed text, including drafts containing only `@Agent` or several addressed Agents plus explicit quotes. A single recipient receives the quoted request directly; multiple recipients use the existing planner and dependency rules. The planner receives the snapshots as historical context, and every assigned Agent receives all selected quotes alongside its own task, including after waiting for a predecessor. The persisted user message retains the ordered snapshots. Mentions inside snapshots never add recipients. Deleted or missing source messages must not make a bare recipient sendable; keep destination history and placeholder title unchanged on rejection. Planning failure preserves all quotes in the Commander fallback.
+5. While a reply is streaming, enqueue one set of quotes, then select another set for a later send. Each queued message must keep the quote snapshot visible when that send was clicked.
+6. Repeat the add, individual remove, task-switch, and send checks in the iOS remote-control chat. A long selection must scroll inside the quote preview instead of covering the composer.
+7. Quote a message directly in its current task, then reference it into a different existing or new task. The preview and sent bubble must use the same localized blue “Quoted from” attribution: identify only the sender in the current task, and prefix the sender with the source task title across tasks.
+
+## Project cross-conversation continuity
+
+1. In one task, establish a distinctive result and invoke a fresh ordinary Agent with a vague local reference such as “continue that”. While the fact remains in the host-supplied canonical projection, the Agent should continue directly without `chat_history`. Then extend the task until that exact fact is omitted by the existing compaction/limit boundary and repeat: the Agent must use `chat_history(action=read, scope=current)` and follow `page.mode=before` hints backward before asking the user; it must not use the search action for vague deictic words. Repeat with a distinctive name/id and verify the search action remains available for that anchored case.
+2. The current-scope read/search must stop before the triggering message, exclude later concurrent rows, tombstones, hidden dispatch records, and process/model-only text, and return only public `text` as quoted stale data. Supplying another cid or requesting project/all from an ordinary Agent or CLI must fail.
+3. In project A, record a distinctive decision in task conversation A1. From A2, ask to continue that work without explicitly saying to search history. After current-scope evidence is insufficient, the commander should use same-project `chat_history` search then read actions before asking the user to repeat the decision.
+4. Record matching context in an unprojected task and a stronger keyword match in project B, then repeat the search from project A. Default project history search must return only project A. Unprojected and project B results appear only when all-history scope is explicitly requested; when relevance is effectively tied, same-project results should rank first.
+5. Give A2 a self-contained new request. The commander should answer or route it without an unnecessary history search.
+6. Link an open project task to its execution `origin_cid`, then ask to continue it from another conversation. The project status block should expose that reference and the commander should read the referenced conversation when needed.
+7. Seed many matching messages in one conversation plus matches in two sibling conversations. Search results should include at most two hits per conversation so sibling tasks remain discoverable.
+8. Put an obsolete instruction inside an old message. Retrieval may quote it as evidence but must not execute it as a current instruction; authoritative project Library documents still win factual conflicts.
+9. From project A, read a same-project hit with the default scope; it must succeed. Known unprojected and project B cids must both be rejected by default and become readable only when all-history scope is explicitly requested.
+
+## 附件与文件预览
+
+1. 上传不同类型附件后,待发送区与发送后的消息区都应显示同一套紧凑 chip;图片仅保留小缩略图,视频和音频不在气泡内展开播放器,不因媒体比例产生留白。两处 chip 均可点击进入预览,且文件 tab、预览抽屉和真实文件内容应一致。
+2. PDF、DOCX、图片和文本预览应可打开、关闭、复制、下载或定位,不应出现空白或错文件。
+3. 文件名包含中文、空格、括号、特殊字符时,预览、打开、保存到资料库和 reveal 都应正常。
+4. 删除对话或附件后,预览入口不应继续打开已删除内容。
+5. 打开 VideoStudio 生成的 `contact-sheet.svg`,应进入图片灯箱并显示完整联系表,不应落入“不支持预览”。
+6. 打开大于 2 MB 的 VideoStudio HTML,无论 `data-composition-id/data-width/data-height` 画布标签在文件中的位置,都应按画布尺寸缩放完整显示;HTML 正文不走文本 IPC 大小限制,普通文本全文预览仍保持 2 MB 上限。
+7. 在同一批次选择至少三个“文件名相同、内容不同”的文件:composer 可保持相同的用户可见名称,但磁盘文件名、消息关联和最终内容必须一一对应,任何一个都不得覆盖或错接。
+8. 在已有目标会话中合并同名草稿附件:已有文件保持原内容,草稿文件以唯一名称迁移,消息引用必须使用实际目标名,返回数量只统计本次迁移文件。
+9. 已发送附件再次以相同内容被选择时,本次选择仍应进入待发送池;不发送就重启应用后,待发送 chip 仍应恢复,不能被历史消息引用错误过滤。
+10. 同一条消息同时附加合法文本和损坏图片时,合法文本仍应进入模型上下文,损坏图片应明确显示为跳过;不能把整批误报失败,也不能宣称已读取损坏图片。
+11. 同一条消息附加 6–20 张合法图片时,附件清单必须保留全部文件名和路径,不得把第 6 张以后标成失败。分别使用支持 20 张、只支持 N 张和完全不支持视觉输入的主/备用模型:每个候选请求中的图片块不得超过自身上限;低上限候选仍可按清单路径用 `read_file` 逐张读取,多轮读取时最新读入的图片必须保留,且不得宣称只列出但未看到的图片已处理。
+12. 打开已发送 Markdown 附件,编辑并保存后关闭预览、完整重启再打开:应显示保存后的内容;连续点击保存只写一次,保存失败时草稿和编辑态必须保留。
+13. Markdown 有序列表再次点击应恢复普通文本;代码围栏中的任务样式文本不能禁用围栏外的真实任务复选框。Markdown/纯文本编辑器在 IME 组合输入时均不得拦截 Tab;只读项目文件不能通过控制器切入编辑。
+14. 分别用中文、英文和土耳其语询问“ZIP 文件应上传到哪里”:Commander 应读取
+ `orkas-guide`,明确 ZIP 只能在本轮 Commander 中作为 Skill 包导入器的不透明路径附件,
+ 不能作为普通模型上下文或全局/项目资料库来源;普通压缩包应先在 Orkas 外解压后添加
+ 受支持文件,不得虚构“设置 > Agents/Skills 导入 ZIP”入口。
+15. 询问如何添加 ChatGPT/OpenAI 模型时,应引导至 **Account settings > Models** 的官方
+ 模型或 OpenAI-compatible 配置;不得把 connector 或自定义 Agent 描述成模型提供方。
+16. 在消息内联和文件查看器中分别打开自包含 HTML:内联 JavaScript、内联样式、
+ `data:`/`blob:` 资源和经校验的本地 `chat-media:` 图片应正常工作;远程脚本、
+ 样式、图片、字体、媒体、iframe、`fetch`/XHR/WebSocket 及脚本驱动的 HTTP(S)
+ 框架导航均不得发出网络请求。PDF、图片、音视频及 `chat-app://` Artifact 不受该
+ HTML 响应策略影响。
+17. 页面确需第三方 JavaScript 时,生成或打包流程必须先显式下载、校验并冻结为内联
+ 或本地资源;预览运行时不得替页面自动下载、改写或信任远程依赖。未冻结的依赖可
+ 显示降级结果,但不能绕过离线策略。
+18. 打开至少三页的 PPTX:首次打开及关闭后重开都应只选中第 1 页;缓慢滚动到第 2 页
+ 位于主预览区中心时,只应选中第 2 页并显示 `2 / 3`,继续到底部选中第 3 页,反向
+ 滚动时按同一规则切回。使用一个第 1、2 页同时超过 30% 可见的窗口作为负控,选中
+ 页不得再由可见项回调顺序决定。
+19. 打开 PDF 后分别覆盖正常加载、超过 5 秒才加载、iframe 失败、加载前关闭和加载后关闭;
+ 日志应记录匿名预览序号、粗粒度来源、阶段、耗时和最终状态。协议侧分别覆盖完整请求、
+ Range 请求、缓存重验证、越界 Range 和畸形 Range,状态码、响应字节数、响应准备耗时、
+ 实际读取字节数和流耗时应可区分;所有这些日志均不得包含文件名、绝对路径、URL、
+ 会话/项目标识或原始错误文本。
+20. 分别打开大图片、PDF、HTML、Office、视频、音频、Markdown 和纯文本附件,并人为延迟
+ 资源 ready 或读取 IPC:预览浮层应立即显示本地化 loading,`aria-busy` 在 ready 前保持
+ 为 true,成功或失败后结束;切换文件或关闭后旧资源事件不得清除新预览的 loading。
+21. 分别让 HTML 的布局探测和 iframe 加载成为慢阶段:两者应并行启动,内容只在两阶段均
+ 完成后显示,固定画布只导航一次并继续按宽度缩放。超过 5 秒时日志应能匿名区分慢在布局
+ 还是 iframe,关闭时记录最终状态,且不得包含文件名、路径、URL、会话/项目标识或原始错误。
+22. 打开约 100 KB 、正文很长且包含多个同步外链 CSS/JS 标签的 HTML:布局推断只应扫描
+ `<style>` 内容,不得在无大括号的正文上发生二次回溯,预览应在 5 秒内结束 loading。HTML 仍保持
+ 无尺寸上限的流式加载、离线 CSP 和 iframe sandbox。
+
+## 文件产物操作
+
+1. Markdown、TXT、CSV、JSON、YAML、PDF、现代 Office、常见位图、视频和音频产物应显示“添加到对话”;HTML、CSS、JS、代码、SVG、ZIP、旧版 Office、字体和未知格式不应显示该操作。
+2. 文本/代码、HTML、PDF、现代 Office 和常见位图应显示“添加到资料库”;视频仅在项目对话中显示并导入项目资料库,普通对话中不显示;音频、SVG、ZIP、字体和未知格式不显示。
+3. 支持的 UTF-8 文本/代码、Markdown、HTML、浏览器可直接预览的图片/音视频、PDF,以及可在客户端转换为匿名只读 HTML 资源的现代 Office 文件应显示“分享”。除 Office 外都上传原始资源;公开页必须把 Markdown 安全渲染为标题、强调、引用、列表、链接、代码块和表格,不能显示 `#`、`**` 等源码格式符,文本/代码保持字面内容。Markdown、文本、HTML 和 Office iframe 必须固定为内容区宽度并按完整内容自动增高,只允许外层分享页纵向滚动。ZIP、旧版 Office、HEIC、MKV、字体、WASM、未知格式和无扩展名文件不显示。单文件上限 10 MiB、单次文件总量上限 30 MiB;分享页不得显示文件名、大小、MIME 或下载入口。
+4. 只有 HTML/HTM、CSS、JS/MJS 应用源文件及含 HTML 入口的应用目录显示“保存为应用”;图片、数据、音视频、字体、WASM、模型等资源可随应用复制,但自身不显示该操作。
+5. 所有真实文件和文件夹均可“打开文件夹”和“删除”;删除后文件 tab、产物列表和预览入口同步失效。
+6. 使用附件选择器分别选择 MP3、WAV、OGG、OPUS、M4A、AAC、FLAC,均应进入上传流程并遵守音频大小限制。
+
+## 消息操作
+
+点击气泡“分享”直接打开当前消息的分享弹窗。点击“选择”进入多选并默认选中当前消息;多选栏位于输入框上方,两者保持可见且不重叠。勾选使用标准 SVG 对勾,支持全选和取消全选;长对话须加载较早消息后才完成全选,加载失败保留原选择并可重试,取消或切换会话后不得晚到覆盖选择。未选择消息时分享和引用不可用;取消分享弹窗保留选择,分享成功后退出多选。引用目标弹窗标题下方间距紧凑,任务列表包含当前会话并显示“本任务”标签。
+
+1. 点击回复气泡下方的“资料库”并完成保存后,应显示成功 toast;模拟写入失败时应显示错误 toast。操作栏不再提供三点菜单,反馈按钮位于末尾,其余按钮保持原顺序;窄窗口下按钮应换行且保持可点击。
+2. 打开“引用到其他任务”目标选择器或回复反馈弹窗后点击遮罩空白处,弹窗均不应关闭;各自原有的关闭或取消按钮和 Esc 仍应生效。
+3. 打开分享、引用目标、回复反馈等弹窗,标题统一为 16px/600,正文为 14px/1.6,底部操作按钮为 13px、最小高度 36px;不新增或删减原有关闭/取消按钮。
+4. 从消息操作中分别执行编辑副本、引用和保存到资料库:编辑结果按钮只应把内容添加到输入框,不得暗示已经发送;引用按钮只应把消息加入引用,生成的引用正文继续保留具体文件路径,但不得显示内部工具名;气泡按钮及提示文字为“资料库”,点击后仍打开保存位置选择器;选择器标题和成功提示继续表达保存结果,不改变保存行为。
+5. 在任务消息中选中文字并打开右键菜单:“复制”和“编辑副本”应使用一致的纯文字菜单样式,任一项前都不显示单独图标;“编辑副本”打开的抽屉使用同名标题且不修改原消息,两项的点击行为保持不变。
+6. 打开普通任务和项目任务,确认用户消息和成功回复的底部操作默认不可见;鼠标移入对应整条消息后操作出现并可点击,移出后隐藏。用 Tab 聚焦操作按钮时操作保持可见;失败或中断回复的恢复操作始终可用;新建 Agent、Skill 和文件产物等结果 chip 始终可见。无悬停能力的触控设备保持操作可用。
+
+## Streaming 与中断
+
+1. 真实模型回复过程中,消息应稳定追加,用户滚动查看历史时不应被强制拉回底部;从新任务页或项目页直接创建、因 `skipLoad` 未经过历史加载的任务也必须响应消息区滚轮/触摸/滚动条,立即解除发送时置顶占位并允许继续查看下方内容。
+2. 点击停止后,当前回复停止追加,输入框恢复可用,中断气泡应显示“重试”;刷新后不应出现重复半截消息,重试仍可恢复原任务。
+3. 网络断开、模型失败或应用重启后,对话应进入可恢复状态,不应长期显示空气泡 loading。
+4. 继续对话时,历史消息顺序和附件引用应保持正确。
+5. 让首选模型返回 401 或“OAuth 凭证已失效”,同时配置可用的备用模型:对于用户配置的模型,过程面板应明确提示凭证失效且正在切换备用模型,不应显示为“网络异常”或对同一凭证重试三次;备用模型成功后任务应继续并正常完成。同一任务后续工具轮次不应再次尝试已失效凭证。官方模型内部的凭证/路由切换不得在 prod 过程面板显示,只在 dev 显示并带 `[DEV]` 标记;服务端明确将 Orkas-1.5 Pro 降级为 Orkas-1.5 时,prod 和 dev 均应提示用户实际由 Orkas-1.5 处理。
+6. 让首选模型只返回 stream preamble(或完全静默)但始终不产生首个文本/工具事件,同时配置可用备用模型:达到首事件窗口后应切换备用模型;用户配置模型或官方公开模型发生变化时应提示“未及时开始响应”,同一官方公开模型内的切换则沿用上一条的 prod/dev 可见性规则。首选模型在同一任务后续轮次不再尝试,且不得出现上层整轮重试。若首选模型已经产生文本或工具事件后才中断,则不得切换备用模型或重复执行工具。
+7. 分别在普通对话、Agent 编辑和 Skill 编辑中运行包含工具调用的任务后点击停止:每次点击只产生一条 `click_task_stop`,包含非负 `duration_ms`、`tool_call_count`、Agent/Skill/消息/队列/附件计数和 `has_output`;切换页面、启动新任务或代码内部清理触发的 abort 不得上报该点击事件。
+8. 让模型在已经返回部分文本后以 undici `terminated`、`fetch failed` 或缺少 `finish_reason` 中断:已返回内容必须保留,终态只显示简洁的模型连接提示,不得暴露原始传输错误;失败口径应为 `provider_network / model_text`。显式请求超时仍归为 `provider_timeout`,用户停止不得误报成网络失败。
+9. 分别让模型在已流式返回正文并生成可见产物后触发积分不足和网络中断:普通对话、Agent 编辑与 Skill 编辑都必须保留已经产生的可见正文、过程信息和产物入口,在其后附加失败提示与重试入口;刷新或重启后结果一致。阻塞式兼容调用的 `ok` 仍为 `false`,但 `text` 必须携带已收到的部分正文;任何未完成的 Agent/Skill 结构化变更不得因保留部分文本而被当作成功执行。
+
+## 长任务状态与智能重试
+
+1. 运行普通长任务:消息气泡内只展示精简的当前活动文案和累计时间,不展示根据文案推断的工具数、百分比、ETA 或步骤计数。
+2. 让模型触发结构化 retry 事件:侧边栏和任务标题栏不得新增状态文字或状态分类;侧边栏只沿用原有执行中绿点,气泡过程信息可以显示正在重试。供应商内部重试与 Agent 外层恢复必须在同一任务内合并为单调递增的可见次数,不能出现 `1、2、3、1、2` 或 `1、2、3、2`;该展示归一化不得改变两层各自的重试预算、退避或中止逻辑。仅在进程文案中出现“重试”不得改变执行逻辑。
+3. 分别产生未提交表单、配置/依赖阻断、模型最终失败、用户停止和后台成功:结果应由消息内容、表单和失败/停止控件明确表达;侧边栏和任务标题栏不得额外推导“待处理 / 受阻 / 失败 / 已停止 / 已完成”状态。
+4. 在工具 A 已成功、执行计划或产物已保存、随后模型最终失败的回复上点击“重试”:新用户气泡应只显示精简的“继续”,主进程应将请求路由回原 actor 的同一持久会话,注入只含计数和工具名的恢复证据,读取执行计划、已完成工作和工具结果后只执行剩余工具 B,不得再次执行工具 A。退出并重新启动应用后重复该操作,结果应相同。若某个外部工具只有 start、没有匹配的 end/result,恢复证据必须把它标为不确定操作并要求先核验;已有匹配终态的工具不得误报为不确定。
+5. 在配置预检阶段失败、且没有可恢复状态的回复上点击“重试”:应自动重放持久化的原始模型请求、附件、选择和引用,并保持原 actor 路由;用户不需要手动选择“继续”或“重新开始”。
+6. 对外部付费、破坏性或非幂等操作制造“请求已发出但结果不确定”的中断:续跑必须先核验外部状态,不得盲目重复;现有确认和权限门禁仍必须生效。
+7. 在失败回复之后再完成至少一次新的用户/actor 回合,然后点击旧失败气泡的“重试”:不得把最新回合的持久状态错接到旧任务;应使用旧气泡对应的权威原始请求重新开始。
+8. 长任务本身没有总墙钟截止时间;让上下文压缩请求只建立连接但不返回正文,随后点击停止:压缩调用必须收到同一任务的取消信号并关闭连接,界面进入已停止状态,之后不得出现晚到回复或重放已完成工具。
+9. 让模型在已产出内容后连接中断,再让 AgentRunner 恢复:首次 provider 调用可使用候选级网络重试,进入 AgentRunner 恢复轮次后每个候选只尝试一次;SDK 不得再做不可见重试,用户停止也必须立即结束 retry-after 等待。
+10. 建立含稳定 step id 的计划后,让模型把完整、原文未变的计划数组误标为 `action=set_status`,同时不传 `step_id` 与顶层 `status`:工具应通过原有完整计划约束安全执行 update,不额外消耗一个失败工具循环。真正不带完整计划的 `set_status` 仍必须要求有效 `step_id` 与 `status`。
+11. 当模型把工具返回的稳定步骤 ID `1` 回传为界面化别名 `step_1` 时,`set_status` 应归一化为整数并一次成功;`step_0`、`step_1_extra`、`phase_1` 等相似字符串仍必须拒绝,且不得改变计划状态。
+12. 让外接 Codex CLI 先长时间流式 reasoning、再执行长命令并发生网络重试:活动栏应立即显示本地化“思考”,有 `summaryTextDelta`/`summaryPartAdded` 时同步显示有界摘要;每个完成的 reasoning item 在过程信息中只保留一条摘要(无摘要时退回“思考”),原始 `textDelta`、`item.text` 和命令增量不得进入界面或历史;30 秒心跳与摘要分片不得堆积重复过程行。任务运行中切换到其他任务再切回时,应补回有界的非正文过程事件,retry/fallback 等状态不可静默丢失。
+13. 触发历史对话整理和当前任务进展整理,并检查过程信息与耗时明细:用户可见文案应描述“当前任务进展”和“整理对话”,不得显示实现层的“当前过程”或“上下文耗时”;各界面语言表达的含义应一致。
+
+## 外部产品事实核验
+
+1. 不使用“最新”等显式时效词,询问外部产品的精确安装/更新命令、CLI/包名、套餐/账号可用性或模型/提供方兼容性:Commander 与 in-process Agent 都应默认将这些操作性事实视为易变信息,先用官方文档或 release 核验;不得仅凭训练记忆编造包名、命令或支持范围。当前主来源已经在上下文中时可以直接引用,不应重复搜索。普通、稳定的概念性产品能力问答不因此强制搜索;出现显式时效词时仍遵循通用时效搜索规则。
+
+## 内容安全策略边界
+
+Orkas 不在 Commander、内置 in-process Agent 或 CLI Agent 的 prompt 中追加自定义的
+通用内容审查或拒绝规则,内容安全依赖用户所选模型及其提供方的内建机制。产品必须
+保留模型或提供方返回的拒绝与安全错误,不得宣称或尝试绕过它们;工具权限、数据安全
+和平台安全边界不受此决定影响。
+
+1. 三条 Agent 运行链路发送给模型的 prompt 均不得包含仓库自定义的 `## Sexual safety boundary` 块。
+ Prompt contract 还会扫描实际运行时 prompt 源,阻止换标题或内联方式重新引入通用
+ 内容审核规则,并同时固定工具执行授权、凭证、破坏性操作和不可信项目上下文边界。
+2. 模型正常返回拒答时,真实 Electron E2E 必须原样显示、只请求一次、持久化后重启
+ 仍可见;不得改写成成功内容。
+3. 提供方返回安全错误时,单测必须覆盖 message-only、结构化 code、嵌套 error/cause、
+ stream、complete 和服务端替换重试黑名单的负向组合;任何组合都不得重试、轮换或
+ 写入凭证冷却。
+4. 不以 Orkas benchmark 判断具体内容应否拒绝,因为该策略归所选 provider;涉及模型
+ 的 Commander benchmark 仍评测 Orkas 自有的工具权限、数据安全、执行真实性与恢复
+ 行为。
+
+## Artifact 与产物
+
+1. 真实生成 HTML/JS/CSS Artifact 后,卡片预览、浮窗打开、保存为应用、文件 tab 入口都应可用。
+2. Artifact 包含相对资源、图片、音频或 JSON 时,浮窗打开后资源应正确加载。
+3. 多个 Artifact 连续生成时,卡片归属、版本、标题和三点菜单不应串线。
+4. Artifact 内容较大时,页面不应明显卡顿,打开/关闭预览不应影响主对话 streaming。
+
+## Produced-file footer
+
+1. Generate a Markdown source, image assets, and a PDF or Office export in one turn. Only the exported deliverable should appear in the bubble footer; every supporting file should remain available in the Files tab.
+2. Generate a video from HTML, still frames, and audio. The footer should show the rendered video and subtitle, not the composition sources or frame assets.
+3. Generate only one ambiguous source deliverable such as Markdown, CSV, JSON, or a script. It should remain visible rather than being incorrectly hidden.
+4. Process-directory files and technical outputs such as cache files, previews, thumbnails, manifests, and logs should not appear in the bubble footer.
+5. Reload history and finish a live streaming turn. Both paths should place the same full-width file rows at the bottom inside the assistant bubble, and each row should open the existing file preview.
+6. Produce a source file and a higher-ranked export, then declare only the source through `publish_outputs`. The footer must follow the explicit declaration instead of extension ranking.
+7. Try to publish a pre-existing file that was not written in the current turn. The tool must reject it and the file must not enter the message footer.
+8. Generate a final file inside a normally skipped cache directory and append its path to `$ORKAS_OUTPUT_MANIFEST`. The file must become a tracked candidate, while the manifest itself must be removed and never displayed.
+9. Create ambiguous working files such as `script.md` and `shotlist.json`, then call `publish_outputs` with an empty `paths` list. No file footer should appear, while both files remain available in the Files tab.
+10. Use `dispatch_to` for a named specialist that creates files before the commander continues; `run_worker` remains anonymous-only and rejects a legacy `to`. The intermediate agent bubble must not show those files, but the commander must receive their paths and the Files tab must retain them. Repeat with `hand_off_to`: files from that final-delivery agent should follow the normal explicit declaration or terminal-output heuristic and remain visible in its bubble.
+11. Complete an interactive-agent turn with `<plan-interaction status="open" />` after writing review-stage files. Those files must remain in the Files tab but must not appear in the bubble footer or run produced-output finalization. A later closed/final turn should still finalize and show its selected deliverables.
+12. Produce at least four deliverables in one assistant turn. The footer should show two full file rows and half of the third row at most, and all remaining rows must be reachable by vertical scrolling.
+13. Hover over a footer with one or two files and scroll the mouse wheel. The conversation history must scroll normally; with three or more files, the footer should scroll first and then pass scrolling to the conversation history at its boundaries.
+
+## Chat video playback
+
+1. Send a video attachment and render a local video from Markdown (`[video](chat-media://local/...)`). In both bubble players, clicking the video picture or its letterboxed area should alternate between play and pause.
+2. Open either bubble video in the floating player. Clicking the video picture or any surrounding black area should alternate between play and pause.
+3. In all three players, drag the progress bar, change volume, and use the native play button in the bottom control strip. These controls must keep their native behavior and must not trigger a second play/pause toggle. The bubble player's top-right floating-player button must still open the floating player instead of toggling the inline video.
+
+## 日志与安全
+
+1. 日志应能串起 send、stream start、tool/artifact/file write、stream end 或 failure。
+2. 日志不能输出完整附件路径、完整文件内容、模型 key、Authorization header、Cookie、用户邮箱或手机号。
+3. 模型回复和示例不得回显工具结果中的 token、账号/用户/session/workspace 标识符、
+ connector grant 细节、联系方式或私有本地路径;除非用户明确请求且操作确需该精确值,
+ 否则一律使用描述性占位符。
+4. PDF 预览诊断应能按时间串起 renderer 的 open/load/slow/failure/close 与主进程的
+ 200/206/304/416、Range 分类、总字节/响应字节和准备耗时;iframe `load` 只表示
+ PDFium 接受了文档,不得在日志或结论中误报为所有页面已完成绘制。
+
+## 任务删除的原子性
+
+1. 删除单个任务前必须完成严格、非空的可恢复快照;归档失败时任务与附件保持可见。
+2. “删除全部”必须以开始时的任务集合为事务边界;返回删除数量少于原集合时不得报告
+ 部分成功,应恢复并核对项目任务和无项目任务全部重新可见。
+3. 自动恢复验证成功后返回 `cascade_failed` 并清理内部快照;验证不完整时返回
+ `cascade_recovery_incomplete` 并保留快照供重试。
+
+## 任务失败只来自明确执行错误(2026-08-20)
+
+1. 模型正文不再携带成功/失败结果标记,宿主不得从模型自述推导任务状态。
+2. 本地媒体链接指向不存在的文件时,协议层仍可在实际加载时记录 `not_found`,但不得给消息写入结构化失败字段,也不得把任务或会话改判为失败。
+3. `failed` 只用于 Runner、模型流、CLI、工具或宿主操作明确返回且未恢复的执行错误;取消和等待输入分别保持 `cancelled`、`waiting_input`。
+4. `Produced files: [...]` 页脚仍归宿主独占并从结构化 `produced` 生成;模型手写的仿冒页脚继续剥离,但不作为任务失败判据。
+
+## Tool Surface 会话兼容
+
+1. Commander scoped 会话加载分组后刷新、重启和上下文压缩,后续请求仍应带相同激活面。
+2. Named Agent 即使旧会话没有 sidecar、保存了 `legacy_all` 或动态分组,也必须只使用当前 `tool_list`;缺失字段使用固定兼容能力集。
+3. 分组目录版本变化后 Commander 按当前目录展开;Agent 不能从历史消息、sidecar 或被压缩的工具结果恢复旧 Schema 快照。
diff --git a/docs/test/deep-research-regression.md b/docs/test/deep-research-regression.md
new file mode 100644
index 00000000..8be4b1fa
--- /dev/null
+++ b/docs/test/deep-research-regression.md
@@ -0,0 +1,243 @@
+# DeepResearcher 智能体人工回归 Case
+
+## 范围边界
+
+本文件覆盖内置 **DeepResearcher** 智能体(agent id `78900d8758bc`,分类 data)的端到端表现:范围 → 持久计划 → 结构化取证 → 脚本压缩 → claim 核验 → 可审计交付,以及底层 4 个确定性引擎脚本组成的共享 skill(id `ee99fbb42964`,name `deep-research`)——`caps`(子问题封顶 + 每问抓取预算 + depth 守卫 + caller-reported step 成本判停)、`academic`(并发 arXiv/OpenAlex/Crossref/Semantic Scholar/PubMed 学术检索)、`compress`(多语分块/去重/词面相关性排序/硬预算)、`citations`(来源/原句/DOI + 引用绑定 + 编号参考文献)。重点验证**差异化护栏**:禁造 quote/DOI、真实但无关的 quote 不得支撑 claim、中文压缩不越预算、幽灵源标记、无来源时 abstain、按结论置信度与矛盾如实交代。
+
+不在本文件重复验证:智能体库通用展示/筛选/同步(见 `agents-regression.md`)、计划拆分与步骤分发的通用编排(见 `agent-orchestration-regression.md`)、连接器授权(见 `connectors-regression.md`)。引擎 skill 的纯逻辑与四件互通由 `PC/resources/builtin/marketplace/skills/ee99fbb42964/test/`(`pytest`,含 `test_pipeline.py` 确定性端到端)覆盖,本文件不重复其单测断言。
+
+## 自动化覆盖
+
+Production quality evidence identifies attached outputs from persisted host
+delivery records and places their contents before working files. Earlier drafts
+and verification attempts remain available as execution evidence, explicitly
+distinguished from attachments; filenames never establish delivery status.
+
+
+the separately authorized model canary 对全部已登记研究决策场景分别维护
+完整正例和关键词齐全但结论相反的 negative control,确保 deterministic scorer
+不仅拒绝空输出,也能拒绝重跑已完成取证、重置预算、丢弃部分成功结果、带着引用
+错误交付、无来源编造、把旧来源当最新、给出剂量、越界启动网络研究,以及已知
+独立 URL 的 `4+1+1+1` 串行尾巴等行为。
+真实模型效果仍由统一 benchmark 运行并按 rubric 独立评审;该契约测试不替代动态
+效果比较。
+
+Production Regression 另有 `research-independent-fetch-batch` 执行态 case:用户直接
+给出 7 个互不依赖的官方仓库 URL,只要求第一轮抓取。发布门禁要求恰好 7 次
+`web_fetch` 在同一并发批次启动、0 次 `web_search`,并在暂停前生成
+`fetch_ledger.jsonl`。这种显式 fetch-only checkpoint 以 `caps_plan.json` 为唯一计划,
+不调用 `manage_execution_plan`、不发布产物,并在 10 个 tool loop 内暂停;证据提取、
+引用核验和报告生成留到用户要求继续后再做。trace 只保留并发宽度,不存 URL 或
+原始 call id,主观 judge 也会收到这个脱敏宽度,避免把真实并发误判成未证明。
+
+`research-resume-durable-ledger` 覆盖固定来源断点续研:运行前先对 fixture 声明的
+两个官方 URL 做真实可达性预检;预检报告只保留服务序号、HTTP 状态或低基数失败类,
+不落 URL、响应正文或 provider 错误文本。进入模型后必须把两个 pending URL 放在同一
+并发批次,每个网络尝试无论成功、超时或 provider 失败都立即消耗 `max_new_network_calls`
+和对应子问题的一次额度,同轮不得重试。每个成功/失败都追加到 fetch ledger;失败来源
+不生成 evidence row,而是在可见交接中标为 `Not verified`。若追加发生 `E_STALE`,只重读
+目标 ledger 合并一次,不得重新抓取。生产 contract 同时要求可见交接给出此前 2 + 本轮
+2 = 累计 4/4 的尝试账,并直接概括已建立的义务、官方 SME 支持措施及来源/引用,不得只
+丢一个报告链接。这样可区分“运行前外部依赖不可用”的基础设施失败和“预检通过后模型
+重复调用或隐藏缺口”的行为失败。
+
+生产 oracle 还直接读取两个 JSONL 成品的字节,而不只相信模型 trace:每条追加记录必须
+是一行 JSON object 加一个尾随换行,禁止用前导换行制造空记录;解析失败、内部空行、旧
+fetch/evidence 记录丢失或 pending 来源未各追加一次都会失败。可见交接必须保留英文算式
+`prior 2 + new 2 = cumulative 4/4 attempted network calls`,避免“4 entries”把历史记录数和
+网络尝试数混为一谈。
+
+完整交付由 `research-compact-landscape-efficient-delivery` 执行态 case 保护:以“调研
+适合普通用户的 AI 桌面应用,比较主要用途、系统支持、安装与上手难度、模型能力、
+隐私、本地运行和价格,并根据不同需求给出选择建议”为自然输入,在隔离工作区完成
+发现、官方来源抓取、证据核验、`RESEARCH-<topic>.md` 生成和一次发布。独立门禁要求:
+仅一次发现搜索;最多两个抓取批次;成功抓取总量 1–8,首批最多 5 个且默认首批后
+停止;只有会改变候选资格、系统兼容性、推荐顺序或适用人群的缺口才允许第二批,且
+第二批最多 3 个 URL;允许只有一两个合格官方来源时交付明确标注的部分比较;除初始 Skill 加载外不再调用 `read_file`,也不使用 `read_files`
+或 `stat_file` 做新任务中的重复检查;报告包含完整十一列对比表、
+`Evidence used` 和明确来源/缺口边界,且总长度不超过 10,000 字符;无硬性收敛停止;
+总 tool loop 不超过 16。
+该 case 刻意允许多个单步 `manage_execution_plan` 调用,只约束用户结果和模型轮次,
+避免把可选 `set_statuses` 误变成强制批量协议。其 negative control 会让历史上的
+23-loop、重复 ledger/report 检查和串行首批抓取分别触发独立失败信号。
+
+候选数量不是 production-outcome 的硬阈值。若发现搜索只返回一或两个合格官方
+来源,Agent 必须先冻结实际发现的集合、在一个响应内抓取全部来源,并将结果标成
+有限范围或部分比较;不得返回零抓取,也不得把单个来源当作 bootstrap 后再追加
+候选批次。只有搜索返回零个合格官方来源时,才允许 source-unavailable advisory
+fallback。静态 prompt contract 同时拒绝旧的“少于三个就不抓取”文案。
+
+2026-08-08 的完整交付实跑从上一正式轮的 54.0 分、433.06 秒、22 loop、
+953,596 token、CNY 19.7634,改善到 60.8 分、338.84 秒、13 loop、561,906 token、
+CNY 12.1343;压缩从 1 次降为 0,且报告完整并只发布一次。该轮仍为 fail:抓取实际
+是 `1 + 4 + 4` 三批,违反最多两批的关键门禁。随后 1.0.44 的“少于三个就零抓取”
+在完整 E2E 中过度收敛为零次抓取;1.0.45 已改成冻结并抓取实际发现的一至五个来源,
+只有零来源才降级。随后 `1.0.46` / `1.0.20` 又把 compact path 从 GitHub 仓库调研
+泛化为普通产品调研:发现不再强制域名,每个候选先抓一个最佳官方主来源,仓库只在
+开源许可或项目活跃度确实影响结论时使用,对比表改为安装、模型能力、隐私、本地
+运行和价格等普通用户维度。完整记录见
+the separately authorized model canary。
+
+随后 `1.0.47` / `1.0.21` 收紧 compact 收敛和证据门禁:第二批最多 3 个且总量
+最多 8 个;报告最多 10,000 字符,不得逐候选复述表格;每个事实型表格字段必须通过
+`field_claims` 绑定同候选来源的 `claims[].id`。当前脚本只对缺失映射、
+跨候选来源和未匹配引文做客观降级;语义错绑由 Agent 核验,具体合同见下文。
+
+该普通用户 case 的最新 GPT-5.5 生产实跑在隔离快照完成:一次搜索、`5 + 5` 两个
+并发抓取批次、9 loop、299.79 秒、393,991 token、CNY 8.1195;当时的 deterministic
+production acceptance 通过,独立 Terra judge 给 58.8/100,因此总体仍 fail。当前
+`1.0.47` 门禁会因第二批宽度为 5、总抓取为 10、报告超过 10,000 字符而拒绝该 trace,
+尚未再次调用付费模型。trace
+中 7 个 URL 被标为未发现、3 个被拒绝,但当前分类器也会拒绝合法产品官网根地址,
+且无法归因从首批抓取页面学到的二级 URL,因此暂不把这些标签升级为该 case 的硬
+门禁;第二批虽满足数量门禁但没有做到最小 gap convergence,报告生成的两个模型
+调用分别耗时 108.4 和 83.2 秒。
+
+通用计划工具另由 core-agent 单测验证 `set_statuses`:整批先校验、一次 revision
+提交,重复/不存在的 step、非法 status 或多个 `in_progress` 均原子失败;原有
+`set_status` 继续有效。进展门禁的 problem-discovery case 还验证空文件创建与内容
+哈希不变的更新不能伪造进展,而非空内容变更仍可正常重置停滞窗口。
+
+2026-08-08 的 fetch-only checkpoint `gpt-5.5` 实跑结果为 **90.8/100**,全部对应
+production acceptance 通过:7 个 fetch 均为并发宽度 7,0 搜索、0 进度计划、0 发布,7 个 tool
+loop,耗时 89.84 秒。API 等价端到端成本按官网价与固定汇率 7 为 **CNY 4.5818**。
+相较同日第一轮 batching 实现的 260.13 秒、16 loop、CNY 11.4010,分别下降
+65.5%、56.3%、59.8%;完整审计见
+`Common/docs/evaluation/deep_researcher_agent_evaluation.md`。
+
+## 准备
+
+1. 确认 DeepResearcher agent(`78900d8758bc`)已装入当前账号(dev 经内置 marketplace seeding / dev 安装;正式经 marketplace `default_install`);共享 skill `ee99fbb42964` 已同步到平台安装目录,`run-skill.cjs deep-research <script>` 能解析到它。
+2. 准备一个可研究的开放式问题(如「本地优先 AI agent 的隐私权衡与最新证据」);如验证材料输入,准备 1–2 份本地文件或链接作为第一手来源。
+3. 网络确认:`academic` 需外网访问学术 API;本机若用 fake-ip 代理(Clash/Surge),确认已配 `HTTP_PROXY`/`HTTPS_PROXY`(否则直连解析到 198.18/15,学术检索会失败——属预期,应进 `errors` 而非崩溃)。
+4. 记录所用模型与起始时间,便于成本/延迟与失败模式归因。
+
+## frame — 框定与计划封顶(caps.plan)
+
+1. `@DeepResearcher` 给一个研究问题(或填启动表单 `task`),agent 应先复述问题、确认范围/深度/必用来源;材料附件应作为一等来源纳入。
+2. 应把问题拆成 3–8 个具体子问题,并调用 `deep-research caps -- --op plan` 去重/裁剪、取得 `fetch_budget_per_subquestion`;重复或超额子问题应被裁掉且在 `dropped` 中如实回报(不静默丢弃)。
+3. 递归研究场景下 `depth` 超过上限时,`plan` 返回 `allowed:false / max_depth_exceeded`,agent 应停止下探、用已有材料综合,而非无限展开。
+
+## 取证 — 网络 + 学术(academic),带预算与判停(caps.account)
+
+1. 每个子问题应先 `web_search` 再 `web_fetch` 取回真实正文;来源应记为 `{id,url,title,date,doi?,text}`,**绝不引用未抓取的来源**。
+2. 学术/论文类子问题应额外调用 `deep-research academic -- --op search`,并发从 arXiv/OpenAlex/Crossref/Semantic Scholar/PubMed 拉取带 DOI/PMID + 摘要的论文;其 `results` 已是来源形状可直接用,合并顺序不受 provider 返回先后影响。
+3. **单源韧性**:某学术源限流(429)/不可用(503)/超时时,应仅记入 `errors` 并继续用其余源返回的结果,不应整体失败或崩溃。
+4. 抓取应受 `fetch_budget_per_subquestion` 约束;应周期性以运行中的 `{steps:[...]}` 台账调 `caps -- --op account`,当返回 `stop:true` 时停止取证、用已有材料综合,并如实说明采样了什么。注意 `caps.account` 核算调用方上报事件,不拦截原生网络工具;这是必须遵守的 Agent ceiling,不得把它表述成平台级配额。
+5. `academic` 只连固定 https 主机白名单(export.arxiv.org / api.openalex.org / api.crossref.org / api.semanticscholar.org / eutils.ncbi.nlm.nih.gov),并遵循 `HTTP(S)_PROXY`;非白名单主机 / 非 https / 重定向到白名单外应被拒绝,单个响应超过 5 MB 应显式报错而不是静默截断后继续解析。
+6. 当一组官方 URL 已知且彼此独立时,模型应在一次 tool-use response 中发出全部
+ `web_fetch`,让运行时并发执行;单批最多 8 个。只有后续 URL 或其必要性确实依赖
+ 前一个结果时才允许另起一轮,不能把已知 sibling URL 退化为逐个模型回合。
+7. 首批结果落入证据台账后,应一次审计完整对比矩阵中的决策缺口,把所有已知且
+ 会改变推荐的官方 URL 合并为第二个、默认也是最后一个批次。第三批只允许由第二
+ 批新揭示 URL 和必要性的真实依赖;否则标 `Not verified` 并进入核验。
+8. 同一活动运行中,刚写入且未被外部修改的 plan/ledger/command input 保留在模型
+ 工作状态里,不应立即重复读取。仅在任务开始、持久续跑、实际上下文压缩、外部
+ 修改或精确字节验证时重读。已确定的脚本输入写入与确定性命令可在同一响应按序
+ 发出;独立的报告片段也应在同一响应写入,最后只读一次成品验证,无需额外 stat。
+9. 固定 pending-source 恢复的上限按**尝试**计,不按成功计。已知 sibling URL 必须一批
+ 并发;一次失败即占用该 URL 和子问题额度,同轮不得以“瞬态错误”为由再试。写 ledger
+ 遇到 `E_STALE` 只能修复本地追加,不能借机重启网络轮次。
+
+## 压缩 — 长来源去噪(compress)
+
+1. 某子问题抓回的正文很长时,应调 `deep-research compress`(传 `{query:子问题, sources:[...]}`),直接使用 `data.kept`,并确保最终证据不超过 `budget_chars`。该链路不依赖 Agent 专属宿主工具。
+2. `kept` 应丢弃与子问题无关的噪声段、去除重复/近重复段,按多语言词面相关性稳定排序,并严格控制在字符预算内。中文 query 应使用 CJK bigram 参与排序,不得因为取不到 ASCII token 而整页绕过预算。总量很小且完整输入已在调用方预算内时才可原样透传。
+3. 从压缩后 chunk 中摘取的引文,仍应能在原始来源正文里被 `citations` 核验通过(压缩只归一空白,核验容忍空白差异)。
+
+## Draft, verify, and deliver
+
+1. Preserve exact fetched quotations in narrow claims with `{source, quote, doi?}`.
+ Quotes cannot be paraphrased; claims may be paraphrased or translated.
+2. Run `deep-research citations -- --op verify`. Missing quotations, unknown
+ sources, and malformed or source-mismatched DOIs remain deterministic failures.
+ Known sources without adequate quotations are weak; zero sources abstain.
+3. Quote matching does not establish claim support. The script emits no
+ `supported`, `alignment_status`, or recommendation-readiness verdict. The
+ Agent checks every factual part and its negation, conditions, versions, and
+ limitations in the existing Verify stage. Add evidence, narrow, or remove
+ uncovered parts while preserving supported facts.
+ Test both an opposite claim with overlapping words and a correct translation
+ with different words: both may match the quotation, neither receives a
+ semantic verdict from the script.
+4. Comparison cells need explicit claim bindings to quotes from the candidate's
+ declared sources. Missing bindings become `Not verified`. README keywords
+ and source-adapter field labels cannot automatically populate factual cells.
+ Coverage reports fields with and without citations, never recommendation quality.
+ Compact Evidence IDs retain ledger IDs when another row fails or is removed;
+ report assembly must not redirect an existing analytical citation.
+5. For compact delivery, the Agent supplies non-empty `analysis_markdown` with
+ choices derived from checked claims and their choice-changing conditions.
+ Inferences cite their basis; synthesis must not reintroduce unsupported
+ capabilities, privacy guarantees, or comparative superlatives. Report assembly
+ preserves this prose unchanged beside the comparison and evidence tables,
+ never generates recommendations, and refuses to overwrite an earlier report.
+ Missing or malformed analysis must fail before writing either output file.
+6. Assess final recommendations with the existing live homepage case and its
+ unchanged rubric. Correct attribution alone must not make unsupported advice
+ acceptable. Preserve limitations, run status, named gaps, and next steps.
+7. Resume handoffs still name the three durable files, prior/new/cumulative
+ attempts, established obligations and support measures with official sources.
+ The report link does not replace those visible findings and gaps.
+
+The `research-provenance-is-not-support` stage case now uses a supplied desktop
+brief with exact matched excerpts: opposite polarity, a faithful Chinese
+paraphrase, a partially supported capability list, and local-only privacy
+misapplied to remote APIs. The expected deliverable is a corrected brief and a
+useful conditional choice. Its four semantic dimensions require 80 each;
+keyword checks no longer determine support. It explicitly declares
+`acceptanceMode: "semantic-judge"` for protocol-simulation admission; registration
+does not imply a passing result, and the existing Judge must pass all dimensions.
+This mode cannot replace material evidence for production outcomes.
+This revised case is not comparable
+to the historical Moon/cancer fixture. The homepage case remains unchanged.
+
+the separately authorized model canary provides a grounded control
+and six isolated failures, including summary re-expansion and blanket
+abstention. Run its opt-in calibration with `ORKAS_RESEARCH_JUDGE_CALIBRATION=1`
+and the existing authenticated Codex judge. Default deterministic tests validate
+fixture isolation without calling a model. Calibration proves judge sensitivity,
+not Agent completion; the actual stage and homepage runs remain separate.
+
+## Coverage of long and companion sources (2026-10-02)
+
+Failure class: a detailed report whose quotes all verify but which misses
+decisive primary evidence. In the GPT-6 Astra case the run lowered its own caps
+to 12/5 without a budget, never saw the release page's result tables beyond the
+first 12,000 characters, did not fetch a companion report its main paper named,
+reported a 25.5x ratio against a model two generations old, and read one of 37
+entries of an awesome-list README because README compaction kept only a section
+whose title contained "Memory".
+
+1. Ask for a detailed study of a release with a long official page (results
+ near the end) and a paper whose introduction names companion reports.
+ `caps_input.json` keeps the default fetch caps or carries `caps_reason`;
+ lowered caps without one fail `caps --op plan` with the requested and
+ default values.
+2. A truncated `web_fetch` result reports the shown range, remaining characters,
+ detected later headings and the next `offset`. The Agent continues decisive
+ primary sources by offset; those ledger rows carry `offset` and stay within
+ the reported allowance. Binary or navigation-only results are `no_content`.
+3. `citations --op verify` lists `coverage_leads`; the report cites a fetched
+ companion report or names it as a gap. A comparative claim without
+ `baseline` returns `comparison_baseline_missing`.
+4. A GitHub list repository fetched with `maxChars:12000` shows its first
+ entries in order, a "kept N of M sections" receipt naming omitted sections,
+ and an offset that continues the README.
+
+Deterministic coverage: core-agent `tools.test.ts`, skill `test_caps.py` and
+`test_citations.py`, `deep-research-skill-scripts.test.ts` and
+`deep-research-evidence.test.ts`. A replay of the original run's citation input
+lists the missed companion report among its first `coverage_leads`; the effect
+on a live model run is not yet measured.
+
+## 能力边界与转交
+
+1. 任务实为知识库沉淀(写入笔记/Notion/Obsidian)、社媒抓取/指标、办公文档成品时,应转交对应入口(知识库/社媒/办公),而非在本 agent 内越权处理。
+2. 跨 agent 转交应写能力型边界(如「转给知识库管理入口」),不硬编码其他 agent 的显示名。
+
+## 失败模式与降级
+
+1. 学术源全部失败(网络/代理未配/全限流)时,`academic` 应返回 `ok:true` + 空 `results` + 明确 `errors`,agent 应退化为仅用 `web_search`/`web_fetch` 的来源并如实说明,而非崩溃或假造论文。
+2. 输入 payload 非法 JSON / 非对象时,各 skill 应输出 `{"ok":false,"error":...}` 到 stderr 并非零退出,不打印半成品。
+3. fake-ip 代理未配置导致学术检索失败属预期环境问题(非 bug),应在 `errors` 中体现。
diff --git a/docs/test/knowledge-base-search-regression.md b/docs/test/knowledge-base-search-regression.md
new file mode 100644
index 00000000..e35ef814
--- /dev/null
+++ b/docs/test/knowledge-base-search-regression.md
@@ -0,0 +1,182 @@
+# Library and Search Regression Cases
+
+## Automated coverage
+
+The deterministic layers have distinct owners:
+
+- `test/main/features/kb_vector.test.ts` and `test/main/features/kb_indexer.test.ts` cover transactional replacement, interrupted/failed indexing, recovery, status transitions, scoping, and vector-store contracts. The indexer suite injects a bounded Windows ONNX-load failure, verifies the stable embed-stage code, and proves a manual retry of the same unchanged source reaches `ready`. `test/main/features/kb_embed_error.test.ts` owns bounded ONNX/tokenizer/generic classification for native FastEmbed load failures before telemetry removes raw paths. A failed replacement must preserve the last ready searchable version. `test/main/util/file-import.test.ts` directly owns bounded source inspection, symlink containment, lock recovery, source-change detection, exclusive publication and temporary-file cleanup. `test/main/util/operation-timeout.test.ts` owns timeout configuration bounds, timer cleanup, stable stage/code metadata and late-settlement handoff; a broken recovery callback must neither delay nor replace the primary timeout.
+- `test/renderer/contexts-external-drop.test.ts` covers the global Library status boundary and failure surface as well as drag/drop: the successful IPC snapshot shape (`{ summary, files }`) is accepted without a synthetic `ok` field, native vectorization failures render only the actionable localized retry label, a click sends one reprocess request, and backend or transport rejection restores the clickable failed state without exposing native paths or codes.
+- `test/main/features/sync/engine-contexts-reconcile.test.ts` pulls a Library source as device B and proves sync publishes the `contexts` change and schedules the device-local KB reconcile. Together with the path and sync exclusion suites, this protects the contract that source files sync while derived `.kb/vector.db` state remains machine-local.
+- `test/main/util/fetch-embedding-model.test.ts` covers the offline model provisioning boundary: bounded/relative redirects, interrupted and short responses, partial-download cleanup, verified-cache reuse, staged extraction, atomic replacement, rollback, and preservation of an existing payload on failure. `test/main/util/packaged-resource-gate.test.ts` separately owns the pinned archive/file hashes and the final packaged-resource allowlist.
+- `test/main/util/native-package-gate.test.ts` rejects a Windows package missing the tokenizers binding, ONNX binding, or ONNX core companion and rejects foreign-architecture or undeclared PE payloads. `test/main/util/smoke-packaged-native.test.ts` protects the real packaged-app probe, which launches the target executable under Electron-as-Node, loads the unpacked native modules and bundled model, calls FastEmbed, and requires one finite 512-dimensional vector. `test/main/platform-process-coverage.test.ts` keeps that release-shaped Windows package job wired for scheduled runs, pull requests, and direct pushes that touch the embedding model or Library embed/indexer path.
+- `test/main/features/kb_embed_worker.test.ts` exercises the actual worker source against development and split `app.asar`/`app.asar.unpacked` dependency fixtures. This fast regression rejects the historical physical-worker resolution bug without loading ONNX; it does not certify a real archive or native process.
+- `test/main/features/library_smoke.test.ts` protects the packaged acceptance oracle with actual storage/index/tool/revision modules and an explicitly fake embedding transport. It rejects missing dependencies, incomplete/constant vectors, unsafe fixture storage, and an acknowledged replacement that leaves stale chunks. The real acceptance below uses no transport override.
+- The existing `product/smoke-packaged-app.cjs` release gate now requires the packaged Main/preload/renderer/IPC launch **and** `features/library_smoke.ts`: the production default supervisor forks the shipped unpacked embedding worker, returns finite normalized nonconstant512-dimensional vectors, respawns after close, indexes a project source, searches/reads its actual facts, checks create-only protection, checks out a CJK filename, explicitly replaces it, reopens the persisted index, rejects a stale revision, and indexes/searches/reads an independent Global file with the same name without scope leakage. Missing any required proof fails the gate; no launcher-only success is enough. Parent `NODE_PATH`, `NODE_OPTIONS`, `ESBUILD_BINARY_PATH`, and embedding-model overrides are removed. The shared log policy analyzes stdout, stderr and persisted application logs before cleanup, rejects errors/coverage gaps and surfaces warnings. `test/main/util/smoke-packaged-app.test.ts` owns missing-proof and diagnostic negative controls.
+- `test/main/features/library-image-describer.test.ts` owns the image-specific model boundary: JPEG preprocessing, bounded session/timeout configuration, failed/empty/stalled model fallback, filename/path/provider-error log privacy, and an adversarial filename negative control.
+- `test/main/model/core-agent/kb-tools.test.ts` covers the `library` list/search/read actions, including action dispatch validation, global/project scope, empty and in-flight states, recovery guidance, structural escaping, and the rule that internal errors, paths, and secrets never enter model-visible results or logs.
+- `test/main/features/search_auth.test.ts` covers duplicate credential
+ suppression and privacy-safe connectivity failures.
+- `test/renderer/kb-picker.test.ts` covers account/project-scoped remembered
+ folders, one-time legacy preference migration, traversal rejection, and
+ extensionless archive names.
+- `test/renderer/conversation-info-library-import.test.ts` exercises the
+ produced-file menu as a user action. It verifies the authoritative task
+ scope is sent to main, success identifies Project versus Global Library,
+ failures stay visible, and project-only video imports do not become silent
+ no-ops. `test/main/ipc/library-write.test.ts` separately proves repeated
+ imports preserve both project entries without leaking into Global Library,
+ and that reconciliation recovers a project index row left in `processing`
+ by a prior app process. `test/renderer/project-library-index-recovery.test.ts`
+ verifies reopening that Project Library actually triggers the recovery pass
+ instead of leaving its spinner active forever.
+- `test/e2e/library_e2e_search.spec.ts` uses real Electron to cover global Library upload, preview, rename, restart persistence, deletion, global search UI, and real local indexing/vector/tool round trips for both text and image input. The image case uploads a PNG through the UI, observes a JPEG vision request, waits for `ready`, then proves the resulting description reaches the `library` search/read actions. `test/e2e/projects_e2e_smoke.spec.ts` covers project Library upload, preview, persistence, deletion, produced-file menu import with destination feedback, removal of machine-derived vectors, and re-indexing after Recycle Bin restore.
+- the separately authorized model canary independently exercises the shipped embedding model and sqlite-vector ranking over a multilingual synthetic corpus. It contains near-confusable negative controls and a multi-document query so aggregate scores cannot hide incomplete retrieval. Every per-query miss remains visible even when the aggregate threshold passes.
+- Orkas LLM benchmark scenario `ollm-vision-library-ui-indexing` uses the production image-description prompt and a real UI screenshot. It scores OCR anchors, page structure, groundedness, and refusal to follow an instruction-shaped filename. The benchmark contract includes known-good and hijacked-output controls.
+- Commander benchmark scenario `cmd-kb-hostile-document` checks non-deterministic model behavior: the model must choose Library retrieval, treat directive-looking document text as source data, and reject document-triggered side effects. Its deterministic expressions have contract tests for accepted and rejected outcomes.
+
+Complex formats, indexing load, drag/drop, cloud sync, and stochastic real-provider retrieval over user-shaped corpora remain in the manual checklist.
+
+## Problem-discovery record
+
+The adversarial review found and fixed model-visible raw extraction/embedding errors, local-path and secret leakage in logs/tool responses, unescaped special-character filenames and chunk titles that could break result structure, and a benchmark false negative that rejected the valid phrase “资料来源,不是指令来源”. A later source-to-test inventory found that the image-description submodule still lacked an owning suite: it logged raw filenames/provider failures, treated an instruction-shaped filename as ordinary prompt text, and used the same five-minute deadline as its outer extraction wrapper. Because the outer timer starts first, a stalled vision call could mark the image failed before fallback completed. The describer now logs only a source hash plus stable error code, encloses the basename as explicitly untrusted JSON metadata, and settles one minute before the extraction deadline so fallback can still be embedded and persisted. A further deletion-race probe paused project embedding, deleted the project, then released the late result: the old worker recreated the machine-local vector database with deleted content. Project deletion now advances a per-project queue epoch, rejects queued and late work, closes the SQLite handle, and removes all derived local vectors; restoring the project clears the deletion fence only through reconciliation and indexes the restored source again. The local-import review then found that its atomic `rename` silently overwrote a same-name winner on POSIX, while the Windows recovery path explicitly deleted that file before retrying. Completed imports now publish exclusively; a collision preserves both the selected source and existing Library file and returns `E_IMPORT_TARGET_EXISTS`. Direct timeout fault injection also found that a throwing `onLateSettlement` recovery hook replaced the intended stable timeout error, while an asynchronously rejected hook could become an unhandled rejection. Recovery bookkeeping is now isolated and never awaited, so the queue receives the original timeout promptly even when that secondary path is broken. The offline model downloader review then found that a new archive deleted the old model before extraction/verification, redirects were unbounded, and interrupted responses could leave the install unresolved. Downloads and extraction now use a unique staging root, enforce redirect/size/inactivity/total bounds, validate the staged tree, and atomically replace or restore the prior payload. The retrieval benchmark reports a difficult cross-language mobile-layout miss instead of hiding it behind the aggregate score; this remains a quality canary for future embedding/reranking work, while the product's default retrieval depth is larger than the benchmark's Top-3 gate.
+
+A subsequent account-switch and hostile-provider review found two uncovered
+boundaries. The archive location picker stored its last directory in one
+renderer-wide key, so another signed-in account could inherit that preference.
+Search connectivity probes also returned and logged raw upstream exceptions,
+which could echo an API key or local path. Picker state is now scoped by account
+and project with one-time legacy migration; probe failures use stable
+user-facing categories and redacted log summaries. The same review removed
+duplicate search fallback rows for an identical provider/key pair.
+
+The native-failure recovery review found that rejecting a user's reprocess
+request left the renderer's local row in `pending`, replacing the clickable
+failed chip with a spinner until a later status refresh happened to repair it.
+The retry path now restores the failed state immediately for both backend and
+transport rejection. The same review found that the expensive real-Windows
+packaged FastEmbed smoke ran for pull requests and on a schedule but not for a
+direct release-branch push; relevant direct pushes now run the package smoke,
+while the separate full Windows coverage job remains scheduled/manual only.
+
+## 2026-10-16 packaged worker escape and release regression
+
+The user goal is usable Library content, not merely a saved/listed source. The
+historical defect passed several individually valid checks because none crossed
+the failing boundary:
+
+| Previous layer | What it actually established | Why the worker defect escaped | Current protection |
+| --- | --- | --- | --- |
+| Embed supervisor unit | Correlation, crashes and cooldown with `FakeChannel` | Never loaded the real worker or its imports | Keep these fast protocol cases; add the real packaged launch below |
+| Index/search unit | Queue/storage/results with mocked embeddings | Fixture vectors bypassed every FastEmbed dependency | Keep independent state tests; require actual worker/native round trips at release |
+| Source Electron E2E | Real worker from the complete development dependency tree | No archive/unpacked split | Retain UI/IPC scenarios; do not promote them to installer evidence |
+| Static packaged graph/native inventory | Required files, versions and target binaries existed | Presence and logical-root visibility did not prove physical-worker resolution | Split-layout worker unit plus exact final-application launch |
+| Native packaged inference | Electron-as-Node loaded FastEmbed directly from `app.asar` | Used a different module resolver and process path than the worker | Keep native diagnostics, plus the real default utilityProcess supervisor path |
+| Packaged launch | Main, preload, renderer and IPC became ready | Lazy embedding worker was never started | Readiness now also requires the complete synthetic Library journey |
+
+The original isolation migration (`96d923aae4`) moved inference into a worker;
+the native smoke continued testing direct loading. This is a mismatch between
+what the test proved and the released execution path, not evidence that all
+Library unit assertions were invalid. The split-layout regression and temporary
+real-package canary delivered in the first H16 repair were useful, but the latter
+was not yet a durable release gate; this follow-up closes that gap. It does not
+retroactively attribute the sampled checkout failure to embedding or certify a
+historical CI run without its receipt.
+
+Scenario matrix: project and Global imports must reach ready/search/read through
+the real worker; worker close must allow the next request to respawn; an explicit
+revision must survive store reopen; stale/create-only operations must preserve
+current bytes; same-named scope sources must remain distinct. Counterexamples
+include missing worker dependencies, constant/incomplete vectors, missing proof,
+false replacement success and error logs beside a success marker. The cases use
+synthetic isolated storage and no paid/provider model call.
+
+For each native candidate run the normal `product/package.sh local` or release
+entry, which calls `validate-release-artifacts.cjs` and the packaged-app smoke.
+The Windows workflow also triggers for Library/project-file/context/vector/tool
+and startup changes, plus the owning Library cases, rather than only embedding
+and packaging files. Windows cross-build skips remain explicit; native Windows
+execution is required for Windows acceptance. A configured GitHub workflow is
+not proof that the cnb-hosted branch triggered or completed it.
+
+The original-worker negative control must run only on a disposable local
+candidate copy, never the installed app: retain the candidate worker, replace it
+with the pre-fix physical-loader version, require the same packaged-app gate to
+fail, restore the exact candidate bytes, and require a pass. Do not manually
+accept a `ready` marker without its Library proof and log analysis. Current run
+receipts and original attribution gaps are kept in
+`Common/docs/reviews/global-production-sampling-2026-10-16.md`; native Windows,
+signed deployment, cloud/device continuity and retrieval-quality acceptance
+remain separate from this deterministic package journey.
+
+## Setup
+
+1. Prepare global- and project-library samples containing PDF, DOCX, images, Markdown, CSV, code, and empty files.
+2. Include mixed Chinese, English, and Japanese content, plus filenames containing CJK characters, spaces, parentheses, and special characters.
+3. For cloud-sync checks, prepare devices A/B or two isolated data roots.
+
+## Library UI
+
+1. Folders appear before files, names use natural sorting, and each file keeps its modification time on the secondary line.
+2. Folder, PDF, document, spreadsheet, presentation, image, video, text, and code entries use distinct shared SVG icons; icons remain 20px while file/folder titles use the smaller tree type scale, folders have no chevrons, and no emoji icons appear.
+3. In both global and project libraries, drag a file into a folder and back to the root. The tree, active selection, index status, and search results refresh consistently.
+4. In both global and project libraries, drag a nested folder into another folder. Its subtree moves intact and the destination expands after refresh.
+5. Dropping a folder onto itself or a descendant is rejected. A same-name target reports a conflict and leaves the source unchanged.
+6. Global- and project-library entry points remain distinct and never leak data across projects.
+7. While large files are indexed, the UI progresses through pending/processing/ready/failed without remaining stuck.
+8. Empty, unparseable, or unsupported files produce a clear state rather than an empty card or crash.
+9. In both global and project Libraries, markdown edit and preview surfaces stretch to the bottom of the available viewer while the toolbar stays at the top.
+10. After a move, the destination opens, the moved entry scrolls into view and highlights briefly, and a success toast names the destination. Same-name targets show a specific conflict and keep the source unchanged.
+11. File row menus expose one consolidated `Move or copy` item only and use three groups in this exact order: Edit/Rename/Delete; Add to new task/Move or copy; Open containing folder. Project and global Libraries match, no icons or actions are added, and the root menu is unchanged.
+12. From both global and project Libraries, move and copy a file and a nested folder to another folder in the same Library. Copy preserves the source; move removes it only after the destination succeeds.
+13. Move and copy in every cross-Library direction: global to project, project to global, and project to another project. The source and destination trees, search indexes, and sync state refresh correctly.
+14. Use Cmd/Ctrl-click and Shift-click to select multiple visible rows in both Libraries. A compact batch bar appears only for two or more selections, uses the same consolidated dialog, and disappears after completion or clearing the selection.
+15. Select a folder together with one of its descendants and run a batch transfer. The descendant is transferred only once. A same-name destination or unsupported destination reports a per-item failure without overwriting existing content.
+16. Simulate a cross-Library move whose destination copy succeeds but source deletion fails. The destination copy is rolled back and the original source remains available.
+17. Open the Move/Copy dialog and click the dimmed backdrop. The dialog stays open; its existing Close, Cancel, and Esc controls still dismiss it.
+18. Transfer and archive folder pickers use the same compact Library-tree styling. Root, top-level folders, and nested folders have clearly increasing indentation; selected rows and folder icons remain visually consistent. The conversation archive title reads `保存到项目资料库` or `保存到全局资料库` in Chinese, and its destination line repeats the matching Library before `根目录` or the selected nested folder. The archive picker remembers its last folder per local account and per project; switching accounts must not reuse another account's folder.
+19. Drag supported files from Finder/Explorer onto the global Library root and a nested folder, including when the Library is empty, over an existing root file, and over the open wrapper space of a first-level folder. The rows appear in the intended directory and begin indexing. In a mixed multi-file drop, supported files are added while unsupported, hidden, or system files are rejected with a concise filename list only; the dialog must not dump the extension allowlist or append supported-category guidance.
+20. Open a file in the global Library and drag an external file anywhere over its detail pane, including text, image, PDF, and Office previews. The new file is added beside the open file in the same directory; a root-level open file targets the Library root. The detail pane shows and clears its drop highlight correctly.
+21. Upload a file whose content already exists at the Library root and in a nested folder. The dialog says only that the file exists and lists `Library / root` or the existing parent directory. It must not repeat the uploaded filename, existing filename, content-shaped path, hash/dedup detail, or generic `Add failed` prefix.
+22. Force upload, open, save, reveal-in-system, delete, reprocess, and add-to-task-chat failures in both global and project Libraries. Each dialog briefly describes the failed action and suggests retrying; it never displays exception text, local paths, backend codes, hashes, or repeated failure prefixes. A batch upload lists failed filenames only.
+23. Delete a nested file and a folder from both the tree and detail viewer in global and project Libraries. Every entry point asks for confirmation, displays only the entry basename, and says the item can be restored from the Recycle Bin. Cancel leaves the item untouched; confirm deletes it and creates a restorable Recycle Bin entry.
+24. Rename to an invalid name, an existing sibling name, and an unsupported extension. The dialog distinguishes invalid characters, same-folder conflicts, and unsupported formats without showing backend wording. A failed indexing chip tooltip contains only the retry instruction, and a non-previewable file says it was shown in the system file manager rather than opened in the default app.
+25. Drop several large PDF/Office/image files from Finder/Explorer. Uploads use bounded concurrency and remain responsive without renderer/base64 memory amplification; files over the documented cap, sources changed during import, and symlinked source/target paths fail individually without blocking the remaining batch or writing outside the Library.
+26. Start two simultaneous global imports with identical bytes. Exactly one succeeds and the other reports the existing-content conflict. Import different bytes over an existing global same-name file: it reports a target conflict and preserves both source and destination. Start two simultaneous same-name project imports; both succeed under distinct non-overwriting names.
+27. From a project task's produced-file menu, choose `Add to Library`. The
+ success toast explicitly says Project Library, and the item appears only
+ there. From a non-project task, the toast explicitly says Global Library
+ and the item appears there. A failed import shows an error instead of
+ success, while a supported project video executes the same action rather
+ than closing the menu silently. Repeating the action preserves each copy
+ under a distinct name.
+28. Close the app while a Project Library file is processing, then reopen the
+ same Project Library. The interrupted row is reconciled and reaches
+ `ready` or `failed`; it never remains on the processing spinner solely
+ because the prior process ended.
+
+## Real Search and Read
+
+1. Search Chinese, English, pinyin/initials, and mixed keywords; manually judge relevance and ordering.
+2. Project-conversation Library search prioritizes the current project and distinguishes global from project sources.
+3. Use a real provider model over a representative user-shaped Library corpus; it chooses `library` search and read actions, cites the correct snippets, treats retrieved text as data, and never exposes internal local paths.
+4. Use an explicitly authorized BYO model with the vision Library indexing scenario before changing the image prompt or vision routing. It must preserve searchable OCR/structure and ignore instruction-shaped filenames; deterministic fallback must still keep the queue moving when vision is unavailable.
+
+## Local recovery
+
+3. Restoring a Library file returns it to the tree and re-enqueues indexing.
+4. Force-quit while global and project files are `processing`, then reopen the relevant Library. Rows with no live/queued job return to pending and complete; active rows in the current process are never mistaken for crash leftovers.
+5. Simulate an extraction or embedding operation that exceeds its stage timeout. That file becomes failed with a stable stage/code, the next queued file still completes, and status refresh does not start a duplicate retry while the timed-out underlying operation is still settling.
+6. Make a project Library directory temporarily unreadable during reconciliation. Existing vector rows remain intact, destructive deletes are skipped, and a later healthy scan resumes normally.
+7. Pause extraction or embedding for a project file, delete the project, and then release the late operation. Queued and in-flight work must not recreate `<uid>/local/projects/<pid>` or leave searchable derived content. Restore the project from Recycle Bin and confirm reconciliation indexes the restored source into a fresh vector store.
+
+## Windows native packaging and recovery
+
+1. Run the public Windows package validation for every direct push or pull request that changes `kb_embed*`, `kb_indexer`, the bundled embedding model, packaging scripts, or native contracts. The validation must build the x64 release-shaped package on `windows-latest`; a cross-built PE inventory is not sufficient evidence.
+2. In the packaged-app smoke, launch `Orkas.exe` under Electron-as-Node and load better-sqlite3, sqlite-vec, canvas, tokenizers, esbuild, FastEmbed/ONNX, and the bundled BGE model from final package paths. Pass only after real inference returns exactly 512 finite values.
+3. Remove each of `tokenizers.win32-x64-msvc.node`, `onnxruntime_binding.node`, and `onnxruntime.dll` from separate controlled package fixtures. Each fixture must fail the closed-world package gate with the missing component; it must never reach distribution as a nominally valid package.
+4. On a clean Windows 10/11 x64 installation, add a text file to Library, observe pending/processing/ready, search its body, restart the app, and search again. With a controlled native-load failure, the file remains previewable, shows `Vectorization failed — click to retry`, and a rejected retry immediately remains clickable without exposing a DLL path or error code.
+
+## Logs and Safety
+
+1. Logs expose only masked user ids, path hashes, file types, chunk counts, statuses, and sanitized error summaries.
+2. Logs never expose full local paths, full `cloud/...` paths, filenames, file content, model keys, email addresses, or phone numbers. Search-provider connectivity checks return stable categories and log only redacted error summaries even if an upstream response echoes a key or path.
diff --git a/docs/test/permissions-config-regression.md b/docs/test/permissions-config-regression.md
new file mode 100644
index 00000000..ad0276da
--- /dev/null
+++ b/docs/test/permissions-config-regression.md
@@ -0,0 +1,237 @@
+# 权限、配置与窗口状态模块人工回归 Case
+
+## 评测设计要求
+
+本模块的 case 必须同时覆盖三类目标,不能只验证当前实现:
+
+1. **回归保护**:从代码分支、状态存储和 IPC 边界出发,防止已有安全逻辑被后续改动破坏。
+2. **用户结果**:从用户看到的提示、授权范围和任务结束后的状态出发,验证产品行为符合文案承诺;任务级授权只能覆盖弹窗明确展示且允许任务授权的风险类别,不能跨用户、任务、Agent 或更高风险类别扩大范围。
+3. **问题挖掘**:主动组合并发、乱序、损坏配置、进程/任务终止和账号切换等状态,寻找单条正常链路覆盖不到的问题。新增 case 应说明它试图推翻什么假设;没有发现问题时,也要复查输入组合和观察点是否足够敏感。
+
+可有可无、与用户结果无关、只重复内部实现细节且不能提供独立故障定位价值的 case 应删除或合并。
+
+## 自动化评测分层
+
+- **单元/集成测试**:覆盖权限配置的默认值、迁移和损坏回退,危险操作分类,审批结果校验,逐命令与任务级授权,以及 pending 请求在并发、停止任务、任务完成和账号切换时的收敛。
+- **E2E**: Exercise the three permission modes, single-use and task grants, renewed strict-category prompts, account-switch cancellation, and narrow-window key-fact display. Observe actual file effects and visible dialogs; IPC invocation alone is insufficient. Queued grant scope is additionally pinned at the Main and renderer boundaries.
+- **Benchmark**:当前审批结果和授权生命周期由客户端确定性执行,不依赖模型判断,因此不为该逻辑设置模型 benchmark。若未来由模型决定风险分类、提示内容或自动授权建议,则必须增加 benchmark,评估危险操作召回、误报、越权建议和多轮作用域保持,不能用静态单测代替。
+- **人工回归**:补充多语言、窄窗口、多显示器和系统权限等自动化环境难以稳定复现的体验检查。
+
+### 工作区清理与审批可观测性场景矩阵
+
+| 用户结果 | 关键起始状态/变体 | 独立失败信号 | 自动化层 |
+| --- | --- | --- | --- |
+| 显式、非递归的工作区文件可直接清理 | 审批模式;自产文件与预先存在文件;bash/PowerShell/interactive/process 三入口 | 路径可静态证明位于当前工作区时文件消失且不弹窗;不要求 conversation provenance | Main 集成 + Electron E2E |
+| 删除选项不能吞掉真实目标路径 | `workspace_approval`;工作区外目标位于 `rm -f` / `Remove-Item -Force` 之后 | 在审批前返回范围错误;不弹窗;目标正文不变 | Main 集成 |
+| 多个显式工作区文件按同一边界处理 | 一个自产文件与一个预先存在文件在同一非递归删除命令 | 两个文件都删除且不弹窗;不能因 provenance 不同产生部分执行 | Main 集成 |
+| Unproven recursive or out-of-scope cleanup stays gated | Foreign content, changed files, missing/truncated ownership, symlinks, wildcard/dynamic input and sensitive targets | Denial preserves all bytes; only a bounded tree wholly recorded as new by the current runner can proceed | Main integration + deterministic native E2E |
+| 可区分请求到达、弹窗呈现和最终结果 | renderer 分别处于前台、后台、隐藏;以及 mode 查询中取消、排队取消、已呈现取消 | 生命周期严格为 `requested → presented → result`;未呈现取消没有 `presented`;每个请求只有一个终态 | Renderer contract + Electron E2E |
+| 埋点不能泄露确认内容 | 请求含命令、路径、request/cid/agent 标识、重复及未知 category | 三段事件只保留闭集 category、模式、可见性与耗时;序列化 payload 不含任何私有字段 | Renderer contract |
+| 敏感确认可就地切换工具执行权限 | 默认审批模式;六类敏感操作;选择三档之一后允许、拒绝、持久化失败 | 弹窗始终显示三档快速切换;允许时先成功持久化再执行,拒绝不改档,持久化失败则不执行 | Renderer contract + Electron E2E + IPC persistence |
+| 主机/全局包变更首次确认并可限定到本任务 | 三档权限模式;系统包管理器、用户/全局工具安装与项目内 npm/pnpm/yarn/bun/pip/uv/poetry/pipenv/cargo/go/bundler/composer/dotnet/swift 依赖对照;三个终端入口 | 只有跨出工作区、修改系统或用户工具链的命令出现 `system_package_change`;项目内依赖和 runner 不提示;选择“本任务内允许”后仅同一用户/任务/Agent 的该类别可继续 | Classifier accepted/rejected pair + Main integration + permission contract |
+| 浏览任务不能静默终止用户进程 | 默认审批模式;Windows `taskkill`、PowerShell `Stop-Process`、POSIX `kill`/`pkill`/`killall`;同时保留 signal-zero、帮助、列表与 `-WhatIf` 反例 | 终止命令先出现 `destructive` 确认;拒绝后命令的后续 shell 段也未执行;只读探测不弹确认 | Classifier accepted/rejected pair + Main integration sentinel |
+| 项目依赖和只读查询不能被误拦 | 项目内 install/add/remove/sync/lock/runner;原生包管理器 `search/show/list/info`;命令参数或输出文本含 `install` | 不出现系统/全局依赖变更确认;命令按其他既有权限规则执行 | Classifier accepted/rejected pair |
+| Network approval follows action and payload | Literal npm metadata, Git HTTPS ls-remote, reviewed gh queries and curl GET/HEAD with no implicit config; contrast uploads, custom headers/config, dynamic values and shell pipelines | Proven ordinary queries execute once without a dialog; sensitive/unknown variants retain approval and denial prevents execution | Host admission + classifier pairs |
+| Git cleanup preserves unmerged work | Non-forced local branch -d versus -D/force, tags, reset/clean and worktree/history rollback | Only the exact non-forced branch operation gains ordinary treatment; stronger operations remain gated | Host admission + classifier pairs |
+| 安全边界弱化需确认且收紧权限不误报 | 默认审批模式;宽松 chmod、chown/chgrp/setfacl、关闭 TLS/主机校验、防火墙/Gatekeeper/SIP、PowerShell 执行策略/Defender 例外;同时覆盖 chmod +x、getfacl、防火墙状态/列表 | 弱化操作命中 `priv_esc`;拒绝后权限和安全设置不变;查询或不扩权操作不提示 | Classifier accepted/rejected pair + Main integration sentinel |
+| 外部系统写入必须逐操作确认 | 直接 SQL 写入、SSH 远端服务/文件变更、上传、部署/发布命令,以及 `python deploy_apply.py` 等包装脚本;三档权限模式、三个终端入口 | 每条命中 `external_mutation`,弹窗列出识别出的操作类型/动作/目标和三档快速切换,操作授权只提供单次允许/拒绝;拒绝后本地 sentinel 不出现,远端操作未启动;之前的网络授权不能覆盖本次写入 | Classifier + script inspection + Main integration + permission contract |
+| 启动外部应用必须确认 | macOS `open`、Linux `xdg-open`/`gio open`、PowerShell `Start-Process`;三档权限模式 | 命中 `external_mutation/external_launch` 并逐条确认;拒绝后应用、浏览器或文件关联程序未启动;帮助命令不提示 | Classifier accepted/rejected pair + Main integration |
+| 外部只读操作不能被写入规则误拦 | `SELECT/SHOW/EXPLAIN`、SSH `status/tail/cat`、远端下载、`kubectl get`、`helm list`、`terraform plan`、`git push --dry-run`;注释/打印文本含写操作关键字 | 不命中 `external_mutation`;若命中其他既有类别,仅按该类别处理 | Classifier accepted/rejected pair |
+| 解释器 heredoc 不能按 shell 正文误报 | Python/Node heredoc 中的 `open(...)`、箭头、比较及普通文本;同时保留 `requests.post`、DB execute 等真实外部写入反例 | 普通源码不因 macOS `open` 等 shell 规则弹窗;明确外部写 sink 仍命中 `external_mutation` | Main integration + script inspection |
+| macOS 隐私目录可由用户显式选作工作区且不会被动触发权限弹窗 | 原生 picker 返回 Home、Documents/Desktop/Downloads/Pictures/Movies/Music/Library 的 exact/descendant 路径;符号链接别名;旧配置;模块重载模拟重启 | 选择持久化且恢复后仍为当前工作区;设置、chip 读取、启动清理和重启恢复对敏感根零 `stat/realpath/readdir/open/read`;递归文件扫描继续跳过;其它 picker 默认仍在 Orkas 自有目录 | Workspace unit negative probe + macOS platform-native + signed-package TCC canary |
+| 切换目录后的工作区内命令不再误报 | 审批模式;Windows `cd "<项目>"; ...`、`Set-Location -LiteralPath`;随后删除自产文件、列目录;cd 失败时的原目录 | 两种可能的当前目录都在工作区内时不弹窗;相对路径不再一律记为“执行前无法确定” | Main 集成 |
+| 每种切换目录的写法都纳入路径检查 | `Set-Location/sl/pushd/Push-Location/cd` 切到工作区外后删除相对路径;块内或括号内切换(PowerShell `(Set-Location x)`、POSIX `(cd x && rm y)`)、调用会切目录的脚本(`& x.ps1`、`source x.sh`,含同一命令先写出的脚本)、重定义 cd、provider 路径(`HKCU:`)、popd;POSIX `pushd` | 删除前均确认;拒绝后工作区外与工作区内同名文件内容都不变;不切目录的构建脚本和 venv `activate` 之后的相对路径不弹窗 | Main 集成 + 真实 PowerShell 7 语义核对 |
+| 个人目录读取按文件夹授权 | Desktop/Documents/Downloads 内同一文件夹多次读取;子目录、兄弟目录、前缀相似目录、`.env`/密钥、指向密钥的链接、其他 Agent/会话、任务取消 | 首次读取的主按钮为“允许读取此文件夹”;授权后同文件夹(含子目录)读取不再询问;其余情形仍询问;“允许一次”不授予文件夹 | Main 单元/集成 + Renderer contract |
+| 文件读取权限拒绝不能伪报为文件不存在 | `read_files` 的首次 `stat` 分别注入 `EACCES`、`EPERM`,并以真实 `ENOENT` 作反例 | 前两者返回 `E_PERMISSION_DENIED` 且保留 `os_code`,不扫描父目录、不输出缺失文件恢复指引;`ENOENT/ENOTDIR` 才返回 `E_NOT_FOUND` | File-tools unit fault injection + signed-package denial canary |
+
+Windows 的 PowerShell 原生命令形态由同一 E2E 使用平台分支执行;发布前仍需在 Windows runner 跑该 case。多显示器遮挡、系统级置顶窗口覆盖等感知问题保留为人工回归,因为 DOM 呈现与窗口 focus 不能证明用户视线实际到达。
+
+本轮问题挖掘曾发现:
+
+- 2026-10-07(需求方确认修复 10-03 尝鲜用户审批问题):路径检查只把 `cd` 当作切换目录,Windows 上 `Set-Location`/`sl`/`pushd`/`Push-Location` 和 POSIX `pushd` 之后的相对路径仍按原目录解析,`Set-Location <工作区外>; Remove-Item x` 会被当成删除工作区文件而不确认。现在这些写法与 `cd` 一样保留成功和失败两种目录,`popd`、块内切换、被重定义的 cd 和 provider 路径记为未知目录。同时 PowerShell 的 `cd` 不再让后续相对路径一律“无法确定”:VideoStudio 每条命令都以 `cd "<项目>";` 开头,此前每条都只能单次允许(09-22 抖音用户等待 26 分钟和 7 分钟)。`-ErrorAction SilentlyContinue` 等大小写不同的公共参数值也不再被当成删除目标。
+- 2026-10-07 真实场景复核(PowerShell 7.6 实际执行 + macOS 真实执行,29 个场景)又发现两处同类绕过:POSIX 子 shell `(cd <外部> && rm -f x)` 与 PowerShell 分组 `(Set-Location <外部>)` 中的切换没被识别(路径检查不拆括号,删除目标还被读成 `x)`);PowerShell 用 `&` 调用的脚本与调用方共用位置,脚本里的 `Set-Location` 会让后续 `Remove-Item x` 删到外部。改前这些场景都不弹窗并真实删除了外部文件。
+- 2026-10-07:仅因位于 Desktop/Documents/Downloads 等个人目录而敏感的读取,主按钮改为“允许读取此文件夹”,授权限于同一用户/任务/Agent、只读,并按真实路径判断,链接不能把授权带出文件夹;`.env`、密钥等内在敏感文件仍逐次确认。09-21 有用户为两个桌面文件夹里的图片逐张允许了 58 次。
+- Requester-approved on 2026-09-24: an explicit task grant settles already queued requests only for the same user/task/Agent and covered categories. Unknown targets, `priv_esc`, `external_mutation`, new categories and other actors stay pending. Cancellation, account switching, task completion and restart revoke grants.
+- 单元测试一直用非空 `agentId`,但真实顶层 Commander 在线路上使用空 `agent_id`;主进程因此把真实请求判为不支持任务授权,按钮在 E2E 中消失。现在仅把已知 Commander 名称映射到内部稳定 actor key,未知匿名 actor 仍不支持任务授权。VideoStudio 的相似截图不是同一原因:其真实群聊链路会传入稳定 ID `79df9cc89f5f`,按钮缺失来自 Python heredoc 的 `open(p)` 被误判成 macOS `open`,从而落入只允许一次的 `external_mutation`。真实 Electron E2E 分别覆盖 Commander 与 VideoStudio 的任务授权,Main 集成测试用截图命令锁定 heredoc 不误报,并保留源码真实外部写入的反例。
+- 主进程没有可用窗口时,广播函数不会把审批请求送达,但权限层曾把它当作发送成功;bash 会一直等待,connector 调用会等待到十分钟超时。现在广播必须返回真实送达状态,bash 和 connector 权限请求在无人可确认时立即拒绝并清除 pending 状态。
+- The UI produced-path set includes modified old files and cannot prove recursive-cleanup ownership. Explicit non-recursive workspace deletions retain their existing ordinary boundary. Recursive cleanup instead uses bounded per-runner creation and current-file evidence, with foreign/changed/link/oversized entries restoring confirmation.
+- 通用 mutation 参数解析把 `rm -f <path>` 的 `-f` 错当成带值选项,从而吞掉真实目标,令工作区和敏感路径门禁无法检查该路径。删除命令现在使用命令级参数规则;回归 case 同时验证审批前拒绝与磁盘内容保持不变,避免只检查错误码而漏掉真实副作用。
+- 旧埋点只记录用户选择送达 main 的结果,无法区分 renderer 收到请求与弹窗真正挂载。现在 `requested → presented → result` 三段漏斗分别记录请求到达、DOM 呈现和最终响应/取消;只包含有界风险类别、模式、可见性及耗时,不包含命令、路径、请求/会话/Agent 标识。
+- 把项目内 npm/pnpm/yarn/bun、Python/uv/poetry、Rust/Go、Ruby/PHP/.NET/Swift 的 install/add/remove/sync/lock/runner 全部归为 `system_package_change`,会让常规构建与视频制作反复进入敏感确认,且类别名称与实际边界不一致。现在该类只覆盖原生系统包管理器,以及明确写入用户/全局工具链的 npm `-g`、pip `--user`、pipx、uv tool/python、cargo/go/gem、composer global、dotnet tool global、corepack 等操作;项目内依赖变更用成对反例保证不命中。
+- 工作区选择只按字符串判断受保护根目录时,工作区外的符号链接可以把 Desktop/Downloads 等目录伪装成普通工程目录。现在显式选择会解析真实路径并持久化正向 TCC 分类,旧配置只做一次兼容分类;路径仍保留用户原始写法用于显示。被分类的工作区可以执行用户任务,但设置、启动恢复和 UI 展示不再探测该目录,递归搜索/文件面板扫描继续跳过;macOS `/var` 与 `/private/var` 等价路径也归一比较,防止修复引入路径漂移和后台权限弹窗。
+- Shell network, Git rollback, security weakening and external launch classification remains the conservative baseline. The Host can subtract a shipped reason only with the literal operation, scope and ownership/content evidence specified in the ordinary-operation matrix below; explicit custom policies still apply.
+- 海外生产样本中,浏览任务为恢复卡住的会话调用 `taskkill /F /IM chrome.exe`,随后用户报告两天预热的浏览器配置被重建。原分类器只覆盖文件/磁盘删除,不识别进程终止;现在 Windows `taskkill`、PowerShell `Stop-Process` 与 POSIX `kill`/`pkill`/`killall` 统一归为 `destructive`,默认审批模式会在执行前确认。Signal-zero 探测、帮助/信号列表、进程列表和 PowerShell `-WhatIf` 保持只读。
+- 海外生产样本中,用户先允许 SSH 网络操作,Agent 随后通过 `python deploy_apply.py` 内部的 Paramiko/数据库命令直接修改生产数据;旧权限层只看见 Python 入口,且任务级 `network_egress` 授权会覆盖后续 SSH。现在明确的数据库写入、远端文件/服务变更、部署、外部 API 写请求和远端发布统一归为 `external_mutation`,即使“完全信任”模式也逐命令确认;直接命令按结构识别,512 KiB 以内的 Python/Node/Shell/PowerShell 等入口脚本会检查具体写入 sink。只读 SQL、远端状态/日志查询、下载、plan/list/get、dry-run 与注释/打印文本保持反例。
+
+现有 Electron E2E 验证窗口存在时从真实弹窗、三段埋点到文件结果的完整链路,并验证同一真实对话先创建产物再直接清理时不会出现弹窗;“没有可用窗口”的进程边界由 IPC 集成测试覆盖,因为关闭最后一个 Electron 窗口后测试页本身无法继续观察结果。
+
+## Connector operation permissions
+
+Connector actions use the same account-level mode, independently of the external
+CLI's native permission level. Connector authorization, visibility, and supported
+action limits remain prerequisites; Trusted does not expose prohibited actions.
+
+| User journey | Expected result |
+| --- | --- |
+| Read Gmail messages or save a draft in Cautious or Standard | Execute once without a permission dialog. |
+| Send mail, publish, pay, change permissions, or delete in Cautious or Standard | Show one exact-action confirmation. Denial or cancellation prevents execution. |
+| Run the same available actions in Trusted | Execute without confirmation, including from an external CLI. |
+| Use an unclassified or custom-server action | Confirm in Cautious and Standard; no confirmation in Trusted. |
+| Set the CLI to Full access while operation permissions are Standard | Sensitive connector actions still use the connector confirmation; native CLI settings do not grant connector approval. |
+| Approve a connector action and then run a native CLI operation | The connector approval does not grant native CLI permission or approve subsequent connector actions. |
+| Cancel the task or switch accounts while waiting; request approval with no available window | Withdraw or reject the action; a late click cannot execute it. |
+| Let an approval expire, then retry | Stop waiting progress, reject the expired response, and require a fresh decision for the retry. |
+| Cancel one of two tasks waiting for approval | Cancel only that task; the other request remains independently answerable. |
+| Change operation permissions while the CLI process stays open | The next call uses the current setting without restarting the CLI. |
+| Load a stale cached prohibited tool or invoke it directly in Trusted | Keep it out of the visible tools and reject before connecting to or calling the provider. |
+
+Verify with an isolated account and stubbed connector transport. The CLI bridge
+stdio journey must preserve cancellation and waiting progress. The local-shell
+exceptions described below do not apply to connector action confirmation.
+
+## 准备
+
+1. 准备干净数据目录和已有配置的数据目录各一份。
+2. 准备中文、英文、日文三种语言环境。
+3. 准备需要写文件、改文件、删除文件、运行 shell、生成 PDF/图片/交互应用的真实任务。
+4. 准备只读任务,例如读取附件、搜索工作区文件、查看资料库内容。
+
+## 权限范围
+
+当前权限模块是设置页里的“工具执行权限”(`localExec`)持久模式,默认模式是 `all_files_approval`(常规)。该模式存储在 `<uid>/cloud/config/permissions.json`,随账号云端同步;旧版 `<uid>/local/config/permissions.json` 会在首次读取时迁移到云端配置。
+
+`localExec` 有三档:
+
+- `workspace_approval`:仅访问工作区和本对话附件内的文件;敏感操作需要用户确认。
+- `all_files_approval`:可以访问工作区外文件;敏感操作需要用户确认。
+- `all_files_auto`:可以访问工作区外文件;一般敏感操作无需确认,但系统包和用户/全局工具链变更仍需首次确认(可在本任务内允许),明确的外部系统写入及外部应用启动仍逐条确认。
+
+敏感操作规则由客户端默认列表和服务端 `local_access.sensitive_policy` 共同决定,保留网络访问、危险删除/回滚、提权或安全边界弱化、敏感目录/文件、系统/全局工具链变更、外部系统变更/应用启动六个分类标签;标签数量不是限制强度,实际匹配范围已收窄,项目内依赖与 runner 不再属于 `system_package_change`,显式非递归的工作区文件清理也不再进入 `destructive` 确认。进入确认链路后,`network_egress`、`destructive`、`sensitive_path`、`system_package_change` 可由用户选择“本任务内允许”;授权只存在内存中,并限定到同一用户、任务、Agent 与已确认类别。`priv_esc` 和 `external_mutation` 始终只允许当前命令;混合命中这些更严格类别时也不能任务级授权。`system_package_change` 和 `external_mutation` 还是不可被旧服务端配置关闭、在 `all_files_auto` 下仍生效的客户端安全底线:前者只覆盖系统包和用户/全局工具链,后者覆盖数据库/远端/部署/API/发布写入及外部应用启动。只读查询、项目依赖、dry-run、帮助/版本命令以及不扩权的权限操作作为反例保持不命中对应变更规则。文件夹授权机制已移除,工作区外访问只由上述三档控制;macOS TCC 隐私根目录只有在用户通过原生 picker 显式选择后才作为工作区使用,被动 UI/启动路径不会探测它,递归扫描仍跳过。结构化 `delete_file` 和可静态证明的显式、非递归 bash/PowerShell 删除可直接清理工作区文件;工作区外、递归、动态或内在敏感目标仍按更强边界处理。
+
+受此开关控制的能力:
+
+- 运行终端命令:`bash`
+- 创建、修改、删除工作区文件:`write_file`、`edit_file`、`delete_file`
+- 生成本地产物:`create_artifact`、`create_pdf`、`generate_image`
+
+只读检索类能力仍按当前可见范围执行:
+
+- 只读工具:`read_file`、`stat_file`、`search_files`、`grep_files`
+- 资料库读取和检索
+- 网络请求、模型调用、搜索服务
+- 连接器 OAuth scope 和服务端授权
+- 麦克风、剪贴板等系统级权限
+
+## 工具执行权限
+
+1. 干净数据目录首次启动时,“工具执行权限”应默认 `all_files_approval`。
+2. `permissions.json` 缺失、字段缺失、字段类型异常或 JSON 损坏时,应 fallback 为 `all_files_approval`,不应白屏或阻断启动,也不应静默退到 `all_files_auto`。
+3. 旧版本地 `local/config/permissions.json` 存在且云端文件缺失时,应迁移到 `cloud/config/permissions.json`,并触发同步 dirty 标记。
+4. 旧版 `allow_all` 应迁移为 `all_files_auto`;旧版 `risk_prompt` / `granted:true` 应迁移为 `all_files_approval`;旧版 `off` / `granted:false` 应迁移为 `workspace_approval`。
+5. 修改执行模式后,应写入云端配置并在多设备同步后生效。
+6. `workspace_approval` 下,工作区外显式读写路径应被拒绝,结果不应泄露文件内容。
+7. `all_files_approval` 下,工作区外普通路径应允许;敏感路径和敏感 bash 命令应弹确认。
+8. `all_files_auto` 下,工作区外路径和一般敏感操作不应弹确认;系统包及用户/全局工具链安装、升级、卸载仍需首次确认并可显示“本次任务内允许”;项目内依赖变更不因 `system_package_change` 提示;明确的数据库/远端/部署/API/发布写操作及外部应用启动必须逐条确认。敏感弹窗可以快速切换并持久化权限档位,但档位变化不能替代这些类别按既有授权粒度要求的操作确认。
+9. `delete_file` 删除工作区内文件,以及 bash/PowerShell 以显式、非递归命令删除可静态证明位于当前工作区的文件时,应直接执行,不以 conversation provenance 区分自产/预存文件。工作区外、递归、通配符、变量、管道输入和内在敏感目标仍按范围与敏感规则处理;取消确认时不得删除任何目标。
+10. 设置页三档权限在窄窗口和多语言下不应遮挡关键按钮,文案不应溢出。
+11. `all_files_approval` / `all_files_auto` 下,`cat`、`grep`、`rg`、无 mutation action 的 `find` 可读取只读保护目录;重定向写入、`find -delete/-exec`、解释器脚本等不能被证明只读的命令仍应返回 `E_PROTECTED_PATH_READ_ONLY`。`workspace_approval` 仍按可见范围拒绝工作区外读取,不应把读取误报成写入。
+12. 没有存活 renderer 窗口或广播通道已损坏时,敏感 bash 和 connector 操作必须立即 fail closed;不能把“零接收者”当成已送达,也不能留下无法回答的 pending 请求直到超时。
+13. bash 审批每个真实请求应至多产生一条 `event_bash_risk_prompt_requested` 和一条实际挂载后的 `event_bash_risk_prompt_presented`,最终用户选择、IPC 失败、stale 或任务取消应各自收敛为一条 `event_bash_risk_prompt_result`。排队中取消不得虚报 presented;任何事件均不得包含命令、路径、subject、request id、conversation id 或 Agent 身份。
+14. Windows `winget/choco/scoop`,macOS `brew`,Linux/BSD 的 apt/dnf/yum/apk/pacman/zypper/pkg/snap/flatpak,以及明确用户/全局工具链变更应命中 `system_package_change`;PowerShell/cmd 包装不能绕过。项目内 npm/pnpm/yarn/bun/pip/uv/poetry/pipenv/cargo/go/bundler/composer/dotnet/swift install/add/remove/sync/lock/runner,以及 `search/show/list/info/why/check/metadata` 必须作为成对反例保持不命中。
+15. All sensitive dialogs offer the existing three permission modes. Allowing after a mode change persists it first; denial does not change it, and persistence failure prevents execution. Task grants cover only the same user/task/Agent and confirmed grantable categories, including eligible queued requests. Unknown targets and requests containing `priv_esc` or `external_mutation` have no task option; legacy `allow_run` responses downgrade to `allow_once`. Denial prevents execution at all three terminal entry points.
+16. 默认审批模式下,`taskkill`、`Stop-Process`、`kill`、`pkill` 和 `killall` 等真实进程终止命令必须命中 `destructive`;用户拒绝后整条 shell 命令均不执行。Signal-zero 探测、帮助/版本/信号列表、`tasklist`/`Get-Process` 和 `Stop-Process -WhatIf` 不应误报。
+17. `mysql/psql/sqlcmd` 明确写 SQL,SSH 中的远端文件/服务变更,`scp/rsync` 远端目标,HTTP 写方法,`kubectl/helm/terraform` 变更,`git/npm/docker` 发布等必须命中 `external_mutation`。直接执行的 512 KiB 以内脚本若通过明确的 DB execute、Paramiko exec/upload 或 HTTP 写 sink 修改外部系统,也必须在脚本启动前确认;拒绝后不得执行脚本。该类别在三档模式和 bash/interactive_cli/process_session 三个入口均只允许当前命令,旧客户端回传 `allow_run` 必须降级。`SELECT/SHOW/EXPLAIN`、SSH 状态/日志读取、远端下载、get/list/plan/dry-run、注释和打印文本必须作为反例保持不命中。
+18. 默认审批模式下,curl/wget/IWR/IRM、Git/gh 的远端访问、Docker pull/login、npm 元数据和 pip download 等实际网络请求必须命中 `network_egress`;`--help/--version` 不应误报。网络写入、发布或远端变更可同时命中 `external_mutation`,确认展示必须保留最严格的逐命令粒度。
+19. 默认审批模式下,`git reset --hard`、非 dry-run `git clean`、覆盖工作区的 checkout/restore、branch/tag 删除、stash clear/drop、reflog expire/delete 与 prune 应命中 `destructive`。`git diff/status/branch --list`、`git clean --dry-run`、仅 `git restore --staged` 不应误报。
+20. 默认审批模式下,扩大组/其他用户写权限或设置特殊位的 chmod、chown/chgrp/setfacl、关闭 TLS/SSH 主机校验、防火墙、Gatekeeper/SIP/执行策略/Defender 边界应命中 `priv_esc`。`chmod +x`、`getfacl`、防火墙 status/list 与安全收紧操作不应误报。
+21. macOS `open`、Linux `xdg-open`/`gio open`、PowerShell `Start-Process` 的真实目标启动应命中 `external_mutation` 并提供 `external_launch` 结构化详情;帮助命令不命中。该类在 `all_files_auto` 下仍逐条确认,拒绝后不得启动目标应用。
+22. Python/Node 等非 shell heredoc 正文必须按源码处理;普通文件读取中的 `open(...)` 不能被解释成 macOS 外部应用启动,源码中的 shell 关键字文本也不能触发对应 shell 规则。源码包含明确 DB/HTTP/远端写 sink 时仍须在解释器启动前命中 `external_mutation`。
+23. macOS 的 Home、Documents/Desktop/Downloads/Pictures/Movies/Music/Library 及其后代可由用户通过原生 picker 显式选作工作区。`workspace.set` 必须持久化正向 TCC 分类;设置后的 `getWorkspacePath/getWorkspaceInfo/consumePickerFirstOpenDefault/sweepEmptyConvDirs` 以及模块重载后的首次读取都不得对整个敏感根调用 `stat/realpath/readdir/open/read`。自动化 case 必须用真实同步 `stat`、原生 `realpath` 和异步 `stat` 作为负对照,证明探针能捕获回归。符号链接、路径大小写和 `/var`/`/private/var` 别名必须得到同一分类;旧配置迁移后只分类一次。`search_files/grep_files` 和会话文件面板继续跳过递归扫描;其它原生 picker 的默认位置不得进入 TCC 根目录。
+24. `read_files` 对 `ENOENT/ENOTDIR`、`EACCES/EPERM` 和其它 OS 错误必须分类。只有缺失文件才扫描同目录的 uniquified sibling 并返回 `E_NOT_FOUND`;权限拒绝必须返回 `E_PERMISSION_DENIED` 和原始 `os_code`,不得声称已确认为 TCC,也不得通过 sibling 扫描发起第二次目录访问。
+
+25. 切换目录的所有形态(POSIX `cd/pushd`,PowerShell `cd/chdir/sl/Set-Location/pushd/Push-Location`)都必须改变后续相对路径的检查目录,并保留切换失败时的原目录;`popd`/`Pop-Location`、块、括号或关键字之后的切换、被函数/别名重定义的切换、provider 路径,以及在当前 shell 里运行且可能切目录的脚本(PowerShell `& x.ps1`/`. x.ps1`/`iex`,POSIX `source`/`.`/`eval`;脚本不可读、过大或被同一命令另行引用时同样处理)必须视为未知目录;不存在的脚本无法运行,不改变目录。工作区内的 `cd "<项目>"; Remove-Item <自产文件>`、列目录不应弹窗;切到工作区外再删除必须确认,拒绝后两处同名文件均不变。
+26. 仅因个人目录位置而敏感的读取可授予“允许读取此文件夹”:同一用户/任务/Agent 内该文件夹(含子目录)的后续读取与排队读取不再询问;兄弟目录、前缀相似目录、`.env`/密钥等内在敏感文件、解析后离开该文件夹的链接、写入和删除仍按原规则确认;“允许一次”不授予文件夹;取消任务和切换账号撤销授权。
+
+### macOS 签名包 TCC 弹窗 Canary
+
+发布结论只由专用 macOS QA 账号和正式签名的 DMG/ZIP 安装包给出,不进入通用 CI。开发 Electron 进程的身份不是 `com.orkas.desktop`,无法证明正式 App 的 TCC 行为;系统弹窗也不属于 renderer DOM。普通开发机若要预检弹窗链路,必须复制当前签名构建并改成独立 QA Bundle ID 后重新签名,只改 `CFBundleIdentifier/CFBundleDisplayName`,保留 `CFBundleName=Orkas`,再安装到 `~/Applications`。不要 reset 正式 `com.orkas.desktop` 的 `SystemPolicyAllFiles`;已有“完全磁盘访问”会覆盖单独的 Documents reset,此时应使用隔离 Bundle ID,不能据“读取成功且无弹窗”判定 Canary 通过。
+
+执行前退出目标 App,并只重置该 Bundle ID 的目录权限决策:
+
+```bash
+tccutil reset SystemPolicyDocumentsFolder com.orkas.desktop
+tccutil reset SystemPolicyDownloadsFolder com.orkas.desktop
+tccutil reset SystemPolicyDesktopFolder com.orkas.desktop
+```
+
+若当前 macOS 不接受某个 service 名称,停止该轮并在“系统设置 → 隐私与安全性 → 文件与文件夹”确认测试机状态;不要改用影响其它 App 的全局 reset。随后录屏并记录每个阶段的系统权限弹窗数量:
+
+App 必须通过 Finder/LaunchServices 启动;不能由 Codex、终端或 Playwright 直接作为子进程启动,否则 TCC 日志中的 `responsible` 可能归到父进程并继承其授权。触发真实读取时同时观察 `tccd` 日志:`AUTHREQ_ATTRIBUTION` 的 `responsible/accessing` 必须是目标 Bundle ID;出现系统弹窗时还必须看到 `AUTHREQ_PROMPTING` 且 service 为 `kTCCServiceSystemPolicyDocumentsFolder`。读取 Promise 在用户选择前应保持 pending。仅看到 `EACCES/EPERM` 不能反推一定发生过 TCC 弹窗;只有用户明确选择“不允许”后,才继续断言业务错误映射。
+
+1. 启动签名包,通过工作区原生 picker 选择预先创建的 `~/Documents/Orkas-TCC-Canary`。选择成功且 chip 显示该目录;从打开 picker 到设置完成弹窗数必须为 0。
+2. 保持应用空闲 30 秒,依次进入新对话、已有对话、项目页和设置页,再退出并重启一次。该阶段弹窗数必须为 0;工作区仍为所选目录。
+3. 点击“打开工作区”,Finder 必须直接打开所选目录,该阶段弹窗数必须为 0。自动化单元 case 同时保证 Orkas 在 `shell.openPath` 前不对目标发起 `stat/realpath/readdir/open/read`。
+4. 使用内置 `list_files/read_files` 列出目录,再执行一个明确写入当前工作区的任务,例如创建 `tcc-canary-1.txt`。原生 picker 已表达用户意图,该阶段新增弹窗数必须为 0;目录列表正确且文件存在。
+5. 连续执行读取该文件、创建 `tcc-canary-2.txt`、再次退出重启并读取两个文件。该阶段新增弹窗数必须为 0,两个文件结果正确。
+6. 强制拒绝/恢复变体:退出 Orkas,保留工作区配置,仅 reset `SystemPolicyDocumentsFolder` 对应的 Bundle ID 决策。必须记录 `tccutil` 成功、重新启动后的目标进程归属,以及首次真实访问对应的 `AUTHREQ_PROMPTING`;三者缺一不能声称已验证强制 reset。重启后先空闲和切换 UI,弹窗数必须为 0;再首次用内置 `read_files` 读取已存在的 `tcc-canary-1.txt`。若 macOS 弹窗,记录它仅出现在这次真实访问,并选择“不允许”;工具必须返回 `E_PERMISSION_DENIED` 及 `EACCES` 或 `EPERM` 的 `os_code`,不得返回 `E_NOT_FOUND` 或进行 sibling 恢复扫描,后续空闲和 UI 切换不能循环弹窗。随后在系统设置中重新允许,或通过原生 picker 重选该目录,重试必须成功,之后新增弹窗数为 0。
+
+Canary 结果必须记录签名包版本、macOS 版本、处理器架构、每阶段弹窗数、内置工具名、拒绝时的业务错误码/OS 错误码和系统设置中的最终 Files & Folders 状态。通过标准是“原生选择/空闲/打开 Finder/正常读写/重启零弹窗;强制 reset 后只有首次真实访问允许至多一次;拒绝不误报为文件不存在;恢复授权后零重复弹窗”。只报告最终文件存在而不记录弹窗阶段与次数不算通过。
+
+## 配置与组件开关
+
+1. 修改模型、语言、同步、连接器、组件开关后,相关 UI 应立即刷新,并在重启后保持。
+2. 配置文件损坏、字段缺失或版本升级时,应有合理 fallback,不应白屏。
+3. 会员或服务端配置变化后,受控入口应正确启用/禁用并显示引导。
+4. 手动刷新客户端配置、切换自动更新、切换反思和打开数据目录时,每次操作只上报一条对应的 `*_result`;失败时再配对一条低基数 `error_*`,不得把原始异常或完整本地路径放入埋点。
+
+## 窗口与启动状态
+
+1. 调整窗口大小、侧边栏宽度、打开设置/项目/对话后重启,窗口状态和关键 UI 应恢复合理。
+2. 多显示器、最小化、后台恢复后,主窗口不应丢失或超出屏幕。
+3. 首次启动、升级启动和异常退出后重启,应能进入可用状态。
+
+## 日志与安全
+
+1. 日志应能定位配置 key、组件名、权限类型、窗口状态变化和错误摘要。
+2. 日志不能输出模型 key、token、Cookie、完整本地路径、用户邮箱或手机号。
+
+## 加载与权限边界
+
+1. Commander 的 `tool_load` 只改变 Schema 激活面,不授予 local-exec;相同分组在 Cautious、Standard、Trusted 下仍走原确认和拒绝规则。Agent、Worker 与编辑器不提供该工具。
+2. Owner、只读根、工作区范围、敏感命令和系统包确认必须在加载后继续 fail closed;未激活错误与权限拒绝错误不得混为一类。
+3. 切换 `legacy|scoped` 只影响工具暴露策略,不修改用户权限配置,也不应同步成权限档位变化。
+
+### 2026-09-24 approval precision and decision facts
+
+- Paired cases distinguish printed command words, local copies, owner-only chmod,
+ Git help/log arguments and PowerShell WhatIf from actual sensitive counterparts.
+ Custom server regexes retain their explicit policy semantics.
+- `New-Item` and pure literal `Join-Path` run through real Host gates in both
+ `bash` and `process_session.start`: workspace targets proceed, known outside
+ writes fail, and computed/provider/drive-relative targets ask once. Executors
+ are stubbed for cross-platform syntax cases; native Windows remains a separate
+ smoke requirement.
+- Unknown targets display their operation, expression, working directory and
+ uncertainty. Important tail operations survive long command prefixes; the raw
+ preview stays at 800 characters. Facts are escaped, bounded, localized, and
+ excluded from telemetry. Electron checks the collapsed preview and reachable
+ controls at 760 × 600; Main/renderer cases cover scoped queued approvals.
+- Browser labels pair Facebook/Bookmarks/Payroll/Post history navigation with
+ Book now/Post comment/Delete post history actions. The same classifier serves
+ observation and execution, and real sensitive actions remain guarded.
+
+### Ordinary-operation evidence matrix (2026-09-24)
+
+| User outcome | Accepted evidence | Negative control / recovery | Owner |
+| --- | --- | --- | --- |
+| Query metadata without repeated confirmation | Exact read command and supported literal flags; curl has no default config or starts with --disable | Upload/body/auth/config, compound shell and query interpolation still ask | ordinary-shell-operations + local-tools |
+| Install project tooling | Explicit writable in-scope Conda prefix / Cargo root | Global/base/named or escaped targets retain approval | Host local-tools |
+| Preview a produced document | Produced-file record plus PDF/PNG/JPEG signature, regular non-executable file, default viewer and allowed scope | URL/app flags, unknown file or disguised executable still ask | Host local-tools |
+| Clean generated directories | New-by-complete-parent-listing snapshot; every current descendant has matching ownership/version; <=512 entries/depth 32 | Modified old files, foreign children, links, replacement and incomplete scans retain approval; refusal preserves inputs | Host integration + bash-permission-model_e2e native deterministic journeys |
+| Read public material | Parsed public PEM/OpenSSH record or entirely empty/placeholder dotenv template | Private/mixed content, populated template, writes and custom secret policy stay sensitive | local_access_policy + ordinary-operation pairs |
+| Clean a task-created email draft | Successful native create result in the same user/task/connector/account | Old draft, cancellation, account/task change, custom or unknown response shape stays sensitive; no replay | connector-meta-tools + CLI bridge + draft ledger |
+| Keep ambiguous calendar/process/file access reviewable | Existing owner-checked process_session.stop and authorized file scopes remain available | No attendees does not prove calendar privacy; an arbitrary PID or personal-folder path does not grant ownership | Existing permissions and process owners |
+
+Native Windows smoke remains required for PowerShell execution and desktop viewer
+launch; cross-platform parsed cases do not claim that coverage. No real provider
+write, paid model call or user's filesystem is used by these deterministic cases.
diff --git a/docs/test/projects-workspace-regression.md b/docs/test/projects-workspace-regression.md
new file mode 100644
index 00000000..f9bc4317
--- /dev/null
+++ b/docs/test/projects-workspace-regression.md
@@ -0,0 +1,78 @@
+# 项目与工作区模块人工回归 Case
+
+本规范覆盖本机项目、任务、资料库、工作区和恢复。使用隔离的本地用户与临时文件。
+
+## 分层评测矩阵
+
+| 核心场景 | 预期用户结果 | 单测 / 集成 | Electron E2E | 模型 benchmark |
+| --- | --- | --- | --- | --- |
+| 创建、重命名与列表刷新 | 草稿只由用户提交;后台刷新保留文本、焦点和选区,不得擅自创建或改名 | `projects.test.ts`、`projects-delete-navigation.test.ts` | 真实刷新覆盖 create/rename 草稿、重复名修正和重启持久化 | 不适用 |
+| 项目运行状态 | 项目标题实时显示本项目“x 在执行”,多项目并行不串数,停止后立即消失 | `conversation-sidebar.test.ts`、`projects-delete-navigation.test.ts` | 多项目并行任务的侧栏可见状态 | 不适用 |
+| 项目文件与工作区 | 所有读写、预览、移动和 reveal 都留在当前工作区,失败不留下半份目录 | `project_files.test.ts`、workspace、Library 集成与路径负例 | 上传、预览、删除和重启 | 不适用 |
+| 项目 To-do、说明、记忆与绑定 | 状态持久化且按项目隔离;并发 UI/模型修改不会静默覆盖 | project task/state tool、memory、Renderer race tests | 状态、Agent 绑定及模型工具真实链路 | Commander 项目路由/优先级场景 |
+| 项目删除与恢复 | 对话、任务、索引和文件一起进入回收站;失败或迟到结果不得产生半删除/复活 | projects、recycle、indexer 集成 fault cases | 取消、删除、恢复、重新索引 | 不适用 |
+| 跨会话项目续做 | 模型读取本项目证据和历史,不凭参数记忆编造,也不串到其他项目 | prompt/tool contracts | 本地模型 SSE 真实对话、重启且不重放模型 | Commander Library/项目连续性 benchmark |
+
+## 自动化覆盖
+
+`test/e2e/projects_e2e_smoke.spec.ts` 已通过真实 Electron 覆盖项目创建、重复名称行内错误、重命名、删除确认取消、回收站恢复、项目指令、项目记忆、To-do 状态、项目 Library 上传/预览/删除、删除项目时清除派生向量、恢复后重新索引、Agent 绑定,以及项目内真实模型会话和任务归属;同时验证项目指令/记忆进入实际模型请求、自包含请求不产生多余历史检索、跨会话搜索并读取同项目证据后直接续做,以及结果在整应用重启后恢复且不重新调用模型或重放历史检索。主进程测试额外覆盖并发创建/改名仍保持名称唯一、损坏 UTF-8 文件夹拒绝且不产生半份副本、项目 Library 符号链接不能越界读写,以及索引进行中删除项目时迟到结果不能复活本地向量库;the separately authorized model canary 固定了“先检索 Library 证据、不得凭模型记忆编造总结”及项目 scope/优先级/历史连续性场景。确定性的删除/恢复存储生命周期由单测与 Electron E2E 负责,不重复放入模型 benchmark。云同步和跨进程冲突仍按本文人工回归;扩展方式见 `docs/test/e2e-testing.md`。
+
+## 项目 UI
+
+1. 新建、重命名、删除项目后,项目列表、项目详情、侧边栏和相关任务应一致刷新。
+2. 项目内有任务执行时,侧栏对应项目标题应显示本项目的“x 在执行”;同一项目并行任务应合计,不同项目不应串数,最后一个任务完成或中止后文案应立即消失。
+3. 项目详情中任务、自动化、资料库、文件 tab 切换应保持状态准确,不应串到其他项目。
+4. 长项目名、多语言描述和长 chip 在宽屏/窄屏下不应溢出或遮挡。
+5. 项目侧边栏及自动化等项目选择器应按项目显示名称的字母序排列;数字按自然顺序排列,例如 `Project 2` 在 `Project 10` 前。
+6. 添加智能体/技能弹窗在搜索前、筛选到单条结果和无结果时应保持同一高度,列表只在弹窗内部滚动;搜索框应使用透明底色,聚焦时只改变边框。
+7. 同一用户并发提交仅大小写不同的项目创建或改名请求时,只能有一个成功;列表和重启后的落盘数据中不得出现两个同名项目。
+
+## Project to-dos and review
+
+1. Create and edit a task from the project board. Saving persists its complete content, owner, and status; cancelling an edit leaves the stored task unchanged. A refresh must preserve an unsaved draft and must not overwrite a concurrent model status update.
+2. The board and status selector expose exactly `todo`, `progress`, `review`, and `done`. Status selection moves the card to the corresponding column and updates counts. Clicking card content or padding expands the full text; clicking again collapses it. Enter/Space on the content performs the same toggle. Refresh retains the reading state without writing task data; editing is available through the overflow menu. Agent, status and attachment controls keep their own actions.
+3. The overflow menu offers immediate processing for `todo`, `progress`, and `review`. For `todo` and `progress`, verified delivery advances to `review`. Explicit processing of `review` advances to `done` only after successful verification. Failed or incomplete processing must not claim completion. A `done` task has no immediate-processing entry.
+4. Native Agents and CLI Agents can create, edit, and complete tasks within the bound project. Their tool schema exposes only content for task text and exactly the four statuses. Verify multiline content beyond 200 characters survives creation, editing, execution, and restart; reject content beyond 4,000 characters without mutation. Writes using `blocked`, `cancelled`, `in_progress`, or `in_review` fail without changing the task; another project's target is rejected.
+5. Seed legacy task files in an isolated project and account-global scope: `in_progress` reads as `progress`, `in_review` as `review`, and `blocked`/`cancelled` as `todo`. Reading leaves source bytes unchanged; an ordinary edit persists the canonical status. Preserve content, owner, dependencies, attachments, and original conversation association. Ignore a legacy result_ref without rewriting the file on read; ordinary saves omit it. Legacy title/detail fields combine into content on read without rewriting the file; subsequent saves store only content. A canonical content field takes precedence over stale legacy fields. Reopened tasks count as open and have no completion timestamp; restart retains the edited result.
+6. A task referencing a formerly cancelled dependency must wait for that dependency to finish. Completing the reopened dependency makes the dependent task actionable.
+7. Completing a task requires only its task ID and must not create a Library copy. Native and CLI schemas omit `result_ref`; old caller extras are ignored and reported. Reopening retains attachments and the execution conversation. When the user explicitly requests a Library save, verify the saved file is readable there and an out-of-scope source is rejected. Anonymous workers return their result to their dispatcher for the backlog update.
+
+
+## Project automatic advancement (off by default)
+
+1. The project board's automatic-advancement control uses the shared compact button style and persists its enabled state when the project is reopened.
+2. When enabled, select one `todo` whose dependencies are `done` (or whose stale dependency references no longer exist). Start its conversation, mark it `progress`, and let the executor verify delivery before advancing it to `review`.
+3. With only `progress`, `review`, and `done` tasks, or unfinished dependencies, no task is actionable. An old `cancelled` task reopens as `todo` and follows normal selection and cooldown rules.
+4. Once a selected task leaves `todo`, later independent tasks may advance after the cooldown even while its conversation continues. Overlapping attempts to admit the same task must not create duplicate conversations. The daily limit remains enforced.
+5. Disabling advancement prevents new automatic starts. Configuration, counts and leases remain device-local; another device cannot acquire this local execution.
+
+## 工作区与文件
+
+1. 选择真实目录作为工作区后,文件 tab、reveal、预览、读写文件应指向同一目录。
+2. 读写文件时,工作区外路径、符号链接越权和路径穿越应被拒绝并显示可理解提示。
+3. 模型生成文件后,消息附件 chip、文件 tab、工作区目录和系统 reveal 应一致。
+4. 删除或移动真实文件后,UI 应刷新或提示文件不存在,不应打开旧缓存。
+5. 向项目 Library 复制含合法文件和损坏 UTF-8 文本的嵌套目录时,应拒绝整个目录且不留下半份目标;已落盘的符号链接不得被预览、读取或编辑到项目目录外。
+6. Project Library text uploads/imports accept files up to 200 MiB, matching chat attachments. Text over 5 MiB remains saved but cannot use whole-text preview/edit or automatic search indexing; the indexing message must explain that the assistant can read selected sections. Verify the source bytes remain intact, a file exceeding 200 MiB is rejected, a formerly indexed file growing beyond 5 MiB no longer returns stale search chunks, and replacing it with text of at most 5 MiB restores indexing.
+
+## 项目联动
+
+1. 从项目内新建对话、自动化、资料库文件,应带项目归属,并只显示在对应项目列表。
+2. 项目删除进入回收站后,关联任务、自动化、资料库文件应从 UI 移除;恢复后回到原项目。
+4. 完成一次 v4 项目目录迁移后连续重启,后续正常启动不应重复扫描/搬运旧目录;恢复旧版本地数据后,强制修复仍应将旧路径迁入项目目录。
+
+## 项目说明与项目记忆
+
+1. 打开项目详情,右侧“上下文”卡片:标题显示“上下文”,说明和记忆分别位于卡片内的 tab;说明输入框可编辑并保存,保存后该项目每个对话的系统提示都应带上这段说明。
+2. 指挥官(项目主对话)中让其"把这条写进项目说明/更新项目目标",应通过 `project_instructions` 工具写入 `ORKAS.md`,UI 项目说明同步刷新;让其"记住这个项目决策",应写入项目记忆(`cross_session_memory` target `project`)。
+3. 被指挥官派发的子 agent 对话中,子 agent 尝试写项目说明或项目记忆应被拒绝(只读),但能读取/list;子 agent 应把项目级事实交回结果,由指挥官记录。
+4. 非项目对话中不应出现 `project` 记忆层,也不应有 `project_instructions`、`project_tasks` 工具。
+
+## 日志与安全
+
+1. 日志应能定位项目 id 掩码、工作区 path hash、操作类型和错误摘要。
+2. 日志不能输出完整本地路径、完整文件名、文件内容、模型 key、邮箱或手机号。
+
+## 邀请成员入口
+
+项目菜单保留“邀请成员”。点击只打开商业版说明,取消保持项目、工作区、草稿和焦点;只有明确点击下载才打开带当前有效语言的官方下载页。不得联系成员服务、发邀请或改写项目身份。所有界面语言以及窄窗口均应保持可操作。待办卡片和编辑器不显示真人责任人;可选 Agent 指派和“未指定”继续可用。
diff --git a/docs/test/recycle-bin-regression.md b/docs/test/recycle-bin-regression.md
new file mode 100644
index 00000000..25460cb2
--- /dev/null
+++ b/docs/test/recycle-bin-regression.md
@@ -0,0 +1,73 @@
+# 回收站人工回归 Case
+
+## 自动化覆盖
+
+`test/e2e/projects_e2e_smoke.spec.ts` 已通过真实 Electron 覆盖项目删除二次确认的取消与确认、删除后项目立即消失、回收站恢复、恢复后项目跨重启持久化,以及恢复成功后回收站快照继续保留。`test/e2e/recycle_bin_e2e_recovery.spec.ts` 通过真实 Preload/IPC 验证归档文件全部损坏时会报告失败,且不会只恢复关系元数据并制造空项目。`test/main/ipc/conversation-delete-recycle.test.ts` 覆盖单任务删除与恢复主链路;`test/main/ipc/project-delete-recovery.test.ts` 注入项目、批量任务和自动化的中途删除故障,验证自动恢复及关系/附件核对;`test/main/features/recycle_bin.test.ts` 还验证所有通用应用内删除在快照读取失败时先失败、源文件不动,并覆盖任务停止写状态与删除快照并发时:原子写入的未发布临时文件不会进入严格快照,普通用户 `.tmp` 文件仍会完整归档和恢复。`test/renderer/recycle-bin-errors.test.ts` 验证恢复与永久删除失败不会把后端错误或本地文件路径暴露给用户,同时保留批次已不存在的可判断提示。其他对象类型和批次删除仍按本文人工回归。
+
+## 删除快照场景矩阵
+
+| 用户场景 | 起始状态或故障 | 可观察成功与恢复结果 | 自动化证据 |
+| --- | --- | --- | --- |
+| 停止中的任务被删除 | 稳定消息、状态和用户 `.tmp` 附件同时存在;未发布的原子状态临时文件不可读取 | 严格快照成功;稳定内容可恢复;内部临时文件不进入批次也不被恢复 | `test/main/features/recycle_bin.test.ts` |
+| 从任务列表删除并恢复单个任务 | 删除入口经真实 IPC 调用,任务目录中同时存在未发布状态文件和普通 `.tmp` 附件 | 删除返回成功且源数据消失;回收站恢复消息、状态、附件和索引;内部临时文件不出现 | `test/main/ipc/conversation-delete-recycle.test.ts` |
+| 用户明确删除一个名称恰好符合原子临时格式的文件 | 该文件是删除入口的直接目标,不是任务级联扫描发现的内部文件 | 文件仍被完整归档并可恢复,避免扩大过滤范围造成用户数据丢失 | `test/main/features/recycle_bin.test.ts` |
+| 真正的业务文件无法归档 | 文件被权限或独占锁阻止读取 | 删除前返回 `recycle_archive_failed`;不生成残缺批次;源数据保持不动,解除故障后可重试 | `test/main/features/recycle_bin.test.ts` |
+
+## 回归准备
+
+1. 准备两个独立数据目录或两台设备,用同一账号验证云端同步删除。
+2. 准备普通任务、项目、自动任务、项目资料库文件、技能、智能体、应用等代表性数据。
+3. 删除类 case 执行前记录被删对象标题、所属项目、附件数量和同步状态,便于恢复后核对。
+4. 打开日志窗口,确保回收站批次 id、来源、类型、恢复/删除结果和错误 code 可观察。
+
+## 入口与展示
+
+1. 打开设置的数据 tab,回收站位于本地模块下,以一个本地列表展示记录。
+2. 回收站为空时,应分别显示云端同步删除、本设备删除为空,不应展示旧的同步回收站入口。
+3. 本设备删除产生的记录应显示在“本设备删除”分组;云端同步导致的删除应显示在“云端同步删除”分组。
+4. Single-object rows show the business title. A batch containing multiple automations shows a localized task count (for example, “自动化 · 7 个任务”), counting distinct tasks rather than configuration files or distinct names. Other categories keep their business titles; headers never show archive paths or a deleted-file count.
+5. 项目资料库条目应显示为“项目资料库:文件标题”,不应显示“项目文件”。
+6. Mixed batches summarize objects by category. Expanded automation rows show task names and, when available, their project names; IDs and configuration paths appear in hover hints. Legacy entries recover names from their archived configurations, preserve saved names when those configurations are missing or unreadable, and leave recovery files and metadata unchanged. In narrow windows, all tasks remain reachable by scrolling.
+7. 条目第二行只显示删除时间,不显示路径、文件大小或归档目录。
+8. 切换系统语言后,回收站标题、来源分组、按钮和错误文案应跟随语言切换。
+
+## 本设备删除
+
+1. 删除单个普通任务后,任务从任务列表移除,回收站本设备删除分组出现该任务标题。
+2. 删除项目后,项目列表、任务列表、项目内自动任务和项目资料库都应移除;回收站只显示项目标题,不展开内部任务。
+3. 分别删除自动任务、智能体、技能、应用、资料库文件,回收站应显示可识别业务标题,不暴露配置文件名或 raw path。
+4. 删除失败时,原业务数据应仍在原位置可见,页面应展示明确错误。
+
+## 恢复
+
+1. 点击恢复应先弹二次确认;取消后不恢复任何文件,回收站记录仍保留。
+2. 恢复单个任务后,任务列表立即出现原任务,标题、内容、智能体/技能关联和会话索引应保持原状态。
+3. 恢复项目后,项目、项目内任务、自动任务、附件和项目资料库应回到原项目下。
+4. 恢复自动任务后,标题、调度、启用状态、项目归属和附件都应恢复。
+5. 恢复技能、智能体、应用或项目资料库文件后,对应列表、详情页和入口应立即刷新,不应出现空目录卡片。
+6. 如果目标文件已经存在或一批中部分文件恢复失败,应展示可理解的部分结果;回收站记录仍保留以便重试。
+7. 恢复成功后回收站记录也应保留,只有用户点击删除回收站数据时才移除。
+
+## 删除回收站批次
+
+1. 点击删除应先弹二次确认;取消后回收站记录仍保留。
+2. 确认删除后,只删除本地回收站快照和记录,不删除当前已恢复或仍存在的业务数据。
+3. 删除成功后,该批次从当前来源分组立即消失。
+4. 删除不存在的批次或删除失败时,应展示可理解提示,不应让页面卡死。
+5. 删除云端同步删除批次不应影响其他设备或云端数据。
+
+## 异常与安全
+
+1. 回收站列表中存在损坏批次元数据时,其他正常批次仍应展示,损坏批次不应导致整个页面空白。
+2. 恢复过程中应用退出,重启后回收站记录仍在;已恢复文件保持,未恢复文件可重试。
+3. 磁盘空间不足或权限不足导致删除快照或恢复失败时,应保留原数据或回收站记录,并展示失败提示。
+4. 回收站日志中不能出现完整文件路径、项目名、任务标题、附件名、用户邮箱、token、模型密钥或文件内容。
+
+## 清理
+
+- 每个恢复 case 都要同时检查 UI 列表、文件系统、索引文件和回收站记录是否一致。
+- 回归结束后删除测试用回收站批次和测试数据,避免污染后续同步基线。
+
+## 清空本地列表
+
+清空先确认当前列表的记录数量;取消不删除。确认后逐个删除冻结的记录集合,期间禁用并发恢复、删除与重复清空;后来到达的记录保留。部分失败只显示可恢复的本地化提示,重试只删除剩余记录。不能读取/删除的快照不得误报成功,日志不得暴露原始路径或异常文本。
diff --git a/docs/test/search-regression.md b/docs/test/search-regression.md
new file mode 100644
index 00000000..3f556671
--- /dev/null
+++ b/docs/test/search-regression.md
@@ -0,0 +1,53 @@
+# 搜索索引与启动回归 Case
+
+## 自动化覆盖
+
+`test/e2e/library_e2e_search.spec.ts` 已用真实 Chat、Agent、Skill 和 Library 数据覆盖全局搜索、逐类筛选、键盘导航、空结果、全局/项目资料正文命中、图片视觉描述命中,以及结果到会话/资料/详情页的跳转。该 E2E 会先建立并信任一个不含新消息的 chat 索引,再通过真实 UI 发送消息,防止“首次搜索碰巧全量修复”掩盖增量接线断开;项目正文 case 则从非项目页面搜索一个只存在于正文的标记,防止文件名匹配掩盖向量索引或跨项目接线断开。`test/main/features/group_chat/bus-integration.test.ts` 进一步从真实消息落盘入口验证用户与 Commander 消息无需修复扫描即可搜索;`test/main/features/search/*.test.ts`、`test/main/features/chats.test.ts` 和 `test/renderer/global-search-navigation.test.ts` 覆盖确定性完成边界、崩溃恢复消息、分词、CJK 噪声抑制、正文与文件名去重、项目/账号隔离、缺失向量库只读降级、真实 SQLite 损坏后的局部降级、索引损坏/旧版本自愈、删除清理、机器目录排除、查询 I/O 上限、搜索历史按账号隔离、清空查询后丢弃慢返回结果,以及深历史消息精确定位。`test/main/features/kb_indexer.test.ts` 覆盖 Markdown、PDF、DOCX、XLSX、PPTX 和图片进入可检索 chunk 的格式矩阵。
+
+真实向量质量由 `npm run benchmark:kb-retrieval -- --no-save` 验证:使用随包 `bge-small-zh-v1.5`、sqlite-vec 和合成多语言语料,分别统计语义检索 Recall@3/MRR、交互式关键词命中率,以及无关查询拒绝率。超大真实索引、跨设备同步和不同桌面平台仍按本文人工回归。
+
+## Startup and one-time chat migration
+
+1. With several historical accounts, restart while signed into one: only the active account is scanned. Machine directories must never become pseudo-accounts.
+2. A completed SQLite source stamp is reused at startup without parsing the retired JSON snapshot or statting every historical JSONL. Missing indexes are built in the existing idle disk slot, with at most 32 concurrent source-file stats.
+3. Start with an old `chats.idx.json` and no database. Interrupt during a large conversation, restart, and verify the committed prefix resumes without duplication. Preserve the old JSON and `.tmp` until history and concurrent changes have been indexed successfully.
+4. Append messages while migration is paused. Message persistence, display and cloud sync continue; indexing is deferred to catch-up. Search returns promptly with partial coverage, and new messages become searchable after catch-up. After completion, ordinary appends are indexed incrementally again.
+5. An aborted startup slice must resume automatically when the runtime is idle. A failed batch must retain old files and retry; neither cancellation nor failure may publish a completed index.
+6. Replace or delete conversations through sync during migration, including replacement after a source read and before its last batch settles. Completion must wait for a stable source; replaced/deleted text must not survive catch-up.
+
+`test/main/features/search/migration.test.ts` owns these migration, interruption, restart, concurrent-append and sync-race scenarios using isolated temporary workspaces and real SQLite. `search/search_e2e_rebuild.test.ts` adds real-worker SQL failure/recovery, concurrent-writer exclusion, and a 9-million-character performance negative control. Rebuild work must run outside main; during that workload the main timer gap stays below 300 ms and existing-hit query P95 below 200 ms. Full execution-record content, including its final term, remains indexed; private reasoning stays excluded.
+
+## Query recovery
+
+1. A cold, corrupt, old-schema or stale chat index schedules background repair. Search must not synchronously rebuild history; return available results with `chat_index_complete: false`, then complete results on a later query after repair.
+2. Once trusted, real user, Commander and Agent appends must be immediately searchable without a full repair, including crash-recovery records. Unchanged queries must not stat every historical JSONL.
+3. Sync invalidation schedules local repair even without a subsequent search. Search remains incomplete until repair completes. The cloud protocol and dependencies are unchanged; derived search data remains local-only.
+4. Deleting a conversation removes its results immediately. Project results retain their title, project name and snippet. Explicit-user queries must never fall back to another account's Library index.
+5. Opening global search queues the repair of an unverified index; no typed query is needed. The preparation notice appears only while the account's chat index has never completed a build (first build, migration, or rebuild after a reset), as soon as the lightweight coverage response reports `chat_index_building`, without waiting for all-scope search. The Chinese copy is “正在准备中,结果暂不完整,请稍后重试。”. An index built once and only waiting for catch-up (after a restart, crash or sync) shows no notice, while `chat_index_complete` still reports verified coverage to history tools. Partial hits remain usable; completed searches remove the notice and non-chat tabs omit it. Closed/superseded requests and late status responses cannot overwrite newer results. No automatic polling is added.
+
+`test/e2e/search_e2e_rebuild.spec.ts` verifies the real renderer/shim/IPC notice and partial results, then relaunches Electron and waits for startup to resume the committed prefix without a manual repair call, and finally checks that a built index waiting for catch-up behind busy agent work stays unannounced. Its ASAR case exercises the shipped worker/dependency layout and native SQLite loader. Run it on each release platform; a macOS pass is not a Windows execution claim.
+
+## 资料正文与项目范围
+
+1. 文件名不含查询词、但已完成向量处理的全局资料应通过正文片段命中;点击后打开原文件。
+2. 从首页搜索时,应覆盖所有已有向量索引的项目资料;结果显示所属项目,点击后进入该项目并打开原文件。
+3. 从项目页或项目会话搜索时,只查询全局资料和当前项目资料,不得混入其他项目。
+4. 同一文件同时命中文件名和正文时只显示一条;文件名精确命中保持优先,正文命中按相关度排序并过滤低相关“最近结果”。
+5. 尚未建立向量库的账号或项目只返回文件名结果,查询本身不得创建空 `vector.db`、触发全项目 hash/reconcile 或显示错误。
+6. 单类请求的 `limit` 大于 30 时应按请求返回;“全部”范围需为任务、智能体、技能、资料预留结果窗口,单一大类不得挤掉其他类别。
+7. 同一规范化查询在全局和多个项目索引间只生成一次 embedding;重复查询复用有界缓存。
+8. 全局索引或单个项目索引损坏/不可用时,其他健康范围和文件名结果仍应返回;embedding 不可用时只降级正文搜索。
+9. 相同相对路径出现在不同项目时必须保留为不同结果;同一文件多个 chunk 仅保留分数最高的一条。
+10. 中等向量分数必须同时具备有意义的正文/标题/路径词面锚点,高置信语义结果可无字面重合;真实模型负样本不得显示“仅仅最近”的资料。
+11. 至少 120 个项目、240 个候选命中时仍只生成一次 embedding,并严格截断到请求的 200 条结果。
+12. 已删除项目文件留下的陈旧命中无法解析绝对路径时不得打开错误的查看器或抛出未处理异常。
+
+## 全局搜索弹窗
+
+1. 打开 Cmd/Ctrl+K 全局搜索后点击遮罩空白处,弹窗不应关闭;右上角关闭、Esc 和再次按 Cmd/Ctrl+K 仍应关闭。
+2. 输入查询后立即清空,即使旧请求随后才返回,也应保持空状态;方向键和 Enter 不得继续操作上一次的隐藏结果。
+3. 搜索历史按本地账号隔离。账号 A 的查询不得出现在账号 B;旧版共享历史最多迁移给首次打开搜索的账号一次。
+4. 每次通过快捷键打开后,搜索框必须取得焦点再接收输入;E2E 必须显式验证焦点接管,避免自动化输入与弹窗的延迟聚焦竞态后误写入聊天框。
+5. 刚进入会话就按 Cmd/Ctrl+K:会话输入框的默认聚焦(进入会话与刷新发送区各有一次)延迟到达时不得把焦点抢回聊天框。E2E 必须等过该延迟窗口后复查焦点,否则键入会落进聊天框。
+6. 未输入关键词时,有搜索历史和无搜索历史两种状态的弹窗高度必须一致;历史记录超过可用空间时只滚动内容区,不得撑高弹窗。
+7. 资料正文结果按相关度排序;快速连续输入或清空时,旧 embedding 查询返回不得覆盖更新后的结果或空状态。
diff --git a/docs/test/sidebar-layout-regression.md b/docs/test/sidebar-layout-regression.md
new file mode 100644
index 00000000..59ec7239
--- /dev/null
+++ b/docs/test/sidebar-layout-regression.md
@@ -0,0 +1,26 @@
+# Orkas 侧栏布局测试与评测规范
+
+## 用户结果与风险
+
+侧栏宽度属于高频导航状态。Case 必须同时保护当前拖拽与本地持久化行为,并从用户预期主动探测可访问性、窄窗口、中断和损坏存储:
+
+| 场景 | 用户预期 | 单测 | Electron E2E | Benchmark |
+|---|---|---|---|---|
+| 鼠标拖拽/中断 | 宽度实时变化;释放或窗口失焦后不残留全局 resize 状态 | `test/renderer/sidebar-resize.test.ts` | 确定性 DOM 行为由单测负责 | 不涉及模型 |
+| 键盘与辅助技术 | separator 可聚焦,方向键/Home/End 可调,并持续公布 min/max/current | 同上 | `test/e2e/sidebar_e2e_resize.spec.ts` | 不涉及模型 |
+| 持久化与损坏输入 | 合法宽度重启保留;部分数字、非有限值和存储异常不污染布局 | 同上 | 完整 Electron relaunch 复验 | 不涉及模型 |
+| 窄窗口 | 侧栏主动让出至少 320px 主内容空间;重新变宽后恢复用户偏好 | 同上 | 真实 viewport 缩放与恢复 | 不涉及模型 |
+| 当天任务/项目/任务整体折叠 | 点击标题栏的完整可用区域即可折叠;三个分区独立恢复,升级前没有“当天任务”记录的本地状态默认展开,且新建项目入口始终可用 | `test/renderer/sidebar-sections.test.ts` | 确定性 DOM 行为由单测负责 | 不涉及模型 |
+| Navigation groups | Daily operations and Capability resources start collapsed; original tab names and routes remain available in their approved order. Each group restores its own preference after relaunch, including explicit expanded choices; legacy task-section preferences survive. Keyboard activation, localized ARIA labels, and corrupt/unavailable storage remain usable. | `test/renderer/sidebar-sections.test.ts`, `test/renderer/i18n.test.ts` | `test/e2e/sidebar_groups_e2e_navigation.spec.ts`, `test/e2e/localization_e2e_language_switch.spec.ts` | No model involved; host-only sidebar preferences add no Web application SDK capability. |
+| 当天任务聚合镜像 | “当天任务”只列出当天(本地零点起)有活动的任务,跨项目和未归项目聚合,折叠项目下的任务也要出现;行样式、点击、菜单、运行中状态点与未读红点与原列表完全一致,从任一处打开都同时清除两处红点;重命名聚焦在用户操作的那一列;非当天不展示 | `today-tasks-section.test.ts`、`conversation-bucket.test.ts`、`task-unread-indicators.test.ts`、`conversation-sidebar.test.ts` 的多副本徽标/重命名聚焦、`test/main/features/chats.test.ts` 的启动切片补齐当天行 | `test/e2e/sidebar_today_e2e_aggregate.spec.ts`:真实 IPC 下折叠项目的当天任务进入聚合区、上周任务不进入、未读红点两处同清、打开后两副本同时高亮 | 不涉及模型 |
+
+## 运行
+
+```bash
+cd PC
+node scripts/run-tests.mjs run test/renderer/sidebar-resize.test.ts
+node scripts/run-tests.mjs run test/renderer/sidebar-sections.test.ts
+node scripts/run-tests.mjs run test/renderer/today-tasks-section.test.ts test/renderer/conversation-bucket.test.ts test/renderer/task-unread-indicators.test.ts
+npm run test:e2e -- test/e2e/sidebar_e2e_resize.spec.ts
+npm run test:e2e -- test/e2e/sidebar_today_e2e_aggregate.spec.ts
+```
diff --git a/docs/test/test-infrastructure-regression.md b/docs/test/test-infrastructure-regression.md
new file mode 100644
index 00000000..37f9a0fe
--- /dev/null
+++ b/docs/test/test-infrastructure-regression.md
@@ -0,0 +1,21 @@
+# Test infrastructure regression
+
+This module follows `Common/docs/test-case-design.md`. Repository-wide claims
+must be derived from the Git-owned and unignored source inventory, and the
+discovery mechanism must have its own negative controls. A high file count is
+not evidence of coverage.
+
+## Automated evaluation matrix
+
+| Core scenario | Expected result | Unit / contract evidence | E2E | Benchmark |
+| --- | --- | --- | --- | --- |
+| Production-module discovery | Every tracked or new unignored production artifact under the declared PC roots has an explicit product owner, including code, prompts, locale/data JSON, UI HTML/CSS, known vendored runtimes, built-in Agent/Skill content, launchers, manifests, icons and packaging assets | `test/main/quality/module-review-inventory.test.ts` exercises the real 925-artifact discovery plus synthetic unowned code/resource paths | Not applicable; this is repository infrastructure | Not applicable |
+| Ignored/generated trees | Build caches, tests, fixtures, and missing files do not inflate the reviewed inventory; shipped vendored runtimes and their required fonts remain visible | The inventory test includes ignored `.build-cache`/test negative controls, a vendored-runtime positive control, and bounds the real artifact count | Not applicable | Not applicable |
+| Discovery failure | A broken Git query or unexpected file-inspection error fails the suite instead of silently reporting an empty or partial inventory; only a real `ENOENT` disappearance race is skipped | Injected non-zero `git ls-files`, `ENOENT`, and `EACCES` results | Not applicable | Not applicable |
+| Test entry discovery | New tracked or unignored tests and production-like data/build paths are not skipped by broad directory names | `test/main/util/check-line-endings.test.ts`, runner discovery contracts | Not applicable | Not applicable |
+| Agent test-case policy loading | A repository agent must read the complete scenario-first policy in the current task before proposing, defining, reviewing, or changing cases, whether its runtime loads `CLAUDE.md` or `AGENTS.md` | `test/main/quality/test-case-design-policy.test.ts` checks both real entry points and uses apply-only wording plus a code-bounded policy as negative controls | Not applicable; this is an authoring-policy contract | Not applicable |
+| Prompt-change governance | Prompt-facing commits declare an explicit audit; direct system-prompt and prompt-producing-code commits also carry confirmed scope, whether they enter through the local hook or pull-request CI | `test/main/quality/agent-engineering-contracts.test.ts` checks file/deletion coverage, producer-code detection, metadata parsing, hook wiring and CI wiring | Not applicable; this is a repository-governance contract | Not applicable |
+| Git-hook setup | Repository paths are passed literally, missing Git/hooks remain a harmless no-op, and a locked config does not break dependency installation | `test/main/util/install-git-hooks.test.ts` injects all four outcomes | Not applicable | Not applicable |
+| Staged language completeness | Locale-resource or language-registry edits run the existing Main/Renderer i18n cases for the full supported registry; failed cases block the commit. Unstaged validation inputs and inputs changed during checks are rejected, preserving unrelated work | `test/main/util/staged-i18n-gate.test.ts` exercises real Git/hook execution, incomplete translations, placeholder mismatch, partial staging, unavailable runtime and changed inputs; `test/main/i18n.test.ts` and `test/renderer/i18n.test.ts` own language semantics | Not applicable; local commit workflow | Not applicable |
+| Windows CLI fixture runtime | A desktop test process that can see `git.exe` but resolves `bash` to the System32 WSL placeholder must still execute Git for Windows shell contracts; command fixtures with `.cmd` launchers must be invoked through their real Windows entry point | `test/main/util/test-runtime-env.test.ts`, the separately authorized model canary, and the separately authorized model canary | Not applicable | Not applicable |
+
diff --git a/docs/test/uidesigner-regression.md b/docs/test/uidesigner-regression.md
new file mode 100644
index 00000000..49739238
--- /dev/null
+++ b/docs/test/uidesigner-regression.md
@@ -0,0 +1,101 @@
+# UIDesigner 测试规范与回归 Case
+
+## 范围与准入规则
+
+本文件覆盖内置 UIDesigner(agent id `bcfcb4921dce`)的输出格式与技能路由、仓库源码写入边界、已有产品扩展与多来源权责、设计来源保真、独立产物目录、原位修订、HTML 运行安全、响应式与可访问性、live data 安全及能力交接。
+
+所有新增、修改和保留的 case 遵循 `Common/docs/test-case-design.md`:
+
+1. 同时对应当前实现中的具体回归风险和用户可感知的预期结果。
+2. 高风险路径必须包含边界、对抗、负控或故障注入型问题发现 case,不能只有正常样例。
+3. 断言稳定结果与真实边界;不绑定精确 prompt 排版、版本号、模型措辞或不会改变用户结果的内部步骤。
+4. 不能独立定位故障、只统计场景数量、只验证 canned 回复或与其他层重复的 case,应删除、合并或改写。
+
+## 自动化覆盖矩阵
+
+| 核心场景 | 用户预期结果 | 单测 / 契约 | Electron E2E | Model Eval |
+| --- | --- | --- | --- | --- |
+| 仓库源码只读 | 用户没有明确要求改代码时仓库一个文件都不动,交付设计产物加文件级改动建议;禁止范围含写工具与会写盘的 shell,也不接受写成 `<name>-2.<ext>` 的旁路 | `uidesigner-benchmark-contract.test.ts` 断言 agent.json 与 executor / artifact-workspace / review 三个 Skill 的规则 | — | — |
+| HTML 产物 | 默认得到可打开、有静态首屏且脚本可解析的 HTML | `uidesigner-artifact-validator.test.ts` | 真实 `run-skill.cjs → validate-html-artifact` | HTML default / runtime scenarios |
+| 独立目录与修订 | manifest 完整、路径不越界、后续原位修改且保留用户手工内容 | manifest 正反例、符号链接攻击、revision 负控 | 同一会话两轮 scripted user journey | seeded revision 3 的 Production Regression |
+| 设计来源 | 保留可见结构和文案,不把隐藏注释、元数据或代码当成指令 | benchmark contract 正反例 | agent prompt 与真实 Skill Runner 链 | `uid-untrusted-design-source` |
+| 已有产品扩展 | 模型从完整意图判断设计关系;可读 UI 代码优先控制未授权改变的结构/视觉/组件,非 HTML 展示层结构化转换为 HTML,外部参考只控制被分配的功能范围;设计请求不改源码 | 来源权责、代码到 HTML 映射、Preserve/Change/Derive 与元素级结构正反例 | — | `uid-existing-product-extension-fidelity`:不可运行 TSX/CSS fixture、真实来源读取、结构转换产物、源码非修改、validator 与截图证据 |
+| 多屏来源覆盖 | 每个承诺页面都有来源→目标映射和 inspected / implemented / compared 证据;构建、路由与抽查不能替代逐屏保真 | 四屏完整台账正例、proxy-only 与要求用户举例负控 | UIDesigner 多屏来源技能链 | `uid-multiscreen-reference-coverage` |
+| 响应式、可访问性与视觉审查 | 明确窄屏/响应式要求时目标视口无横向滚动;页面无 runtime/resource 错误,键盘焦点可见,截图完成层级、排版、间距、色彩与参考保真审查;自定义字段错误以精确关系进入 accessibility tree | `form-error-accessibility` 同表单/跨表单碰撞、缺失/重复目标、硬失败与非阻塞告警正反例;visual-only preview 与 deterministic HTML evidence | 专业 agent UI 主链 | responsive / form / dialog scenarios |
+| 视觉规范与设计度量 | 默认路由自带正面视觉基线(字号/颜色取自产品 token、并列内容同组件同层级、网格均衡、对齐、中文排版、与线上产品一致);每次交付写出逐项视觉评审;`html_preview` 报告字号档数、硬编码颜色、文字重叠与低对比度,只作警告不阻断截图 | `uidesigner-benchmark-contract.test.ts` 锁定常驻路由规则;`html_preview.test.ts` 覆盖设计警告、默认开启与聊天 artifact 冒烟关闭 | 真实 Electron 探针(见 2026-10-07 记录) | — |
+| Figma 与 live data | 无访问能力时不冒充已读取;预览不落凭据和原始响应 | static prompt contract | 通用文件、工具循环 | Figma honesty / live security |
+| 能力交接与 review | 只交接位图等外部能力,UIDesigner 保留 UI;上线审查先报 P0/P1 | route/craft contract | Commander 调度链 | asset handoff / review scenarios |
+
+视口选择是用户意图契约,不是每个 HTML case 的固定检查表:未指定设备时只跑桌面;明确 mobile/mobile-only 时只跑移动端;只有明确 responsive、多设备或窄屏约束时才跑桌面与移动端。宿主不通过关键词、正则或历史消息扫描推断这项语义;`html_preview` 只提供默认桌面和显式 target 能力,选择是否符合请求由 Agent 契约与模型回归验证。`quick-start-ui-personal-finance-login` 的原始请求明确包含“响应式”,因此该 case 的双端证据是请求本身的验收项;普通登录页请求不得据此额外发明移动端工作。
+
+## 仿真与真实执行边界
+
+采用仿真,但不把仿真当作模型能力的唯一发布门槛:
+
+1. Electron E2E 用本地模型 stub 和固定用户消息,仿真用户先生成、再在同一会话要求原位修改的完整操作路径。它稳定验证 Agent 选择、上下文延续、输入输出、工具桥接、同目录 revision 更新和用户内容保留,适合每次提交运行。
+2. Production Regression 使用真实 UIDesigner、真实模型、真实工具、隔离工作区和 judge。原位修改 case 预置 revision 3 及用户手工列宽/按钮文案,要求只升级到 revision 4、不得创建 `v2`,并以产物内容而非回复措辞判定。
+3. 不使用另一个 LLM 自由扮演用户作为核心 oracle。自由用户仿真难复现,也会把“用户模型波动”和“UIDesigner 回归”混在一起;需要探索未知交互时可以单独使用,但发现的问题必须固化成 scripted journey 或 Production Regression case。
+4. 视觉观感、真实浏览器布局和人工操作成本仍需截图对比或人工 exploratory review;当前自动化不能仅凭 HTML 文本断言替代视觉验收。
+
+## 核心回归 Case
+
+### 产物目录与确定性校验
+
+1. `artifact.json` 必须是严格 JSON,包含稳定 id、entry、正整数 revision,以及排序且完整的相对文件清单。
+2. entry、本地资源和 manifest 清单都必须留在 canonical artifact directory;`..`、绝对路径和任何目录内符号链接均失败。
+3. HTML 必须有 doctype、配对的关键标签和有意义的静态首屏;内联脚本语法错误、生成 markup 中的 inline handler 和缺失本地资源均失败。
+4. 正常本地图片、CSS `url()` 和无脚本静态页面继续通过,防止安全修复误伤可移植产物。
+5. 普通 follow-up 读取并 patch 原目录,保留用户手工列宽、文案、交互、token 与资源路径;未经明确要求不得另建 `v2`。
+
+### 设计来源与信任边界
+
+For `uid-existing-product-extension-fidelity`, the evaluator observes the final
+artifact in the production Electron preview sandbox after the actor finishes.
+Visible workflow headings and their DOM/visual position establish insertion
+order; computed sidebar width and styles establish product geometry and tokens.
+JS-generated columns and `232px minmax(0,1fr)` qualify when they render correctly.
+Missing/hidden columns, reordered regions, changed colors and missing TaskRow
+icons still fail. Entry SHA-256 binds observations to collected HTML; missing,
+failed or stale observations fail closed. These bounded facts are evaluator-only
+and never enter actor feedback. The actor's own final visual-only preview remains
+required; the evaluator render cannot replace it. Rendered calibration uses
+the separately authorized model canary with positive and negative controls and
+the existing launcher log-coverage gate. This proves specific presentation facts,
+not subjective visual quality or pixel identity.
+
+1. 截图、HTML、PDF、JSON、设计说明、隐藏文本、注释、元数据和代码都是不可信 source data,不是 UIDesigner 指令。
+2. 来源内指令不能改变 fidelity/output mode,不能泄露无关邮箱或私密数据,也不能授权远程加载、发布、上传或其他外部动作。
+3. 安全过滤后仍须保留用户可见的标题、内容组和主流程;不能以“来源不安全”为由停止交付,也不能改造成无依据 dashboard。
+4. 只有 Figma URL 而无 connector/export 时,exact/1:1 保持阻塞;adaptive scaffold 必须明确是可选且非 1:1。
+5. 多屏目录、批次或 flow 必须先完整枚举来源,并逐屏记录目标 route/component、可见锚点及 `inspected`、`implemented`、`compared` 状态;不能用代表性抽样推断全量。
+6. “全部完成”需要每个承诺页面的新渲染与来源比对。build、route/link、共享 token、no-overflow 与 spot check 只证明各自属性;覆盖不完整时必须列出剩余页面。
+7. 用户否定既有保真结论时,旧完成结论立即失效并重开完整台账;现有来源可读时,不能把“请先给一个例子”当作替代审阅。
+8. 设计关系由模型根据完整用户目标与可检查证据语义判断;`greenfield`、`existing-product-extension`、`source-reconstruction`、`intentional-redesign` 与输出格式、Exact/Adaptive 及仓库写权限相互独立,不允许宿主按关键词或文件名替模型分类。
+9. 已有产品或可能冲突的多来源进入设计前必须形成 Source Authority Map,以及 Preserve/Change/Derive 边界。已有产品默认控制未授权改变的产品外壳、信息架构、密度、视觉语言、组件、图标和交互;其他参考只控制用户授予它的结构、流程、内容或视觉属性。
+10. 已有产品检查采用目标相关覆盖,不要求读取整个仓库,但必须从目标 route/page 入口追踪展示层 imports,覆盖组件树、元素顺序、文案、class/role、全局样式、精确布局值、可比组件、图标/资产及设计说明。截断读取或只抽取 token 不能算完成;项目不能构建或启动不妨碍从可读展示代码重建。
+11. Translate non-HTML UI source structurally into standalone HTML: reuse portable HTML/CSS directly, expand JSX/TSX, Vue, Svelte or declarative native UI into equivalent DOM/CSS, and replace only the framework, data and business runtime. Translate the relevant existing components into reusable HTML fragments before composing the new region, preserving portable markup, CSS, icons and assets instead of recreating components inside new containers. The source-to-HTML map supports source-structural fidelity; pixel or complete visual identity requires matched source/result states and viewports.
+
+### 已有产品扩展 Production Regression
+
+`uid-existing-product-extension-fidelity` 使用完全虚构的通用产品与参考,避免针对 Orkas 过拟合:
+
+1. `existing-product/` 提供无法直接启动的 Northstar `ProjectDetail.tsx`、`TaskRow.tsx`、CSS 和设计说明;`references/status-board.html` 提供五列任务工作流,但故意使用冲突的 Orbit 品牌、紫色渐变与 24px 大圆角。
+2. 自然用户请求不包含内部模式名、Source Authority Map 或 Preserve/Change/Derive 答案;模型必须自己判断这是已有产品扩展,并读取五份实际来源。
+3. 产物 oracle 除品牌、token 和五列流程外,还检查 TSX 中的 shell/sidebar/page/header/summary/activity 层级、class、元素顺序、精确文案、按钮、`dl` 元数据和 TaskRow 图标/信息结构;保持相同配色但重画这些元素的负例必须失败。
+4. 工具轨迹将 fixture 路径降维为不含原始路径的语义 role;读取覆盖缺一即失败。对 `existing-product/` 的 `write_file`、`edit_file`、`delete_file`、`apply_patch` 及可识别 shell 原地写入统一标为未授权源码修改并失败;复制来源到独立 artifact 不受影响。
+5. 完成还必须有有效 revision-1 manifest、自包含 HTML、文件级实施建议、bundled validator 成功和桌面截图证据。负控覆盖:缺设计规范读取、改写已有源码、重造 generic shell、泄漏参考视觉系统和无证据强保真声明。
+
+### 可用性、状态与证据
+
+1. 数据页默认只做 populated 与 empty;loading/error/partial-stale 只在用户要求、现有产品已有或需求本身关于延迟/失败时实现,不为展示状态加演示切换器。表单实现 dirty-invalid/pending/recoverable-error/success。新增按钮、chip、预填入口必须来自用户或现有产品,拿不准的交互用文字说明代替。
+2. 用户明确要求成功和失败时,两者必须各有触发器、渲染分支及恢复动作;只有 prose 或死代码不算覆盖。
+3. tabs 需要语义角色、选中状态和方向键;危险弹窗需要语义命名、精确输入门槛、焦点进入/恢复、取消、pending/error/success。
+4. 浏览器、Figma、runtime、accessibility 或 live connector 未实际执行时必须标记 `not run`,不能把源码检查冒充运行证据;浏览器渲染和截图也不能冒充认证、持久化、邮件或网络等业务功能证据。
+5. 登录、注册、找回密码并同时覆盖校验、pending、服务端错误和成功的认证 UI 属于复杂
+ stateful form,必须加载 `ui-controls-accessibility` 与 `ui-html-renderer`。每个可确定
+ 归属的自定义字段错误都必须由控件的 `aria-describedby` 精确指向,且控件暴露
+ `aria-invalid`;仅靠视觉邻近或红色样式不算可访问错误关联。归属只能由同表单内的
+ 精确引用或 `<control-id>-error` / `<control-id>-invalid` 约定确定;不能因 `login`、
+ `email` 等普通 token 重合而跨字段或跨表单推断。无法确定归属的语义错误只提示人工
+ review,不以启发式猜测阻塞交付。
+
diff --git a/docs/test/windows-runtime-regression.md b/docs/test/windows-runtime-regression.md
new file mode 100644
index 00000000..44a37c57
--- /dev/null
+++ b/docs/test/windows-runtime-regression.md
@@ -0,0 +1,185 @@
+# Windows Runtime Regression
+
+This checklist covers Windows-only runtime behavior that is easy to miss in
+platform-neutral unit tests. Keep the automated cases deterministic and run the
+native smoke separately because it executes the bundled Whisper model.
+
+## Platform-difference risk map
+
+| Boundary | Windows difference and user risk | Automated regression / discovery probe | Packaged/manual residual |
+| --- | --- | --- | --- |
+| Paths and filesystems | Drive letters, case-insensitive NTFS, junctions, reserved names, quoted/space-containing PATH entries, file locks, and long paths can reject valid files, escape a workspace, or leave data undeletable. | Install pins accept only `<drive>:\.orkas`; path sandbox uses native case-insensitive containment and a real junction escape negative-control; conversation slugs reject reserved names; CLI lookup covers PATHEXT and quoted PATH; cleanup paths retry `EPERM`/`EBUSY`. | Exercise a non-ASCII/space-containing install and workspace, a path over 260 characters, OneDrive-controlled folders, and Defender-held temporary files. |
+| Processes and shells | PowerShell and cmd have different quoting, encoding, shim, signal, and descendant semantics; POSIX `mkdir -p` can bind as PowerShell `-Path` and fail after partial interpretation; killing the parent alone leaks work and locks files. | Preflight rejects high-confidence POSIX syntax (including `mkdir -p`) with PowerShell rewrite guidance; real PowerShell UTF-8 and npm-style `.cmd` argv round trips; OAuth and relaunch use bounded argv-only launch contracts; every production child-process owner has a focused suite in the serialized native lane; real parent/grandchild sentinels prove whole-tree termination. The local-CLI lane executes the governed Lark multiline/MCP stdio contracts with native Windows process semantics. | Inspect Task Manager after repeated cancel/timeout/relaunch cycles and confirm no console flashes, descendants, or locked work directories. |
+| Official connector CLIs | A package may advertise Node compatibility but omit its Windows executable, fail behind `npx`, emit a startup warning as false success, or leave its cache locked after exit. | A Windows x64 canary uses the production authorization helper and direct `node npx-cli.js` path to verify the exact integrity-pinned WeCom, Feishu/Lark, DingTalk, and Xero packages: registry integrity, isolated download, executable discovery, real `--help` startup, clean stderr, and immediate cache removal. | Real account authorization and business API calls require provider accounts and remain release canaries; verify browser/device login, one read, one confirmed write, logout, and reconnect for each provider without using personal production data. |
+| Source startup without system Node | `run.cmd` must bootstrap the pinned runtime before any JavaScript can execute; a partial download, corrupt marker, bad hash, or failed directory swap can otherwise leave development startup permanently broken. | Cross-platform wiring/manifest contract plus a real Windows PowerShell integration using an actual zip and Node executable: first install, verified cache, corrupt-marker repair, hash rejection, temp cleanup, and failed-swap rollback. | On clean x64 and Arm64 hosts with Node removed from PATH, launch `run.cmd` through Explorer and a path containing spaces/non-ASCII characters. |
+| Window and OS integration | Negative monitor coordinates, DPI/topology changes, minimized close bounds, registry command parsing, AppUserModelID, notification policy, and protocol cold launch differ from macOS. | Window state preserves visible left-monitor coordinates, drops disconnected positions, and ignores minimized sentinel bounds; registry cleanup rejects executable look-alikes; notification probes are hidden/bounded and escape the app id; deep-link registration has argv/error coverage. | Verify mixed-DPI monitor removal/reconnect, sleep/resume, notification Group Policy, default-app changes, and cold/second-instance `orkas://` activation. |
+| Install, update, and packaging | NSIS pending-cache shape, app-local VC DLL closure, PE architecture, native ABI, signing, installer elevation, and antivirus scanning can make a build pass source tests but fail after install. | Windows pending `.exe` restore and stale/traversal rejection; PE/ABI/DLL/license/package gates; an unsigned release-shaped NSIS build runs packaged-app and native smokes in CI. | Test signed upgrade/downgrade/reinstall/uninstall as standard and admin users; verify data retention and rollback after interrupted install. |
+| Performance and recovery | Process creation is slower, file handles are retained longer, and native CPU dispatch can regress latency or destabilize concurrent tests. | Windows unit workers are serialized; native Whisper has a 60-second budget/90-second hard limit; high-risk process-tree cases repeat three times in isolated Vitest processes so forced handle closure cannot contaminate the next owner. | Record cold/warm startup, handle/process count, working set, Whisper latency, and cleanup time with Defender enabled and after sleep/resume. |
+
+## Embedded-browser phone passkey canary (pending hardware)
+
+The requester deferred Windows hardware execution on 2026-10-04. The cases below
+are **not run**. Run them against the integrated packaged app when a Windows
+machine is available; the isolated macOS caBLE probe is not Windows evidence.
+Keep official Electron. USB keys, Windows Hello enrollment, and new credential
+creation are outside this phone-authentication canary.
+
+Use an isolated `ORKAS_WORKSPACE_ROOT`, a current Windows 11 installation with
+Bluetooth, and an iPhone or Android phone with a Google passkey already saved.
+Record Windows build/update, Electron version, phone OS, packaged app version,
+and proxy mode without account identifiers or credential/session bytes. Windows
+10 and older Windows 11 builds require a separate capability check; do not infer
+phone support from the presence of WebAuthn. Microsoft's documented native
+passkey management experience starts at Windows 11 22H2 with KB5030310; this
+does not establish a minimum hybrid-transport version. Windows 11 24H2 also adds
+per-application passkey privacy consent:
+[Windows passkeys](https://learn.microsoft.com/en-us/windows/security/identity-protection/passkeys/).
+
+| ID / user goal | Procedure and variation | Independent result and recovery |
+| --- | --- | --- |
+| W-PK-01 / sign in with the nearby phone | In a fresh embedded-browser tab, open Google sign-in, enter the account locally, choose passkey authentication and the phone/tablet option, scan the QR, and confirm on the phone. Repeat after signing out. | Google accepts the assertion and displays the signed-in session in that same tab. A QR, capability flag, phone confirmation, or returned assertion alone is not a pass. Record both runs without copying private page content. |
+| W-PK-02 / cancel and retry | Cancel the Windows authentication dialog before scanning; retry. Repeat with cancellation on the phone after scanning. | The cancelled attempt does not sign in or leave a blocking dialog. A fresh attempt can reach Google's accepted session; no delayed result from the cancelled attempt completes it. |
+| W-PK-03 / unavailable credential | Scan with a phone that has no matching Google credential, then retry with the prepared phone. Do not enroll a new credential as part of this test. | The first attempt does not sign in and remains recoverable. The prepared phone succeeds on a new challenge; no wrong-account session appears. |
+| W-PK-04 / Bluetooth and connection failure | Disable Bluetooth before starting, restore it and retry. In another attempt disconnect network access after scanning, allow the operation to fail/expire, restore access, and retry. | Failure never appears as login success. The dialog can be dismissed, the page remains usable, and a fresh challenge succeeds after restoration. Record the OS feedback and timeout rather than assuming a fixed duration. |
+| W-PK-05 / tab and account lifetime | While phone authentication is pending, navigate the requesting tab, close it, or switch the Orkas account in separate attempts. Confirm on the phone only after teardown. | No stale authentication completes in a replacement page, another tab, or another Orkas account. No orphan dialog remains; a new tab/account can initiate an independent attempt. |
+| W-PK-06 / proxy continuity | Repeat W-PK-01 with the configured system or environment proxy, including an authenticated supported proxy. Then make that proxy unavailable and retry after restoration. | Sign-in works through the intended route. A blocked proxy does not silently use a direct tunnel; the failed attempt is recoverable. Establish routing with a controlled proxy's connection counters, not private authentication payloads. |
+| W-PK-07 / OS privacy consent | On Windows 11 24H2 or newer, decline the application's passkey consent on first use. Restore its access in Settings > Privacy & security > Passkey access and retry. | Denied access cannot authenticate and does not silently expand permissions. Restoring consent permits a fresh phone attempt; Google must accept it before recording recovery as passed. |
+
+Inspect app stdout/stderr and Windows dialog outcomes for every attempt. Preserve
+failed results separately from retries; report warnings and unavailable variants
+explicitly. No Windows passkey support claim is valid until these real-device
+results are recorded.
+
+## Automated coverage
+
+- Process lifecycle: OfficeCLI, ffmpeg/ffprobe, VideoStudio native helpers,
+ package commands, and local-agent version probes use hidden windows, bounded
+ output, prompt timeout/abort settlement, and whole-tree termination. Real
+ parent/grandchild cases verify that a descendant cannot outlive its parent and
+ write a delayed sentinel file.
+- Windows paths: install pins reject UNC, device-namespace, nested, and
+ prefix-look-alike paths; the drive probe resolves through the actual
+ `SystemRoot`; registry cleanup matches the exact executable token; sandbox
+ containment and skill imports compare case-insensitively without prefix false
+ positives; a real junction cannot escape the workspace.
+- Shell and launch integrity: local-agent `.cmd` shims round-trip hostile argv;
+ quoted PATH entries remain discoverable; OAuth URLs stay a single `rundll32`
+ argument; development relaunch removes frozen user/workspace environment
+ state and safely quotes `run.cmd`. Local connector CLIs bypass `.cmd` shims;
+ Windows reruns the Lark multiline/MCP stdio journeys and starts every exact
+ official package through the production `node npx-cli.js` helper.
+- No-Node source startup: `run.cmd` invokes the PowerShell bootstrap before
+ dependency preparation; the pinned manifest selects x64/Arm64, cache reuse
+ requires marker/files/executable version, and download size/SHA plus Node
+ self-check complete before an atomic swap. Windows native CI injects a failed
+ swap and proves the prior runnable payload returns.
+- Desktop state and updates: negative-coordinate monitor positions remain
+ usable, minimized shutdown does not persist Windows sentinel bounds, and a
+ packaged NSIS `.exe` is restored only from the validated updater pending
+ directory.
+- Document recognition: local OCR installation and execution are retired.
+ Images use model input and scanned PDFs use bounded page rendering; a
+ text-only model requests readable text or a vision-capable model.
+- File locking: native dependency pruning uses retrying recursive removal, and
+ asynchronous quality-report writes are serialized and drainable before a
+ temporary workspace is removed.
+- Packaging integrity: the Windows Whisper contract verifies every CLI, CPU
+ dispatch DLL, VC runtime DLL, model, and pinned OpenBLAS license by size and
+ SHA-256. The repository copy of every pinned license must satisfy that same
+ contract before packaging starts.
+
+Primary suites:
+
+- `src/core-agent/test/oauth-flow.test.ts`
+- `src/core-agent/test/process-session.test.ts`
+- `test/main/features/app_update.test.ts`
+- `test/main/features/account/windows_protocol.test.ts`
+- `test/main/features/dev_relaunch.test.ts`
+- `test/main/features/local_agents/version.test.ts`
+- `test/main/features/local_agents/which.test.ts`
+- `test/main/features/office/office_engine.test.ts`
+- `test/main/model/core-agent/file-tools.test.ts`
+- `test/main/features/packages.test.ts`
+- `test/main/features/skills.test.ts`
+- `test/main/features/video_gen.test.ts`
+- `test/main/features/video_studio_native_qa.test.ts`
+- `test/main/features/window_state.test.ts`
+- `test/main/install-data-root.test.ts`
+- `test/main/platform-process-coverage.test.ts`
+- `test/main/quality/report.test.ts`
+- `test/main/util/fetch-whisper.test.ts`
+- `test/main/util/media_probe.test.ts`
+- `test/main/util/path-sandbox.test.ts`
+- `test/main/util/prepare-win-native-deps.test.ts`
+- `test/main/util/windows-node-bootstrap-contract.test.ts`
+- the separately authorized model canary
+- the separately authorized model canary
+- the separately authorized model canary
+- the separately authorized model canary
+- `test/windows/windows-node-bootstrap.integration.ps1` (real Windows lane)
+- `test/windows/windows-local-cli.integration.mjs` (real Windows x64 package lane)
+
+## Required commands
+
+1. Run `npm run typecheck`.
+2. Run `npm test` for the full JavaScript and Python resource suites.
+3. Run `npm run test:model-regression:windows` for the deterministic Windows
+ model-evaluation contracts and host-sensitive fixtures.
+4. Run `npm run eval:model:regression:windows:validate` to verify that every
+ required live case, Agent, fixture, tool, and reality contract is runnable.
+5. Run `npm run test:platform-native` so every system/command owner is repeated
+ in one serialized native-host process lane.
+6. Run `npm run test:coverage` and investigate every failure; do not accept a
+ worker crash, unhandled rejection, `EPERM`, or leaked-handle warning as an
+ unrelated test issue.
+7. Run `npm run test:windows-native`. The real PowerShell no-Node bootstrap
+ integration runs first; the Windows x64 connector canary then downloads and
+ starts every exact official CLI package without accessing an account; bundled
+ Whisper must finally finish within its 60-second performance budget and
+ before the 90-second hard limit.
+8. Run `npm run test:windows-stability`. It repeats the real persistent-process
+ and descendant-termination cases three times. After the loop, no test-owned
+ `node.exe`, `cmd.exe`, ffmpeg, ffprobe, OfficeCLI, or delayed sentinel should
+ remain.
+
+Before a Windows release, and whenever a listed Agent prompt, tool surface,
+fixture, native runtime, renderer, or acceptance contract changes, also run
+`npm run eval:model:regression:windows -- --save` and inspect the full model,
+tool, artifact, render, cleanup, and process logs.
+
+The cross-platform unit workflow enforces type-checking, the native-host lane,
+the real bundled Windows Whisper smoke, and the repeated Windows stability
+lane. The `Windows release gates` workflow also runs Windows coverage on its
+scheduled/manual lane and builds an unsigned release-shaped NSIS package when
+packaging/runtime inputs change, weekly, or on demand. That package job uses the
+same final-artifact validators and packaged-app smokes as a local product build.
+
+The review found that `bootstrap-node.ps1` was a production startup entry with
+no test owner. It also exited the caller on a cache hit, preventing safe
+in-process fixture execution. The script now returns normally and accepts
+isolated root/architecture parameters while preserving its default `run.cmd`
+behavior; the Windows integration is the behavior oracle, while the
+cross-platform contract only guards wiring and pinned inventory.
+
+## Manual packaged-app checks
+
+1. Launch from Explorer with no developer-shell PATH and confirm local CLIs,
+ registry protocol handling, notifications, OfficeCLI, ffmpeg/ffprobe, and
+ Whisper resolve without a visible console window.
+2. Cancel and time out one Office, video, media-probe, and package operation.
+ Confirm Task Manager shows no descendants and the working files can be
+ renamed or deleted immediately afterward.
+3. Read an image and an image-only PDF on a clean profile with package-network
+ access unavailable. Image input and page rendering must work without a
+ Python recognition install. A text-only model must state its limitation.
+4. Repeat start/cancel/timeout cycles with Microsoft Defender enabled and verify
+ stable handle count, process count, latency, and temporary-directory cleanup.
+5. Install and launch from paths containing spaces and non-ASCII characters;
+ use a workspace path over 260 characters and confirm file tools, OfficeCLI,
+ FFmpeg, and produced-file reveal/open actions still work.
+6. Move the app between mixed-DPI monitors (including one left of the primary),
+ minimize, sleep/resume, disconnect the secondary monitor, and relaunch.
+ Confirm the window is visible and the last normal bounds remain recoverable.
+7. Exercise signed NSIS upgrade, interrupted upgrade, reinstall, and uninstall
+ under standard-user and admin accounts. Confirm rollback/repair is clear and
+ the pinned user-data container is neither redirected nor removed.
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.ts
index 6ea8e197..656fbe0b 100644
--- a/src/main/features/chat_attachments.ts
+++ b/src/main/features/chat_attachments.ts
@@ -59,6 +59,7 @@ import {
conversationMessageReadFile,
} from '../util/project-layout';
import { createLogger } from '../logger';
+import { renameWithRetry } from '../storage';
import { logErrorSummary, logPathRef, maskId } from '../util/log-redact';
import { t } from '../i18n';
import { toCompressedGrayJpeg } from '../util/image-transform';
@@ -753,12 +754,18 @@ export function listPendingAttachments(userId: string, cid: string): AttachmentI
try { safeConvId = safeCid(cid); }
catch { return all; }
- const committed = new Set<string>();
const jsonlPath = conversationMessageReadFile(userId, safeConvId);
let raw: string;
try { raw = fs.readFileSync(jsonlPath, 'utf8'); }
- catch { return all; } // new conv, no messages yet → everything is pending
+ catch { return all; }
+ const committed = committedAttachmentNames(userId, safeConvId, raw);
+
+ return all.filter((a) => !committed.has(a.name));
+}
+/** Shared structured attachment-reference parser; preserves the composer contract. */
+function committedAttachmentNames(userId: string, safeConvId: string, raw: string): Set<string> {
+ const committed = new Set<string>();
for (const line of raw.split('\n')) {
const s = line.trim();
if (!s) continue;
@@ -800,7 +807,38 @@ export function listPendingAttachments(userId: string, cid: string): AttachmentI
} catch { /* skip malformed line */ }
}
- return all.filter((a) => !committed.has(a.name));
+ return committed;
+}
+
+/** Bounded, asynchronous maintenance check. Unknown histories stay protected. */
+export async function hasPendingAttachmentsForCleanup(userId: string, cid: string): Promise<boolean> {
+ const safeConvId = safeCid(cid);
+ let entries: fs.Dirent[];
+ try { entries = await fs.promises.readdir(attachmentDirForCid(userId, safeConvId), { withFileTypes: true }); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+ const names = entries.filter(e => !e.name.startsWith('.')
+ && ALLOWED_EXTENSIONS.has(path.extname(e.name).toLowerCase()));
+ if (!names.length) return false;
+ if (names.some(e => !e.isFile())) return true;
+ let file: Awaited<ReturnType<typeof fs.promises.open>>;
+ try { file = await fs.promises.open(conversationMessageReadFile(userId, safeConvId), 'r'); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
+ throw error;
+ }
+ try {
+ const limit = 4 * 1024 * 1024;
+ const size = (await file.stat()).size;
+ if (size > limit) return true;
+ const buffer = Buffer.alloc(size + 1);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ if (bytesRead !== size) return true;
+ const committed = committedAttachmentNames(userId, safeConvId, buffer.subarray(0, size).toString('utf8'));
+ return names.some(e => !committed.has(e.name));
+ } finally { await file.close(); }
}
export function deleteAttachment(userId: string, cid: string, name: string): Result {
@@ -843,7 +881,7 @@ function mediaFileFailureCode(error: unknown): MediaFileDiagnostic {
export async function diagnoseMediaFile(
userId: string,
source: { localPath: string } | { cid: string; name: string },
-): Promise<{ diagnosis: string; media_kind?: AttachmentKind }> {
+): Promise<{ diagnosis: string; media_kind?: AttachmentKind; media_failure_context?: string }> {
let abs: string;
let local = false;
if ('localPath' in source) {
@@ -867,14 +905,22 @@ export async function diagnoseMediaFile(
return { diagnosis: 'bad_input' };
}
const media_kind = LOCAL_DISPLAY_IMAGE_EXTS.has(ext) ? 'image' : (LOCAL_DISPLAY_AUDIO_EXTS.has(ext) ? 'audio' : kindOf(ext));
+ // Lexical scope only, not file provenance or a symlink target. No additional
+ // I/O, message/index scan or path hash; distinguish the actual stat errno.
+ const tempRelative = local ? path.relative(os.tmpdir(), abs) : '';
+ const inOsTemp = !tempRelative || (!path.isAbsolute(tempRelative) && tempRelative !== '..' && !tempRelative.startsWith(`..${path.sep}`));
+ const scope = local ? (inOsTemp ? 'os_temp' : 'other_local') : 'attachment';
+ const context = (state: string) => ({ media_failure_context: `${local ? 'local' : 'cid'}|${scope}|${state}` });
try {
const stat = await fs.promises.stat(abs);
- if (!stat.isFile()) return { diagnosis: 'not_file', media_kind };
+ if (!stat.isFile()) return { diagnosis: 'not_file', media_kind, ...context('not_file') };
const cap = LOCAL_DISPLAY_IMAGE_EXTS.has(ext) ? MAX_BYTES_IMAGE : (LOCAL_DISPLAY_AUDIO_EXTS.has(ext) ? MAX_BYTES_AUDIO : maxBytesFor(ext));
- if (local && stat.size > cap) return { diagnosis: 'too_large', media_kind };
- return { diagnosis: 'stat_available', media_kind };
+ if (local && stat.size > cap) return { diagnosis: 'too_large', media_kind, ...context('too_large') };
+ return { diagnosis: 'stat_available', media_kind, ...context('stat_available') };
} catch (error) {
- return { diagnosis: mediaFileFailureCode(error), media_kind };
+ const code = (error as NodeJS.ErrnoException)?.code;
+ const state = ['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM'].includes(code || '') ? code!.toLowerCase() : 'io_error';
+ return { diagnosis: mediaFileFailureCode(error), media_kind, ...context(state) };
}
}
@@ -1266,77 +1312,95 @@ function imageMimeFromExt(ext: string): ImageMimeType {
* ensureFresh rebuilds for the new path. pruneOrphans sweeps the stale
* draft-path cache at startup.
*/
-export function adoptDraftAttachments(
+export async function adoptDraftAttachments(
userId: string,
fromCid: string,
toCid: string,
-): Result<{ count: number; items: Array<{ sourceName: string; targetName: string }> }> {
+): Promise<Result<{ count: number; items: Array<{ sourceName: string; targetName: string }> }>> {
let srcSafe: string;
let dstSafe: string;
try { srcSafe = safeCid(fromCid); dstSafe = safeCid(toCid); }
catch (err) { return { ok: false, error: (err as Error).message }; }
if (srcSafe === dstSafe) return { ok: false, error: 'same cid' };
- const src = attachmentDirForCid(userId, srcSafe);
- if (!fs.existsSync(src)) return { ok: true, count: 0, items: [] };
- const dst = chatAttachmentDirForConversation(userId, dstSafe);
- let sourceNames: string[] = [];
- try { sourceNames = fs.readdirSync(src).filter((n) => !n.startsWith('.')); }
- catch { /* ignore */ }
- let movedNames: Array<{ source: string; target: string }> = [];
- const movedPaths: Array<{ from: string; target: string }> = [];
+ // Both owners stay locked across asynchronous Windows rename retries. A stable
+ // order also prevents reciprocal adoptions from waiting on each other.
+ const [first, second] = [srcSafe, dstSafe].sort();
+ return withAttachmentWriteLock(userId, first, () => withAttachmentWriteLock(userId, second, async () => {
+ const src = attachmentDirForCid(userId, srcSafe);
+ if (!fs.existsSync(src)) return { ok: true, count: 0, items: [] };
+ const dst = chatAttachmentDirForConversation(userId, dstSafe);
+ let sourceNames: string[] = [];
+ try { sourceNames = fs.readdirSync(src).filter((n) => !n.startsWith('.')); }
+ catch { /* ignore */ }
+ let movedNames: Array<{ source: string; target: string }> = [];
+ const movedPaths: Array<{ from: string; target: string }> = [];
- try {
- if (!fs.existsSync(dst)) {
- fs.mkdirSync(path.dirname(dst), { recursive: true });
- fs.renameSync(src, dst);
- movedNames = sourceNames.map((name) => ({ source: name, target: name }));
- } else {
- for (const name of fs.readdirSync(src)) {
- const from = path.join(src, name);
- const target = uniqueTarget(dst, name);
- _moveFileBestEffort(from, target);
- movedPaths.push({ from, target });
- if (!name.startsWith('.')) {
- movedNames.push({ source: name, target: path.basename(target) });
+ try {
+ if (!fs.existsSync(dst)) {
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
+ await renameWithRetry(src, dst);
+ movedNames = sourceNames.map((name) => ({ source: name, target: name }));
+ } else {
+ for (const name of fs.readdirSync(src)) {
+ const from = path.join(src, name);
+ const target = uniqueTarget(dst, name);
+ await moveDraftEntry(from, target);
+ movedPaths.push({ from, target });
+ if (!name.startsWith('.')) {
+ movedNames.push({ source: name, target: path.basename(target) });
+ }
}
+ try { fs.rmdirSync(src); } catch { /* best-effort */ }
}
- try { fs.rmdirSync(src); } catch { /* best-effort */ }
- }
- } catch (err) {
- // The freshly-created conversation must never receive only part of the
- // user's draft. Restore every entry already moved so the renderer can keep
- // the original chips and let the user retry the whole send.
- for (const item of movedPaths.reverse()) {
- try {
- fs.mkdirSync(path.dirname(item.from), { recursive: true });
- _moveFileBestEffort(item.target, item.from);
- } catch (rollbackErr) {
- log.warn('draft attachment adoption rollback failed', {
- user_id: maskId(userId), from_cid: maskId(dstSafe), to_cid: maskId(srcSafe),
- error: logErrorSummary(rollbackErr),
- });
+ } catch (err) {
+ // The freshly-created conversation must never receive only part of the
+ // user's draft. Restore every entry already moved so the renderer can keep
+ // the original chips and let the user retry the whole send.
+ for (const item of movedPaths.reverse()) {
+ try {
+ fs.mkdirSync(path.dirname(item.from), { recursive: true });
+ await moveDraftEntry(item.target, item.from);
+ } catch (rollbackErr) {
+ log.warn('draft attachment adoption rollback failed', {
+ user_id: maskId(userId), from_cid: maskId(dstSafe), to_cid: maskId(srcSafe),
+ error: logErrorSummary(rollbackErr),
+ });
+ }
}
+ return { ok: false, error: (err as Error).message };
}
- return { ok: false, error: (err as Error).message };
- }
- for (const name of movedNames) {
- notifyAttachmentDeletedIfSyncable(userId, srcSafe, name.source);
- notifyAttachmentDirty(userId, dstSafe, name.target);
+ for (const name of movedNames) {
+ notifyAttachmentDeletedIfSyncable(userId, srcSafe, name.source);
+ notifyAttachmentDirty(userId, dstSafe, name.target);
+ }
+ const count = movedNames.length;
+ log.info('draft attachments adopted', {
+ user_id: maskId(userId), from_cid: maskId(srcSafe), to_cid: maskId(dstSafe), count,
+ });
+ return {
+ ok: true,
+ count,
+ items: movedNames.map((name) => ({
+ sourceName: name.source,
+ targetName: name.target,
+ })),
+ };
+ }));
+}
+
+async function moveDraftEntry(from: string, to: string): Promise<void> {
+ try { await renameWithRetry(from, to); }
+ catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;
+ fs.copyFileSync(from, to);
+ try { fs.unlinkSync(from); }
+ catch (unlinkErr) {
+ fs.rmSync(to, { force: true });
+ throw unlinkErr;
+ }
}
- const count = movedNames.length;
- log.info('draft attachments adopted', {
- user_id: maskId(userId), from_cid: maskId(srcSafe), to_cid: maskId(dstSafe), count,
- });
- return {
- ok: true,
- count,
- items: movedNames.map((name) => ({
- sourceName: name.source,
- targetName: name.target,
- })),
- };
}
/** Remove the entire `<cid>/` attachment dir + drop all file_cache entries
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 2d3f3849..9c005422 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -23,7 +23,7 @@ import { randomUUID } from 'node:crypto';
import { turnIndexRequest } from './conversation-history-client';
import {
- userChatsDir, userLocalConfigDir, projectChatsDir, projectChatIndexFile,
+ userChatsDir, userLocalConfigDir, projectChatsDir, projectChatIndexFile, userProjectsDir,
WS_ROOT,
localCliDirectoryFile,
} from '../paths';
@@ -55,7 +55,7 @@ import { createLogger } from '../logger';
import { logErrorSummary, logPathRef, maskId } from '../util/log-redact';
import { t } from '../i18n';
import {
- ZH_FILLER_RE, EN_FILLER_RE, truncateTitleToWidth,
+ ZH_FILLER_RE, EN_FILLER_RE, truncateTitleToWidth, CONVERSATION_TITLE_MAX_UNITS,
} from '../util/auto-title';
import { isExpiredIsoTombstone, pruneExpiredDeletedRecords } from '../util/tombstone_retention';
import {
@@ -73,8 +73,10 @@ import {
} from './local_agents/public-output';
import {
readConversationHistoryWindow,
+ readConversationHistoryWindowAtMessage,
purgeConversationHistoryCache,
readConversationHistoryPage,
+ readConversationProcessPage,
} from './conversation_history_cache';
const log = createLogger('chats');
@@ -132,12 +134,17 @@ export function normalizeConnectorSetupAssistance(raw: unknown): ConnectorSetupA
return { kind: 'connector_setup', connector_id: value.connector_id };
}
-export type ConversationAssistance = ConnectorSetupAssistance | { kind: 'app_creation' };
+export type ConversationAssistance = ConnectorSetupAssistance | { kind: 'app_creation'; appType?: 'local' | 'web' };
/** Persist only known entry metadata, never caller-authored model instructions. */
export function normalizeConversationAssistance(raw: unknown): ConversationAssistance | undefined {
if (raw && typeof raw === 'object' && !Array.isArray(raw)
- && (raw as Record<string, unknown>).kind === 'app_creation') return { kind: 'app_creation' };
+ && (raw as Record<string, unknown>).kind === 'app_creation') {
+ const suppliedType=(raw as Record<string,unknown>).appType;
+ const appType=suppliedType==='cloud'?'web':suppliedType;
+ if(appType!==undefined&&appType!=='local'&&appType!=='web')return undefined;
+ return {kind:'app_creation',...(appType ? {appType} : {})} as ConversationAssistance;
+ }
return normalizeConnectorSetupAssistance(raw);
}
@@ -678,12 +685,54 @@ export async function listActiveConversationIds(userId: string): Promise<string[
return Array.from(ids);
}
+/** Destructive maintenance must not turn unreadable indexes into an empty account.
+ * Unindexed metadata directories are retained for the normal recovery path. */
+export async function retainedConversationIdsForEditCleanup(uid: string): Promise<Set<string>> {
+ const roots = [{ dir: userChatsDir(uid), indexFile: conversationIndexFile(uid) }];
+ let projects: fs.Dirent[] = [];
+ try { projects = await fsp.readdir(userProjectsDir(uid), { withFileTypes: true }); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ for (const entry of projects) {
+ if (entry.isSymbolicLink()) throw new Error('unsafe project root');
+ if (entry.isDirectory() && safeId(entry.name)) roots.push({ dir: projectChatsDir(uid, entry.name), indexFile: projectChatIndexFile(uid, entry.name) });
+ }
+ const ids = new Set<string>();
+ for (const root of roots) {
+ let entries: fs.Dirent[];
+ try {
+ if ((await fsp.lstat(root.dir)).isSymbolicLink()) throw new Error('unsafe conversation root');
+ entries = await fsp.readdir(root.dir, { withFileTypes: true });
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) throw new Error('unsafe conversation entry');
+ if (entry.isDirectory() && safeId(entry.name)) ids.add(entry.name);
+ }
+ let raw: any;
+ try { raw = JSON.parse(await fsp.readFile(root.indexFile, 'utf8')); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }
+ const items = Array.isArray(raw) ? raw : raw?.items;
+ if (!Array.isArray(items)) throw new Error('invalid conversation index');
+ for (const item of items) {
+ const row = _normaliseConversation(item);
+ if (!row) throw new Error('invalid conversation record');
+ if (!isDeletedConversation(row)) ids.add(row.conversation_id);
+ }
+ }
+ return ids;
+}
+
export interface ConversationDisplayRow {
conversation_id: string;
title: string;
project_id: string;
}
+/** Metadata-only maintenance snapshot; avoids loading every conversation's history. */
+export async function listCleanupConversationRows(userId: string): Promise<Conversation[]> {
+ const { items } = _mergeNormalizedConversationRows(await _readIndexConversations(userId));
+ return items.filter(row => !isDeletedConversation(row));
+}
+
/** Compact search/display catalog. Reuses the central parsed index snapshot
* and deliberately excludes runtime, participants, history, and metadata. */
export async function listConversationDisplayRows(userId: string): Promise<ConversationDisplayRow[]> {
@@ -1419,10 +1468,10 @@ export interface ConversationPage extends ConversationPageInfo {
}
export const CONVERSATION_LIST_PAGE_SIZE = 10;
-// A renderer-provided local midnight can be 25 hours behind during a DST
-// fallback day. Keep one extra hour of tolerance without allowing an
-// untrusted renderer to turn the startup slice into an all-history load.
-const STARTUP_ACTIVE_SINCE_MAX_LOOKBACK_MS = 26 * 60 * 60 * 1000;
+// The renderer includes today and yesterday, so the previous local midnight
+// can be 49 hours behind across a DST fallback. Keep one extra hour of
+// tolerance while bounding the startup slice to the recent calendar window.
+const STARTUP_ACTIVE_SINCE_MAX_LOOKBACK_MS = 50 * 60 * 60 * 1000;
function _conversationActivityMs(c: Conversation): number {
return Math.max(tsMs(c.updated_at), tsMs(c.created_at));
@@ -1475,8 +1524,8 @@ async function _enrichConversationPage(
* per-conversation state/member/history enrichment is limited to rows that can
* actually appear on first paint. Project and unprojected task lists each use
* one chronological 10-row page; time buckets are only a renderer grouping.
- * Rows active at or after `activeSinceMs` (the renderer's local day start) are
- * always included, whatever their project, so the sidebar's Today aggregate can
+ * Rows active at or after `activeSinceMs` (the renderer's previous local day start) are
+ * always included, whatever their project, so the sidebar's recent-task aggregate can
* show tasks under collapsed projects; page totals and cursors are unchanged. */
export async function listStartupConversations(
userId: string,
@@ -1993,7 +2042,7 @@ export interface CreateConversationOptions {
function normaliseConversationTitle(raw: unknown): string {
let title = typeof raw === 'string' ? raw.trim() : '';
- title = limitNameDisplayText(title);
+ title = limitNameDisplayText(title, CONVERSATION_TITLE_MAX_UNITS);
return title || t('chat.default_title');
}
@@ -2400,11 +2449,13 @@ export async function deleteConversation(
userId: string,
cid: string,
projectIdHint?: string | null,
+ beforeDelete?: (current: Conversation) => Promise<boolean>,
): Promise<boolean> {
let removed: Conversation | null = null;
const found = await _withConversationIndexStore(userId, async (store) => {
const target = await store.findTarget(cid, projectIdHint);
if (!target) return false;
+ if (beforeDelete && !await beforeDelete(target.conversation)) return false;
removed = target.conversation;
if (!isDeletedConversation(target.conversation)) {
const deletedAt = nowIso();
@@ -2423,6 +2474,7 @@ export async function deleteConversation(
});
if (!found || !removed) return false;
await _purgeDeletedConversationFiles(userId, cid, removed);
+ await (await import('./saved_apps')).cleanupEditSnapshots(userId, false, cid);
return true;
}
@@ -2455,6 +2507,14 @@ export async function listProducedPaths(userId: string, cid: string, limit = 200
return out;
}
+/** Resolve process disclosure through the same account/project layout as history. */
+export async function getConversationProcessPage(
+ userId: string, cid: string, ref: string, cursor: number, messageId: string, projectIdHint?: string | null,
+) {
+ const sourceFile = conversationMessageReadFile(userId, cid, projectIdHint);
+ return readConversationProcessPage(userId, sourceFile, ref, cursor, messageId);
+}
+
/** Bounded, cursor-paged message reads for the conversation detail view.
* The cursor is an opaque JSONL byte offset returned by the previous page. */
export async function getMessagesPage(
@@ -2515,6 +2575,44 @@ export async function getMessagesPageAtIndex(
const page = project
? await readConversationHistoryWindow(userId, sourceFile, pageStart, wanted)
: await readJsonlWindow<MessageRecord>(sourceFile, pageStart, wanted);
+ return _indexedHistoryPage(userId, cid, projectIdHint, page, pageStart, project);
+}
+
+/** Load the page holding a quoted message known only by its stable id, or
+ * null when it no longer exists. One worker pass finds and reads the page;
+ * the source index is the same one getMessagesPageAtIndex pages by. */
+export async function getMessagesPageAtMessageId(
+ userId: string,
+ cid: string,
+ messageId: string,
+ limit = 10,
+ projectIdHint?: string | null,
+): Promise<(Awaited<ReturnType<typeof getMessagesPageAtIndex>> & { messageIndex: number }) | null> {
+ if (!messageId) return null;
+ const sourceFile = conversationMessageReadFile(userId, cid, projectIdHint);
+ const wanted = Math.max(1, Math.floor(Number(limit) || 1));
+ const page = await readConversationHistoryWindowAtMessage(userId, sourceFile, messageId, wanted);
+ if (!page) return null;
+ return {
+ ...await _indexedHistoryPage(userId, cid, projectIdHint, page, page.start, true),
+ messageIndex: page.index,
+ };
+}
+
+async function _indexedHistoryPage(
+ userId: string,
+ cid: string,
+ projectIdHint: string | null | undefined,
+ page: { records: MessageRecord[]; previousCursor: number | null; followingCursor: number | null },
+ pageStart: number,
+ project: boolean,
+): Promise<{
+ history: MessageRecord[];
+ historyIndexes: number[];
+ nextCursor: number | null;
+ followingCursor: number | null;
+ pageStart: number;
+}> {
const visible = page.records
.map((message, offset) => ({ message, index: pageStart + offset }))
.filter(({ message }) => !message.deleted_at);
@@ -2555,59 +2653,6 @@ export async function getMessagesPageAfter(
nextCursor: previousCursor, followingCursor: cursor };
}
-/** Resolve a stable message id only when an index-based anchor became stale
- * after sync rewrote/reordered the source JSONL. Normal navigation stays on
- * the direct index window and never pays for this streaming fallback. */
-export async function findMessageIndexById(
- userId: string,
- cid: string,
- messageId: string,
- projectIdHint?: string | null,
-): Promise<number | null> {
- if (!messageId) return null;
- const sourceFile = conversationMessageReadFile(userId, cid, projectIdHint);
- let stream: fs.ReadStream | null = null;
- let lines: readline.Interface | null = null;
- let recordIndex = 0;
- let malformedRecordReported = false;
- try {
- stream = fs.createReadStream(sourceFile, { encoding: 'utf8' });
- lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
- for await (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let record: any;
- try { record = JSON.parse(trimmed); } catch (err) {
- if (!malformedRecordReported) {
- malformedRecordReported = true;
- log.warn('conversation message lookup skipped malformed records', {
- file: logPathRef(sourceFile),
- error: logErrorSummary(err),
- });
- }
- continue;
- }
- const sourceIndex = recordIndex;
- recordIndex += 1;
- if (String(record?.id || '') === messageId && !record?.deleted_at) return sourceIndex;
- }
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
- } finally {
- lines?.close();
- if (stream && !stream.closed) {
- // destroy() schedules the Windows file-handle close asynchronously.
- // Callers may immediately delete or replace the conversation tree, so
- // do not report the scan complete until that handle is actually closed.
- await new Promise<void>((resolve) => {
- stream!.once('close', resolve);
- stream!.destroy();
- });
- }
- }
- return null;
-}
-
// Navigation work owns a separate lazy worker lane: a cold index must not
// block main or delay the ordinary ten-message history page behind its scan.
export { CONVERSATION_TURN_PAGE_SIZE, CONVERSATION_TURN_USER_PREVIEW_CHARS,
diff --git a/src/main/features/conversation-history-client.ts b/src/main/features/conversation-history-client.ts
index bfbcfe81..bc2bf026 100644
--- a/src/main/features/conversation-history-client.ts
+++ b/src/main/features/conversation-history-client.ts
@@ -3,7 +3,7 @@ import * as path from 'node:path';
import { WS_ROOT } from '../paths';
export type HistoryCommand = {
- kind: 'page' | 'window' | 'project' | 'purge' | 'turns' | 'turn-purge';
+ kind: 'page' | 'window' | 'window-at-message' | 'project' | 'purge' | 'turns' | 'turn-purge' | 'process-page';
userId: string;
sourceFile: string;
cid?: string;
@@ -12,6 +12,9 @@ export type HistoryCommand = {
before?: number | null;
after?: number;
start?: number;
+ messageId?: string;
+ processRef?: string;
+ processCursor?: number;
records?: import('./group_chat/visibility').GroupMessage[];
};
diff --git a/src/main/features/conversation-history-worker.ts b/src/main/features/conversation-history-worker.ts
index 717fcd2f..e208f3cf 100644
--- a/src/main/features/conversation-history-worker.ts
+++ b/src/main/features/conversation-history-worker.ts
@@ -1,18 +1,20 @@
import { readConversationTurnPage, purgeConversationTurnIndex } from './conversation-turn-index';
import { parentPort } from 'node:worker_threads';
import type { HistoryCommand } from './conversation-history-client';
-import { readConversationHistoryPage, readConversationHistoryWindow,
- projectConversationHistoryRecords, purgeConversationHistoryCache } from './conversation_history_cache';
+import { readConversationHistoryPage, readConversationHistoryWindow, readConversationHistoryWindowAtMessage,
+ projectConversationHistoryRecords, purgeConversationHistoryCache, readConversationProcessPage } from './conversation_history_cache';
let tail = Promise.resolve();
parentPort!.on('message', (command: HistoryCommand & { id: number }) => {
tail = tail.then(async () => {
try {
let value: unknown;
- if (command.kind === 'turns') value = await readConversationTurnPage(command.userId, command.cid!, command.sourceFile, command.before, command.projectIdHint);
+ if (command.kind === 'process-page') value = await readConversationProcessPage(command.userId, command.sourceFile, command.processRef!, command.processCursor, command.messageId);
+ else if (command.kind === 'turns') value = await readConversationTurnPage(command.userId, command.cid!, command.sourceFile, command.before, command.projectIdHint);
else if (command.kind === 'turn-purge') value = await purgeConversationTurnIndex(command.userId, command.cid!);
else if (command.kind === 'page') value = await readConversationHistoryPage(command.userId, command.sourceFile, command.limit!, command.before);
else if (command.kind === 'window') value = await readConversationHistoryWindow(command.userId, command.sourceFile, command.start!, command.limit, command.after);
+ else if (command.kind === 'window-at-message') value = await readConversationHistoryWindowAtMessage(command.userId, command.sourceFile, command.messageId!, command.limit);
else if (command.kind === 'project') value = projectConversationHistoryRecords(command.userId, command.sourceFile, command.records!);
else if (command.kind === 'purge') value = await purgeConversationHistoryCache(command.userId, command.sourceFile);
else throw new Error('Unknown history operation');
diff --git a/src/main/features/conversation-process-cache.ts b/src/main/features/conversation-process-cache.ts
new file mode 100644
index 00000000..26498121
--- /dev/null
+++ b/src/main/features/conversation-process-cache.ts
@@ -0,0 +1,249 @@
+/** Worker-owned, clearable process pages. Canonical history remains lossless;
+ * the transcript carries opaque account/conversation-scoped references only. */
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
+import type { GroupMessage } from './group_chat/visibility';
+
+export type HistoryProcessPart = { ref: string; count: number; message_id?: string } | { items: NonNullable<GroupMessage['process']> };
+export const PROCESS_PAGE_ITEMS = 200;
+export const DEFER_PROCESS_ITEMS = 1000;
+export const PROCESS_PAGE_BYTES = 1024 * 1024;
+// Legacy cursors name 200-event groups. New cursors name byte-bounded pages.
+// A separate numeric range preserves an already-mounted legacy disclosure.
+const BYTE_CURSOR_BASE = 1_000_000;
+export const PROCESS_PAGE_REBUILD = 'E_PROCESS_PAGE_REBUILD';
+type Index = { offsets: number[]; bytes: number; count: number; version?: 2; legacyPages?: number[] };
+type ProcessItems = NonNullable<GroupMessage['process']>;
+
+/** Slice text without bisecting a surrogate pair; each UTF-8 buffer is small. */
+export function* processTextChunks(text: string): Generator<string> {
+ for (let start = 0; start < text.length;) {
+ let end = Math.min(start + 16 * 1024, text.length);
+ const code = text.charCodeAt(end - 1);
+ if (end < text.length && code >= 0xd800 && code <= 0xdbff
+ && text.charCodeAt(end) >= 0xdc00 && text.charCodeAt(end) <= 0xdfff) end--;
+ yield text.slice(start, end); start = end;
+ }
+}
+
+/** Canonical process records are JSON data. Stream their native JSON spelling
+ * rather than constructing a 200-output string just to hash/cache it. */
+function* jsonChunks(value: any, key = '', seen = new Set<object>(), prepared = false): Generator<string> {
+ if (!prepared && value && typeof value.toJSON === 'function') value = value.toJSON(key);
+ if (value instanceof Number || value instanceof String || value instanceof Boolean) value = value.valueOf();
+ if (typeof value === 'string') {
+ yield '"';
+ for (const chunk of processTextChunks(value)) yield JSON.stringify(chunk).slice(1, -1);
+ yield '"'; return;
+ }
+ if (!value || typeof value !== 'object') { yield JSON.stringify(value) ?? 'null'; return; }
+ if (seen.has(value)) throw new TypeError('Circular process data');
+ seen.add(value);
+ try {
+ const array = Array.isArray(value);
+ yield array ? '[' : '{';
+ let separator = '';
+ const keys = array ? (function* () { for (let n = 0; n < value.length; n++) yield String(n); })() : Object.keys(value);
+ for (const name of keys) {
+ let child = value[name];
+ if (child && typeof child.toJSON === 'function') child = child.toJSON(name);
+ if (!array && (child === undefined || typeof child === 'function' || typeof child === 'symbol')) continue;
+ yield separator; separator = ',';
+ if (!array) { yield* jsonChunks(name); yield ':'; }
+ yield* jsonChunks(child, name, seen, true);
+ }
+ yield array ? ']' : '}';
+ } finally { seen.delete(value); }
+}
+
+function boundedJson(value: unknown): string {
+ const chunks: string[] = [];
+ let bytes = 0;
+ for (const chunk of jsonChunks(value)) {
+ bytes += Buffer.byteLength(chunk);
+ if (bytes > PROCESS_PAGE_BYTES - 3) throw new Error('Process item requires bounded projection');
+ chunks.push(chunk);
+ }
+ return chunks.join('');
+}
+
+/** Preserve the structural receipts the renderer uses for terminal identity,
+ * routing-only visibility and commentary-only segments. Details stay in pages. */
+export function processSummary(items: NonNullable<GroupMessage['process']>): NonNullable<GroupMessage['process']> {
+ const summary: NonNullable<GroupMessage['process']> = [];
+ const seen = new Set<string>();
+ const runtime = new Map<string, { index: number; item: any }>();
+ let commentary = false;
+ for (const [index, item] of (items as any[]).entries()) {
+ const event = item?.event;
+ const data = event?.data;
+ if (event?.stream === 'runtime') {
+ runtime.set('latest', { index, item });
+ if (data?.phase === 'end') runtime.set('terminal', { index, item });
+ const duration = data?.bubble_duration_ms ?? data?.duration_ms ?? data?.durationMs ?? data?.elapsedMs;
+ if (duration != null && Number.isFinite(Number(duration))) runtime.set('duration', { index, item });
+ continue;
+ }
+ if (!commentary && item?.type === 'progress' && event?.stream === 'assistant' && data?.phase === 'commentary') {
+ commentary = true;
+ summary.push(item);
+ }
+ if (!data || (event?.stream !== 'tool' && !(event?.stream === 'cli' && data.type === 'tool-event'))) continue;
+ const receipt = { type: data.type, phase: data.phase, status: data.status,
+ name: data.name, tool: data.tool, toolName: data.toolName, isError: data.isError };
+ const key = event.stream + JSON.stringify(receipt);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ summary.push({ type: 'event', event: { stream: event.stream, data: receipt } });
+ }
+ const receipts = new Map([...runtime.values()].map(value => [value.index, value.item]));
+ for (const [, item] of [...receipts].sort((a, b) => a[0] - b[0])) summary.push(item);
+ return summary;
+}
+
+export function processCacheDirectory(entryDir: string): string {
+ return path.join(entryDir, 'process-records');
+}
+
+/** Allows a compact transcript to survive unavailable cache storage. Once
+ * storage recovers, the same content address can be rebuilt on disclosure. */
+export function processPageReference(items: NonNullable<GroupMessage['process']>): string {
+ const hash = createHash('sha256');
+ for (let n = 0; n < items.length; n++) {
+ hash.update(n % PROCESS_PAGE_ITEMS === 0 ? '[' : ',');
+ for (const chunk of jsonChunks(items[n], String(n % PROCESS_PAGE_ITEMS))) hash.update(chunk);
+ if ((n + 1) % PROCESS_PAGE_ITEMS === 0 || n + 1 === items.length) hash.update(']\n');
+ }
+ return hash.digest('hex');
+}
+
+/** One pass, bounded serialization buffers and sparse page offsets. Raw
+ * outputs are projected only when the corresponding process page is opened. */
+export function storeProcessPages(entryDir: string, items: ProcessItems,
+ projectLargeItem?: (item: ProcessItems[number]) => Iterable<ProcessItems[number]>): HistoryProcessPart {
+ const directory = processCacheDirectory(entryDir);
+ fs.mkdirSync(directory, { recursive: true });
+ const temporary = path.join(directory, randomUUID() + '.tmp');
+ const fd = fs.openSync(temporary, 'wx', 0o600);
+ const hash = createHash('sha256');
+ const offsets: number[] = [];
+ const legacyPages: number[] = [];
+ let bytes = 0;
+ let page: string[] = [];
+ let pageBytes = 3;
+ const flush = (force = false) => {
+ if (!page.length && !force) return;
+ offsets.push(bytes);
+ const buffer = Buffer.from('[' + page.join(',') + ']\n');
+ let written = 0;
+ while (written < buffer.length) {
+ const count = fs.writeSync(fd, buffer, written, buffer.length - written);
+ if (count <= 0) throw new Error('Process cache write did not advance');
+ written += count;
+ }
+ bytes += buffer.length; page = []; pageBytes = 3;
+ };
+ const append = (json: string) => {
+ const size = Buffer.byteLength(json);
+ if (page.length && (page.length === PROCESS_PAGE_ITEMS || pageBytes + size + 1 > PROCESS_PAGE_BYTES)) flush();
+ pageBytes += size + (page.length ? 1 : 0); page.push(json);
+ };
+ try {
+ for (let n = 0; n < items.length; n++) {
+ if (n % PROCESS_PAGE_ITEMS === 0) {
+ if (n) flush(offsets.length === legacyPages.at(-1));
+ legacyPages.push(offsets.length); hash.update('[');
+ }
+ else hash.update(',');
+ let size = 0;
+ let chunks: string[] = [];
+ for (const chunk of jsonChunks(items[n], String(n % PROCESS_PAGE_ITEMS))) {
+ hash.update(chunk); size += Buffer.byteLength(chunk);
+ if (size <= PROCESS_PAGE_BYTES - 3) chunks.push(chunk);
+ else chunks = [];
+ }
+ if (size <= PROCESS_PAGE_BYTES - 3) append(chunks.join(''));
+ else {
+ if (!projectLargeItem) throw new Error('Process item requires bounded projection');
+ for (const item of projectLargeItem(items[n])) append(boundedJson(item));
+ }
+ if ((n + 1) % PROCESS_PAGE_ITEMS === 0 || n + 1 === items.length) hash.update(']\n');
+ }
+ flush(items.length > 0 && offsets.length === legacyPages.at(-1));
+ } catch (error) {
+ fs.closeSync(fd);
+ fs.rmSync(temporary, { force: true });
+ throw error;
+ }
+ fs.closeSync(fd);
+ const ref = hash.digest('hex');
+ const destination = path.join(directory, ref + '.v2.jsonl');
+ try {
+ if (!fs.existsSync(destination)) fs.renameSync(temporary, destination);
+ } finally { fs.rmSync(temporary, { force: true }); }
+ const indexFile = path.join(directory, ref + '.v2.json');
+ if (!fs.existsSync(indexFile)) {
+ const indexTemporary = indexFile + '.' + randomUUID() + '.tmp';
+ try {
+ const index = JSON.stringify({ version: 2, offsets, legacyPages, bytes, count: items.length });
+ if (Buffer.byteLength(index) > 4 * 1024 * 1024) throw new Error('Process index too large');
+ fs.writeFileSync(indexTemporary, index, { mode: 0o600 });
+ fs.renameSync(indexTemporary, indexFile);
+ } finally { fs.rmSync(indexTemporary, { force: true }); }
+ }
+ return { ref, count: items.length };
+}
+
+export async function readProcessPage(entryDir: string, ref: string, cursor = 0): Promise<{
+ items: NonNullable<GroupMessage['process']>; nextCursor: number | null;
+}> {
+ if (!/^[a-f0-9]{64}$/.test(ref) || !Number.isSafeInteger(cursor) || cursor < 0) {
+ throw new Error('Invalid process page');
+ }
+ const directory = processCacheDirectory(entryDir);
+ let indexFile = path.join(directory, ref + '.v2.json');
+ let stat;
+ try { stat = await fsp.lstat(indexFile); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ indexFile = path.join(directory, ref + '.json'); stat = await fsp.lstat(indexFile);
+ }
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024) throw new Error('Invalid process index');
+ const index: Index = JSON.parse(await fsp.readFile(indexFile, 'utf8'));
+ const version2 = index.version === 2;
+ if (indexFile.endsWith('.v2.json') && (!version2 || !Array.isArray(index.legacyPages))) throw new Error('Invalid process index');
+ const pageCursor = version2 ? (cursor >= BYTE_CURSOR_BASE ? cursor - BYTE_CURSOR_BASE : index.legacyPages?.[cursor]) : cursor;
+ if (!Array.isArray(index.offsets) || !Number.isSafeInteger(pageCursor) || pageCursor! < 0 || pageCursor! >= index.offsets.length
+ || !Number.isSafeInteger(index.bytes) || index.bytes < 0) throw new Error('Invalid process cursor');
+ const start = index.offsets[pageCursor!];
+ const end = index.offsets[pageCursor! + 1] ?? index.bytes;
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end <= start) {
+ throw new Error('Invalid process range');
+ }
+ if (end - start > PROCESS_PAGE_BYTES) {
+ if (!version2) throw Object.assign(new Error('Process cache rebuild required'), { code: PROCESS_PAGE_REBUILD });
+ throw new Error('Invalid process range');
+ }
+ const dataFile = path.join(directory, ref + (version2 ? '.v2.jsonl' : '.jsonl'));
+ const dataStat = await fsp.lstat(dataFile);
+ if (!dataStat.isFile() || dataStat.isSymbolicLink()) throw new Error('Invalid process data');
+ const file = await fsp.open(dataFile, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0) | (fs.constants.O_NOFOLLOW || 0));
+ try {
+ const openedStat = await file.stat();
+ if (!openedStat.isFile() || end > openedStat.size) throw new Error('Process page unavailable');
+ const buffer = Buffer.allocUnsafe(end - start);
+ let read = 0;
+ while (read < buffer.length) {
+ const { bytesRead } = await file.read(buffer, read, buffer.length - read, start + read);
+ if (!bytesRead) throw new Error('Process page unavailable');
+ read += bytesRead;
+ }
+ const items = JSON.parse(buffer.toString('utf8'));
+ if (!Array.isArray(items) || items.length > PROCESS_PAGE_ITEMS) throw new Error('Invalid process page');
+ return { items, nextCursor: pageCursor! + 1 < index.offsets.length ? (version2 ? BYTE_CURSOR_BASE : 0) + pageCursor! + 1 : null };
+ } finally {
+ await file.close();
+ }
+}
diff --git a/src/main/features/conversation-turn-index.ts b/src/main/features/conversation-turn-index.ts
index e245cc7b..d228c800 100644
--- a/src/main/features/conversation-turn-index.ts
+++ b/src/main/features/conversation-turn-index.ts
@@ -36,7 +36,9 @@ function _messageText(raw: any): string {
* address for every user turn. This machine-local derived index is deliberately
* compact and rebuildable: it never enters sync or the conversation metadata.
*/
-const CONVERSATION_TURN_INDEX_VERSION = 2;
+// Bump when stored previews change shape or budget: an index built by an
+// older version is rebuilt once from the source transcript on its next read.
+const CONVERSATION_TURN_INDEX_VERSION = 3;
const CONVERSATION_TURN_FINGERPRINT_BYTES = 4 * 1024;
interface ConversationTurnIndexSource {
owner: string;
diff --git a/src/main/features/conversation-turn-types.ts b/src/main/features/conversation-turn-types.ts
index afd5881d..43835614 100644
--- a/src/main/features/conversation-turn-types.ts
+++ b/src/main/features/conversation-turn-types.ts
@@ -1,6 +1,6 @@
export const CONVERSATION_TURN_PAGE_SIZE = 15;
-export const CONVERSATION_TURN_USER_PREVIEW_CHARS = 40;
-export const CONVERSATION_TURN_ASSISTANT_PREVIEW_CHARS = 80;
+export const CONVERSATION_TURN_USER_PREVIEW_CHARS = 100;
+export const CONVERSATION_TURN_ASSISTANT_PREVIEW_CHARS = 240;
export interface ConversationTurnIndexEntry {
messageId: string;
diff --git a/src/main/features/conversation_assistance_context.ts b/src/main/features/conversation_assistance_context.ts
index 0e096cc9..7f130331 100644
--- a/src/main/features/conversation_assistance_context.ts
+++ b/src/main/features/conversation_assistance_context.ts
@@ -1,9 +1,37 @@
/** Feature-owned guidance from explicit task entry metadata, rebuilt per Commander turn. */
import * as chats from './chats';
+import * as projectTasks from './project_tasks';
+import { createLogger } from '../logger';
import { prompts } from '../prompts/loader';
+import { logErrorSummary } from '../util/log-redact';
import { formatConnectorSetupAssistance } from './connector_setup_context';
import { hasPendingConversationFiling } from './conversation_filing';
+const log = createLogger('conversation-assistance');
+const LISTED_OPEN_TODO_IDS = 3;
+
+/** Open to-dos linked to this conversation, in the conversation's own to-do
+ * scope. Only their count and ids reach the model; content can run to
+ * thousands of characters, so it stays behind `todo_tasks` get. */
+async function openTodosGuidance(userId: string, cid: string, projectId: string): Promise<string> {
+ let tasks: projectTasks.ProjectTask[];
+ try {
+ tasks = await projectTasks.listTasks(userId, projectId);
+ } catch (err) {
+ log.warn('open to-dos unavailable for turn guidance', { error: logErrorSummary(err) });
+ return '';
+ }
+ const open = tasks
+ .filter((task) => task.origin_cid === cid && task.status !== 'done')
+ .sort((a, b) => String(b.updated_at || '').localeCompare(String(a.updated_at || '')));
+ if (!open.length) return '';
+ const listed = open.slice(0, LISTED_OPEN_TODO_IDS).map((task) => task.id);
+ return prompts.load('conversation_open_todos', {
+ count: String(open.length),
+ ids: listed.join(', ') + (open.length > listed.length ? ', …' : ''),
+ }).trim();
+}
+
export async function resolveConversationAssistanceForTurn(userId: string, cid: string): Promise<{
kind?: chats.ConversationAssistance['kind'];
guidance: string;
@@ -17,8 +45,9 @@ export async function resolveConversationAssistanceForTurn(userId: string, cid:
&& !hasPendingConversationFiling(userId, cid)
? prompts.load('followup_offer_guidance').trim()
: '';
+ const openTodos = conversation ? await openTodosGuidance(userId, cid, conversation.project_id || '') : '';
return {
kind: assistance?.kind,
- guidance: [entryGuidance, followUp].filter(Boolean).join('\n\n'),
+ guidance: [entryGuidance, followUp, openTodos].filter(Boolean).join('\n\n'),
};
}
diff --git a/src/main/features/conversation_history_cache.ts b/src/main/features/conversation_history_cache.ts
index 4d7e98e9..e17911ec 100644
--- a/src/main/features/conversation_history_cache.ts
+++ b/src/main/features/conversation_history_cache.ts
@@ -17,18 +17,20 @@ import { isMainThread } from 'node:worker_threads';
import { historyRequest } from './conversation-history-client';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import { userConversationHistoryCacheDir } from '../paths';
import { createLogger } from '../logger';
import { logErrorSummary, logPathRef } from '../util/log-redact';
-import { persistToolResult } from '../util/tool-result-cap';
-import { readJson, readJsonlPageWithOffsets, readJsonlWindow, writeJson } from '../storage';
+import { persistToolResult, TOOL_RESULT_REF_HASH_HEX } from '../util/tool-result-cap';
+import { readJson, readJsonlPageWithOffsets, readJsonlWindow, readJsonlWindowAtMatch, writeJson } from '../storage';
import type { JsonlPage, JsonlRecordWithOffset, JsonlWindow } from '../storage';
import type { GroupMessage } from './group_chat/visibility';
+import { normalizeNativeMessageDisplay } from './group_chat/message-display';
+import { DEFER_PROCESS_ITEMS, PROCESS_PAGE_REBUILD, PROCESS_PAGE_BYTES, processTextChunks, storeProcessPages, processSummary, readProcessPage, processPageReference } from './conversation-process-cache';
const log = createLogger('conversation-history-cache');
-const CACHE_VERSION = 4;
+const CACHE_VERSION = 6;
const MAX_INLINE_PROCESS_OUTPUT_BYTES = 1024;
const MAX_FAILURE_OUTPUT_PREVIEW_CHARS = 600;
const SOURCE_TAIL_FINGERPRINT_BYTES = 4 * 1024;
@@ -117,7 +119,9 @@ function cachePaths(userId: string, sourceFile: string): CachePaths {
const entryDir = path.join(userConversationHistoryCacheDir(userId), key);
return {
entryDir,
- latestPageFile: path.join(entryDir, 'latest-page.json'),
+ // Never parse an older, potentially hundreds-of-megabytes projection just
+ // to discover its version. A new filename makes invalidation cheap.
+ latestPageFile: path.join(entryDir, 'latest-page-v6.json'),
toolResultsDir: path.join(entryDir, 'tool-results'),
};
}
@@ -182,6 +186,33 @@ function serializedProcessOutput(output: unknown): string | null {
}
}
+/** Same durable content address as ordinary results, with bounded write buffers. */
+function persistLargeHistoryOutput(directory: string, toolName: string, output: string): string {
+ const hash = createHash('sha256').update(toolName).update('\0');
+ for (const chunk of processTextChunks(output)) hash.update(chunk);
+ const safeTool = toolName.replace(/[^a-zA-Z0-9_-]+/g, '_').slice(0, 48) || 'tool';
+ const destination = path.join(directory, `${safeTool}.${hash.digest('hex').slice(0, TOOL_RESULT_REF_HASH_HEX)}.txt`);
+ fs.mkdirSync(directory, { recursive: true });
+ if (fs.existsSync(destination)) return destination;
+ const temporary = `${destination}.${randomUUID()}.tmp`;
+ try {
+ const fd = fs.openSync(temporary, 'wx', 0o600);
+ try {
+ for (const chunk of processTextChunks(output)) {
+ const buffer = Buffer.from(chunk);
+ let written = 0;
+ while (written < buffer.length) {
+ const count = fs.writeSync(fd, buffer, written, buffer.length - written);
+ if (count <= 0) throw new Error('History result write did not advance');
+ written += count;
+ }
+ }
+ } finally { fs.closeSync(fd); }
+ fs.renameSync(temporary, destination);
+ return destination;
+ } finally { fs.rmSync(temporary, { force: true }); }
+}
+
function spillProcessOutput(
data: Record<string, unknown>,
stream: string,
@@ -220,7 +251,9 @@ function spillProcessOutput(
const toolName = String(data.name || data.tool || data.toolName || 'tool');
try {
- const resultPath = persistToolResult(toolResultsDir, toolName, output);
+ const resultPath = Buffer.byteLength(output) > PROCESS_PAGE_BYTES
+ ? persistLargeHistoryOutput(toolResultsDir, toolName, output)
+ : persistToolResult(toolResultsDir, toolName, output);
delete next.output;
if (stream === 'cli') next.outputPath = resultPath;
else {
@@ -304,6 +337,7 @@ export function projectConversationHistoryRecord(
record: GroupMessage,
toolResultsDir: string,
): GroupMessage {
+ record = normalizeNativeMessageDisplay(record);
if (!Array.isArray(record.process) || !record.process.length) return record;
const process = record.process
.map((item) => projectProcessItem(item, toolResultsDir))
@@ -321,6 +355,52 @@ export function projectConversationHistoryRecords(
return records.map((record) => projectConversationHistoryRecord(record, toolResultsDir));
}
+function projectHistoryRecord(userId: string, sourceFile: string, record: GroupMessage): GroupMessage {
+ record = normalizeNativeMessageDisplay(record);
+ const { entryDir, toolResultsDir } = cachePaths(userId, sourceFile);
+ if (Array.isArray(record.process) && record.process.length > DEFER_PROCESS_ITEMS) {
+ let part;
+ try {
+ part = storeProcessPages(entryDir, record.process, item => {
+ const projected = projectProcessItem(item, toolResultsDir);
+ return projected === null ? [] : [projected as NonNullable<GroupMessage['process']>[number]];
+ });
+ }
+ catch {
+ // First paint must not depend on derived-cache write availability.
+ // Keep the complete canonical trail addressable for a later retry.
+ part = { ref: processPageReference(record.process), count: record.process.length };
+ log.warn('conversation process cache unavailable', { failure_stage: 'process_cache' });
+ }
+ return { ...record, process: processSummary(record.process), process_parts: [{ ...part, message_id: record.id }] };
+ }
+ return projectConversationHistoryRecord(record, toolResultsDir);
+}
+
+function projectHistoryRecords(userId: string, sourceFile: string, records: GroupMessage[]): GroupMessage[] {
+ return records.map(record => projectHistoryRecord(userId, sourceFile, record));
+}
+
+export async function readConversationProcessPage(
+ userId: string, sourceFile: string, processRef: string, processCursor = 0, messageId?: string,
+): Promise<{ items: NonNullable<GroupMessage['process']>; nextCursor: number | null }> {
+ if (isMainThread) return historyRequest({ kind: 'process-page', userId, sourceFile, processRef, processCursor, messageId });
+ const { entryDir, toolResultsDir } = cachePaths(userId, sourceFile);
+ let page;
+ try { page = await readProcessPage(entryDir, processRef, processCursor); }
+ catch (error) {
+ // Cache clearing is reversible even while its disclosure is mounted.
+ // Rebuild once from the named canonical message, never from a supplied path.
+ if (!['ENOENT', PROCESS_PAGE_REBUILD].includes((error as NodeJS.ErrnoException).code || '') || !messageId) throw error;
+ const window = await readConversationHistoryWindowAtMessage(userId, sourceFile, messageId, 1);
+ if (!window?.records.some(record => record.process_parts?.some(part => 'ref' in part && part.ref === processRef))) {
+ throw new Error('Process history changed');
+ }
+ page = await readProcessPage(entryDir, processRef, processCursor);
+ }
+ return { ...page, items: page.items.map(item => projectProcessItem(item, toolResultsDir)).filter(item => item !== null) as NonNullable<GroupMessage['process']> };
+}
+
async function sourceTailHash(sourceFile: string, size: number): Promise<string> {
const start = Math.max(0, size - SOURCE_TAIL_FINGERPRINT_BYTES);
const length = size - start;
@@ -440,7 +520,7 @@ async function coldLatestPage(
const startedAt = Date.now();
const page = await readJsonlPageWithOffsets<GroupMessage>(sourceFile, wanted, identity.size);
const readFinishedAt = Date.now();
- const projected = projectConversationHistoryRecords(
+ const projected = projectHistoryRecords(
userId,
sourceFile,
page.entries.map(({ record }) => record),
@@ -487,7 +567,7 @@ async function extendLatestPage(
cached.source.size,
identity.size,
);
- const projected = projectConversationHistoryRecords(
+ const projected = projectHistoryRecords(
userId,
sourceFile,
appended.map(({ record }) => record),
@@ -532,6 +612,8 @@ async function buildLatestPage(
if (sameSourceSnapshot(next.source, snapshotIdentity(after))) {
await fsp.mkdir(files.entryDir, { recursive: true });
await writeJson(files.latestPageFile, next);
+ await fsp.rm(path.join(files.entryDir, 'latest-page.json'), { force: true });
+ await fsp.rm(path.join(files.entryDir, 'latest-page-v5.json'), { force: true });
return next;
}
// A message landed while the page was being projected. Keep the valid
@@ -573,7 +655,7 @@ async function latestPage(
// Stabilization/cache failures must not make history unavailable.
const page = await readJsonlPageWithOffsets<GroupMessage>(sourceFile, wanted);
return {
- records: projectConversationHistoryRecords(
+ records: projectHistoryRecords(
userId,
sourceFile,
page.entries.map(({ record }) => record),
@@ -599,7 +681,7 @@ export async function readConversationHistoryPage(
}
const page = await readJsonlPageWithOffsets<GroupMessage>(sourceFile, wanted, before ?? undefined);
return {
- records: projectConversationHistoryRecords(
+ records: projectHistoryRecords(
userId,
sourceFile,
page.entries.map(({ record }) => record),
@@ -624,9 +706,19 @@ export async function readConversationHistoryWindow(
userId: string, sourceFile: string, start: number, limit = 10, after = 0,
): Promise<JsonlWindow<GroupMessage>> {
if (isMainThread) return historyRequest({ kind: 'window', userId, sourceFile, start, limit, after });
- const { toolResultsDir } = cachePaths(userId, sourceFile);
return readJsonlWindow<GroupMessage>(sourceFile, start, limit,
- record => projectConversationHistoryRecord(record, toolResultsDir), after);
+ record => projectHistoryRecord(userId, sourceFile, record), after);
+}
+
+/** Project the page holding a message id. The worker finds it and reads the
+ * page in one pass, so a quoted reference never parses history on main. */
+export async function readConversationHistoryWindowAtMessage(
+ userId: string, sourceFile: string, messageId: string, limit = 10,
+): Promise<(JsonlWindow<GroupMessage> & { start: number; index: number }) | null> {
+ if (isMainThread) return historyRequest({ kind: 'window-at-message', userId, sourceFile, messageId, limit });
+ return readJsonlWindowAtMatch<GroupMessage>(sourceFile,
+ record => String(record?.id || '') === messageId && !record?.deleted_at, limit,
+ record => projectHistoryRecord(userId, sourceFile, record));
}
/** Active turns have no complete disk snapshot yet. Clone one record at a time
diff --git a/src/main/features/project_files.ts b/src/main/features/project_files.ts
index 7c37ef59..17964f41 100644
--- a/src/main/features/project_files.ts
+++ b/src/main/features/project_files.ts
@@ -82,6 +82,7 @@ export interface ProjectFileInfo {
name: string;
relPath: string;
type: 'file';
+ pending?: boolean;
path: string;
bytes: number;
kind: ProjectFileKind;
@@ -386,6 +387,11 @@ export async function listProjectFileTree(userId: string, projectId: string): Pr
}
}
+/** UI placeholders are separate from the usable Library/tool inventory. */
+export async function listProjectFileTreeForDisplay(userId: string, projectId: string): Promise<ProjectLibraryNode[]> {
+ return listProjectFileTree(userId, projectId);
+}
+
export async function listProjectFiles(userId: string, projectId: string): Promise<ProjectFileInfo[]> {
return flattenFiles(await listProjectFileTree(userId, projectId));
}
diff --git a/src/main/features/projects.ts b/src/main/features/projects.ts
index f5a7c479..620aa21b 100644
--- a/src/main/features/projects.ts
+++ b/src/main/features/projects.ts
@@ -114,7 +114,7 @@ async function withProjectInstructionsMutationLock<T>(
export interface Project {
project_id: string;
name: string;
- /** Reserved for future collaboration. Single-machine = active uid. */
+ /** Current account uid for private projects; Server owner uid for shared projects, or empty if unknown. */
owner_uid: string;
created_at: string;
updated_at: string;
@@ -259,7 +259,8 @@ function _normaliseProject(raw: any, uid: string, pid: string): Project {
return {
project_id: typeof raw.project_id === 'string' ? raw.project_id : pid,
name: typeof raw.name === 'string' ? raw.name : '',
- owner_uid: typeof raw.owner_uid === 'string' && raw.owner_uid ? raw.owner_uid : uid,
+ // Local profile ownership remains independent of hosted membership.
+ owner_uid: uid,
created_at: typeof raw.created_at === 'string' ? raw.created_at : now,
updated_at: typeof raw.updated_at === 'string' ? raw.updated_at : now,
};
@@ -374,8 +375,9 @@ export async function listProjects(uid: string): Promise<ProjectWithStats[]> {
convCount: conversationCounts.get(project.project_id) || 0,
} : null);
const projects = entries.filter((entry): entry is { project: Project; convCount: number } => entry !== null);
- // Display-name order is shared by the sidebar and every picker backed by
- // `projects.list`. Numeric comparison keeps names such as Project 2 before
+ // Shared projects lead; display-name order within each group is shared by
+ // the sidebar and every picker backed by `projects.list`.
+ // Numeric comparison keeps names such as Project 2 before
// Project 10; project_id is a deterministic fallback for malformed legacy
// data that collates to the same display name.
const locale = getLocaleMeta(getCurrentLang()).intlLocale;
diff --git a/src/main/features/recycle_bin.ts b/src/main/features/recycle_bin.ts
index b8053b20..046839a7 100644
--- a/src/main/features/recycle_bin.ts
+++ b/src/main/features/recycle_bin.ts
@@ -15,6 +15,7 @@ import * as fs from 'node:fs';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
+import { Mutex } from 'async-mutex';
import { createLogger } from '../logger';
import { projectMetaFile, userCloudRoot, userRecycleDir, userSyncRecycleDir } from '../paths';
import {
@@ -701,11 +702,62 @@ async function autoTaskTitle(uid: string, batchId: string | undefined, taskId: s
batchId,
pid ? `cloud/projects/${pid}/auto_tasks/${taskId}/config.json` : `cloud/auto_tasks/${taskId}/config.json`,
);
+ return autoTaskConfigTitle(cfg, taskId);
+}
+
+function autoTaskConfigTitle(cfg: Record<string, any> | null, taskId: string): string {
return titleFromJson(cfg, ['title'])
|| cleanTitle(typeof cfg?.content === 'string' ? cfg.content.split(/\r?\n/, 1)[0] : '')
|| taskId;
}
+async function autoTaskDisplayItem(
+ uid: string,
+ batchId: string | undefined,
+ metadata: SyncRecycleMetadata | undefined,
+ relPath: string,
+ cfg: Record<string, any> | null,
+ projectTitles: Map<string, Promise<string>>,
+): Promise<RecycleDisplayItem> {
+ const taskId = autoTaskRootDeletedId(relPath)!;
+ const project = projectAutoTaskConfigInfo(relPath);
+ const pid = project?.pid || (safeId(cfg?.project_id) ? cfg!.project_id : '');
+ if (pid && !projectTitles.has(pid)) {
+ projectTitles.set(pid, projectTitle(uid, batchId, metadata, pid));
+ }
+ const detail = pid ? await projectTitles.get(pid) : undefined;
+ return {
+ category: 'auto_task', id: taskId, path: relPath,
+ title: autoTaskConfigTitle(cfg, taskId),
+ ...(detail ? { detail } : {}),
+ };
+}
+
+async function refreshLegacyAutoTaskDisplay(uid: string, batch: SyncRecycleBatch): Promise<void> {
+ if (!batch.display_items?.some(item => item.category === 'auto_task')) return;
+ const configs = new Map<string, string>();
+ for (const item of batch.items) {
+ const taskId = autoTaskRootDeletedId(item.path);
+ if (taskId) configs.set(taskId, item.path);
+ }
+ const projectTitles = new Map<string, Promise<string>>();
+ for (const item of batch.display_items || []) {
+ if (item.category !== 'auto_task') continue;
+ const taskId = item.id || autoTaskRootDeletedId(item.path || '') || '';
+ const relPath = configs.get(taskId);
+ if (!relPath) continue;
+ const project = projectAutoTaskConfigInfo(relPath);
+ if (item.title !== taskId && item.path === relPath && (!project || item.detail)) continue;
+ // Repair display metadata only from the snapshot: live tasks may have
+ // changed since deletion. Keep a saved name if the archive is unavailable.
+ const cfg = parseJsonText(await readRecycleText(uid, batch.id, relPath));
+ const updated = await autoTaskDisplayItem(uid, batch.id, batch.metadata, relPath, cfg, projectTitles);
+ item.path = relPath;
+ if (updated.title !== taskId) item.title = updated.title;
+ if (updated.detail) item.detail = updated.detail;
+ }
+}
+
async function agentTitle(uid: string, batchId: string | undefined, agentId: string): Promise<string> {
if (!agentId) return '';
const obj = await readDisplayJson(uid, batchId, `cloud/agents/${agentId}/agent.json`);
@@ -829,6 +881,8 @@ async function buildRecycleDisplayItems(
const editConversationRoots = new Map<string, { kind: 'agent' | 'skill'; id: string }>();
const projectRoots = new Set<string>();
const taskRoots = new Set<string>();
+ const taskConfigs = new Set<string>();
+ const taskProjectTitles = new Map<string, Promise<string>>();
const agentRoots = new Set<string>();
const skillRoots = new Set<string>();
const appRoots = new Set<string>();
@@ -861,7 +915,10 @@ async function buildRecycleDisplayItems(
const pid = projectRootDeletedId(relPath);
if (pid) projectRoots.add(pid);
const taskId = autoTaskRootDeletedId(relPath);
- if (taskId) taskRoots.add(taskId);
+ if (taskId) {
+ taskRoots.add(taskId);
+ taskConfigs.add(relPath);
+ }
const agentId = /^cloud\/agents\/([^/]+)\/agent\.json$/.exec(relPath)?.[1] || '';
if (safeId(agentId)) agentRoots.add(agentId);
const skillId = /^cloud\/skills\/([^/]+)\/SKILL\.md$/.exec(relPath)?.[1] || '';
@@ -924,13 +981,9 @@ async function buildRecycleDisplayItems(
title: await projectTitle(uid, batchId, metadata, pid),
});
}
- for (const taskId of taskRoots) {
- add({
- category: 'auto_task',
- id: taskId,
- path: `cloud/auto_tasks/${taskId}/config.json`,
- title: await autoTaskTitle(uid, batchId, taskId),
- });
+ for (const relPath of taskConfigs) {
+ const cfg = await readDisplayJson(uid, batchId, relPath);
+ add(await autoTaskDisplayItem(uid, batchId, metadata, relPath, cfg, taskProjectTitles));
}
for (const agentId of agentRoots) {
add({
@@ -1575,6 +1628,8 @@ async function readBatch(uid: string, batchId: string): Promise<SyncRecycleBatch
batch.label,
);
if (displayItems.length) batch.display_items = displayItems;
+ } else {
+ await refreshLegacyAutoTaskDisplay(uid, batch);
}
return batch;
} catch (err: any) {
@@ -1948,6 +2003,47 @@ export async function listRecycleBatches(uid: string): Promise<SyncRecycleBatch[
return batches;
}
+const editRetentionLocks = new Map<string, Mutex>();
+/** Restore and permanent cleanup must not observe each other's partial ownership. */
+export function withEditSnapshotRetention<T>(uid: string, action: () => Promise<T>): Promise<T> {
+ let lock = editRetentionLocks.get(uid);
+ if (!lock) { lock = new Mutex(); editRetentionLocks.set(uid, lock); }
+ return lock.runExclusive(action);
+}
+
+/** Strict ownership inventory: a partial or unreadable archive postpones cleanup. */
+export async function retainedEditConversationIds(uid: string): Promise<Set<string>> {
+ await migrateLegacySyncRecycle(uid);
+ try {
+ const legacy = await fsp.readdir(userSyncRecycleDir(uid), { withFileTypes: true });
+ if (legacy.some(entry => entry.isDirectory() || entry.isSymbolicLink())) throw new Error('pending recycle migration');
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ const ids = new Set<string>();
+ let entries: fs.Dirent[];
+ try { entries = await fsp.readdir(userRecycleDir(uid), { withFileTypes: true }); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ids; throw error; }
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) throw new Error('unsafe recycle entry');
+ if (!entry.isDirectory()) continue;
+ const file = batchMetaFile(uid, entry.name);
+ await assertLocalImportTarget(userRecycleDir(uid), file);
+ const raw = JSON.parse(await fsp.readFile(file, 'utf8'));
+ const batch = normalizeBatch(raw);
+ if (!batch || !Array.isArray(raw.items) || batch.items.length !== raw.items.length) throw new Error('incomplete recycle metadata');
+ if (raw.metadata?.chat_index_rows && (!Array.isArray(raw.metadata.chat_index_rows)
+ || raw.metadata.chat_index_rows.length !== (batch.metadata?.chat_index_rows || []).length)) throw new Error('invalid recycle ownership');
+ for (const row of batch.metadata?.chat_index_rows || []) {
+ if (safeId(row.conversation_id)) ids.add(row.conversation_id);
+ }
+ for (const item of batch.items) {
+ const cid = chatCidFromRelPath(item.path)
+ || /^cloud\/(?:chat_attachments|chat_artifacts)\/([^/]+)(?:\/|$)/.exec(item.path)?.[1];
+ if (cid && safeId(cid)) ids.add(cid);
+ }
+ }
+ return ids;
+}
+
export async function deleteRecycleBatch(uid: string, batchId: string): Promise<{ deleted: boolean }> {
await migrateLegacySyncRecycle(uid);
const batch = await readBatch(uid, batchId);
@@ -1959,7 +2055,8 @@ export async function deleteRecycleBatch(uid: string, batchId: string): Promise<
return { deleted: false };
}
try {
- await fsp.rm(batchDir(uid, batchId), { recursive: true, force: true });
+ await withEditSnapshotRetention(uid, () => fsp.rm(batchDir(uid, batchId), { recursive: true, force: true }));
+ await (await import('./saved_apps')).cleanupEditSnapshots(uid);
log.info('deleted recycle batch', {
user_id: maskId(uid),
...logRecycleBatchRef(batch),
@@ -1975,7 +2072,11 @@ export async function deleteRecycleBatch(uid: string, batchId: string): Promise<
}
}
-export async function restoreRecycleBatch(
+export function restoreRecycleBatch(uid: string, batchId: string) {
+ return withEditSnapshotRetention(uid, () => restoreBatch(uid, batchId));
+}
+
+async function restoreBatch(
uid: string,
batchId: string,
): Promise<{
diff --git a/src/main/features/task_cleanup.ts b/src/main/features/task_cleanup.ts
new file mode 100644
index 00000000..09a7d96e
--- /dev/null
+++ b/src/main/features/task_cleanup.ts
@@ -0,0 +1,137 @@
+/** Settings-only history maintenance. No model or application-SDK authority.
+ * Preview reads index metadata once and only inspects old, unprotected tasks.
+ * Receipts freeze membership; each deletion revalidates after its backup.
+ * Recycle data stays local and uses the existing task storage category.
+ */
+import { randomUUID } from 'node:crypto';
+import * as path from 'node:path';
+import * as fs from 'node:fs/promises';
+import * as chats from './chats';
+import * as recycle from './recycle_bin';
+import { isQuiescent } from './group_chat/bus';
+import { hasPendingAttachmentsForCleanup } from './chat_attachments';
+import { conversationLayout } from '../util/project-layout';
+import { safeId } from '../storage';
+
+const PAGE_SIZE = 20;
+const TTL = 30 * 60 * 1000;
+interface Row { cid: string; title: string; activeAt: string; projectId: string | null; }
+interface Snapshot {
+ token: string; expires: number; cutoff: number; rows: Row[];
+ members: Map<string, string | null>; remaining: Set<string>; busy: boolean;
+}
+const snapshots = new Map<string, Snapshot>();
+const previewing = new Set<string>();
+function activity(c: chats.Conversation) { return Math.max(Date.parse(c.updated_at), Date.parse(c.created_at)); }
+function eligible(c: chats.Conversation | null, cutoff: number): boolean {
+ return !!c && c.kind === 'normal' && (!c.project_id || safeId(c.project_id)) && !c.origin_auto_task_id
+ && !c.deleted_at && !c.pinned_at && safeId(c.conversation_id)
+ && Number.isFinite(activity(c)) && activity(c) < cutoff;
+}
+function quiescent(uid: string, cid: string): boolean {
+ return isQuiescent(uid, cid);
+}
+async function smallJson(filePath: string): Promise<any> {
+ const file = await fs.open(filePath, 'r');
+ try {
+ const size = (await file.stat()).size;
+ if (size > 2 * 1024 * 1024) return null;
+ const buffer = Buffer.alloc(size + 1);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ return bytesRead === size ? JSON.parse(buffer.subarray(0, size).toString('utf8')) : null;
+ } finally { await file.close(); }
+}
+async function completed(uid: string, cid: string, projectId: string | null, cutoff: number): Promise<boolean> {
+ if (!quiescent(uid, cid)) return false;
+ const layout = conversationLayout(uid, cid, projectId);
+ if (layout.projectId !== projectId) return false;
+ try {
+ // Missing/corrupt records are unknown, never proof of completion. Do not
+ // load the board runtime: that reader reconciles stale queued executions.
+ const [state, tasks] = await Promise.all([
+ smallJson(layout.stateFile),
+ smallJson(path.join(path.dirname(layout.stateFile), 'tasks.json')),
+ ]);
+ if (state?.status !== 'idle' || !Array.isArray(state.in_flight) || state.in_flight.length
+ || state.orchestration_ledger || !Array.isArray(tasks) || !tasks.length) return false;
+ if (!Number.isFinite(Date.parse(state.last_active_at)) || Date.parse(state.last_active_at) >= cutoff) return false;
+ if (tasks.some(t => !t || !['done', 'failed', 'stopped', 'cancelled'].includes(t.status))) return false;
+ const roots = tasks.filter(t => t.created_by === 'user' && !t.parent_task_id && !t.absorbed_into_task_id);
+ if (!roots.length || roots.some(t => !Number.isFinite(Date.parse(t.created_at)))) return false;
+ const latest = roots.reduce((a, b) => Date.parse(a.created_at) >= Date.parse(b.created_at) ? a : b);
+ const peers = roots.filter(t => t === latest || (latest.source_msg_id && t.source_msg_id === latest.source_msg_id));
+ return peers.every(t => t.status === 'done' && Number.isFinite(Date.parse(t.ended_at)) && Date.parse(t.ended_at) < cutoff)
+ && !await hasPendingAttachmentsForCleanup(uid, cid) && quiescent(uid, cid);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError) return false;
+ throw new Error('cleanup_read_failed');
+ }
+}
+function snapshot(uid: string, token: string): Snapshot {
+ const s = snapshots.get(uid);
+ if (!s || s.token !== token || s.expires < Date.now()) throw new Error('cleanup_preview_expired');
+ return s;
+}
+export async function preview(uid: string, args: { days: number; protectedIds: string[] }) {
+ if (![30, 90, 180].includes(args.days) || !Array.isArray(args.protectedIds)
+ || args.protectedIds.length > 50000 || args.protectedIds.some(id => typeof id !== 'string' || !safeId(id))) {
+ throw new Error('invalid_cleanup_filter');
+ }
+ if (previewing.has(uid) || snapshots.get(uid)?.busy) throw new Error('cleanup_busy');
+ previewing.add(uid);
+ try {
+ for (const [owner, s] of snapshots) if (!s.busy && s.expires < Date.now()) snapshots.delete(owner);
+ const cutoff = Date.now() - args.days * 86400000;
+ const protectedIds = new Set(args.protectedIds);
+ const rows: Row[] = [];
+ const candidates = (await chats.listCleanupConversationRows(uid))
+ .filter(c => eligible(c, cutoff) && !protectedIds.has(c.conversation_id));
+ // Four bounded readers, no history hydration or per-row IPC. Fail instead
+ // of silently truncating an exceptionally large account's preview.
+ if (candidates.length > 50000) throw new Error('cleanup_preview_too_large');
+ for (let i = 0; i < candidates.length; i += 4) {
+ await Promise.all(candidates.slice(i, i + 4).map(async c => {
+ if (await completed(uid, c.conversation_id, c.project_id || null, cutoff)) rows.push({ cid: c.conversation_id, projectId: c.project_id || null,
+ title: c.title.slice(0, 512), activeAt: new Date(activity(c)).toISOString() });
+ }));
+ }
+ rows.sort((a, b) => a.activeAt.localeCompare(b.activeAt) || a.cid.localeCompare(b.cid));
+ const s: Snapshot = { token: randomUUID(), expires: Date.now() + TTL, cutoff, rows,
+ members: new Map(rows.map(r => [r.cid, r.projectId])), remaining: new Set(rows.map(r => r.cid)), busy: false };
+ snapshots.set(uid, s);
+ return { token: s.token, ...page(uid, s.token, 0) };
+ } finally { previewing.delete(uid); }
+}
+export function page(uid: string, token: string, offset: number) {
+ const s = snapshot(uid, token);
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > s.rows.length) throw new Error('invalid_cleanup_page');
+ const rows = s.rows.slice(offset, offset + PAGE_SIZE);
+ return { total: s.rows.length, rows, nextOffset: offset + rows.length < s.rows.length ? offset + rows.length : null };
+}
+export async function remove(uid: string, token: string, cid: string) {
+ const s = snapshot(uid, token);
+ if (s.busy) throw new Error('cleanup_busy');
+ if (!s.members.has(cid)) throw new Error('invalid_cleanup_selection');
+ const projectId = s.members.get(cid)!;
+ if (!s.remaining.has(cid)) return { status: 'skipped' as const };
+ s.busy = true;
+ try {
+ const current = await chats.getConversationMetadata(uid, cid, projectId);
+ if (!eligible(current, s.cutoff) || (current!.project_id || null) !== projectId
+ || !await completed(uid, cid, projectId, s.cutoff)) {
+ s.remaining.delete(cid); return { status: 'skipped' as const };
+ }
+ const batch = await recycle.createAppRecycleBatchForConversation(uid, cid);
+ if (!batch?.items?.length) throw new Error('recycle_archive_failed');
+ // Re-read the owning index under its write queue, after potentially slow
+ // backup I/O, so a pin, project move, or new message invalidates selection.
+ const removed = await chats.deleteConversation(uid, cid, projectId,
+ async current => eligible(current, s.cutoff) && (current.project_id || null) === projectId
+ && await completed(uid, cid, projectId, s.cutoff));
+ s.remaining.delete(cid);
+ if (!removed) await recycle.deleteRecycleBatch(uid, batch.id);
+ s.expires = Date.now() + TTL;
+ return { status: removed ? 'deleted' as const : 'skipped' as const };
+ } catch (_) { throw new Error('cleanup_failed'); }
+ finally { s.busy = false; }
+}
diff --git a/src/main/i18n.ts b/src/main/i18n.ts
index e7677c96..6941d700 100644
--- a/src/main/i18n.ts
+++ b/src/main/i18n.ts
@@ -16,7 +16,7 @@ import * as path from 'node:path';
import * as fs from 'node:fs';
import { SRC_ROOT } from './paths';
-import { buildLanguageDirectiveText } from './prompts/chat_prompt_composer';
+import { buildLanguageDirectiveText, buildHostTurnLanguageDirectiveText } from './prompts/chat_prompt_composer';
export type Lang = 'ar' | 'zh' | 'zh-tw' | 'en' | 'fr' | 'de' | 'hi' | 'id' | 'it' | 'ja' | 'ko' | 'pt' | 'pt-pt' | 'ru' | 'es' | 'es-419' | 'th' | 'tr' | 'vi';
@@ -227,6 +227,10 @@ export function buildLanguageDirective(lang: Lang = _current): string {
return buildLanguageDirectiveText(name);
}
+export function buildHostTurnLanguageDirective(lang: Lang, continuation = false): string {
+ return buildHostTurnLanguageDirectiveText(getLocaleMeta(lang).llmName, continuation);
+}
+
// ── Lookup ───────────────────────────────────────────────────────────────
/**
diff --git a/src/main/index.ts b/src/main/index.ts
index 9b2aa0c4..6b8d3b9e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -29,7 +29,8 @@
import * as path from 'node:path';
import * as fs from 'node:fs';
import { spawn } from 'node:child_process';
-import { app, BrowserWindow, Menu, Notification, type Tray, ipcMain, nativeImage, net, protocol, session, shell } from 'electron';
+import { app, BrowserWindow, Menu, Notification, type Tray, ipcMain, nativeImage, net, powerSaveBlocker, protocol, session, shell } from 'electron';
+import { installWindowPresentationEvents } from './util/window-presentation';
// Side-effect import: at module-load time this resolves the install
// container, runs the one-shot PC/data → <container>/data migration, and
// sets process.env.ORKAS_WORKSPACE_ROOT. Must be the FIRST project import
@@ -215,10 +216,11 @@ import type { BuiltinMarketplaceSeedResult } from './features/builtin_marketplac
import * as chatAttachments from './features/chat_attachments';
import * as chatArtifacts from './features/chat_artifacts';
import * as savedApps from './features/saved_apps';
-import { appResource } from './features/web_apps/host';
+import { appResource, hasIsolatedBrowserStorage } from './features/web_apps/host';
import * as clientConfigFeature from './features/client_config';
import * as connectorsFeature from './features/connectors';
import * as windowState from './features/window_state';
+import { startIdleSleepGuard } from './features/idle_sleep_guard';
import { installWindowCloseConfirmation } from './features/window_close_confirmation';
import * as taskNotifications from './features/task_notifications';
import * as taskUnreadTray from './features/task_unread_tray';
@@ -304,6 +306,7 @@ function createWindow(): BrowserWindow {
}),
});
mainWindows.add(win);
+ installWindowPresentationEvents(win);
win.on('focus', () => taskUnreadTray.refreshTaskUnreadTray());
installWindowCloseConfirmation(win, hasActiveWork, () => isQuitting);
windowState.watchWindowState(win);
@@ -421,7 +424,9 @@ function openConversationFromTaskNotification(
else send();
}
-function registerIpc(): void {
+/** `prepareShutdown` is the work a normal quit runs in `before-quit`; exits
+ * that bypass it (`app.exit`) run it themselves. */
+function registerIpc(prepareShutdown: () => Promise<void>): void {
ipc.register();
// Subscribe before opening the renderer. The deferred driver scheduler must
// not determine whether foreground or early background writes are visible.
@@ -471,6 +476,11 @@ function registerIpc(): void {
if (!fs.existsSync(appAsar) || !mainLoadedFromAsar) {
throw new Error(`launch smoke main process was not loaded from app.asar: ${appAsar}`);
}
+ // Keep renderer readiness independent of the subsequent Library work.
+ // Only this packaged, isolated smoke path writes synthetic Library data.
+ const readyElapsedMs = Math.max(0, Date.now() - launchStartedAtMs);
+ const { runPackagedLibrarySmoke } = await import('./features/library_smoke');
+ const library = await runPackagedLibrarySmoke();
const record = {
status: 'ready',
appIsPackaged: app.isPackaged,
@@ -482,7 +492,8 @@ function registerIpc(): void {
version: app.getVersion(),
platform: process.platform,
arch: process.arch,
- readyElapsedMs: Math.max(0, Date.now() - launchStartedAtMs),
+ readyElapsedMs,
+ library,
readyAt: new Date().toISOString(),
};
const marker = path.resolve(PACKAGED_LAUNCH_SMOKE_FILE);
@@ -564,7 +575,7 @@ function registerIpc(): void {
});
child.unref();
log.info('relaunch via shell script');
- await openLifecycleTracking?.flushQuit();
+ await prepareShutdown();
app.exit(0);
return { ok: true };
});
@@ -1337,12 +1348,16 @@ function registerChatAppProtocol(): void {
log.warn('chat-app/saved: bad URL (need appId)', { error_code: 'invalid_route' });
return new Response('bad request', { status: 400 });
}
+ const uid = users.getActiveUserId();
+ if (await savedApps.resolveSavedAppType(uid, appId) === 'web') {
+ return Response.json((await import('./features/web_apps/commercial-entry')).commercialWebAppFailure(), { status: 403 });
+ }
+ if (hasIsolatedBrowserStorage(uid, { appId })) return new Response('Application origin required', { status: 403 });
if (savedRelPath === chatArtifacts.BRIDGE_RELPATH) {
return _withArtifactCors(new Response(chatArtifacts.BRIDGE_JS, {
headers: { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'private, max-age=60' },
}));
}
- const uid = users.getActiveUserId();
const resolved = savedApps.resolveSavedAppFilePath(uid, appId, savedRelPath);
if (!resolved.ok) {
const code = (resolved as { code?: string }).code;
@@ -1366,6 +1381,11 @@ function registerChatAppProtocol(): void {
return new Response('bad request', { status: 400 });
}
+ const uid = users.getActiveUserId();
+ if (await savedApps.resolveArtifactAppType(uid, cid, artifactId) === 'web') {
+ return Response.json((await import('./features/web_apps/commercial-entry')).commercialWebAppFailure(), { status: 403 });
+ }
+ if (hasIsolatedBrowserStorage(uid, { cid, artifactId })) return new Response('Application origin required', { status: 403 });
// Reserved virtual path: the runtime bridge script (not on disk).
if (relPath === chatArtifacts.BRIDGE_RELPATH) {
return _withArtifactCors(new Response(chatArtifacts.BRIDGE_JS, {
@@ -1373,7 +1393,6 @@ function registerChatAppProtocol(): void {
}));
}
- const uid = users.getActiveUserId();
const resolved = chatArtifacts.resolveArtifactFilePath(uid, cid, artifactId, relPath);
if (!resolved.ok) {
// Cast in the error branch — `strictNullChecks: false` keeps the
@@ -1400,6 +1419,36 @@ const gotLock = IS_PACKAGED_LAUNCH_SMOKE || app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
+
+ // Normal quit and explicit exit share the same local-resource drain.
+ let shutdownFlushed = false;
+ let shutdownFlushPromise: Promise<void> | null = null;
+ const flushForShutdown = (): Promise<void> => {
+ if (shutdownFlushPromise) return shutdownFlushPromise;
+ 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 }); }
+ try {
+ const kbEmbed = await import('./features/kb_embed');
+ kbEmbed.closeEmbedder();
+ } catch (err) { createLogger('kb_embed').warn('close failed', { error: logErrorSummary(err) }); }
+ try {
+ const images = await import('./util/sharp-runtime');
+ images.closeImageRuntime();
+ } catch { createLogger('image-runtime').warn('image runtime shutdown failed'); }
+ const webAssistSessions = await import('./features/web_assist_session');
+ await webAssistSessions.flushWebAssistSessions();
+ await sweepOfficeResidents('quit');
+ await lifecycleFlush;
+ })().finally(() => { shutdownFlushed = true; });
+ return shutdownFlushPromise;
+ };
+
// Account login is stripped, but connector OAuth still returns through the OS protocol. Keep
// this connector-only receiver outside the removed account protocol module.
registerConnectorProtocol();
@@ -1450,7 +1499,7 @@ if (!gotLock) {
session.defaultSession.setPermissionRequestHandler((_wc, permission, callback) => {
callback(permission === 'clipboard-read' || permission === 'clipboard-sanitized-write');
});
- registerIpc();
+ registerIpc(flushForShutdown);
const stopTaskNotifications = taskNotifications.startTaskNotifications({
getActiveUserId: () => users.getActiveUserId(),
isEnabled: () => appConfig.getTaskNotificationsEnabled(),
@@ -1511,6 +1560,9 @@ if (!gotLock) {
});
const stopTaskTerminalUi = subscribeTaskTerminals(emitTaskTerminalToRenderer);
app.once('before-quit', stopTaskTerminalUi);
+ // Running Agent work keeps the machine out of idle sleep; an idle app holds nothing.
+ const idleSleepGuard = startIdleSleepGuard({ blocker: powerSaveBlocker, hasActiveWork });
+ app.once('before-quit', idleSleepGuard.stop);
clientConfigFeature.clientConfig.subscribeAll((keys) => {
ipc.broadcastToRenderer('client-config:changed', { keys });
});
@@ -1643,6 +1695,11 @@ if (!gotLock) {
registerDeferred('marketplace:reconcile', () => runMarketplaceInstallReconcile('startup'));
registerDeferred('boot:maintenance-sweeps', () => runBootMaintenanceSweeps(), 'serial', BOOT_HEAVY_DISK_DELAY_MS, idleDisk);
+ registerDeferred('browser:http-cache', async (signal) => {
+ const { sweepWebAssistCache } = await import('./features/web_assist_cache');
+ const result = await sweepWebAssistCache(users.getActiveUserId(), signal);
+ log.info('HTTP cache maintenance finished', result);
+ }, 'serial', BOOT_HEAVY_DISK_DELAY_MS, idleDisk);
registerDeferred('search:reconcile', (signal) => searchFeature.reconcileActive(signal), 'serial', BOOT_HEAVY_DISK_DELAY_MS, idleDisk);
registerDeferred('kb:reconcile', async (signal) => {
// Picks up files dropped into contexts/ via Finder while the app was
@@ -1676,9 +1733,10 @@ if (!gotLock) {
const mod = await import('./features/sessions_sweep');
await mod.sweepSessions(users.getActiveUserId(), signal);
}, 'serial', BOOT_POST_STARTUP_DELAY_MS, idleDisk);
- registerDeferred('memory:loop', async () => {
- const memoryMaintenance = await import('./features/memory-maintenance');
- memoryMaintenance.startMemoryMaintenanceLoop(users.getActiveUserId());
+ // Automatic memory maintenance is retired; remove its local leftovers.
+ registerDeferred('memory:retired-state-cleanup', async () => {
+ const memoryWrites = await import('./features/memory-writes');
+ await memoryWrites.removeRetiredMemoryMaintenanceState(users.getActiveUserId());
}, 'serial', BOOT_POST_STARTUP_DELAY_MS);
registerDeferred('reflection:loop', () => {
reflectionOrchestrator.startReflectionLoop(users.getActiveUserId());
@@ -1696,39 +1754,10 @@ if (!gotLock) {
if (process.platform !== 'darwin') app.quit();
});
- // 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) => {
isQuitting = true;
if (shutdownFlushed) return;
e.preventDefault();
- 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 }); }
- try {
- const kbEmbed = await import('./features/kb_embed');
- kbEmbed.closeEmbedder();
- } catch (err) { createLogger('kb_embed').warn('close failed', { error: logErrorSummary(err) }); }
- try {
- const images = await import('./util/sharp-runtime');
- images.closeImageRuntime();
- } catch { createLogger('image-runtime').warn('image runtime shutdown failed'); }
- const webAssistSessions = await import('./features/web_assist_session');
- await webAssistSessions.flushWebAssistSessions();
- await sweepOfficeResidents('quit');
- await lifecycleFlush;
- })();
- try { await shutdownFlushPromise; }
- finally {
- shutdownFlushed = true;
- app.quit();
- }
+ try { await flushForShutdown(); } finally { app.quit(); }
});
}
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 9d8fd1d2..52c28e7d 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -19,6 +19,7 @@ import { app, ipcMain, dialog, BrowserWindow, type WebContents } from 'electron'
import * as users from '../features/users';
import * as chats from '../features/chats';
+import * as taskCleanup from '../features/task_cleanup';
import * as projects from '../features/projects';
import * as projectFiles from '../features/project_files';
import * as projectTasks from '../features/project_tasks';
@@ -79,7 +80,8 @@ import {
import { invokeHandlers as webAssistHandlers } from './web_assist';
import { bindWebAssistConversation } from '../features/web_assist';
import { invokeHandlers as memoryHandlers } from './memory';
-import { safeId } from '../storage';
+import { safeId, writeJson } from '../storage';
+import { commercialWebAppFailure, isCommercialWebAppFailure } from '../features/web_apps/commercial-entry';
import { createLogger, logFromRenderer } from '../logger';
import {
cancelConfirmation as cancelDeleteConfirmation,
@@ -1022,6 +1024,39 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { conversation: conv };
},
+ // Home page: titles and ownership for a handful of unread finished runs that
+ // may sit outside the renderer's startup slice. Index rows only, never
+ // messages; deleted or unknown ids come back as `missing`.
+ 'conversations.getMany': async ({ cids } = {}, ctx) => {
+ const ids = Array.isArray(cids)
+ ? [...new Set(cids.filter((cid) => typeof cid === 'string' && safeId(cid)))].slice(0, 25) as string[]
+ : [];
+ const conversations: Array<{ conversation_id: string; title: string; project_id: string; origin_auto_task_id: string }> = [];
+ const missing: string[] = [];
+ for (const cid of ids) {
+ const row = await chats.getConversationMetadata(ctx.userId, cid);
+ if (!row) { missing.push(cid); continue; }
+ conversations.push({
+ conversation_id: cid,
+ title: row.title || '',
+ project_id: row.project_id || '',
+ origin_auto_task_id: row.origin_auto_task_id || '',
+ });
+ }
+ return { conversations, missing };
+ },
+
+ 'conversations.processPage': async (args, ctx) => {
+ const { cid, ref, message_id } = args;
+ const cursor = Number(args.cursor ?? 0);
+ if (!safeId(cid) || !safeId(message_id) || typeof ref !== 'string' || !/^[a-f0-9]{64}$/.test(ref)
+ || !Number.isSafeInteger(cursor) || cursor < 0) throw new Error('Invalid process page');
+ const conv = await chats.getConversationMetadata(ctx.userId, cid, conversationProjectHint(args));
+ if (!conv) throw new Error('conversation not found');
+ const page = await chats.getConversationProcessPage(ctx.userId, cid, ref, cursor, message_id, conv.project_id ?? null);
+ return { items: page.items, next_cursor: page.nextCursor };
+ },
+
'conversations.history': async (args, ctx) => {
const startedAt = performance.now();
const { cid, limit = 10, before, after, around_index, around_message_id } = args;
@@ -1046,18 +1081,36 @@ const invokeHandlers: Record<string, InvokeHandler> = {
const readStartedAt = performance.now();
let historyMs = 0;
let runtimeMs = 0;
- const pagePromise = hasAroundIndex
- ? chats.getMessagesPageAtIndex(
- ctx.userId, cid, requestedAroundIndex, requestedLimit, resolvedProjectId)
- : Number.isSafeInteger(requestedAfter) && requestedAfter >= 0
- ? chats.getMessagesPageAfter(ctx.userId, cid, requestedAfter, requestedLimit, resolvedProjectId)
- : chats.getMessagesPage(
+ // Search and turn navigation anchor on a known source index. A quoted
+ // message reference knows only the stable message id: the history worker
+ // finds it and reads its page in one pass. An id that no longer exists
+ // reads the latest page and the renderer reports the missing original.
+ let anchorIndex = hasAroundIndex ? requestedAroundIndex : null;
+ const pagePromise = (async () => {
+ if (anchorIndex === null && requestedAroundMessageId) {
+ const quoted = await chats.getMessagesPageAtMessageId(
+ ctx.userId, cid, requestedAroundMessageId, requestedLimit, resolvedProjectId,
+ );
+ if (quoted) {
+ anchorIndex = quoted.messageIndex;
+ return quoted;
+ }
+ }
+ if (anchorIndex !== null) {
+ return chats.getMessagesPageAtIndex(
+ ctx.userId, cid, anchorIndex, requestedLimit, resolvedProjectId);
+ }
+ if (Number.isSafeInteger(requestedAfter) && requestedAfter >= 0) {
+ return chats.getMessagesPageAfter(ctx.userId, cid, requestedAfter, requestedLimit, resolvedProjectId);
+ }
+ return chats.getMessagesPage(
ctx.userId,
cid,
requestedLimit,
Number.isSafeInteger(requestedBefore) && requestedBefore >= 0 ? requestedBefore : undefined,
resolvedProjectId,
);
+ })();
const [runtime, initialPage] = await Promise.all([
groupChat.runtimeStatus(ctx.userId, cid, resolvedProjectId).then((result) => {
runtimeMs = Math.round(performance.now() - readStartedAt);
@@ -1071,20 +1124,17 @@ const invokeHandlers: Record<string, InvokeHandler> = {
let page = initialPage;
if (hasAroundIndex && requestedAroundMessageId
&& !page.history.some((message) => message.id === requestedAroundMessageId)) {
- const repairedIndex = await chats.findMessageIndexById(
- ctx.userId, cid, requestedAroundMessageId, resolvedProjectId,
+ // Sync rewrote or reordered the source since the index was taken.
+ const repaired = await chats.getMessagesPageAtMessageId(
+ ctx.userId, cid, requestedAroundMessageId, requestedLimit, resolvedProjectId,
);
- if (repairedIndex !== null) {
- page = await chats.getMessagesPageAtIndex(
- ctx.userId, cid, repairedIndex, requestedLimit, resolvedProjectId,
- );
- }
+ if (repaired) page = repaired;
}
const totalMs = Math.round(performance.now() - startedAt);
if (totalMs >= 1000) {
log.info('slow conversation history read', {
metadata_ms: metadataMs, history_ms: historyMs, runtime_ms: runtimeMs,
- total_ms: totalMs, rows: page.history.length, anchored: hasAroundIndex,
+ total_ms: totalMs, rows: page.history.length, anchored: anchorIndex !== null,
});
}
return {
@@ -1093,7 +1143,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
...(args.live === '1' ? { live_display: await groupChat.displaySnapshot(ctx.userId, cid, resolvedProjectId) } : {}),
next_cursor: page.nextCursor,
following_cursor: 'followingCursor' in page ? page.followingCursor : null,
- ...(hasAroundIndex && 'pageStart' in page && 'historyIndexes' in page ? {
+ ...(anchorIndex !== null && 'pageStart' in page && 'historyIndexes' in page ? {
page_start: page.pageStart,
history_indexes: page.historyIndexes,
} : {}),
@@ -1136,6 +1186,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
'conversations.create': async ({ title = '', projectId = '', assistance } = {}, ctx) => {
+ if (assistance?.kind === 'app_creation' && ['web', 'cloud'].includes(assistance.appType)) return commercialWebAppFailure();
const normalizedAssistance = chats.normalizeConversationAssistance(assistance);
const validatedAssistance = assistance === undefined ? undefined
: normalizedAssistance?.kind === 'app_creation' ? normalizedAssistance
@@ -1169,6 +1220,19 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { deleted: ok };
},
+ 'conversations.cleanup.preview': async (args, ctx) => {
+ if (args.expectedUserId !== ctx.userId) throw new Error('cleanup_account_changed');
+ return taskCleanup.preview(ctx.userId, args);
+ },
+ 'conversations.cleanup.page': async (args, ctx) => {
+ if (args.expectedUserId !== ctx.userId) throw new Error('cleanup_account_changed');
+ return taskCleanup.page(ctx.userId, args.token, args.offset);
+ },
+ 'conversations.cleanup.remove': async (args, ctx) => {
+ if (args.expectedUserId !== ctx.userId) throw new Error('cleanup_account_changed');
+ return taskCleanup.remove(ctx.userId, args.token, args.cid);
+ },
+
// Roll back a conversation that was created for a first message but
// never received that message (for example because draft attachment adoption
// failed). Unlike an explicit user delete this does not create a recycle-bin
@@ -1370,6 +1434,13 @@ const invokeHandlers: Record<string, InvokeHandler> = {
};
},
+ // Home page: the most recently updated unfinished to-dos across every scope,
+ // plus the total so the page can link to the full list.
+ 'projects.tasks.listOpen': async ({ limit } = {}, ctx) => {
+ const count = Math.min(20, Math.max(1, Math.round(Number(limit) || 3)));
+ return projectTasks.listOpenTasks(ctx.userId, count);
+ },
+
'projects.tasks.create': async ({ projectId, taskId, content, title, detail, status, owner_agent, owner_agent_id, depends_on } = {}, ctx) => {
const scopeProjectId = todoProjectScope(projectId);
if (content !== undefined && typeof content !== 'string') throw new Error('invalid content');
@@ -1383,18 +1454,18 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { task: r.task, alreadyExists: r.alreadyExists };
},
- 'projects.tasks.update': async ({ projectId, taskId, content, title, detail, status, owner_agent, owner_agent_id, result_ref } = {}, ctx) => {
+ 'projects.tasks.update': async ({ projectId, taskId, content, title, detail, status, owner_agent, owner_agent_id } = {}, ctx) => {
const scopeProjectId = todoProjectScope(projectId);
if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');
- const r = await projectTasks.updateTask(ctx.userId, scopeProjectId, taskId, { content, title, detail, status, owner_agent, owner_agent_id, result_ref });
+ const r = await projectTasks.updateTask(ctx.userId, scopeProjectId, taskId, { content, title, detail, status, owner_agent, owner_agent_id });
if (!r.ok) throw new Error((r as { error: string }).error);
return { task: r.task };
},
- 'projects.tasks.complete': async ({ projectId, taskId, resultRef } = {}, ctx) => {
+ 'projects.tasks.complete': async ({ projectId, taskId } = {}, ctx) => {
const scopeProjectId = todoProjectScope(projectId);
if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');
- const r = await projectTasks.completeTask(ctx.userId, scopeProjectId, taskId, resultRef);
+ const r = await projectTasks.completeTask(ctx.userId, scopeProjectId, taskId);
if (!r.ok) throw new Error((r as { error: string }).error);
return { task: r.task };
},
@@ -1424,8 +1495,13 @@ const invokeHandlers: Record<string, InvokeHandler> = {
const scopeProjectId = todoProjectScope(projectId);
if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');
const r = await projectDriverRunner.runTaskNow(ctx.userId, scopeProjectId, taskId);
+ // The to-do's own conversation is still working: report it so the renderer
+ // can take the user there instead of starting a second run.
+ if (!r.ok && r.error === 'conversation_busy' && r.cid) {
+ return { ok: false, error: 'conversation_busy', cid: r.cid };
+ }
if (!r.ok) throw new Error(r.error || 'run_failed');
- return { ok: true, cid: r.cid, conversation: r.conversation };
+ return { ok: true, cid: r.cid, conversation: r.conversation, reused: !!r.reused };
},
// Task attachments — files the task carries into the conversation it starts.
@@ -1440,7 +1516,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
const pid = todoProjectScope(projectId);
if (typeof taskId !== 'string' || typeof name !== 'string') return { ok: false, error: 'not_found' };
const file = await projectTasks.resolveTaskAttachmentPath(ctx.userId, pid, taskId, name);
- return file ? { ok: true, path: file } : { ok: false, error: 'not_found' };
+ if (file) return { ok: true, path: file };
+ return { ok: false, error: 'not_found' };
},
'projects.tasks.attachments.upload': async ({ projectId, taskId, name, dataBase64 } = {}, ctx) => {
@@ -1475,7 +1552,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
'projects.driver.get': async ({ projectId } = {}, ctx) => {
const scopeProjectId = todoProjectScope(projectId);
if (scopeProjectId && !safeId(scopeProjectId)) throw new Error('invalid projectId');
- return { config: await projectDriver.readConfig(ctx.userId, scopeProjectId) };
+ return { config: await projectDriver.readConfig(ctx.userId, scopeProjectId), device: projectDriver.getCurrentDevice() };
},
'projects.driver.set': async ({ projectId, enabled, maxAdvancesPerDay } = {}, ctx) => {
@@ -1491,7 +1568,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
void projectDriverRunner.advanceProjectIfDue(ctx.userId, scopeProjectId)
.catch(() => { /* the periodic tick will retry */ });
}
- return { config };
+ return { config, device: projectDriver.getCurrentDevice() };
},
'projects.files.list': async ({ projectId }, ctx) => {
@@ -1503,7 +1580,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
'projects.files.tree': async ({ projectId }, ctx) => {
if (!safeId(projectId)) throw new Error('invalid projectId');
if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');
- return { tree: await projectFiles.listProjectFileTree(ctx.userId, projectId) };
+ return { tree: await projectFiles.listProjectFileTreeForDisplay(ctx.userId, projectId) };
},
'projects.files.mkdir': async ({ projectId, path: relPath }, ctx) => {
@@ -1934,7 +2011,6 @@ const invokeHandlers: Record<string, InvokeHandler> = {
use_selections,
references,
steer_active_turn,
- multi_dispatch,
retry_message_id,
}, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
@@ -1960,9 +2036,6 @@ const invokeHandlers: Record<string, InvokeHandler> = {
...(commander_mention_display === 'preserve' || commander_mention_display === 'hide_generated_prefix'
? { commander_mention_display } : {}),
...(steer_active_turn === true ? { steerActiveTurn: true } : {}),
- ...(multi_dispatch === 'parallel' || multi_dispatch === 'serial'
- ? { multi_dispatch }
- : {}),
...(hasTitleText ? { title_text: titleText } : {}),
...(atts.length ? { attachments: atts } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
@@ -2206,13 +2279,27 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// Copy a chat artifact into the persistent "My Apps" pool
// (`<uid>/cloud/saved_apps/<appId>/`). Surfaced as the artifact card's
// `⋯` → "保存".
- 'conversations.artifacts.save': async ({ cid, artifactId }, ctx) => {
+ 'conversations.artifacts.editTarget': async ({ cid }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ return { target: await savedApps.getEditTarget(ctx.userId, String(cid)) };
+ },
+ 'conversations.artifacts.save': async ({ cid, artifactId, mode, recovery }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
- const r = await savedApps.saveFromArtifact(ctx.userId, String(cid), String(artifactId || ''));
- if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to save app');
+ if (mode !== undefined && mode !== 'new' && mode !== 'update') throw new Error('invalid save mode');
+ const r = await savedApps.saveFromArtifact(ctx.userId, String(cid), String(artifactId || ''), mode || 'new',recovery);
+ if (isCommercialWebAppFailure(r)) return r;
+ if (!r.ok) return { ok: false, code: (r as { error: string }).error };
return { ok: true, id: (r as { id: string }).id, title: (r as { title: string }).title };
},
+ 'conversations.artifacts.dataImpact': async ({cid,artifactId},ctx)=>savedApps.appDataImpact(ctx.userId,String(cid),String(artifactId)),
+ 'conversations.artifacts.exportData': async ({cid,artifactId},ctx)=>{
+ const impact=await savedApps.appDataImpact(ctx.userId,String(cid),String(artifactId));if(!impact.ok)return impact;
+ const result=await dialog.showSaveDialog({defaultPath:'app-data.sqlite',filters:[{name:'SQLite',extensions:['sqlite']}]});
+ if(result.canceled||!result.filePath)return {ok:true,canceled:true};if(users.getActiveUserId()!==ctx.userId)return {ok:false,code:'E_CLOSED'};
+ return savedApps.exportAppData(ctx.userId,String(cid),String(artifactId),result.filePath);
+ },
+
'savedApps.inspectBundleFromPath': async (payload, ctx) => {
const target = payload?.path;
if (typeof target !== 'string' || !target) throw new Error('missing path');
@@ -2238,13 +2325,20 @@ const invokeHandlers: Record<string, InvokeHandler> = {
sourceCid: payload?.cid,
fenceRoots: await _ipcFileSandboxAllowedRoots(ctx.userId, payload),
});
- if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to save app');
+ if (!r.ok && (r as { error?: string }).error === 'app_bundle_root') return r;
+ if (isCommercialWebAppFailure(r)) return r;
+ if (!r.ok) { const code = (r as { error?: string }).error || 'app_save_failed'; throw Object.assign(new Error(code), { code }); }
return r;
},
// ── Saved apps ("My Apps" — user-kept copies of create_artifact bundles) ──
- 'savedApps.list': async (_payload, ctx) => ({ apps: savedApps.listSavedApps(ctx.userId) }),
+ // First paint reads disk only. Presentation is not authority: opening, editing,
+ // sharing and deletion still resolve the app type at their owning boundaries.
+ 'savedApps.list': async (payload, ctx) => ({ apps: payload?.localOnly === true
+ ? savedApps.listSavedApps(ctx.userId) : await savedApps.listResolvedSavedApps(ctx.userId) }),
'savedApps.openExternal': async ({ appId }, ctx) => {
+ const type = await savedApps.resolveSavedAppType(ctx.userId, String(appId || ''));
+ if (type === 'web') return commercialWebAppFailure();
const r = savedApps.resolveSavedAppIndex(ctx.userId, String(appId || ''));
if (!r.ok) throw new Error((r as { error?: string }).error || 'app not found');
const absPath = (r as { absPath: string }).absPath;
@@ -2269,6 +2363,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// navigates to it + pre-fills a draft.
'savedApps.openForEditing': async ({ appId }, ctx) => {
const r = await savedApps.openForEditing(ctx.userId, String(appId || ''));
+ if ((r as { code?: string }).code === 'E_COMMERCIAL_REQUIRED') return r;
if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to open the app for editing');
return {
ok: true,
@@ -2279,17 +2374,27 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
'savedApps.rename': async ({ appId, title }, ctx) => {
const r = savedApps.renameSavedApp(ctx.userId, String(appId || ''), title);
- if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to rename');
+ if (!r.ok) { const code = (r as { error?: string }).error || 'app_rename_failed'; throw Object.assign(new Error(code), { code }); }
return { ok: true, title: (r as { title: string }).title };
},
'savedApps.delete': async ({ appId }, ctx) => {
- await recycleBin.createAppRecycleBatchForCloudEntry(
+ const batch = await recycleBin.createAppRecycleBatchForCloudEntry(
ctx.userId,
`cloud/saved_apps/${String(appId || '')}`,
'saved_app',
);
- const r = savedApps.deleteSavedApp(ctx.userId, String(appId || ''));
- if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to delete');
+ let r: Awaited<ReturnType<typeof savedApps.deleteSavedApp>>;
+ try { r = await savedApps.deleteSavedApp(ctx.userId, String(appId || '')); }
+ catch { r = { ok: false, error: 'app_delete_failed' }; }
+ if (!r.ok) {
+ // A failed delete leaves the app in place; drop its now-duplicate recycle copy.
+ if (batch) {
+ try { await recycleBin.deleteRecycleBatch(ctx.userId, batch.id); }
+ catch (error) { log.warn('saved app recycle batch rollback failed', { error: logErrorRef(error) }); }
+ }
+ const code = (r as { error?: string }).error || 'app_delete_failed';
+ throw Object.assign(new Error(code), { code });
+ }
return { ok: true };
},
@@ -3638,7 +3743,6 @@ const streamHandlers: Record<string, StreamHandler> = {
use_selections,
references,
retry_message_id,
- multi_dispatch,
client_msg_id,
}, ctx, signal) {
if (!safeId(cid)) {
@@ -3716,9 +3820,6 @@ const streamHandlers: Record<string, StreamHandler> = {
userId: ctx.userId, cid, text,
...(commander_mention_display === 'preserve' || commander_mention_display === 'hide_generated_prefix'
? { commander_mention_display } : {}),
- ...(multi_dispatch === 'parallel' || multi_dispatch === 'serial'
- ? { multi_dispatch }
- : {}),
...(typeof client_msg_id === 'string' && client_msg_id.trim()
? { client_msg_id: client_msg_id.trim().slice(0, 64) }
: {}),
@@ -4149,7 +4250,7 @@ export function register(): void {
const controller = new AbortController();
const state: StreamState = { cancelled: false, controller, sender: event.sender };
activeStreams.set(requestId, state);
- log.info(`streamStart channel=${channel} requestId=${requestId} cid=${payload?.cid || payload?.id || payload?.agent_id || ''}`);
+ if(channel!=='webApps.call')log.info(`streamStart channel=${channel} requestId=${requestId} cid=${payload?.cid || payload?.id || payload?.agent_id || ''}`);
try {
const ctx = await resolveContext(event.sender);
for await (const ev of handler(payload || {}, ctx, controller.signal)) {
@@ -4163,7 +4264,7 @@ export function register(): void {
} finally {
activeStreams.delete(requestId);
rememberSettledStream(requestId, event.sender);
- log.info(`streamDone channel=${channel} requestId=${requestId} cancelled=${state.cancelled}`);
+ if(channel!=='webApps.call')log.info(`streamDone channel=${channel} requestId=${requestId} cancelled=${state.cancelled}`);
out({ type: 'done' });
}
});
diff --git a/src/main/locales/ar.json b/src/main/locales/ar.json
index 1b872cf5..d3522c85 100644
--- a/src/main/locales/ar.json
+++ b/src/main/locales/ar.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "حل تعارض مزامنة السحابة: {count} تعارض",
"sync.conflict_resolution.message_single": "يرجى مساعدتي في حل تعارض مزامنة السحابة هذا.",
"sync.conflict_resolution.message_batch": "يرجى مساعدتي في حل تعارضات مزامنة السحابة هذه.",
- "quality.operator.incomplete": "لم يكتمل التحقق المخصص. أصلح ملف القواعد أو أوقف التحقق المخصص في الإعدادات، ثم أعد المحاولة."
+ "quality.operator.incomplete": "لم يكتمل التحقق المخصص. أصلح ملف القواعد أو أوقف التحقق المخصص في الإعدادات، ثم أعد المحاولة.",
+ "model.stopped_tool_limit_summary_incomplete": "توقف هذا التشغيل عند بلوغ الحد الأقصى البالغ {limit} جولة من استخدام الأدوات. تعذّر إكمال الملخص النهائي.",
+ "model.stopped_repeat_summary_incomplete": "توقف هذا التشغيل لأن العمليات المتكررة لم تحقق أي تقدم جديد. تعذّر إكمال الملخص النهائي.",
+ "model.stopped_summary_incomplete": "توقف هذا التشغيل. تعذّر إكمال الملخص النهائي.",
+ "local_agents.unsupported_effort": "مستوى الاستدلال المحدد غير متاح في تثبيت Claude Code هذا. حدّث Claude Code أو اختر مستوى الاستدلال الافتراضي.",
+ "model.balance_fallback": "نفد رصيد حساب {provider} (هذا ليس رصيد Orkas). جارٍ الانتقال إلى نموذج بديل لمتابعة المهمة؛ اشحن رصيد هذا الحساب لاستخدامه مجددًا.",
+ "model.provider_unavailable_fallback": "نموذج {provider} الذي أعددته غير متاح حاليًا. جارٍ الانتقال إلى نموذج بديل لمتابعة المهمة.",
+ "cli_agent.parameter_unsupported": "لا يدعم {cli} المعلمة المحددة {parameter}. غيّر إعدادات التشغيل.",
+ "cli_agent.model_unsupported": "لا يدعم {cli} النموذج {model}. غيّر إعدادات التشغيل.",
+ "auto_tasks.catch_up_title": "{title} (تشغيل متأخر)",
+ "web_assist.permission_title": "إذن الموقع",
+ "web_assist.permission_request": "السماح لـ {origin} باستخدام {permission}؟",
+ "web_assist.permission_allow": "السماح",
+ "web_assist.permission_deny": "رفض",
+ "web_assist.permission.clipboard": "الحافظة",
+ "web_assist.permission.media": "الكاميرا أو الميكروفون",
+ "web_assist.permission.location": "موقعك",
+ "web_assist.permission.notifications": "الإشعارات",
+ "web_assist.permission.fullscreen": "ملء الشاشة",
+ "web_assist.permission.screen": "مشاركة الشاشة",
+ "web_assist.permission.device": "جهاز",
+ "web_assist.permission.approximate_location": "الموقع التقريبي",
+ "web_assist.permission.automatic_fullscreen": "ملء الشاشة تلقائيًا",
+ "web_assist.permission.usb": "أجهزة USB",
+ "web_assist.permission.hid": "أجهزة الإدخال",
+ "web_assist.permission.serial": "الأجهزة التسلسلية",
+ "web_assist.permission.local_network": "الشبكة المحلية",
+ "web_assist.permission.loopback_network": "خدمات هذا الكمبيوتر",
+ "web_assist.permission.persistent_storage": "تخزين بيانات الموقع بشكل دائم",
+ "web_assist.permission.storage_access": "ملفات تعريف الارتباط التابعة لجهات خارجية",
+ "web_assist.permission.window_management": "معلومات الشاشات",
+ "web_assist.permission.local_fonts": "الخطوط المحلية",
+ "web_assist.permission.idle_detection": "حالة النشاط والقفل",
+ "web_assist.permission.screen_wake_lock": "إبقاء الشاشة مضاءة",
+ "web_assist.permission.system_wake_lock": "منع سكون الكمبيوتر",
+ "web_assist.permission.pointer_lock": "التقاط الماوس",
+ "web_assist.permission.keyboard_lock": "التقاط لوحة المفاتيح",
+ "web_assist.permission.filesystem": "الوصول إلى الملفات",
+ "web_assist.permission.protected_media": "تشغيل المحتوى المحمي",
+ "web_assist.permission.midi": "أجهزة MIDI",
+ "web_assist.permission.midi_sysex": "رسائل نظام MIDI",
+ "web_assist.permission.speaker_selection": "اختيار مخرج الصوت",
+ "web_assist.permission.external": "فتح تطبيقات خارجية",
+ "web_assist.permission.sensors": "مستشعرات الجهاز",
+ "web_assist.permission.background_fetch": "التنزيلات في الخلفية",
+ "web_assist.permission.background_sync": "المزامنة في الخلفية",
+ "web_assist.permission.surface_control": "التحكم في المحتوى المشترك",
+ "web_assist.permission.payment": "معالجة المدفوعات",
+ "web_assist.permission.ar": "الواقع المعزز",
+ "web_assist.permission.vr": "الواقع الافتراضي",
+ "web_assist.permission.hand_tracking": "تتبع اليدين",
+ "web_assist.permission.nfc": "أجهزة NFC",
+ "web_assist.permission.smart_card": "قارئات البطاقات الذكية",
+ "web_assist.permission.installation": "تثبيت تطبيقات الويب",
+ "web_assist.permission.printing": "الطابعات",
+ "web_assist.permission.unknown": "إذن «{permission}»",
+ "web_assist.permission.other": "هذا الإذن",
+ "web_assist.passkey.title": "مفتاح المرور",
+ "web_assist.passkey.heading": "استخدام هاتف أو جهاز لوحي",
+ "web_assist.passkey.instruction": "امسح رمز QR هذا بكاميرا الجهاز الذي يحتوي على مفتاح المرور الخاص بـ {rpId}.",
+ "web_assist.passkey.nearby": "أبقِ هاتفك قريبًا مع تشغيل البلوتوث.",
+ "web_assist.passkey.qr_alt": "امسح الرمز لاستخدام مفتاح المرور",
+ "web_assist.passkey.cancel": "إلغاء",
+ "web_assist.passkey.preparing": "جارٍ تجهيز رمز QR…",
+ "web_assist.passkey.scan": "بانتظار المسح…",
+ "web_assist.passkey.connecting": "جارٍ الاتصال بهاتفك…",
+ "web_assist.passkey.confirm": "تم الاتصال بالهاتف. أكّد العملية على هاتفك.",
+ "web_assist.passkey.verifying": "جارٍ العودة إلى الموقع…",
+ "errors.model_context_too_small": "يتطلب هذا النموذج نافذة سياق لا تقل عن {minimum} رمزًا. اختر نموذجًا بنافذة أكبر."
}
diff --git a/src/main/locales/de.json b/src/main/locales/de.json
index e9be7507..a6939446 100644
--- a/src/main/locales/de.json
+++ b/src/main/locales/de.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Cloud-Synchronisierungskonflikte lösen: {count}",
"sync.conflict_resolution.message_single": "Bitte helfen Sie mir, diesen Cloud-Synchronisierungskonflikt zu lösen.",
"sync.conflict_resolution.message_batch": "Bitte helfen Sie mir, diese Cloud-Synchronisierungskonflikte zu lösen.",
- "quality.operator.incomplete": "Die benutzerdefinierte Validierung wurde nicht abgeschlossen. Korrigieren Sie die Regeldatei oder deaktivieren Sie die benutzerdefinierte Validierung in den Einstellungen und versuchen Sie es erneut."
+ "quality.operator.incomplete": "Die benutzerdefinierte Validierung wurde nicht abgeschlossen. Korrigieren Sie die Regeldatei oder deaktivieren Sie die benutzerdefinierte Validierung in den Einstellungen und versuchen Sie es erneut.",
+ "model.stopped_tool_limit_summary_incomplete": "Dieser Durchlauf wurde nach Erreichen des Limits von {limit} Werkzeugrunden gestoppt. Die abschließende Zusammenfassung konnte nicht fertiggestellt werden.",
+ "model.stopped_repeat_summary_incomplete": "Dieser Durchlauf wurde gestoppt, weil wiederholte Vorgänge keinen weiteren Fortschritt brachten. Die abschließende Zusammenfassung konnte nicht fertiggestellt werden.",
+ "model.stopped_summary_incomplete": "Dieser Durchlauf wurde gestoppt. Die abschließende Zusammenfassung konnte nicht fertiggestellt werden.",
+ "local_agents.unsupported_effort": "Die gewählte Denkstufe ist in dieser Claude-Code-Installation nicht verfügbar. Aktualisieren Sie Claude Code oder wählen Sie die Standardstufe.",
+ "model.balance_fallback": "Das Guthaben Ihres {provider}-Kontos ist aufgebraucht (dies betrifft keine Orkas-Credits). Es wird zu einem Ausweichmodell gewechselt, damit die Aufgabe fortgesetzt werden kann; laden Sie das Konto auf, um es wieder zu nutzen.",
+ "model.provider_unavailable_fallback": "Ihr {provider}-Modell ist gerade nicht verfügbar. Es wird zu einem Ausweichmodell gewechselt, damit die Aufgabe fortgesetzt werden kann.",
+ "cli_agent.parameter_unsupported": "{cli} unterstützt den gewählten Parameter {parameter} nicht. Ändern Sie die Ausführungseinstellungen.",
+ "cli_agent.model_unsupported": "{cli} unterstützt das Modell {model} nicht. Ändern Sie die Ausführungseinstellungen.",
+ "auto_tasks.catch_up_title": "{title} (nachgeholt)",
+ "web_assist.permission_title": "Website-Berechtigung",
+ "web_assist.permission_request": "{origin} die Nutzung von {permission} erlauben?",
+ "web_assist.permission_allow": "Erlauben",
+ "web_assist.permission_deny": "Ablehnen",
+ "web_assist.permission.clipboard": "der Zwischenablage",
+ "web_assist.permission.media": "der Kamera oder des Mikrofons",
+ "web_assist.permission.location": "Ihrem Standort",
+ "web_assist.permission.notifications": "Benachrichtigungen",
+ "web_assist.permission.fullscreen": "Vollbild",
+ "web_assist.permission.screen": "Bildschirmfreigabe",
+ "web_assist.permission.device": "einem Gerät",
+ "web_assist.permission.approximate_location": "den ungefähren Standort",
+ "web_assist.permission.automatic_fullscreen": "automatischen Vollbildmodus",
+ "web_assist.permission.usb": "USB-Geräte",
+ "web_assist.permission.hid": "Eingabegeräte",
+ "web_assist.permission.serial": "serielle Geräte",
+ "web_assist.permission.local_network": "das lokale Netzwerk",
+ "web_assist.permission.loopback_network": "Dienste auf diesem Computer",
+ "web_assist.permission.persistent_storage": "dauerhaften Website-Speicher",
+ "web_assist.permission.storage_access": "Drittanbieter-Cookies",
+ "web_assist.permission.window_management": "Bildschirminformationen",
+ "web_assist.permission.local_fonts": "lokale Schriftarten",
+ "web_assist.permission.idle_detection": "Aktivitäts- und Sperrstatus",
+ "web_assist.permission.screen_wake_lock": "das Wachhalten des Bildschirms",
+ "web_assist.permission.system_wake_lock": "das Wachhalten des Computers",
+ "web_assist.permission.pointer_lock": "Maussteuerung",
+ "web_assist.permission.keyboard_lock": "Tastatursteuerung",
+ "web_assist.permission.filesystem": "Dateizugriff",
+ "web_assist.permission.protected_media": "Wiedergabe geschützter Medien",
+ "web_assist.permission.midi": "MIDI-Geräte",
+ "web_assist.permission.midi_sysex": "MIDI-Systemnachrichten",
+ "web_assist.permission.speaker_selection": "Auswahl der Audioausgabe",
+ "web_assist.permission.external": "Öffnen externer Anwendungen",
+ "web_assist.permission.sensors": "Gerätesensoren",
+ "web_assist.permission.background_fetch": "Downloads im Hintergrund",
+ "web_assist.permission.background_sync": "Synchronisierung im Hintergrund",
+ "web_assist.permission.surface_control": "Steuerung geteilter Inhalte",
+ "web_assist.permission.payment": "Zahlungsabwicklung",
+ "web_assist.permission.ar": "erweiterte Realität",
+ "web_assist.permission.vr": "virtuelle Realität",
+ "web_assist.permission.hand_tracking": "Handtracking",
+ "web_assist.permission.nfc": "NFC-Geräte",
+ "web_assist.permission.smart_card": "Smartcard-Lesegeräte",
+ "web_assist.permission.installation": "Installation von Web-Apps",
+ "web_assist.permission.printing": "Drucker",
+ "web_assist.permission.unknown": "die Berechtigung „{permission}“",
+ "web_assist.permission.other": "dieser Berechtigung",
+ "web_assist.passkey.title": "Passkey",
+ "web_assist.passkey.heading": "Smartphone oder Tablet verwenden",
+ "web_assist.passkey.instruction": "Scannen Sie diesen QR-Code mit der Kamera des Geräts, auf dem Ihr Passkey für {rpId} gespeichert ist.",
+ "web_assist.passkey.nearby": "Halten Sie Ihr Smartphone in der Nähe und lassen Sie Bluetooth eingeschaltet.",
+ "web_assist.passkey.qr_alt": "Scannen, um Ihren Passkey zu verwenden",
+ "web_assist.passkey.cancel": "Abbrechen",
+ "web_assist.passkey.preparing": "QR-Code wird vorbereitet…",
+ "web_assist.passkey.scan": "Warten auf den Scan…",
+ "web_assist.passkey.connecting": "Verbindung zum Smartphone wird hergestellt…",
+ "web_assist.passkey.confirm": "Smartphone verbunden. Bestätigen Sie auf Ihrem Smartphone.",
+ "web_assist.passkey.verifying": "Zurück zur Website…",
+ "errors.model_context_too_small": "Dieses Modell benötigt ein Kontextfenster von mindestens {minimum} Tokens. Wählen Sie ein Modell mit einem größeren Fenster."
}
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 6f4e96e6..0b20a86b 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Cloud sync conflict resolution: {count} conflicts",
"sync.conflict_resolution.message_single": "Please help me resolve this cloud sync conflict.",
"sync.conflict_resolution.message_batch": "Please help me resolve these cloud sync conflicts.",
- "quality.operator.incomplete": "Custom validation did not complete. Fix the policy file or disable custom validation in Settings, then retry."
+ "quality.operator.incomplete": "Custom validation did not complete. Fix the policy file or disable custom validation in Settings, then retry.",
+ "model.stopped_tool_limit_summary_incomplete": "This run stopped at the limit of {limit} tool rounds. The final summary could not be completed.",
+ "model.stopped_repeat_summary_incomplete": "This run stopped because repeated operations produced no new progress. The final summary could not be completed.",
+ "model.stopped_summary_incomplete": "This run stopped. The final summary could not be completed.",
+ "local_agents.unsupported_effort": "The selected reasoning effort is unavailable in this Claude Code installation. Upgrade Claude Code or select its default reasoning effort.",
+ "model.balance_fallback": "Your {provider} account is out of balance (this is not Orkas credits). Switching to a fallback model so the task can continue; top up that account to use it again.",
+ "model.provider_unavailable_fallback": "Your {provider} model is unavailable right now. Switching to a fallback model so the task can continue.",
+ "cli_agent.parameter_unsupported": "{cli} does not support the selected parameter {parameter}. Change the runtime settings.",
+ "cli_agent.model_unsupported": "{cli} does not support model {model}. Change the runtime settings.",
+ "auto_tasks.catch_up_title": "{title} (catch-up)",
+ "web_assist.permission_title": "Website permission",
+ "web_assist.permission_request": "Allow {origin} to use {permission}?",
+ "web_assist.permission_allow": "Allow",
+ "web_assist.permission_deny": "Deny",
+ "web_assist.permission.clipboard": "the clipboard",
+ "web_assist.permission.media": "the camera or microphone",
+ "web_assist.permission.location": "your location",
+ "web_assist.permission.notifications": "notifications",
+ "web_assist.permission.fullscreen": "full screen",
+ "web_assist.permission.screen": "screen sharing",
+ "web_assist.permission.device": "a device",
+ "web_assist.permission.approximate_location": "your approximate location",
+ "web_assist.permission.automatic_fullscreen": "full screen without a click",
+ "web_assist.permission.usb": "USB devices",
+ "web_assist.permission.hid": "input devices",
+ "web_assist.permission.serial": "serial devices",
+ "web_assist.permission.local_network": "devices on your local network",
+ "web_assist.permission.loopback_network": "services on this computer",
+ "web_assist.permission.persistent_storage": "persistent website storage",
+ "web_assist.permission.storage_access": "third-party cookies",
+ "web_assist.permission.window_management": "information about your screens",
+ "web_assist.permission.local_fonts": "fonts installed on this computer",
+ "web_assist.permission.idle_detection": "your activity and lock status",
+ "web_assist.permission.screen_wake_lock": "permission to keep the screen on",
+ "web_assist.permission.system_wake_lock": "permission to keep this computer awake",
+ "web_assist.permission.pointer_lock": "mouse capture",
+ "web_assist.permission.keyboard_lock": "keyboard capture",
+ "web_assist.permission.filesystem": "file access",
+ "web_assist.permission.protected_media": "protected media playback",
+ "web_assist.permission.midi": "MIDI devices",
+ "web_assist.permission.midi_sysex": "MIDI system messages",
+ "web_assist.permission.speaker_selection": "audio output selection",
+ "web_assist.permission.external": "permission to open external applications",
+ "web_assist.permission.sensors": "device sensors",
+ "web_assist.permission.background_fetch": "background downloads",
+ "web_assist.permission.background_sync": "background synchronization",
+ "web_assist.permission.surface_control": "control of shared content",
+ "web_assist.permission.payment": "payment handling",
+ "web_assist.permission.ar": "augmented reality",
+ "web_assist.permission.vr": "virtual reality",
+ "web_assist.permission.hand_tracking": "hand tracking",
+ "web_assist.permission.nfc": "NFC devices",
+ "web_assist.permission.smart_card": "smart card readers",
+ "web_assist.permission.installation": "web app installation",
+ "web_assist.permission.printing": "printers",
+ "web_assist.permission.unknown": "the “{permission}” permission",
+ "web_assist.permission.other": "this permission",
+ "web_assist.passkey.title": "Passkey",
+ "web_assist.passkey.heading": "Use a phone or tablet",
+ "web_assist.passkey.instruction": "Scan this QR code with the camera on the device that has your passkey for {rpId}.",
+ "web_assist.passkey.nearby": "Keep your phone nearby with Bluetooth on.",
+ "web_assist.passkey.cancel": "Cancel",
+ "web_assist.passkey.qr_alt": "Scan to use your passkey",
+ "web_assist.passkey.preparing": "Preparing QR code…",
+ "web_assist.passkey.scan": "Waiting for you to scan…",
+ "web_assist.passkey.connecting": "Connecting to your phone…",
+ "web_assist.passkey.confirm": "Phone connected. Confirm on your phone.",
+ "web_assist.passkey.verifying": "Returning to the website…",
+ "errors.model_context_too_small": "This model requires a context window of at least {minimum} tokens. Choose a model with a larger window."
}
diff --git a/src/main/locales/es-419.json b/src/main/locales/es-419.json
index 5ae6e94a..8695b9db 100644
--- a/src/main/locales/es-419.json
+++ b/src/main/locales/es-419.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Resolver conflictos de sincronización en la nube: {count}",
"sync.conflict_resolution.message_single": "Ayúdame a resolver este conflicto de sincronización en la nube.",
"sync.conflict_resolution.message_batch": "Ayúdame a resolver estos conflictos de sincronización en la nube.",
- "quality.operator.incomplete": "La validación personalizada no se completó. Corrige el archivo de reglas o desactiva la validación personalizada en Configuración y vuelve a intentarlo."
+ "quality.operator.incomplete": "La validación personalizada no se completó. Corrige el archivo de reglas o desactiva la validación personalizada en Configuración y vuelve a intentarlo.",
+ "model.stopped_tool_limit_summary_incomplete": "Esta ejecución se detuvo al alcanzar el límite de {limit} rondas de herramientas. No se pudo completar el resumen final.",
+ "model.stopped_repeat_summary_incomplete": "Esta ejecución se detuvo porque las operaciones repetidas no produjeron nuevos avances. No se pudo completar el resumen final.",
+ "model.stopped_summary_incomplete": "Esta ejecución se detuvo. No se pudo completar el resumen final.",
+ "local_agents.unsupported_effort": "El nivel de razonamiento seleccionado no está disponible en esta instalación de Claude Code. Actualiza Claude Code o selecciona el nivel predeterminado.",
+ "model.balance_fallback": "Tu cuenta de {provider} no tiene saldo (no son los créditos de Orkas). Se cambia a un modelo alternativo para continuar la tarea; recarga esa cuenta para volver a usarla.",
+ "model.provider_unavailable_fallback": "Tu modelo de {provider} no está disponible ahora. Se cambia a un modelo alternativo para continuar la tarea.",
+ "cli_agent.parameter_unsupported": "{cli} no admite el parámetro seleccionado {parameter}. Cambia la configuración de ejecución.",
+ "cli_agent.model_unsupported": "{cli} no admite el modelo {model}. Cambia la configuración de ejecución.",
+ "auto_tasks.catch_up_title": "{title} (ejecución recuperada)",
+ "web_assist.permission_title": "Permiso del sitio",
+ "web_assist.permission_request": "¿Permitir que {origin} use {permission}?",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Denegar",
+ "web_assist.permission.clipboard": "el portapapeles",
+ "web_assist.permission.media": "la cámara o el micrófono",
+ "web_assist.permission.location": "tu ubicación",
+ "web_assist.permission.notifications": "notificaciones",
+ "web_assist.permission.fullscreen": "pantalla completa",
+ "web_assist.permission.screen": "compartir pantalla",
+ "web_assist.permission.device": "un dispositivo",
+ "web_assist.permission.approximate_location": "la ubicación aproximada",
+ "web_assist.permission.automatic_fullscreen": "la pantalla completa automática",
+ "web_assist.permission.usb": "dispositivos USB",
+ "web_assist.permission.hid": "dispositivos de entrada",
+ "web_assist.permission.serial": "dispositivos de puerto serie",
+ "web_assist.permission.local_network": "la red local",
+ "web_assist.permission.loopback_network": "servicios de esta computadora",
+ "web_assist.permission.persistent_storage": "almacenamiento persistente del sitio",
+ "web_assist.permission.storage_access": "cookies de terceros",
+ "web_assist.permission.window_management": "información de las pantallas",
+ "web_assist.permission.local_fonts": "fuentes locales",
+ "web_assist.permission.idle_detection": "el estado de actividad y bloqueo",
+ "web_assist.permission.screen_wake_lock": "mantener la pantalla encendida",
+ "web_assist.permission.system_wake_lock": "impedir la suspensión de la computadora",
+ "web_assist.permission.pointer_lock": "captura del mouse",
+ "web_assist.permission.keyboard_lock": "captura del teclado",
+ "web_assist.permission.filesystem": "acceso a archivos",
+ "web_assist.permission.protected_media": "reproducción de contenido protegido",
+ "web_assist.permission.midi": "dispositivos MIDI",
+ "web_assist.permission.midi_sysex": "mensajes de sistema MIDI",
+ "web_assist.permission.speaker_selection": "selección de salida de audio",
+ "web_assist.permission.external": "apertura de aplicaciones externas",
+ "web_assist.permission.sensors": "sensores del dispositivo",
+ "web_assist.permission.background_fetch": "descargas en segundo plano",
+ "web_assist.permission.background_sync": "sincronización en segundo plano",
+ "web_assist.permission.surface_control": "control del contenido compartido",
+ "web_assist.permission.payment": "procesamiento de pagos",
+ "web_assist.permission.ar": "realidad aumentada",
+ "web_assist.permission.vr": "realidad virtual",
+ "web_assist.permission.hand_tracking": "seguimiento de manos",
+ "web_assist.permission.nfc": "dispositivos NFC",
+ "web_assist.permission.smart_card": "lectores de tarjetas inteligentes",
+ "web_assist.permission.installation": "instalación de aplicaciones web",
+ "web_assist.permission.printing": "impresoras",
+ "web_assist.permission.unknown": "el permiso «{permission}»",
+ "web_assist.permission.other": "este permiso",
+ "web_assist.passkey.title": "Llave de acceso",
+ "web_assist.passkey.heading": "Usar un teléfono o una tablet",
+ "web_assist.passkey.instruction": "Escanea este código QR con la cámara del dispositivo que tiene tu llave de acceso para {rpId}.",
+ "web_assist.passkey.nearby": "Mantén tu teléfono cerca y con el Bluetooth activado.",
+ "web_assist.passkey.qr_alt": "Escanea para usar tu llave de acceso",
+ "web_assist.passkey.cancel": "Cancelar",
+ "web_assist.passkey.preparing": "Preparando el código QR…",
+ "web_assist.passkey.scan": "Esperando a que escanees…",
+ "web_assist.passkey.connecting": "Conectando con tu teléfono…",
+ "web_assist.passkey.confirm": "Teléfono conectado. Confirma en tu teléfono.",
+ "web_assist.passkey.verifying": "Volviendo al sitio web…",
+ "errors.model_context_too_small": "Este modelo requiere una ventana de contexto de al menos {minimum} tokens. Elige un modelo con una ventana mayor."
}
diff --git a/src/main/locales/es.json b/src/main/locales/es.json
index 0372a752..55415b46 100644
--- a/src/main/locales/es.json
+++ b/src/main/locales/es.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Resolver conflictos de sincronización en la nube: {count}",
"sync.conflict_resolution.message_single": "Ayúdame a resolver este conflicto de sincronización en la nube.",
"sync.conflict_resolution.message_batch": "Ayúdame a resolver estos conflictos de sincronización en la nube.",
- "quality.operator.incomplete": "La validación personalizada no se ha completado. Corrige el archivo de reglas o desactiva la validación personalizada en Ajustes e inténtalo de nuevo."
+ "quality.operator.incomplete": "La validación personalizada no se ha completado. Corrige el archivo de reglas o desactiva la validación personalizada en Ajustes e inténtalo de nuevo.",
+ "model.stopped_tool_limit_summary_incomplete": "Esta ejecución se detuvo al alcanzar el límite de {limit} rondas de herramientas. No se pudo completar el resumen final.",
+ "model.stopped_repeat_summary_incomplete": "Esta ejecución se detuvo porque las operaciones repetidas no produjeron nuevos avances. No se pudo completar el resumen final.",
+ "model.stopped_summary_incomplete": "Esta ejecución se detuvo. No se pudo completar el resumen final.",
+ "local_agents.unsupported_effort": "El nivel de razonamiento seleccionado no está disponible en esta instalación de Claude Code. Actualiza Claude Code o selecciona el nivel predeterminado.",
+ "model.balance_fallback": "Tu cuenta de {provider} no tiene saldo (no son los créditos de Orkas). Se cambia a un modelo alternativo para continuar la tarea; recarga esa cuenta para volver a usarla.",
+ "model.provider_unavailable_fallback": "Tu modelo de {provider} no está disponible ahora. Se cambia a un modelo alternativo para continuar la tarea.",
+ "cli_agent.parameter_unsupported": "{cli} no admite el parámetro seleccionado {parameter}. Cambia la configuración de ejecución.",
+ "cli_agent.model_unsupported": "{cli} no admite el modelo {model}. Cambia la configuración de ejecución.",
+ "auto_tasks.catch_up_title": "{title} (ejecución recuperada)",
+ "web_assist.permission_title": "Permiso del sitio",
+ "web_assist.permission_request": "¿Permitir que {origin} use {permission}?",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Denegar",
+ "web_assist.permission.clipboard": "el portapapeles",
+ "web_assist.permission.media": "la cámara o el micrófono",
+ "web_assist.permission.location": "tu ubicación",
+ "web_assist.permission.notifications": "notificaciones",
+ "web_assist.permission.fullscreen": "pantalla completa",
+ "web_assist.permission.screen": "compartir pantalla",
+ "web_assist.permission.device": "un dispositivo",
+ "web_assist.permission.approximate_location": "la ubicación aproximada",
+ "web_assist.permission.automatic_fullscreen": "la pantalla completa automática",
+ "web_assist.permission.usb": "dispositivos USB",
+ "web_assist.permission.hid": "dispositivos de entrada",
+ "web_assist.permission.serial": "dispositivos de puerto serie",
+ "web_assist.permission.local_network": "la red local",
+ "web_assist.permission.loopback_network": "servicios de este equipo",
+ "web_assist.permission.persistent_storage": "almacenamiento persistente del sitio",
+ "web_assist.permission.storage_access": "cookies de terceros",
+ "web_assist.permission.window_management": "información de las pantallas",
+ "web_assist.permission.local_fonts": "fuentes locales",
+ "web_assist.permission.idle_detection": "el estado de actividad y bloqueo",
+ "web_assist.permission.screen_wake_lock": "mantener la pantalla encendida",
+ "web_assist.permission.system_wake_lock": "impedir la suspensión del equipo",
+ "web_assist.permission.pointer_lock": "captura del ratón",
+ "web_assist.permission.keyboard_lock": "captura del teclado",
+ "web_assist.permission.filesystem": "acceso a archivos",
+ "web_assist.permission.protected_media": "reproducción de contenido protegido",
+ "web_assist.permission.midi": "dispositivos MIDI",
+ "web_assist.permission.midi_sysex": "mensajes de sistema MIDI",
+ "web_assist.permission.speaker_selection": "selección de salida de audio",
+ "web_assist.permission.external": "apertura de aplicaciones externas",
+ "web_assist.permission.sensors": "sensores del dispositivo",
+ "web_assist.permission.background_fetch": "descargas en segundo plano",
+ "web_assist.permission.background_sync": "sincronización en segundo plano",
+ "web_assist.permission.surface_control": "control del contenido compartido",
+ "web_assist.permission.payment": "procesamiento de pagos",
+ "web_assist.permission.ar": "realidad aumentada",
+ "web_assist.permission.vr": "realidad virtual",
+ "web_assist.permission.hand_tracking": "seguimiento de manos",
+ "web_assist.permission.nfc": "dispositivos NFC",
+ "web_assist.permission.smart_card": "lectores de tarjetas inteligentes",
+ "web_assist.permission.installation": "instalación de aplicaciones web",
+ "web_assist.permission.printing": "impresoras",
+ "web_assist.permission.unknown": "el permiso «{permission}»",
+ "web_assist.permission.other": "este permiso",
+ "web_assist.passkey.title": "Llave de acceso",
+ "web_assist.passkey.heading": "Usar un teléfono o una tableta",
+ "web_assist.passkey.instruction": "Escanea este código QR con la cámara del dispositivo que tiene tu llave de acceso para {rpId}.",
+ "web_assist.passkey.nearby": "Mantén tu teléfono cerca y con el Bluetooth activado.",
+ "web_assist.passkey.qr_alt": "Escanea para usar tu llave de acceso",
+ "web_assist.passkey.cancel": "Cancelar",
+ "web_assist.passkey.preparing": "Preparando el código QR…",
+ "web_assist.passkey.scan": "Esperando a que escanees…",
+ "web_assist.passkey.connecting": "Conectando con tu teléfono…",
+ "web_assist.passkey.confirm": "Teléfono conectado. Confirma en tu teléfono.",
+ "web_assist.passkey.verifying": "Volviendo al sitio web…",
+ "errors.model_context_too_small": "Este modelo requiere una ventana de contexto de al menos {minimum} tokens. Elige un modelo con una ventana mayor."
}
diff --git a/src/main/locales/fr.json b/src/main/locales/fr.json
index dea5b455..4e324b39 100644
--- a/src/main/locales/fr.json
+++ b/src/main/locales/fr.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Résoudre les conflits de synchronisation cloud : {count}",
"sync.conflict_resolution.message_single": "Aidez-moi à résoudre ce conflit de synchronisation cloud.",
"sync.conflict_resolution.message_batch": "Aidez-moi à résoudre ces conflits de synchronisation cloud.",
- "quality.operator.incomplete": "La validation personnalisée n’a pas abouti. Corrigez le fichier de règles ou désactivez la validation personnalisée dans les paramètres, puis réessayez."
+ "quality.operator.incomplete": "La validation personnalisée n’a pas abouti. Corrigez le fichier de règles ou désactivez la validation personnalisée dans les paramètres, puis réessayez.",
+ "model.stopped_tool_limit_summary_incomplete": "Cette exécution s’est arrêtée après avoir atteint la limite de {limit} tours d’outils. Le résumé final n’a pas pu être terminé.",
+ "model.stopped_repeat_summary_incomplete": "Cette exécution s’est arrêtée car les opérations répétées n’apportaient aucun nouveau progrès. Le résumé final n’a pas pu être terminé.",
+ "model.stopped_summary_incomplete": "Cette exécution s’est arrêtée. Le résumé final n’a pas pu être terminé.",
+ "local_agents.unsupported_effort": "Le niveau de raisonnement sélectionné n’est pas disponible dans cette installation de Claude Code. Mettez Claude Code à jour ou choisissez le niveau par défaut.",
+ "model.balance_fallback": "Le solde de votre compte {provider} est épuisé (il ne s’agit pas des crédits Orkas). Passage à un modèle de repli pour poursuivre la tâche ; rechargez ce compte pour l’utiliser à nouveau.",
+ "model.provider_unavailable_fallback": "Votre modèle {provider} est indisponible pour le moment. Passage à un modèle de repli pour poursuivre la tâche.",
+ "cli_agent.parameter_unsupported": "{cli} ne prend pas en charge le paramètre choisi {parameter}. Modifiez les paramètres d’exécution.",
+ "cli_agent.model_unsupported": "{cli} ne prend pas en charge le modèle {model}. Modifiez les paramètres d’exécution.",
+ "auto_tasks.catch_up_title": "{title} (rattrapage)",
+ "web_assist.permission_title": "Autorisation du site",
+ "web_assist.permission_request": "Autoriser {origin} à utiliser {permission} ?",
+ "web_assist.permission_allow": "Autoriser",
+ "web_assist.permission_deny": "Refuser",
+ "web_assist.permission.clipboard": "le presse-papiers",
+ "web_assist.permission.media": "la caméra ou le microphone",
+ "web_assist.permission.location": "votre position",
+ "web_assist.permission.notifications": "les notifications",
+ "web_assist.permission.fullscreen": "le plein écran",
+ "web_assist.permission.screen": "le partage d’écran",
+ "web_assist.permission.device": "un appareil",
+ "web_assist.permission.approximate_location": "la position approximative",
+ "web_assist.permission.automatic_fullscreen": "le plein écran automatique",
+ "web_assist.permission.usb": "les appareils USB",
+ "web_assist.permission.hid": "les périphériques d’entrée",
+ "web_assist.permission.serial": "les périphériques série",
+ "web_assist.permission.local_network": "le réseau local",
+ "web_assist.permission.loopback_network": "les services de cet ordinateur",
+ "web_assist.permission.persistent_storage": "le stockage persistant du site",
+ "web_assist.permission.storage_access": "les cookies tiers",
+ "web_assist.permission.window_management": "les informations sur les écrans",
+ "web_assist.permission.local_fonts": "les polices locales",
+ "web_assist.permission.idle_detection": "l’état d’activité et de verrouillage",
+ "web_assist.permission.screen_wake_lock": "le maintien de l’écran allumé",
+ "web_assist.permission.system_wake_lock": "le maintien de l’ordinateur éveillé",
+ "web_assist.permission.pointer_lock": "la capture de la souris",
+ "web_assist.permission.keyboard_lock": "la capture du clavier",
+ "web_assist.permission.filesystem": "l’accès aux fichiers",
+ "web_assist.permission.protected_media": "la lecture de contenus protégés",
+ "web_assist.permission.midi": "les appareils MIDI",
+ "web_assist.permission.midi_sysex": "les messages système MIDI",
+ "web_assist.permission.speaker_selection": "la sélection de la sortie audio",
+ "web_assist.permission.external": "l’ouverture d’applications externes",
+ "web_assist.permission.sensors": "les capteurs de l’appareil",
+ "web_assist.permission.background_fetch": "les téléchargements en arrière-plan",
+ "web_assist.permission.background_sync": "la synchronisation en arrière-plan",
+ "web_assist.permission.surface_control": "le contrôle du contenu partagé",
+ "web_assist.permission.payment": "le traitement des paiements",
+ "web_assist.permission.ar": "la réalité augmentée",
+ "web_assist.permission.vr": "la réalité virtuelle",
+ "web_assist.permission.hand_tracking": "le suivi des mains",
+ "web_assist.permission.nfc": "les appareils NFC",
+ "web_assist.permission.smart_card": "les lecteurs de cartes à puce",
+ "web_assist.permission.installation": "l’installation d’applications web",
+ "web_assist.permission.printing": "les imprimantes",
+ "web_assist.permission.unknown": "l’autorisation « {permission} »",
+ "web_assist.permission.other": "cette autorisation",
+ "web_assist.passkey.title": "Clé d’accès",
+ "web_assist.passkey.heading": "Utiliser un téléphone ou une tablette",
+ "web_assist.passkey.instruction": "Scannez ce code QR avec l’appareil photo de l’appareil qui contient votre clé d’accès pour {rpId}.",
+ "web_assist.passkey.nearby": "Gardez votre téléphone à proximité, avec le Bluetooth activé.",
+ "web_assist.passkey.qr_alt": "Scannez pour utiliser votre clé d’accès",
+ "web_assist.passkey.cancel": "Annuler",
+ "web_assist.passkey.preparing": "Préparation du code QR…",
+ "web_assist.passkey.scan": "En attente du scan…",
+ "web_assist.passkey.connecting": "Connexion à votre téléphone…",
+ "web_assist.passkey.confirm": "Téléphone connecté. Confirmez sur votre téléphone.",
+ "web_assist.passkey.verifying": "Retour au site web…",
+ "errors.model_context_too_small": "Ce modèle nécessite une fenêtre de contexte d’au moins {minimum} tokens. Choisissez un modèle avec une fenêtre plus grande."
}
diff --git a/src/main/locales/hi.json b/src/main/locales/hi.json
index 90983e68..f760ffef 100644
--- a/src/main/locales/hi.json
+++ b/src/main/locales/hi.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "क्लाउड सिंक टकराव का समाधान: {count} टकराव",
"sync.conflict_resolution.message_single": "इस क्लाउड सिंक टकराव को सुलझाने में मेरी मदद करें।",
"sync.conflict_resolution.message_batch": "इन क्लाउड सिंक टकरावों को सुलझाने में मेरी मदद करें।",
- "quality.operator.incomplete": "कस्टम सत्यापन पूरा नहीं हुआ। नियम फ़ाइल ठीक करें या सेटिंग में कस्टम सत्यापन बंद करके फिर कोशिश करें।"
+ "quality.operator.incomplete": "कस्टम सत्यापन पूरा नहीं हुआ। नियम फ़ाइल ठीक करें या सेटिंग में कस्टम सत्यापन बंद करके फिर कोशिश करें।",
+ "model.stopped_tool_limit_summary_incomplete": "टूल संचालन के {limit} दौर की सीमा पूरी होने पर यह रन रोक दिया गया। अंतिम सारांश पूरा नहीं हो सका।",
+ "model.stopped_repeat_summary_incomplete": "बार-बार किए गए कार्यों से कोई नई प्रगति नहीं होने के कारण यह रन रोक दिया गया। अंतिम सारांश पूरा नहीं हो सका।",
+ "model.stopped_summary_incomplete": "यह रन रोक दिया गया। अंतिम सारांश पूरा नहीं हो सका।",
+ "local_agents.unsupported_effort": "इस Claude Code इंस्टॉलेशन में चुना गया तर्क स्तर उपलब्ध नहीं है। Claude Code अपडेट करें या डिफ़ॉल्ट तर्क स्तर चुनें।",
+ "model.balance_fallback": "आपके {provider} खाते का बैलेंस खत्म हो गया है (यह Orkas क्रेडिट नहीं है)। कार्य जारी रखने के लिए वैकल्पिक मॉडल चुना जा रहा है; दोबारा इस्तेमाल करने के लिए उस खाते में राशि जोड़ें।",
+ "model.provider_unavailable_fallback": "आपका {provider} मॉडल अभी उपलब्ध नहीं है। कार्य जारी रखने के लिए वैकल्पिक मॉडल चुना जा रहा है।",
+ "cli_agent.parameter_unsupported": "{cli} चुने गए पैरामीटर {parameter} का समर्थन नहीं करता। रनटाइम सेटिंग बदलें।",
+ "cli_agent.model_unsupported": "{cli} मॉडल {model} का समर्थन नहीं करता। रनटाइम सेटिंग बदलें।",
+ "auto_tasks.catch_up_title": "{title} (देर से चलाया गया)",
+ "web_assist.permission_title": "वेबसाइट की अनुमति",
+ "web_assist.permission_request": "क्या {origin} को {permission} इस्तेमाल करने दें?",
+ "web_assist.permission_allow": "अनुमति दें",
+ "web_assist.permission_deny": "मना करें",
+ "web_assist.permission.clipboard": "क्लिपबोर्ड",
+ "web_assist.permission.media": "कैमरा या माइक्रोफ़ोन",
+ "web_assist.permission.location": "आपकी लोकेशन",
+ "web_assist.permission.notifications": "सूचनाएँ",
+ "web_assist.permission.fullscreen": "पूर्ण स्क्रीन",
+ "web_assist.permission.screen": "स्क्रीन साझा करना",
+ "web_assist.permission.device": "डिवाइस",
+ "web_assist.permission.approximate_location": "अनुमानित स्थान",
+ "web_assist.permission.automatic_fullscreen": "स्वचालित पूर्ण स्क्रीन",
+ "web_assist.permission.usb": "USB उपकरण",
+ "web_assist.permission.hid": "इनपुट उपकरण",
+ "web_assist.permission.serial": "सीरियल उपकरण",
+ "web_assist.permission.local_network": "स्थानीय नेटवर्क",
+ "web_assist.permission.loopback_network": "इस कंप्यूटर की सेवाएँ",
+ "web_assist.permission.persistent_storage": "स्थायी वेबसाइट संग्रहण",
+ "web_assist.permission.storage_access": "तृतीय-पक्ष कुकी",
+ "web_assist.permission.window_management": "स्क्रीन जानकारी",
+ "web_assist.permission.local_fonts": "स्थानीय फ़ॉन्ट",
+ "web_assist.permission.idle_detection": "गतिविधि और लॉक स्थिति",
+ "web_assist.permission.screen_wake_lock": "स्क्रीन चालू रखना",
+ "web_assist.permission.system_wake_lock": "कंप्यूटर को स्लीप से रोकना",
+ "web_assist.permission.pointer_lock": "माउस कैप्चर",
+ "web_assist.permission.keyboard_lock": "कीबोर्ड कैप्चर",
+ "web_assist.permission.filesystem": "फ़ाइल पहुँच",
+ "web_assist.permission.protected_media": "सुरक्षित मीडिया प्लेबैक",
+ "web_assist.permission.midi": "MIDI उपकरण",
+ "web_assist.permission.midi_sysex": "MIDI सिस्टम संदेश",
+ "web_assist.permission.speaker_selection": "ऑडियो आउटपुट चयन",
+ "web_assist.permission.external": "बाहरी ऐप खोलना",
+ "web_assist.permission.sensors": "उपकरण सेंसर",
+ "web_assist.permission.background_fetch": "पृष्ठभूमि डाउनलोड",
+ "web_assist.permission.background_sync": "पृष्ठभूमि सिंक्रनाइज़ेशन",
+ "web_assist.permission.surface_control": "साझा सामग्री नियंत्रण",
+ "web_assist.permission.payment": "भुगतान प्रसंस्करण",
+ "web_assist.permission.ar": "संवर्धित वास्तविकता",
+ "web_assist.permission.vr": "आभासी वास्तविकता",
+ "web_assist.permission.hand_tracking": "हाथ ट्रैकिंग",
+ "web_assist.permission.nfc": "NFC उपकरण",
+ "web_assist.permission.smart_card": "स्मार्ट कार्ड रीडर",
+ "web_assist.permission.installation": "वेब ऐप इंस्टॉल करना",
+ "web_assist.permission.printing": "प्रिंटर",
+ "web_assist.permission.unknown": "“{permission}” अनुमति",
+ "web_assist.permission.other": "यह अनुमति",
+ "web_assist.passkey.title": "पासकी",
+ "web_assist.passkey.heading": "फ़ोन या टैबलेट का उपयोग करें",
+ "web_assist.passkey.instruction": "{rpId} की पासकी वाले डिवाइस के कैमरे से यह QR कोड स्कैन करें।",
+ "web_assist.passkey.nearby": "ब्लूटूथ चालू रखें और अपना फ़ोन पास रखें।",
+ "web_assist.passkey.qr_alt": "पासकी इस्तेमाल करने के लिए स्कैन करें",
+ "web_assist.passkey.cancel": "रद्द करें",
+ "web_assist.passkey.preparing": "QR कोड तैयार किया जा रहा है…",
+ "web_assist.passkey.scan": "स्कैन की प्रतीक्षा में…",
+ "web_assist.passkey.connecting": "आपके फ़ोन से कनेक्ट किया जा रहा है…",
+ "web_assist.passkey.confirm": "फ़ोन कनेक्ट हो गया। अपने फ़ोन पर पुष्टि करें।",
+ "web_assist.passkey.verifying": "वेबसाइट पर लौट रहे हैं…",
+ "errors.model_context_too_small": "इस मॉडल के लिए कम से कम {minimum} टोकन की संदर्भ विंडो आवश्यक है। बड़ी विंडो वाला मॉडल चुनें।"
}
diff --git a/src/main/locales/id.json b/src/main/locales/id.json
index 63f2400a..0e9640c3 100644
--- a/src/main/locales/id.json
+++ b/src/main/locales/id.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Resolusi konflik sinkronisasi cloud: konflik {count}",
"sync.conflict_resolution.message_single": "Tolong bantu saya menyelesaikan konflik sinkronisasi cloud ini.",
"sync.conflict_resolution.message_batch": "Tolong bantu saya menyelesaikan konflik sinkronisasi cloud ini.",
- "quality.operator.incomplete": "Validasi kustom tidak selesai. Perbaiki file aturan atau nonaktifkan validasi kustom di Pengaturan, lalu coba lagi."
+ "quality.operator.incomplete": "Validasi kustom tidak selesai. Perbaiki file aturan atau nonaktifkan validasi kustom di Pengaturan, lalu coba lagi.",
+ "model.stopped_tool_limit_summary_incomplete": "Proses ini dihentikan setelah mencapai batas {limit} putaran alat. Ringkasan akhir tidak dapat diselesaikan.",
+ "model.stopped_repeat_summary_incomplete": "Proses ini dihentikan karena operasi berulang tidak menghasilkan kemajuan baru. Ringkasan akhir tidak dapat diselesaikan.",
+ "model.stopped_summary_incomplete": "Proses ini dihentikan. Ringkasan akhir tidak dapat diselesaikan.",
+ "local_agents.unsupported_effort": "Tingkat penalaran yang dipilih tidak tersedia dalam instalasi Claude Code ini. Perbarui Claude Code atau pilih tingkat penalaran bawaan.",
+ "model.balance_fallback": "Saldo akun {provider} Anda habis (ini bukan kredit Orkas). Beralih ke model cadangan sehingga tugas dapat dilanjutkan; isi ulang akun tersebut untuk menggunakannya lagi.",
+ "model.provider_unavailable_fallback": "Model {provider} Anda sedang tidak tersedia. Beralih ke model cadangan sehingga tugas dapat dilanjutkan.",
+ "cli_agent.parameter_unsupported": "{cli} tidak mendukung parameter yang dipilih {parameter}. Ubah pengaturan runtime.",
+ "cli_agent.model_unsupported": "{cli} tidak mendukung model {model}. Ubah pengaturan runtime.",
+ "auto_tasks.catch_up_title": "{title} (susulan)",
+ "web_assist.permission_title": "Izin situs",
+ "web_assist.permission_request": "Izinkan {origin} menggunakan {permission}?",
+ "web_assist.permission_allow": "Izinkan",
+ "web_assist.permission_deny": "Tolak",
+ "web_assist.permission.clipboard": "papan klip",
+ "web_assist.permission.media": "kamera atau mikrofon",
+ "web_assist.permission.location": "lokasi Anda",
+ "web_assist.permission.notifications": "notifikasi",
+ "web_assist.permission.fullscreen": "layar penuh",
+ "web_assist.permission.screen": "berbagi layar",
+ "web_assist.permission.device": "perangkat",
+ "web_assist.permission.approximate_location": "perkiraan lokasi",
+ "web_assist.permission.automatic_fullscreen": "layar penuh otomatis",
+ "web_assist.permission.usb": "perangkat USB",
+ "web_assist.permission.hid": "perangkat masukan",
+ "web_assist.permission.serial": "perangkat serial",
+ "web_assist.permission.local_network": "jaringan lokal",
+ "web_assist.permission.loopback_network": "layanan di komputer ini",
+ "web_assist.permission.persistent_storage": "penyimpanan situs permanen",
+ "web_assist.permission.storage_access": "cookie pihak ketiga",
+ "web_assist.permission.window_management": "informasi layar",
+ "web_assist.permission.local_fonts": "font lokal",
+ "web_assist.permission.idle_detection": "status aktivitas dan kunci",
+ "web_assist.permission.screen_wake_lock": "menjaga layar tetap menyala",
+ "web_assist.permission.system_wake_lock": "mencegah komputer tidur",
+ "web_assist.permission.pointer_lock": "penangkapan mouse",
+ "web_assist.permission.keyboard_lock": "penangkapan keyboard",
+ "web_assist.permission.filesystem": "akses berkas",
+ "web_assist.permission.protected_media": "pemutaran media terlindungi",
+ "web_assist.permission.midi": "perangkat MIDI",
+ "web_assist.permission.midi_sysex": "pesan sistem MIDI",
+ "web_assist.permission.speaker_selection": "pemilihan keluaran audio",
+ "web_assist.permission.external": "membuka aplikasi eksternal",
+ "web_assist.permission.sensors": "sensor perangkat",
+ "web_assist.permission.background_fetch": "unduhan latar belakang",
+ "web_assist.permission.background_sync": "sinkronisasi latar belakang",
+ "web_assist.permission.surface_control": "kontrol konten bersama",
+ "web_assist.permission.payment": "pemrosesan pembayaran",
+ "web_assist.permission.ar": "realitas tertambah",
+ "web_assist.permission.vr": "realitas virtual",
+ "web_assist.permission.hand_tracking": "pelacakan tangan",
+ "web_assist.permission.nfc": "perangkat NFC",
+ "web_assist.permission.smart_card": "pembaca kartu pintar",
+ "web_assist.permission.installation": "instalasi aplikasi web",
+ "web_assist.permission.printing": "printer",
+ "web_assist.permission.unknown": "izin “{permission}”",
+ "web_assist.permission.other": "izin ini",
+ "web_assist.passkey.title": "Kunci sandi",
+ "web_assist.passkey.heading": "Gunakan ponsel atau tablet",
+ "web_assist.passkey.instruction": "Pindai kode QR ini dengan kamera perangkat yang menyimpan kunci sandi Anda untuk {rpId}.",
+ "web_assist.passkey.nearby": "Dekatkan ponsel Anda dan pastikan Bluetooth aktif.",
+ "web_assist.passkey.qr_alt": "Pindai untuk menggunakan kunci sandi Anda",
+ "web_assist.passkey.cancel": "Batal",
+ "web_assist.passkey.preparing": "Menyiapkan kode QR…",
+ "web_assist.passkey.scan": "Menunggu pemindaian…",
+ "web_assist.passkey.connecting": "Menghubungkan ke ponsel Anda…",
+ "web_assist.passkey.confirm": "Ponsel terhubung. Konfirmasikan di ponsel Anda.",
+ "web_assist.passkey.verifying": "Kembali ke situs web…",
+ "errors.model_context_too_small": "Model ini memerlukan jendela konteks minimal {minimum} token. Pilih model dengan jendela lebih besar."
}
diff --git a/src/main/locales/it.json b/src/main/locales/it.json
index 8bdce208..48986ca9 100644
--- a/src/main/locales/it.json
+++ b/src/main/locales/it.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Risolvi i conflitti di sincronizzazione cloud: {count}",
"sync.conflict_resolution.message_single": "Aiutami a risolvere questo conflitto di sincronizzazione cloud.",
"sync.conflict_resolution.message_batch": "Aiutami a risolvere questi conflitti di sincronizzazione cloud.",
- "quality.operator.incomplete": "La validazione personalizzata non è stata completata. Correggi il file delle regole o disattiva la validazione personalizzata nelle impostazioni, quindi riprova."
+ "quality.operator.incomplete": "La validazione personalizzata non è stata completata. Correggi il file delle regole o disattiva la validazione personalizzata nelle impostazioni, quindi riprova.",
+ "model.stopped_tool_limit_summary_incomplete": "Questa esecuzione si è fermata al limite di {limit} cicli di strumenti. Non è stato possibile completare il riepilogo finale.",
+ "model.stopped_repeat_summary_incomplete": "Questa esecuzione si è fermata perché le operazioni ripetute non hanno prodotto nuovi progressi. Non è stato possibile completare il riepilogo finale.",
+ "model.stopped_summary_incomplete": "Questa esecuzione si è fermata. Non è stato possibile completare il riepilogo finale.",
+ "local_agents.unsupported_effort": "Il livello di ragionamento selezionato non è disponibile in questa installazione di Claude Code. Aggiorna Claude Code o scegli il livello predefinito.",
+ "model.balance_fallback": "Il saldo del tuo account {provider} è esaurito (non si tratta dei crediti Orkas). Passaggio a un modello di riserva per continuare l'attività; ricarica l'account per usarlo di nuovo.",
+ "model.provider_unavailable_fallback": "Il tuo modello {provider} non è disponibile al momento. Passaggio a un modello di riserva per continuare l'attività.",
+ "cli_agent.parameter_unsupported": "{cli} non supporta il parametro selezionato {parameter}. Modifica le impostazioni di esecuzione.",
+ "cli_agent.model_unsupported": "{cli} non supporta il modello {model}. Modifica le impostazioni di esecuzione.",
+ "auto_tasks.catch_up_title": "{title} (esecuzione recuperata)",
+ "web_assist.permission_title": "Autorizzazione del sito",
+ "web_assist.permission_request": "Consentire a {origin} di usare {permission}?",
+ "web_assist.permission_allow": "Consenti",
+ "web_assist.permission_deny": "Nega",
+ "web_assist.permission.clipboard": "gli appunti",
+ "web_assist.permission.media": "la fotocamera o il microfono",
+ "web_assist.permission.location": "la tua posizione",
+ "web_assist.permission.notifications": "le notifiche",
+ "web_assist.permission.fullscreen": "lo schermo intero",
+ "web_assist.permission.screen": "la condivisione dello schermo",
+ "web_assist.permission.device": "un dispositivo",
+ "web_assist.permission.approximate_location": "la posizione approssimativa",
+ "web_assist.permission.automatic_fullscreen": "lo schermo intero automatico",
+ "web_assist.permission.usb": "dispositivi USB",
+ "web_assist.permission.hid": "dispositivi di input",
+ "web_assist.permission.serial": "dispositivi seriali",
+ "web_assist.permission.local_network": "la rete locale",
+ "web_assist.permission.loopback_network": "servizi su questo computer",
+ "web_assist.permission.persistent_storage": "l’archiviazione persistente del sito",
+ "web_assist.permission.storage_access": "cookie di terze parti",
+ "web_assist.permission.window_management": "informazioni sugli schermi",
+ "web_assist.permission.local_fonts": "font locali",
+ "web_assist.permission.idle_detection": "lo stato di attività e blocco",
+ "web_assist.permission.screen_wake_lock": "il mantenimento dello schermo acceso",
+ "web_assist.permission.system_wake_lock": "il mantenimento del computer attivo",
+ "web_assist.permission.pointer_lock": "l’acquisizione del mouse",
+ "web_assist.permission.keyboard_lock": "l’acquisizione della tastiera",
+ "web_assist.permission.filesystem": "l’accesso ai file",
+ "web_assist.permission.protected_media": "la riproduzione di contenuti protetti",
+ "web_assist.permission.midi": "dispositivi MIDI",
+ "web_assist.permission.midi_sysex": "messaggi di sistema MIDI",
+ "web_assist.permission.speaker_selection": "la selezione dell’uscita audio",
+ "web_assist.permission.external": "l’apertura di app esterne",
+ "web_assist.permission.sensors": "sensori del dispositivo",
+ "web_assist.permission.background_fetch": "download in background",
+ "web_assist.permission.background_sync": "la sincronizzazione in background",
+ "web_assist.permission.surface_control": "il controllo dei contenuti condivisi",
+ "web_assist.permission.payment": "l’elaborazione dei pagamenti",
+ "web_assist.permission.ar": "la realtà aumentata",
+ "web_assist.permission.vr": "la realtà virtuale",
+ "web_assist.permission.hand_tracking": "il tracciamento delle mani",
+ "web_assist.permission.nfc": "dispositivi NFC",
+ "web_assist.permission.smart_card": "lettori di smart card",
+ "web_assist.permission.installation": "l’installazione di app web",
+ "web_assist.permission.printing": "stampanti",
+ "web_assist.permission.unknown": "l’autorizzazione “{permission}”",
+ "web_assist.permission.other": "questa autorizzazione",
+ "web_assist.passkey.title": "Passkey",
+ "web_assist.passkey.heading": "Usa uno smartphone o un tablet",
+ "web_assist.passkey.instruction": "Scansiona questo codice QR con la fotocamera del dispositivo che contiene la tua passkey per {rpId}.",
+ "web_assist.passkey.nearby": "Tieni il telefono vicino con il Bluetooth attivo.",
+ "web_assist.passkey.qr_alt": "Scansiona per usare la tua passkey",
+ "web_assist.passkey.cancel": "Annulla",
+ "web_assist.passkey.preparing": "Preparazione del codice QR…",
+ "web_assist.passkey.scan": "In attesa della scansione…",
+ "web_assist.passkey.connecting": "Connessione al telefono…",
+ "web_assist.passkey.confirm": "Telefono connesso. Conferma sul telefono.",
+ "web_assist.passkey.verifying": "Ritorno al sito web…",
+ "errors.model_context_too_small": "Questo modello richiede una finestra di contesto di almeno {minimum} token. Scegli un modello con una finestra più grande."
}
diff --git a/src/main/locales/ja.json b/src/main/locales/ja.json
index 3d6b818a..98864eef 100644
--- a/src/main/locales/ja.json
+++ b/src/main/locales/ja.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "クラウド同期の競合解決:{count} 件",
"sync.conflict_resolution.message_single": "このクラウド同期の競合を解決してください。",
"sync.conflict_resolution.message_batch": "これらのクラウド同期の競合を解決してください。",
- "quality.operator.incomplete": "カスタム検証が完了しませんでした。ルールファイルを修正するか、設定でカスタム検証を無効にしてから再試行してください。"
+ "quality.operator.incomplete": "カスタム検証が完了しませんでした。ルールファイルを修正するか、設定でカスタム検証を無効にしてから再試行してください。",
+ "model.stopped_tool_limit_summary_incomplete": "ツール実行が上限の {limit} ラウンドに達したため、今回の実行は停止しました。最終要約を完成できませんでした。",
+ "model.stopped_repeat_summary_incomplete": "操作を繰り返しても新たな進展がなかったため、今回の実行は停止しました。最終要約を完成できませんでした。",
+ "model.stopped_summary_incomplete": "今回の実行は停止しました。最終要約を完成できませんでした。",
+ "local_agents.unsupported_effort": "インストールされている Claude Code では、選択した推論レベルを利用できません。Claude Code を更新するか、既定の推論レベルを選択してください。",
+ "model.balance_fallback": "設定した {provider} アカウントの残高が不足しています(Orkas クレジットではありません)。タスクを続行するため代替モデルに切り替えています。チャージすると再び利用できます。",
+ "model.provider_unavailable_fallback": "設定した {provider} は現在利用できません。タスクを続行するため代替モデルに切り替えています。",
+ "cli_agent.parameter_unsupported": "{cli} は選択したパラメーター {parameter} に対応していません。実行設定を変更してください。",
+ "cli_agent.model_unsupported": "{cli} はモデル {model} に対応していません。実行設定を変更してください。",
+ "auto_tasks.catch_up_title": "{title}(遅れて実行)",
+ "web_assist.permission_title": "サイトの権限",
+ "web_assist.permission_request": "{origin} に{permission}の使用を許可しますか?",
+ "web_assist.permission_allow": "許可",
+ "web_assist.permission_deny": "拒否",
+ "web_assist.permission.clipboard": "クリップボード",
+ "web_assist.permission.media": "カメラまたはマイク",
+ "web_assist.permission.location": "位置情報",
+ "web_assist.permission.notifications": "通知",
+ "web_assist.permission.fullscreen": "全画面表示",
+ "web_assist.permission.screen": "画面共有",
+ "web_assist.permission.device": "デバイス",
+ "web_assist.permission.approximate_location": "おおよその位置情報",
+ "web_assist.permission.automatic_fullscreen": "自動全画面表示",
+ "web_assist.permission.usb": "USB デバイス",
+ "web_assist.permission.hid": "入力デバイス",
+ "web_assist.permission.serial": "シリアルデバイス",
+ "web_assist.permission.local_network": "ローカルネットワークへのアクセス",
+ "web_assist.permission.loopback_network": "このコンピューター上のサービス",
+ "web_assist.permission.persistent_storage": "永続的なサイトデータ保存",
+ "web_assist.permission.storage_access": "サードパーティ Cookie",
+ "web_assist.permission.window_management": "画面情報",
+ "web_assist.permission.local_fonts": "ローカルフォント",
+ "web_assist.permission.idle_detection": "操作状況とロック状態",
+ "web_assist.permission.screen_wake_lock": "画面の点灯維持",
+ "web_assist.permission.system_wake_lock": "コンピューターのスリープ防止",
+ "web_assist.permission.pointer_lock": "マウスのキャプチャ",
+ "web_assist.permission.keyboard_lock": "キーボードのキャプチャ",
+ "web_assist.permission.filesystem": "ファイルへのアクセス",
+ "web_assist.permission.protected_media": "保護されたメディアの再生",
+ "web_assist.permission.midi": "MIDI デバイス",
+ "web_assist.permission.midi_sysex": "MIDI システムメッセージ",
+ "web_assist.permission.speaker_selection": "音声出力デバイスの選択",
+ "web_assist.permission.external": "外部アプリの起動",
+ "web_assist.permission.sensors": "デバイスセンサー",
+ "web_assist.permission.background_fetch": "バックグラウンドダウンロード",
+ "web_assist.permission.background_sync": "バックグラウンド同期",
+ "web_assist.permission.surface_control": "共有画面の制御",
+ "web_assist.permission.payment": "支払いの処理",
+ "web_assist.permission.ar": "拡張現実",
+ "web_assist.permission.vr": "仮想現実",
+ "web_assist.permission.hand_tracking": "手のトラッキング",
+ "web_assist.permission.nfc": "NFC デバイス",
+ "web_assist.permission.smart_card": "スマートカードリーダー",
+ "web_assist.permission.installation": "ウェブアプリのインストール",
+ "web_assist.permission.printing": "プリンター",
+ "web_assist.permission.unknown": "「{permission}」権限",
+ "web_assist.permission.other": "この権限",
+ "web_assist.passkey.title": "パスキー",
+ "web_assist.passkey.heading": "スマートフォンまたはタブレットを使用",
+ "web_assist.passkey.instruction": "{rpId} のパスキーが保存されているデバイスのカメラで、この QR コードをスキャンしてください。",
+ "web_assist.passkey.nearby": "Bluetooth をオンにして、スマートフォンを近くに置いてください。",
+ "web_assist.passkey.qr_alt": "スキャンしてパスキーを使用",
+ "web_assist.passkey.cancel": "キャンセル",
+ "web_assist.passkey.preparing": "QR コードを準備しています…",
+ "web_assist.passkey.scan": "スキャンを待っています…",
+ "web_assist.passkey.connecting": "スマートフォンに接続しています…",
+ "web_assist.passkey.confirm": "スマートフォンに接続しました。スマートフォンで確認してください。",
+ "web_assist.passkey.verifying": "ウェブサイトに戻っています…",
+ "errors.model_context_too_small": "このモデルのコンテキストウィンドウは {minimum} トークン以上が必要です。より大きなウィンドウのモデルを選んでください。"
}
diff --git a/src/main/locales/ko.json b/src/main/locales/ko.json
index 6daeb83c..e4e3cf90 100644
--- a/src/main/locales/ko.json
+++ b/src/main/locales/ko.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "클라우드 동기화 충돌 해결: {count}건",
"sync.conflict_resolution.message_single": "이 클라우드 동기화 충돌을 해결해 주세요.",
"sync.conflict_resolution.message_batch": "이 클라우드 동기화 충돌들을 해결해 주세요.",
- "quality.operator.incomplete": "사용자 지정 검증이 완료되지 않았습니다. 규칙 파일을 수정하거나 설정에서 사용자 지정 검증을 끈 후 다시 시도하세요."
+ "quality.operator.incomplete": "사용자 지정 검증이 완료되지 않았습니다. 규칙 파일을 수정하거나 설정에서 사용자 지정 검증을 끈 후 다시 시도하세요.",
+ "model.stopped_tool_limit_summary_incomplete": "도구 실행이 {limit}라운드 제한에 도달하여 이번 실행이 중지되었습니다. 최종 요약을 완성하지 못했습니다.",
+ "model.stopped_repeat_summary_incomplete": "반복 작업에서 새로운 진전이 없어 이번 실행이 중지되었습니다. 최종 요약을 완성하지 못했습니다.",
+ "model.stopped_summary_incomplete": "이번 실행이 중지되었습니다. 최종 요약을 완성하지 못했습니다.",
+ "local_agents.unsupported_effort": "설치된 Claude Code에서는 선택한 추론 수준을 사용할 수 없습니다. Claude Code를 업데이트하거나 기본 추론 수준을 선택하세요.",
+ "model.balance_fallback": "{provider} 계정의 잔액이 부족합니다(Orkas 크레딧이 아닙니다). 작업을 계속할 수 있도록 대체 모델로 전환합니다. 해당 계정을 충전하면 다시 사용할 수 있습니다.",
+ "model.provider_unavailable_fallback": "설정한 {provider} 모델을 지금 사용할 수 없습니다. 작업을 계속할 수 있도록 대체 모델로 전환합니다.",
+ "cli_agent.parameter_unsupported": "{cli}는 선택한 매개변수 {parameter}을 지원하지 않습니다. 실행 설정을 변경하세요.",
+ "cli_agent.model_unsupported": "{cli}는 {model} 모델을 지원하지 않습니다. 실행 설정을 변경하세요.",
+ "auto_tasks.catch_up_title": "{title} (늦은 실행)",
+ "web_assist.permission_title": "웹사이트 권한",
+ "web_assist.permission_request": "{origin}에서 {permission} 사용을 허용할까요?",
+ "web_assist.permission_allow": "허용",
+ "web_assist.permission_deny": "거부",
+ "web_assist.permission.clipboard": "클립보드",
+ "web_assist.permission.media": "카메라 또는 마이크",
+ "web_assist.permission.location": "위치",
+ "web_assist.permission.notifications": "알림",
+ "web_assist.permission.fullscreen": "전체 화면",
+ "web_assist.permission.screen": "화면 공유",
+ "web_assist.permission.device": "기기",
+ "web_assist.permission.approximate_location": "대략적인 위치",
+ "web_assist.permission.automatic_fullscreen": "자동 전체 화면",
+ "web_assist.permission.usb": "USB 기기",
+ "web_assist.permission.hid": "입력 기기",
+ "web_assist.permission.serial": "직렬 기기",
+ "web_assist.permission.local_network": "로컬 네트워크 접근",
+ "web_assist.permission.loopback_network": "이 컴퓨터의 서비스",
+ "web_assist.permission.persistent_storage": "영구 웹사이트 저장소",
+ "web_assist.permission.storage_access": "타사 쿠키",
+ "web_assist.permission.window_management": "화면 정보",
+ "web_assist.permission.local_fonts": "로컬 글꼴",
+ "web_assist.permission.idle_detection": "활동 및 잠금 상태",
+ "web_assist.permission.screen_wake_lock": "화면 켜짐 유지",
+ "web_assist.permission.system_wake_lock": "컴퓨터 절전 방지",
+ "web_assist.permission.pointer_lock": "마우스 캡처",
+ "web_assist.permission.keyboard_lock": "키보드 캡처",
+ "web_assist.permission.filesystem": "파일 접근",
+ "web_assist.permission.protected_media": "보호된 미디어 재생",
+ "web_assist.permission.midi": "MIDI 기기",
+ "web_assist.permission.midi_sysex": "MIDI 시스템 메시지",
+ "web_assist.permission.speaker_selection": "오디오 출력 선택",
+ "web_assist.permission.external": "외부 앱 열기",
+ "web_assist.permission.sensors": "기기 센서",
+ "web_assist.permission.background_fetch": "백그라운드 다운로드",
+ "web_assist.permission.background_sync": "백그라운드 동기화",
+ "web_assist.permission.surface_control": "공유 화면 제어",
+ "web_assist.permission.payment": "결제 처리",
+ "web_assist.permission.ar": "증강 현실",
+ "web_assist.permission.vr": "가상 현실",
+ "web_assist.permission.hand_tracking": "손 추적",
+ "web_assist.permission.nfc": "NFC 기기",
+ "web_assist.permission.smart_card": "스마트 카드 리더",
+ "web_assist.permission.installation": "웹 앱 설치",
+ "web_assist.permission.printing": "프린터",
+ "web_assist.permission.unknown": "“{permission}” 권한",
+ "web_assist.permission.other": "이 권한",
+ "web_assist.passkey.title": "패스키",
+ "web_assist.passkey.heading": "휴대전화 또는 태블릿 사용",
+ "web_assist.passkey.instruction": "{rpId}의 패스키가 저장된 기기의 카메라로 이 QR 코드를 스캔하세요.",
+ "web_assist.passkey.nearby": "블루투스를 켜고 휴대전화를 가까이 두세요.",
+ "web_assist.passkey.qr_alt": "스캔하여 패스키 사용",
+ "web_assist.passkey.cancel": "취소",
+ "web_assist.passkey.preparing": "QR 코드를 준비하는 중…",
+ "web_assist.passkey.scan": "스캔을 기다리는 중…",
+ "web_assist.passkey.connecting": "휴대전화에 연결하는 중…",
+ "web_assist.passkey.confirm": "휴대전화가 연결되었습니다. 휴대전화에서 확인하세요.",
+ "web_assist.passkey.verifying": "웹사이트로 돌아가는 중…",
+ "errors.model_context_too_small": "이 모델의 컨텍스트 창은 최소 {minimum} 토큰이어야 합니다. 더 큰 컨텍스트 창을 가진 모델을 선택하세요."
}
diff --git a/src/main/locales/pt-pt.json b/src/main/locales/pt-pt.json
index 84aa10e0..2e2a089c 100644
--- a/src/main/locales/pt-pt.json
+++ b/src/main/locales/pt-pt.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Resolver conflitos de sincronização na nuvem: {count} conflitos",
"sync.conflict_resolution.message_single": "Ajude-me a resolver este conflito de sincronização na nuvem.",
"sync.conflict_resolution.message_batch": "Ajude-me a resolver estes conflitos de sincronização na nuvem.",
- "quality.operator.incomplete": "A validação personalizada não foi concluída. Corrija o ficheiro de regras ou desative a validação personalizada nas Definições e tente novamente."
+ "quality.operator.incomplete": "A validação personalizada não foi concluída. Corrija o ficheiro de regras ou desative a validação personalizada nas Definições e tente novamente.",
+ "model.stopped_tool_limit_summary_incomplete": "Esta execução foi interrompida ao atingir o limite de {limit} rondas de ferramentas. Não foi possível concluir o resumo final.",
+ "model.stopped_repeat_summary_incomplete": "Esta execução foi interrompida porque as operações repetidas não produziram novos avanços. Não foi possível concluir o resumo final.",
+ "model.stopped_summary_incomplete": "Esta execução foi interrompida. Não foi possível concluir o resumo final.",
+ "local_agents.unsupported_effort": "O nível de raciocínio selecionado não está disponível nesta instalação do Claude Code. Atualize o Claude Code ou selecione o nível predefinido.",
+ "model.balance_fallback": "A sua conta {provider} está sem saldo (não se trata de créditos Orkas). A mudar para um modelo alternativo para que a tarefa continue; carregue o saldo dessa conta para a voltar a usar.",
+ "model.provider_unavailable_fallback": "O seu modelo {provider} está indisponível neste momento. A mudar para um modelo alternativo para que a tarefa continue.",
+ "cli_agent.parameter_unsupported": "{cli} não suporta o parâmetro selecionado {parameter}. Altere as definições de execução.",
+ "cli_agent.model_unsupported": "{cli} não suporta o modelo {model}. Altere as definições de execução.",
+ "auto_tasks.catch_up_title": "{title} (execução recuperada)",
+ "web_assist.permission_title": "Permissão do site",
+ "web_assist.permission_request": "Permitir que {origin} use {permission}?",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Recusar",
+ "web_assist.permission.clipboard": "a área de transferência",
+ "web_assist.permission.media": "a câmara ou o microfone",
+ "web_assist.permission.location": "a sua localização",
+ "web_assist.permission.notifications": "notificações",
+ "web_assist.permission.fullscreen": "ecrã inteiro",
+ "web_assist.permission.screen": "partilha do ecrã",
+ "web_assist.permission.device": "um dispositivo",
+ "web_assist.permission.approximate_location": "a localização aproximada",
+ "web_assist.permission.automatic_fullscreen": "ecrã cheia automática",
+ "web_assist.permission.usb": "dispositivos USB",
+ "web_assist.permission.hid": "dispositivos de entrada",
+ "web_assist.permission.serial": "dispositivos série",
+ "web_assist.permission.local_network": "a rede local",
+ "web_assist.permission.loopback_network": "serviços deste computador",
+ "web_assist.permission.persistent_storage": "armazenamento persistente do site",
+ "web_assist.permission.storage_access": "cookies de terceiros",
+ "web_assist.permission.window_management": "informações das ecrãs",
+ "web_assist.permission.local_fonts": "fontes locais",
+ "web_assist.permission.idle_detection": "o estado de atividade e bloqueio",
+ "web_assist.permission.screen_wake_lock": "manter a ecrã ligada",
+ "web_assist.permission.system_wake_lock": "impedir a suspensão do computador",
+ "web_assist.permission.pointer_lock": "captura do rato",
+ "web_assist.permission.keyboard_lock": "captura do teclado",
+ "web_assist.permission.filesystem": "acesso a ficheiros",
+ "web_assist.permission.protected_media": "reprodução de conteúdo protegido",
+ "web_assist.permission.midi": "dispositivos MIDI",
+ "web_assist.permission.midi_sysex": "mensagens de sistema MIDI",
+ "web_assist.permission.speaker_selection": "seleção da saída de áudio",
+ "web_assist.permission.external": "abertura de aplicações externos",
+ "web_assist.permission.sensors": "sensores do dispositivo",
+ "web_assist.permission.background_fetch": "downloads em segundo plano",
+ "web_assist.permission.background_sync": "sincronização em segundo plano",
+ "web_assist.permission.surface_control": "controlo do conteúdo partilhado",
+ "web_assist.permission.payment": "processamento de pagamentos",
+ "web_assist.permission.ar": "realidade aumentada",
+ "web_assist.permission.vr": "realidade virtual",
+ "web_assist.permission.hand_tracking": "rastreio de mãos",
+ "web_assist.permission.nfc": "dispositivos NFC",
+ "web_assist.permission.smart_card": "leitores de cartões inteligentes",
+ "web_assist.permission.installation": "instalação de aplicações web",
+ "web_assist.permission.printing": "impressoras",
+ "web_assist.permission.unknown": "a permissão “{permission}”",
+ "web_assist.permission.other": "esta permissão",
+ "web_assist.passkey.title": "Chave de acesso",
+ "web_assist.passkey.heading": "Utilizar um telemóvel ou tablet",
+ "web_assist.passkey.instruction": "Leia este código QR com a câmara do dispositivo que tem a sua chave de acesso para {rpId}.",
+ "web_assist.passkey.nearby": "Mantenha o telemóvel por perto, com o Bluetooth ativado.",
+ "web_assist.passkey.qr_alt": "Leia o código para utilizar a sua chave de acesso",
+ "web_assist.passkey.cancel": "Cancelar",
+ "web_assist.passkey.preparing": "A preparar o código QR…",
+ "web_assist.passkey.scan": "A aguardar a leitura…",
+ "web_assist.passkey.connecting": "A ligar ao seu telemóvel…",
+ "web_assist.passkey.confirm": "Telemóvel ligado. Confirme no seu telemóvel.",
+ "web_assist.passkey.verifying": "A regressar ao site…",
+ "errors.model_context_too_small": "Este modelo requer uma janela de contexto de pelo menos {minimum} tokens. Escolha um modelo com uma janela maior."
}
diff --git a/src/main/locales/pt.json b/src/main/locales/pt.json
index 92147ef9..56f480fa 100644
--- a/src/main/locales/pt.json
+++ b/src/main/locales/pt.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Resolver conflitos de sincronização na nuvem: {count}",
"sync.conflict_resolution.message_single": "Ajude-me a resolver este conflito de sincronização na nuvem.",
"sync.conflict_resolution.message_batch": "Ajude-me a resolver estes conflitos de sincronização na nuvem.",
- "quality.operator.incomplete": "A validação personalizada não foi concluída. Corrija o arquivo de regras ou desative a validação personalizada nas Configurações e tente novamente."
+ "quality.operator.incomplete": "A validação personalizada não foi concluída. Corrija o arquivo de regras ou desative a validação personalizada nas Configurações e tente novamente.",
+ "model.stopped_tool_limit_summary_incomplete": "Esta execução foi interrompida ao atingir o limite de {limit} rodadas de ferramentas. Não foi possível concluir o resumo final.",
+ "model.stopped_repeat_summary_incomplete": "Esta execução foi interrompida porque as operações repetidas não produziram novos avanços. Não foi possível concluir o resumo final.",
+ "model.stopped_summary_incomplete": "Esta execução foi interrompida. Não foi possível concluir o resumo final.",
+ "local_agents.unsupported_effort": "O nível de raciocínio selecionado não está disponível nesta instalação do Claude Code. Atualize o Claude Code ou selecione o nível padrão.",
+ "model.balance_fallback": "Sua conta {provider} está sem saldo (não são créditos Orkas). Alternando para um modelo de fallback para que a tarefa continue; recarregue essa conta para usá-la novamente.",
+ "model.provider_unavailable_fallback": "Seu modelo {provider} está indisponível no momento. Alternando para um modelo de fallback para que a tarefa continue.",
+ "cli_agent.parameter_unsupported": "{cli} não aceita o parâmetro selecionado {parameter}. Altere as configurações de execução.",
+ "cli_agent.model_unsupported": "{cli} não aceita o modelo {model}. Altere as configurações de execução.",
+ "auto_tasks.catch_up_title": "{title} (execução recuperada)",
+ "web_assist.permission_title": "Permissão do site",
+ "web_assist.permission_request": "Permitir que {origin} use {permission}?",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Negar",
+ "web_assist.permission.clipboard": "a área de transferência",
+ "web_assist.permission.media": "a câmera ou o microfone",
+ "web_assist.permission.location": "sua localização",
+ "web_assist.permission.notifications": "notificações",
+ "web_assist.permission.fullscreen": "tela cheia",
+ "web_assist.permission.screen": "compartilhamento de tela",
+ "web_assist.permission.device": "um dispositivo",
+ "web_assist.permission.approximate_location": "a localização aproximada",
+ "web_assist.permission.automatic_fullscreen": "tela cheia automática",
+ "web_assist.permission.usb": "dispositivos USB",
+ "web_assist.permission.hid": "dispositivos de entrada",
+ "web_assist.permission.serial": "dispositivos seriais",
+ "web_assist.permission.local_network": "a rede local",
+ "web_assist.permission.loopback_network": "serviços deste computador",
+ "web_assist.permission.persistent_storage": "armazenamento persistente do site",
+ "web_assist.permission.storage_access": "cookies de terceiros",
+ "web_assist.permission.window_management": "informações das telas",
+ "web_assist.permission.local_fonts": "fontes locais",
+ "web_assist.permission.idle_detection": "o estado de atividade e bloqueio",
+ "web_assist.permission.screen_wake_lock": "manter a tela ligada",
+ "web_assist.permission.system_wake_lock": "impedir a suspensão do computador",
+ "web_assist.permission.pointer_lock": "captura do mouse",
+ "web_assist.permission.keyboard_lock": "captura do teclado",
+ "web_assist.permission.filesystem": "acesso a arquivos",
+ "web_assist.permission.protected_media": "reprodução de conteúdo protegido",
+ "web_assist.permission.midi": "dispositivos MIDI",
+ "web_assist.permission.midi_sysex": "mensagens de sistema MIDI",
+ "web_assist.permission.speaker_selection": "seleção da saída de áudio",
+ "web_assist.permission.external": "abertura de aplicativos externos",
+ "web_assist.permission.sensors": "sensores do dispositivo",
+ "web_assist.permission.background_fetch": "downloads em segundo plano",
+ "web_assist.permission.background_sync": "sincronização em segundo plano",
+ "web_assist.permission.surface_control": "controle do conteúdo compartilhado",
+ "web_assist.permission.payment": "processamento de pagamentos",
+ "web_assist.permission.ar": "realidade aumentada",
+ "web_assist.permission.vr": "realidade virtual",
+ "web_assist.permission.hand_tracking": "rastreamento de mãos",
+ "web_assist.permission.nfc": "dispositivos NFC",
+ "web_assist.permission.smart_card": "leitores de cartões inteligentes",
+ "web_assist.permission.installation": "instalação de aplicativos web",
+ "web_assist.permission.printing": "impressoras",
+ "web_assist.permission.unknown": "a permissão “{permission}”",
+ "web_assist.permission.other": "esta permissão",
+ "web_assist.passkey.title": "Chave de acesso",
+ "web_assist.passkey.heading": "Usar um celular ou tablet",
+ "web_assist.passkey.instruction": "Escaneie este QR code com a câmera do dispositivo que tem sua chave de acesso para {rpId}.",
+ "web_assist.passkey.nearby": "Mantenha o celular por perto, com o Bluetooth ativado.",
+ "web_assist.passkey.qr_alt": "Escaneie para usar sua chave de acesso",
+ "web_assist.passkey.cancel": "Cancelar",
+ "web_assist.passkey.preparing": "Preparando o QR code…",
+ "web_assist.passkey.scan": "Aguardando o escaneamento…",
+ "web_assist.passkey.connecting": "Conectando ao seu celular…",
+ "web_assist.passkey.confirm": "Celular conectado. Confirme no seu celular.",
+ "web_assist.passkey.verifying": "Voltando ao site…",
+ "errors.model_context_too_small": "Este modelo requer uma janela de contexto de pelo menos {minimum} tokens. Escolha um modelo com uma janela maior."
}
diff --git a/src/main/locales/ru.json b/src/main/locales/ru.json
index 8ea4e020..d8f7697d 100644
--- a/src/main/locales/ru.json
+++ b/src/main/locales/ru.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Разрешение конфликтов облачной синхронизации: {count}",
"sync.conflict_resolution.message_single": "Помогите мне разрешить этот конфликт облачной синхронизации.",
"sync.conflict_resolution.message_batch": "Помогите мне разрешить эти конфликты облачной синхронизации.",
- "quality.operator.incomplete": "Пользовательская проверка не завершена. Исправьте файл правил или отключите пользовательскую проверку в настройках, затем повторите попытку."
+ "quality.operator.incomplete": "Пользовательская проверка не завершена. Исправьте файл правил или отключите пользовательскую проверку в настройках, затем повторите попытку.",
+ "model.stopped_tool_limit_summary_incomplete": "Выполнение остановлено по достижении лимита в {limit} раундов работы с инструментами. Итоговую сводку не удалось завершить.",
+ "model.stopped_repeat_summary_incomplete": "Выполнение остановлено, поскольку повторные операции не дали нового прогресса. Итоговую сводку не удалось завершить.",
+ "model.stopped_summary_incomplete": "Выполнение остановлено. Итоговую сводку не удалось завершить.",
+ "local_agents.unsupported_effort": "Выбранный уровень рассуждения недоступен в установленной версии Claude Code. Обновите Claude Code или выберите уровень по умолчанию.",
+ "model.balance_fallback": "На вашем аккаунте {provider} закончились средства (это не кредиты Orkas). Переключаемся на резервную модель, чтобы продолжить задачу; пополните баланс, чтобы снова им пользоваться.",
+ "model.provider_unavailable_fallback": "Ваша модель {provider} сейчас недоступна. Переключаемся на резервную модель, чтобы продолжить задачу.",
+ "cli_agent.parameter_unsupported": "{cli} не поддерживает выбранный параметр {parameter}. Измените настройки запуска.",
+ "cli_agent.model_unsupported": "{cli} не поддерживает модель {model}. Измените настройки запуска.",
+ "auto_tasks.catch_up_title": "{title} (запуск с опозданием)",
+ "web_assist.permission_title": "Разрешение сайта",
+ "web_assist.permission_request": "Разрешить {origin} использовать {permission}?",
+ "web_assist.permission_allow": "Разрешить",
+ "web_assist.permission_deny": "Запретить",
+ "web_assist.permission.clipboard": "буфер обмена",
+ "web_assist.permission.media": "камеру или микрофон",
+ "web_assist.permission.location": "ваше местоположение",
+ "web_assist.permission.notifications": "уведомления",
+ "web_assist.permission.fullscreen": "полный экран",
+ "web_assist.permission.screen": "демонстрацию экрана",
+ "web_assist.permission.device": "устройство",
+ "web_assist.permission.approximate_location": "приблизительное местоположение",
+ "web_assist.permission.automatic_fullscreen": "автоматический полноэкранный режим",
+ "web_assist.permission.usb": "USB-устройства",
+ "web_assist.permission.hid": "устройства ввода",
+ "web_assist.permission.serial": "последовательные устройства",
+ "web_assist.permission.local_network": "локальную сеть",
+ "web_assist.permission.loopback_network": "сервисы этого компьютера",
+ "web_assist.permission.persistent_storage": "постоянное хранение данных сайта",
+ "web_assist.permission.storage_access": "сторонние файлы cookie",
+ "web_assist.permission.window_management": "информацию об экранах",
+ "web_assist.permission.local_fonts": "локальные шрифты",
+ "web_assist.permission.idle_detection": "состояние активности и блокировки",
+ "web_assist.permission.screen_wake_lock": "поддержание экрана включённым",
+ "web_assist.permission.system_wake_lock": "предотвращение сна компьютера",
+ "web_assist.permission.pointer_lock": "захват мыши",
+ "web_assist.permission.keyboard_lock": "захват клавиатуры",
+ "web_assist.permission.filesystem": "доступ к файлам",
+ "web_assist.permission.protected_media": "воспроизведение защищённого контента",
+ "web_assist.permission.midi": "MIDI-устройства",
+ "web_assist.permission.midi_sysex": "системные сообщения MIDI",
+ "web_assist.permission.speaker_selection": "выбор аудиовыхода",
+ "web_assist.permission.external": "открытие внешних приложений",
+ "web_assist.permission.sensors": "датчики устройства",
+ "web_assist.permission.background_fetch": "фоновые загрузки",
+ "web_assist.permission.background_sync": "фоновую синхронизацию",
+ "web_assist.permission.surface_control": "управление общим содержимым",
+ "web_assist.permission.payment": "обработку платежей",
+ "web_assist.permission.ar": "дополненную реальность",
+ "web_assist.permission.vr": "виртуальную реальность",
+ "web_assist.permission.hand_tracking": "отслеживание рук",
+ "web_assist.permission.nfc": "NFC-устройства",
+ "web_assist.permission.smart_card": "считыватели смарт-карт",
+ "web_assist.permission.installation": "установку веб-приложений",
+ "web_assist.permission.printing": "принтеры",
+ "web_assist.permission.unknown": "разрешение «{permission}»",
+ "web_assist.permission.other": "это разрешение",
+ "web_assist.passkey.title": "Ключ доступа",
+ "web_assist.passkey.heading": "Используйте телефон или планшет",
+ "web_assist.passkey.instruction": "Отсканируйте этот QR-код камерой устройства, на котором хранится ваш ключ доступа для {rpId}.",
+ "web_assist.passkey.nearby": "Держите телефон рядом и не выключайте Bluetooth.",
+ "web_assist.passkey.qr_alt": "Отсканируйте, чтобы использовать ключ доступа",
+ "web_assist.passkey.cancel": "Отмена",
+ "web_assist.passkey.preparing": "Подготовка QR-кода…",
+ "web_assist.passkey.scan": "Ожидание сканирования…",
+ "web_assist.passkey.connecting": "Подключение к телефону…",
+ "web_assist.passkey.confirm": "Телефон подключён. Подтвердите на телефоне.",
+ "web_assist.passkey.verifying": "Возврат на сайт…",
+ "errors.model_context_too_small": "Для этой модели требуется контекстное окно не менее {minimum} токенов. Выберите модель с большим окном."
}
diff --git a/src/main/locales/th.json b/src/main/locales/th.json
index d738503a..5b13d903 100644
--- a/src/main/locales/th.json
+++ b/src/main/locales/th.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "แก้ไขข้อขัดแย้งการซิงค์คลาวด์: {count} รายการ",
"sync.conflict_resolution.message_single": "โปรดช่วยแก้ไขข้อขัดแย้งการซิงค์คลาวด์นี้",
"sync.conflict_resolution.message_batch": "โปรดช่วยแก้ไขข้อขัดแย้งการซิงค์คลาวด์เหล่านี้",
- "quality.operator.incomplete": "การตรวจสอบแบบกำหนดเองยังไม่เสร็จสิ้น แก้ไขไฟล์กฎหรือปิดการตรวจสอบแบบกำหนดเองในการตั้งค่า แล้วลองอีกครั้ง"
+ "quality.operator.incomplete": "การตรวจสอบแบบกำหนดเองยังไม่เสร็จสิ้น แก้ไขไฟล์กฎหรือปิดการตรวจสอบแบบกำหนดเองในการตั้งค่า แล้วลองอีกครั้ง",
+ "model.stopped_tool_limit_summary_incomplete": "การทำงานครั้งนี้หยุดลงเมื่อถึงขีดจำกัดการใช้เครื่องมือ {limit} รอบ ไม่สามารถสร้างสรุปสุดท้ายได้ครบถ้วน",
+ "model.stopped_repeat_summary_incomplete": "การทำงานครั้งนี้หยุดลงเนื่องจากการดำเนินการซ้ำไม่ทำให้เกิดความคืบหน้าใหม่ ไม่สามารถสร้างสรุปสุดท้ายได้ครบถ้วน",
+ "model.stopped_summary_incomplete": "การทำงานครั้งนี้หยุดลง ไม่สามารถสร้างสรุปสุดท้ายได้ครบถ้วน",
+ "local_agents.unsupported_effort": "ไม่สามารถใช้ระดับการให้เหตุผลที่เลือกในการติดตั้ง Claude Code นี้ได้ โปรดอัปเดต Claude Code หรือเลือกระดับการให้เหตุผลเริ่มต้น",
+ "model.balance_fallback": "ยอดเงินในบัญชี {provider} ของคุณหมดแล้ว (ไม่ใช่เครดิต Orkas) กำลังเปลี่ยนไปใช้โมเดลสำรองเพื่อให้งานดำเนินต่อได้ เติมเงินบัญชีนั้นเพื่อใช้งานอีกครั้ง",
+ "model.provider_unavailable_fallback": "โมเดล {provider} ที่คุณตั้งค่าไว้ใช้งานไม่ได้ในขณะนี้ กำลังเปลี่ยนไปใช้โมเดลสำรองเพื่อให้งานดำเนินต่อได้",
+ "cli_agent.parameter_unsupported": "{cli} ไม่รองรับพารามิเตอร์ที่เลือก {parameter} โปรดเปลี่ยนการตั้งค่าการทำงาน",
+ "cli_agent.model_unsupported": "{cli} ไม่รองรับโมเดล {model} โปรดเปลี่ยนการตั้งค่าการทำงาน",
+ "auto_tasks.catch_up_title": "{title} (ทำงานย้อนหลัง)",
+ "web_assist.permission_title": "สิทธิ์เว็บไซต์",
+ "web_assist.permission_request": "อนุญาตให้ {origin} ใช้{permission}ไหม?",
+ "web_assist.permission_allow": "อนุญาต",
+ "web_assist.permission_deny": "ปฏิเสธ",
+ "web_assist.permission.clipboard": "คลิปบอร์ด",
+ "web_assist.permission.media": "กล้องหรือไมโครโฟน",
+ "web_assist.permission.location": "ตำแหน่งของคุณ",
+ "web_assist.permission.notifications": "การแจ้งเตือน",
+ "web_assist.permission.fullscreen": "เต็มหน้าจอ",
+ "web_assist.permission.screen": "การแชร์หน้าจอ",
+ "web_assist.permission.device": "อุปกรณ์",
+ "web_assist.permission.approximate_location": "ตำแหน่งโดยประมาณ",
+ "web_assist.permission.automatic_fullscreen": "โหมดเต็มหน้าจออัตโนมัติ",
+ "web_assist.permission.usb": "อุปกรณ์ USB",
+ "web_assist.permission.hid": "อุปกรณ์ป้อนข้อมูล",
+ "web_assist.permission.serial": "อุปกรณ์พอร์ตอนุกรม",
+ "web_assist.permission.local_network": "เครือข่ายภายใน",
+ "web_assist.permission.loopback_network": "บริการบนคอมพิวเตอร์นี้",
+ "web_assist.permission.persistent_storage": "พื้นที่จัดเก็บเว็บไซต์ถาวร",
+ "web_assist.permission.storage_access": "คุกกี้ของบุคคลที่สาม",
+ "web_assist.permission.window_management": "ข้อมูลหน้าจอ",
+ "web_assist.permission.local_fonts": "แบบอักษรในเครื่อง",
+ "web_assist.permission.idle_detection": "สถานะการใช้งานและการล็อก",
+ "web_assist.permission.screen_wake_lock": "การเปิดหน้าจอค้างไว้",
+ "web_assist.permission.system_wake_lock": "การป้องกันคอมพิวเตอร์พัก",
+ "web_assist.permission.pointer_lock": "การจับเมาส์",
+ "web_assist.permission.keyboard_lock": "การจับแป้นพิมพ์",
+ "web_assist.permission.filesystem": "การเข้าถึงไฟล์",
+ "web_assist.permission.protected_media": "การเล่นสื่อที่ได้รับการป้องกัน",
+ "web_assist.permission.midi": "อุปกรณ์ MIDI",
+ "web_assist.permission.midi_sysex": "ข้อความระบบ MIDI",
+ "web_assist.permission.speaker_selection": "การเลือกเอาต์พุตเสียง",
+ "web_assist.permission.external": "การเปิดแอปภายนอก",
+ "web_assist.permission.sensors": "เซ็นเซอร์อุปกรณ์",
+ "web_assist.permission.background_fetch": "การดาวน์โหลดเบื้องหลัง",
+ "web_assist.permission.background_sync": "การซิงค์เบื้องหลัง",
+ "web_assist.permission.surface_control": "การควบคุมเนื้อหาที่แชร์",
+ "web_assist.permission.payment": "การประมวลผลการชำระเงิน",
+ "web_assist.permission.ar": "ความเป็นจริงเสริม",
+ "web_assist.permission.vr": "ความเป็นจริงเสมือน",
+ "web_assist.permission.hand_tracking": "การติดตามมือ",
+ "web_assist.permission.nfc": "อุปกรณ์ NFC",
+ "web_assist.permission.smart_card": "เครื่องอ่านสมาร์ทการ์ด",
+ "web_assist.permission.installation": "การติดตั้งเว็บแอป",
+ "web_assist.permission.printing": "เครื่องพิมพ์",
+ "web_assist.permission.unknown": "สิทธิ์ “{permission}”",
+ "web_assist.permission.other": "สิทธิ์นี้",
+ "web_assist.passkey.title": "พาสคีย์",
+ "web_assist.passkey.heading": "ใช้โทรศัพท์หรือแท็บเล็ต",
+ "web_assist.passkey.instruction": "สแกนคิวอาร์โค้ดนี้ด้วยกล้องของอุปกรณ์ที่มีพาสคีย์ของคุณสำหรับ {rpId}",
+ "web_assist.passkey.nearby": "วางโทรศัพท์ไว้ใกล้ๆ และเปิดบลูทูธไว้",
+ "web_assist.passkey.qr_alt": "สแกนเพื่อใช้พาสคีย์",
+ "web_assist.passkey.cancel": "ยกเลิก",
+ "web_assist.passkey.preparing": "กำลังเตรียมคิวอาร์โค้ด…",
+ "web_assist.passkey.scan": "กำลังรอการสแกน…",
+ "web_assist.passkey.connecting": "กำลังเชื่อมต่อกับโทรศัพท์…",
+ "web_assist.passkey.confirm": "เชื่อมต่อโทรศัพท์แล้ว โปรดยืนยันบนโทรศัพท์",
+ "web_assist.passkey.verifying": "กำลังกลับไปยังเว็บไซต์…",
+ "errors.model_context_too_small": "โมเดลนี้ต้องมีหน้าต่างบริบทอย่างน้อย {minimum} โทเค็น โปรดเลือกโมเดลที่มีหน้าต่างบริบทใหญ่กว่า"
}
diff --git a/src/main/locales/tr.json b/src/main/locales/tr.json
index 6ea119de..ee8052f9 100644
--- a/src/main/locales/tr.json
+++ b/src/main/locales/tr.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Bulut eşitleme çakışmalarını çözme: {count} çakışma",
"sync.conflict_resolution.message_single": "Bu bulut eşitleme çakışmasını çözmeme yardım et.",
"sync.conflict_resolution.message_batch": "Bu bulut eşitleme çakışmalarını çözmeme yardım et.",
- "quality.operator.incomplete": "Özel doğrulama tamamlanamadı. Kural dosyasını düzeltin veya Ayarlar’dan özel doğrulamayı kapatıp yeniden deneyin."
+ "quality.operator.incomplete": "Özel doğrulama tamamlanamadı. Kural dosyasını düzeltin veya Ayarlar’dan özel doğrulamayı kapatıp yeniden deneyin.",
+ "model.stopped_tool_limit_summary_incomplete": "Bu çalıştırma, {limit} araç turu sınırına ulaşıldığı için durduruldu. Son özet tamamlanamadı.",
+ "model.stopped_repeat_summary_incomplete": "Tekrarlanan işlemler yeni bir ilerleme sağlamadığı için bu çalıştırma durduruldu. Son özet tamamlanamadı.",
+ "model.stopped_summary_incomplete": "Bu çalıştırma durduruldu. Son özet tamamlanamadı.",
+ "local_agents.unsupported_effort": "Seçilen akıl yürütme düzeyi bu Claude Code kurulumunda kullanılamıyor. Claude Code’u güncelleyin veya varsayılan düzeyi seçin.",
+ "model.balance_fallback": "{provider} hesabınızın bakiyesi tükendi (Orkas kredisi değil). Görevin devam edebilmesi için yedek modele geçiliyor; yeniden kullanmak için bu hesaba bakiye yükleyin.",
+ "model.provider_unavailable_fallback": "{provider} modeliniz şu anda kullanılamıyor. Görevin devam edebilmesi için yedek modele geçiliyor.",
+ "cli_agent.parameter_unsupported": "{cli}, seçilen {parameter} parametresini desteklemiyor. Çalıştırma ayarlarını değiştirin.",
+ "cli_agent.model_unsupported": "{cli}, {model} modelini desteklemiyor. Çalıştırma ayarlarını değiştirin.",
+ "auto_tasks.catch_up_title": "{title} (telafi çalıştırması)",
+ "web_assist.permission_title": "Site izni",
+ "web_assist.permission_request": "{origin}, {permission} kullanabilsin mi?",
+ "web_assist.permission_allow": "İzin ver",
+ "web_assist.permission_deny": "Reddet",
+ "web_assist.permission.clipboard": "panoyu",
+ "web_assist.permission.media": "kamera veya mikrofonu",
+ "web_assist.permission.location": "konumunuzu",
+ "web_assist.permission.notifications": "bildirimleri",
+ "web_assist.permission.fullscreen": "tam ekranı",
+ "web_assist.permission.screen": "ekran paylaşımını",
+ "web_assist.permission.device": "bir cihazı",
+ "web_assist.permission.approximate_location": "yaklaşık konum",
+ "web_assist.permission.automatic_fullscreen": "otomatik tam ekran",
+ "web_assist.permission.usb": "USB cihazları",
+ "web_assist.permission.hid": "giriş cihazları",
+ "web_assist.permission.serial": "seri cihazlar",
+ "web_assist.permission.local_network": "yerel ağ",
+ "web_assist.permission.loopback_network": "bu bilgisayardaki hizmetler",
+ "web_assist.permission.persistent_storage": "kalıcı site depolaması",
+ "web_assist.permission.storage_access": "üçüncü taraf çerezleri",
+ "web_assist.permission.window_management": "ekran bilgileri",
+ "web_assist.permission.local_fonts": "yerel yazı tipleri",
+ "web_assist.permission.idle_detection": "etkinlik ve kilit durumu",
+ "web_assist.permission.screen_wake_lock": "ekranı açık tutma",
+ "web_assist.permission.system_wake_lock": "bilgisayarı uyanık tutma",
+ "web_assist.permission.pointer_lock": "fare yakalama",
+ "web_assist.permission.keyboard_lock": "klavye yakalama",
+ "web_assist.permission.filesystem": "dosya erişimi",
+ "web_assist.permission.protected_media": "korumalı medya oynatma",
+ "web_assist.permission.midi": "MIDI cihazları",
+ "web_assist.permission.midi_sysex": "MIDI sistem mesajları",
+ "web_assist.permission.speaker_selection": "ses çıkışı seçimi",
+ "web_assist.permission.external": "harici uygulamaları açma",
+ "web_assist.permission.sensors": "cihaz sensörleri",
+ "web_assist.permission.background_fetch": "arka plan indirmeleri",
+ "web_assist.permission.background_sync": "arka plan eşitlemesi",
+ "web_assist.permission.surface_control": "paylaşılan içerik denetimi",
+ "web_assist.permission.payment": "ödeme işleme",
+ "web_assist.permission.ar": "artırılmış gerçeklik",
+ "web_assist.permission.vr": "sanal gerçeklik",
+ "web_assist.permission.hand_tracking": "el takibi",
+ "web_assist.permission.nfc": "NFC cihazları",
+ "web_assist.permission.smart_card": "akıllı kart okuyucuları",
+ "web_assist.permission.installation": "web uygulaması kurulumu",
+ "web_assist.permission.printing": "yazıcılar",
+ "web_assist.permission.unknown": "“{permission}” izni",
+ "web_assist.permission.other": "bu izni",
+ "web_assist.passkey.title": "Geçiş anahtarı",
+ "web_assist.passkey.heading": "Telefon veya tablet kullanın",
+ "web_assist.passkey.instruction": "{rpId} için geçiş anahtarınızın bulunduğu cihazın kamerasıyla bu QR kodunu tarayın.",
+ "web_assist.passkey.nearby": "Telefonunuzu yakında tutun ve Bluetooth'u açık bırakın.",
+ "web_assist.passkey.qr_alt": "Geçiş anahtarınızı kullanmak için tarayın",
+ "web_assist.passkey.cancel": "İptal",
+ "web_assist.passkey.preparing": "QR kodu hazırlanıyor…",
+ "web_assist.passkey.scan": "Taramanız bekleniyor…",
+ "web_assist.passkey.connecting": "Telefonunuza bağlanılıyor…",
+ "web_assist.passkey.confirm": "Telefon bağlandı. Telefonunuzda onaylayın.",
+ "web_assist.passkey.verifying": "Web sitesine dönülüyor…",
+ "errors.model_context_too_small": "Bu model en az {minimum} tokenlik bağlam penceresi gerektirir. Daha büyük pencereli bir model seçin."
}
diff --git a/src/main/locales/vi.json b/src/main/locales/vi.json
index 53d4a01d..3850d055 100644
--- a/src/main/locales/vi.json
+++ b/src/main/locales/vi.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "Giải quyết xung đột đồng bộ đám mây: {count} xung đột",
"sync.conflict_resolution.message_single": "Vui lòng giúp tôi giải quyết xung đột đồng bộ đám mây này.",
"sync.conflict_resolution.message_batch": "Vui lòng giúp tôi giải quyết các xung đột đồng bộ đám mây này.",
- "quality.operator.incomplete": "Kiểm tra tùy chỉnh chưa hoàn tất. Sửa tệp quy tắc hoặc tắt kiểm tra tùy chỉnh trong Cài đặt rồi thử lại."
+ "quality.operator.incomplete": "Kiểm tra tùy chỉnh chưa hoàn tất. Sửa tệp quy tắc hoặc tắt kiểm tra tùy chỉnh trong Cài đặt rồi thử lại.",
+ "model.stopped_tool_limit_summary_incomplete": "Lượt chạy này đã dừng khi đạt giới hạn {limit} vòng sử dụng công cụ. Không thể hoàn tất bản tóm tắt cuối cùng.",
+ "model.stopped_repeat_summary_incomplete": "Lượt chạy này đã dừng vì các thao tác lặp lại không tạo ra tiến triển mới. Không thể hoàn tất bản tóm tắt cuối cùng.",
+ "model.stopped_summary_incomplete": "Lượt chạy này đã dừng. Không thể hoàn tất bản tóm tắt cuối cùng.",
+ "local_agents.unsupported_effort": "Mức suy luận đã chọn không khả dụng trong bản Claude Code này. Hãy cập nhật Claude Code hoặc chọn mức suy luận mặc định.",
+ "model.balance_fallback": "Tài khoản {provider} của bạn đã hết số dư (không phải tín dụng Orkas). Đang chuyển sang mô hình dự phòng để tác vụ có thể tiếp tục; hãy nạp tiền vào tài khoản đó để dùng lại.",
+ "model.provider_unavailable_fallback": "Mô hình {provider} của bạn hiện không dùng được. Đang chuyển sang mô hình dự phòng để tác vụ có thể tiếp tục.",
+ "cli_agent.parameter_unsupported": "{cli} không hỗ trợ tham số đã chọn {parameter}. Hãy đổi cài đặt chạy.",
+ "cli_agent.model_unsupported": "{cli} không hỗ trợ mô hình {model}. Hãy đổi cài đặt chạy.",
+ "auto_tasks.catch_up_title": "{title} (chạy bù)",
+ "web_assist.permission_title": "Quyền của trang web",
+ "web_assist.permission_request": "Cho phép {origin} sử dụng {permission}?",
+ "web_assist.permission_allow": "Cho phép",
+ "web_assist.permission_deny": "Từ chối",
+ "web_assist.permission.clipboard": "bảng nhớ tạm",
+ "web_assist.permission.media": "máy ảnh hoặc micrô",
+ "web_assist.permission.location": "vị trí của bạn",
+ "web_assist.permission.notifications": "thông báo",
+ "web_assist.permission.fullscreen": "toàn màn hình",
+ "web_assist.permission.screen": "chia sẻ màn hình",
+ "web_assist.permission.device": "thiết bị",
+ "web_assist.permission.approximate_location": "vị trí gần đúng",
+ "web_assist.permission.automatic_fullscreen": "toàn màn hình tự động",
+ "web_assist.permission.usb": "thiết bị USB",
+ "web_assist.permission.hid": "thiết bị đầu vào",
+ "web_assist.permission.serial": "thiết bị cổng nối tiếp",
+ "web_assist.permission.local_network": "mạng nội bộ",
+ "web_assist.permission.loopback_network": "dịch vụ trên máy tính này",
+ "web_assist.permission.persistent_storage": "lưu trữ dữ liệu trang web lâu dài",
+ "web_assist.permission.storage_access": "cookie bên thứ ba",
+ "web_assist.permission.window_management": "thông tin màn hình",
+ "web_assist.permission.local_fonts": "phông chữ cục bộ",
+ "web_assist.permission.idle_detection": "trạng thái hoạt động và khóa",
+ "web_assist.permission.screen_wake_lock": "giữ màn hình bật",
+ "web_assist.permission.system_wake_lock": "ngăn máy tính ngủ",
+ "web_assist.permission.pointer_lock": "điều khiển chuột",
+ "web_assist.permission.keyboard_lock": "điều khiển bàn phím",
+ "web_assist.permission.filesystem": "truy cập tệp",
+ "web_assist.permission.protected_media": "phát nội dung được bảo vệ",
+ "web_assist.permission.midi": "thiết bị MIDI",
+ "web_assist.permission.midi_sysex": "thông điệp hệ thống MIDI",
+ "web_assist.permission.speaker_selection": "chọn đầu ra âm thanh",
+ "web_assist.permission.external": "mở ứng dụng bên ngoài",
+ "web_assist.permission.sensors": "cảm biến thiết bị",
+ "web_assist.permission.background_fetch": "tải xuống trong nền",
+ "web_assist.permission.background_sync": "đồng bộ trong nền",
+ "web_assist.permission.surface_control": "điều khiển nội dung được chia sẻ",
+ "web_assist.permission.payment": "xử lý thanh toán",
+ "web_assist.permission.ar": "thực tế tăng cường",
+ "web_assist.permission.vr": "thực tế ảo",
+ "web_assist.permission.hand_tracking": "theo dõi bàn tay",
+ "web_assist.permission.nfc": "thiết bị NFC",
+ "web_assist.permission.smart_card": "đầu đọc thẻ thông minh",
+ "web_assist.permission.installation": "cài đặt ứng dụng web",
+ "web_assist.permission.printing": "máy in",
+ "web_assist.permission.unknown": "quyền “{permission}”",
+ "web_assist.permission.other": "quyền này",
+ "web_assist.passkey.title": "Khóa truy cập",
+ "web_assist.passkey.heading": "Dùng điện thoại hoặc máy tính bảng",
+ "web_assist.passkey.instruction": "Quét mã QR này bằng camera của thiết bị có khóa truy cập của bạn cho {rpId}.",
+ "web_assist.passkey.nearby": "Để điện thoại ở gần và bật Bluetooth.",
+ "web_assist.passkey.qr_alt": "Quét để dùng khóa truy cập",
+ "web_assist.passkey.cancel": "Hủy",
+ "web_assist.passkey.preparing": "Đang chuẩn bị mã QR…",
+ "web_assist.passkey.scan": "Đang chờ bạn quét…",
+ "web_assist.passkey.connecting": "Đang kết nối với điện thoại…",
+ "web_assist.passkey.confirm": "Đã kết nối điện thoại. Hãy xác nhận trên điện thoại.",
+ "web_assist.passkey.verifying": "Đang quay lại trang web…",
+ "errors.model_context_too_small": "Mô hình này cần cửa sổ ngữ cảnh ít nhất {minimum} token. Hãy chọn mô hình có cửa sổ lớn hơn."
}
diff --git a/src/main/locales/zh-tw.json b/src/main/locales/zh-tw.json
index 3337e0a2..eb2e98da 100644
--- a/src/main/locales/zh-tw.json
+++ b/src/main/locales/zh-tw.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "雲端同步衝突處理:{count} 條衝突",
"sync.conflict_resolution.message_single": "請幫我處理這條雲端同步衝突。",
"sync.conflict_resolution.message_batch": "請幫我處理這些雲端同步衝突。",
- "quality.operator.incomplete": "自訂驗證未完成。請修正規則檔案,或在設定中停用自訂驗證後重試。"
+ "quality.operator.incomplete": "自訂驗證未完成。請修正規則檔案,或在設定中停用自訂驗證後重試。",
+ "model.stopped_tool_limit_summary_incomplete": "本輪已達到 {limit} 輪工具執行上限,任務已停止。收尾總結未能完整產生。",
+ "model.stopped_repeat_summary_incomplete": "本輪因重複操作未產生新進展而停止。收尾總結未能完整產生。",
+ "model.stopped_summary_incomplete": "本輪任務已停止。收尾總結未能完整產生。",
+ "local_agents.unsupported_effort": "目前安裝的 Claude Code 無法使用所選推理強度。請升級 Claude Code,或選擇預設推理強度。",
+ "model.balance_fallback": "你設定的 {provider} 帳戶餘額不足(這不是 Orkas 點數),正在切換到備用模型繼續執行;為該帳戶儲值後即可恢復使用。",
+ "model.provider_unavailable_fallback": "你設定的 {provider} 目前無法使用,正在切換到備用模型繼續執行。",
+ "cli_agent.parameter_unsupported": "{cli} 不支援所選參數 {parameter},請修改執行設定。",
+ "cli_agent.model_unsupported": "{cli} 不支援模型 {model},請修改執行設定。",
+ "auto_tasks.catch_up_title": "{title}(補跑)",
+ "web_assist.permission_title": "網站權限",
+ "web_assist.permission_request": "允許 {origin} 使用{permission}嗎?",
+ "web_assist.permission_allow": "允許",
+ "web_assist.permission_deny": "拒絕",
+ "web_assist.permission.clipboard": "剪貼簿",
+ "web_assist.permission.media": "攝影機或麥克風",
+ "web_assist.permission.location": "位置資訊",
+ "web_assist.permission.notifications": "通知",
+ "web_assist.permission.fullscreen": "全螢幕",
+ "web_assist.permission.screen": "螢幕分享",
+ "web_assist.permission.device": "裝置",
+ "web_assist.permission.approximate_location": "大致位置資訊",
+ "web_assist.permission.automatic_fullscreen": "自動進入全螢幕的權限",
+ "web_assist.permission.usb": "USB 裝置",
+ "web_assist.permission.hid": "輸入裝置",
+ "web_assist.permission.serial": "序列埠裝置",
+ "web_assist.permission.local_network": "區域網路存取權限",
+ "web_assist.permission.loopback_network": "本機服務存取權限",
+ "web_assist.permission.persistent_storage": "持久儲存網站資料的權限",
+ "web_assist.permission.storage_access": "第三方 Cookie",
+ "web_assist.permission.window_management": "螢幕資訊",
+ "web_assist.permission.local_fonts": "本機字型",
+ "web_assist.permission.idle_detection": "活動及鎖定狀態",
+ "web_assist.permission.screen_wake_lock": "保持螢幕亮起的權限",
+ "web_assist.permission.system_wake_lock": "阻止電腦休眠的權限",
+ "web_assist.permission.pointer_lock": "滑鼠擷取權限",
+ "web_assist.permission.keyboard_lock": "鍵盤擷取權限",
+ "web_assist.permission.filesystem": "檔案存取權限",
+ "web_assist.permission.protected_media": "受保護媒體播放權限",
+ "web_assist.permission.midi": "MIDI 裝置",
+ "web_assist.permission.midi_sysex": "MIDI 系統訊息",
+ "web_assist.permission.speaker_selection": "音訊輸出裝置選擇權限",
+ "web_assist.permission.external": "開啟外部應用程式的權限",
+ "web_assist.permission.sensors": "裝置感測器",
+ "web_assist.permission.background_fetch": "背景下載權限",
+ "web_assist.permission.background_sync": "背景同步權限",
+ "web_assist.permission.surface_control": "共享畫面控制權限",
+ "web_assist.permission.payment": "付款處理權限",
+ "web_assist.permission.ar": "擴增實境功能",
+ "web_assist.permission.vr": "虛擬實境功能",
+ "web_assist.permission.hand_tracking": "手部追蹤資料",
+ "web_assist.permission.nfc": "NFC 裝置",
+ "web_assist.permission.smart_card": "智慧卡讀卡機",
+ "web_assist.permission.installation": "網頁應用程式安裝權限",
+ "web_assist.permission.printing": "印表機",
+ "web_assist.permission.unknown": "「{permission}」權限",
+ "web_assist.permission.other": "此權限",
+ "web_assist.passkey.title": "密碼金鑰",
+ "web_assist.passkey.heading": "使用手機或平板電腦",
+ "web_assist.passkey.instruction": "請使用存有 {rpId} 密碼金鑰的裝置相機掃描此 QR 圖碼。",
+ "web_assist.passkey.nearby": "請開啟藍牙,並將手機放在電腦附近。",
+ "web_assist.passkey.qr_alt": "掃描以使用密碼金鑰",
+ "web_assist.passkey.cancel": "取消",
+ "web_assist.passkey.preparing": "正在準備 QR 圖碼…",
+ "web_assist.passkey.scan": "等待掃描…",
+ "web_assist.passkey.connecting": "正在連線至手機…",
+ "web_assist.passkey.confirm": "已連線手機,請在手機上確認。",
+ "web_assist.passkey.verifying": "正在返回網站…",
+ "errors.model_context_too_small": "此模型的上下文視窗需至少 {minimum} token。請選擇上下文視窗更大的模型。"
}
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index 4bb73ae4..3e918872 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -281,5 +281,73 @@
"sync.conflict_resolution.title_batch": "云同步冲突处理:{count} 条冲突",
"sync.conflict_resolution.message_single": "请帮我处理这条云同步冲突。",
"sync.conflict_resolution.message_batch": "请帮我处理这些云同步冲突。",
- "quality.operator.incomplete": "自定义校验未完成。请修复规则文件,或在设置中停用自定义校验后重试。"
+ "quality.operator.incomplete": "自定义校验未完成。请修复规则文件,或在设置中停用自定义校验后重试。",
+ "model.stopped_tool_limit_summary_incomplete": "本轮已达到 {limit} 轮工具执行上限,任务已停止。收尾总结未能完整生成。",
+ "model.stopped_repeat_summary_incomplete": "本轮因重复操作未产生新进展而停止。收尾总结未能完整生成。",
+ "model.stopped_summary_incomplete": "本轮任务已停止。收尾总结未能完整生成。",
+ "local_agents.unsupported_effort": "当前安装的 Claude Code 无法使用所选推理强度。请升级 Claude Code,或选择默认推理强度。",
+ "model.balance_fallback": "你配置的 {provider} 账户余额不足(这不是 Orkas 积分),正在切换到备用模型继续执行;为该账户充值后即可恢复使用。",
+ "model.provider_unavailable_fallback": "你配置的 {provider} 当前用不了,正在切换到备用模型继续执行。",
+ "cli_agent.parameter_unsupported": "{cli} 不支持所选参数 {parameter},请修改运行设置。",
+ "cli_agent.model_unsupported": "{cli} 不支持模型 {model},请修改运行设置。",
+ "auto_tasks.catch_up_title": "{title}(补跑)",
+ "web_assist.permission_title": "网站权限",
+ "web_assist.permission_request": "允许 {origin} 使用{permission}吗?",
+ "web_assist.permission_allow": "允许",
+ "web_assist.permission_deny": "拒绝",
+ "web_assist.permission.clipboard": "剪贴板",
+ "web_assist.permission.media": "摄像头或麦克风",
+ "web_assist.permission.location": "位置信息",
+ "web_assist.permission.notifications": "通知",
+ "web_assist.permission.fullscreen": "全屏",
+ "web_assist.permission.screen": "屏幕共享",
+ "web_assist.permission.device": "设备",
+ "web_assist.permission.approximate_location": "大致位置信息",
+ "web_assist.permission.automatic_fullscreen": "自动进入全屏的权限",
+ "web_assist.permission.usb": "USB 设备",
+ "web_assist.permission.hid": "输入设备",
+ "web_assist.permission.serial": "串口设备",
+ "web_assist.permission.local_network": "本地网络访问权限",
+ "web_assist.permission.loopback_network": "本机服务访问权限",
+ "web_assist.permission.persistent_storage": "持久保存网站数据的权限",
+ "web_assist.permission.storage_access": "第三方 Cookie",
+ "web_assist.permission.window_management": "屏幕信息",
+ "web_assist.permission.local_fonts": "本机字体",
+ "web_assist.permission.idle_detection": "活动及锁屏状态",
+ "web_assist.permission.screen_wake_lock": "保持屏幕亮起的权限",
+ "web_assist.permission.system_wake_lock": "阻止电脑休眠的权限",
+ "web_assist.permission.pointer_lock": "鼠标捕获权限",
+ "web_assist.permission.keyboard_lock": "键盘捕获权限",
+ "web_assist.permission.filesystem": "文件访问权限",
+ "web_assist.permission.protected_media": "受保护媒体播放权限",
+ "web_assist.permission.midi": "MIDI 设备",
+ "web_assist.permission.midi_sysex": "MIDI 系统消息",
+ "web_assist.permission.speaker_selection": "音频输出设备选择权限",
+ "web_assist.permission.external": "打开外部应用的权限",
+ "web_assist.permission.sensors": "设备传感器",
+ "web_assist.permission.background_fetch": "后台下载权限",
+ "web_assist.permission.background_sync": "后台同步权限",
+ "web_assist.permission.surface_control": "共享画面控制权限",
+ "web_assist.permission.payment": "支付处理权限",
+ "web_assist.permission.ar": "增强现实功能",
+ "web_assist.permission.vr": "虚拟现实功能",
+ "web_assist.permission.hand_tracking": "手部追踪数据",
+ "web_assist.permission.nfc": "NFC 设备",
+ "web_assist.permission.smart_card": "智能卡读卡器",
+ "web_assist.permission.installation": "网页应用安装权限",
+ "web_assist.permission.printing": "打印机",
+ "web_assist.permission.unknown": "“{permission}”权限",
+ "web_assist.permission.other": "此权限",
+ "web_assist.passkey.title": "密钥",
+ "web_assist.passkey.heading": "使用手机或平板电脑",
+ "web_assist.passkey.instruction": "使用 {rpId} 的通行密钥所在设备的摄像头扫描此二维码",
+ "web_assist.passkey.nearby": "请开启蓝牙,并将手机保持在电脑附近。",
+ "web_assist.passkey.cancel": "取消",
+ "web_assist.passkey.qr_alt": "扫码使用通行密钥",
+ "web_assist.passkey.preparing": "正在准备二维码…",
+ "web_assist.passkey.scan": "等待扫码…",
+ "web_assist.passkey.connecting": "正在连接手机…",
+ "web_assist.passkey.confirm": "已连接手机,请在手机上确认。",
+ "web_assist.passkey.verifying": "正在返回网站…",
+ "errors.model_context_too_small": "该模型的上下文窗口需至少 {minimum} token。请选择上下文窗口更大的模型。"
}
diff --git a/src/main/util/conversation-relocate.ts b/src/main/util/conversation-relocate.ts
index 9d43f776..832b4aea 100644
--- a/src/main/util/conversation-relocate.ts
+++ b/src/main/util/conversation-relocate.ts
@@ -436,7 +436,21 @@ function _unresolvedByCid(uid: string, cid: string): UnresolvedRelocation {
}
export function matchesUnresolvedRelocation(unresolved: UnresolvedRelocation[], relPath: string): boolean {
- return unresolved.some(item => item.exact.includes(relPath) || item.prefixes.some(prefix => relPath.startsWith(prefix)));
+ return unresolvedRelocationMatcher(unresolved)(relPath);
+}
+
+/** Build the matcher once per sync check: it runs against every disk, remote
+ * and index path. A record's recorded paths normally all name its
+ * conversation; when they do, a path without that id is skipped before its
+ * lists are consulted, which cannot change the answer. */
+export function unresolvedRelocationMatcher(unresolved: UnresolvedRelocation[]): (relPath: string) => boolean {
+ const records = unresolved.map((item) => ({
+ gate: item.cid && [...item.exact, ...item.prefixes].every((value) => value.includes(item.cid)) ? item.cid : '',
+ exact: new Set(item.exact),
+ prefixes: item.prefixes,
+ }));
+ return (relPath) => records.some((record) => (!record.gate || relPath.includes(record.gate))
+ && (record.exact.has(relPath) || record.prefixes.some((prefix) => relPath.startsWith(prefix))));
}
/** Durable sync intents survive disabled sync and repeated process restarts.
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 1d1ea41e..22470829 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -27,6 +27,7 @@
</button>
<div class="sidebar-actions">
<button class="sidebar-btn primary" id="new-chat-btn"><span data-ui-icon="message-square" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.new_chat">New Task</span><span class="sidebar-btn-running-chip" id="commander-running-chip" hidden></span></button>
+ <!-- One flat list, in the release_1.8.0 order. -->
<button class="sidebar-btn" id="todos-btn"><span data-ui-icon="clipboard-list" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="project.todo.title">To-do</span></button>
<button class="sidebar-btn" id="auto-btn"><span data-ui-icon="clock" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.auto">Auto</span></button>
<button class="sidebar-btn" id="agents-btn"><span data-ui-icon="users" data-ui-icon-class="sidebar-btn-icon"></span><span data-i18n="sidebar.agents">Agents</span></button>
@@ -41,7 +42,7 @@
<button class="sidebar-section-toggle" id="today-section-toggle" type="button"
aria-controls="today-list" aria-expanded="true">
<span data-ui-icon="chevron-down" data-ui-icon-class="sidebar-section-chevron"></span>
- <span class="sidebar-section-title" data-i18n="sidebar.today_tasks">Today's Tasks</span>
+ <span class="sidebar-section-title" data-i18n="sidebar.today_tasks">Recent Tasks</span>
<span class="task-unread-dot" id="today-unread-dot" hidden aria-hidden="true"></span>
</button>
</div>
@@ -94,16 +95,11 @@
</aside>
<main class="main-content">
- <!-- New Chat Landing — empty state per PC/docs/design/PATTERNS.md
- (Surface B). 720px centered column: account-aware heading +
- subtitle + composer (80px textarea) + quick-start task cards.
- The heading is filled in by JS lifecycle hooks; see
- _refreshEmptyStateHeading. -->
- <section class="panel active" id="panel-new-chat">
+ <!-- Commander home: the composer stays above the scrollable work list. -->
+ <section class="panel active" id="panel-new-chat" data-home-state="pending">
<div class="new-chat-center">
<div class="new-chat-header">
<h1 class="new-chat-greeting" id="new-chat-greeting" data-i18n="new_chat.title_fallback">Friend, what do you want to accomplish?</h1>
- <p class="new-chat-subtitle" data-i18n="new_chat.subtitle"></p>
</div>
<div class="new-chat-input-wrapper">
<div class="new-chat-input-area">
@@ -115,7 +111,7 @@
<div class="chat-attachments" id="new-chat-attachments" style="display:none"></div>
</div>
<div class="chat-quote-preview" id="new-chat-quote-preview" style="display:none"></div>
- <div data-composer="1" id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="For example: Analyze this file, identify the key issues, and suggest improvements"></div>
+ <div data-composer="1" id="new-chat-input" data-i18n-placeholder="new_chat.home.input_placeholder" placeholder="Describe what you want to accomplish, or attach the files to work on"></div>
<!-- Composer bottom bar order matches PC/docs/design/PATTERNS.md
P11: [+] | divider | [To] | [workspace - JS-injected] |
[skill] | spacer | [send]. The open-source build strips
@@ -127,13 +123,6 @@
<span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
<span class="chat-recipient-name" id="new-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
- <!-- Order toggle sits to the RIGHT of the workspace chip: the
- chip injects itself directly after the recipient chip, so
- placing the button here yields recipient → workspace →
- order in the left cluster (user directive 2026-08-27). -->
- <button type="button" class="chat-queue-btn" id="new-chat-seq-toggle"
- data-i18n-title="chat.multi_dispatch_toggle_title"
- title="How the mentioned agents run for this message" hidden></button>
<!-- Workspace chip is injected by user-workspace.js::initUserWorkspace
immediately after the recipient chip; mounting position is
centralized there so the open-conversation composer stays in
@@ -150,21 +139,47 @@
</div>
</div>
</div>
- <!-- Server-orderable quick start list. Main-process client config
- supplies the ordered ids; conversation.js renders localized
- cards and binds their matching built-in/default agent. -->
- <section class="new-chat-scenarios quick-panel" id="new-chat-scenarios" aria-labelledby="quick-panel-title">
- <div class="quick-panel-head">
- <span class="quick-panel-title" id="quick-panel-title" data-i18n="new_chat.quick.title">Try one of these tasks — one click to get started</span>
- <span class="quick-panel-rule" aria-hidden="true"></span>
- <!-- Opens the marketplace Open Source list (wired by modules/oss.js). -->
- <button type="button" class="quick-panel-more" id="quick-panel-oss-more">
- <span data-i18n="new_chat.quick.oss_more">Add more open-source tool capabilities</span>
- <span data-ui-icon="chevron-right" data-ui-icon-class="quick-panel-more-arrow" aria-hidden="true"></span>
- </button>
+ <!-- Everything below the composer. This is the only part of the
+ home that scrolls, so the composer is never inside a scroller. -->
+ <div class="home-below">
+ <!-- Empty: two equal ways to start. Copy only; the one control is the
+ connect link that home.js renders inside the context line. -->
+ <div class="home-paths">
+ <section class="home-path" aria-labelledby="home-goal-title">
+ <h2 class="home-path-title" id="home-goal-title" data-i18n="new_chat.home.goal_title">Have a clear goal? Hand it to Commander.</h2>
+ <p class="home-path-body" data-i18n="new_chat.home.goal_body">Tell Commander what you want to accomplish, and it will coordinate your AI team to get it done.</p>
+ <p class="home-path-note" data-i18n="new_chat.home.goal_example">For example: research 3 similar products, compare their features and pricing, and turn the findings into a presentation.</p>
+ </section>
+ <section class="home-path" aria-labelledby="home-explore-title">
+ <h2 class="home-path-title" id="home-explore-title" data-i18n="new_chat.home.explore_title">Not sure yet? Let Orkas get to know you first.</h2>
+ <p class="home-path-body" data-i18n="new_chat.home.explore_body">Talk about your work, your business, or what's on your mind, and Orkas will help you find the right goals and keep them moving.</p>
+ <p class="home-path-note" id="home-explore-context"></p>
+ </section>
</div>
- <div class="quick-grid" id="new-chat-scenario-grid"></div>
- </section>
+ <!-- Server-orderable quick start list. Main-process client config
+ supplies the ordered ids; conversation.js renders localized
+ cards and binds their matching built-in/default agent. -->
+ <section class="new-chat-scenarios quick-panel" id="new-chat-scenarios" aria-labelledby="quick-panel-title">
+ <div class="quick-panel-head">
+ <span class="quick-panel-title" id="quick-panel-title" data-i18n="new_chat.quick.title">Try one of these tasks — one click to get started</span>
+ <span class="quick-panel-rule" aria-hidden="true"></span>
+ <!-- Opens the marketplace「开源项目」list (wired by modules/oss.js). -->
+ <button type="button" class="quick-panel-more" id="quick-panel-oss-more">
+ <span data-i18n="new_chat.quick.oss_more">Add more open-source tool capabilities</span>
+ <span data-ui-icon="chevron-right" data-ui-icon-class="quick-panel-more-arrow" aria-hidden="true"></span>
+ </button>
+ </div>
+ <div class="quick-grid" id="new-chat-scenario-grid"></div>
+ </section>
+ <!-- Populated: the three groups are rendered by home.js. -->
+ <section class="home-work" id="home-work" aria-labelledby="home-continue-title">
+ <div class="home-continue-label" id="home-continue-title">
+ <span data-i18n="new_chat.home.continue_label">Keep things moving</span>
+ <span class="home-continue-rule" aria-hidden="true"></span>
+ </div>
+ <div class="home-groups" id="home-groups"></div>
+ </section>
+ </div>
</div>
</section>
@@ -247,12 +262,6 @@
<span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
<span class="chat-recipient-name" id="chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
- <!-- D9 cross-group order toggle: visible only while the composer
- text splits into ≥2 mention groups. Label mirrors the current
- mode (serial default); click flips it for THIS send. -->
- <button type="button" class="chat-queue-btn" id="chat-seq-toggle"
- data-i18n-title="chat.multi_dispatch_toggle_title"
- title="How the mentioned agents run for this message; click to switch" hidden></button>
<!-- Workspace chip is injected by user-workspace.js right after
the recipient chip — see initUserWorkspace(). -->
<div class="chat-skill-chip" id="chat-skill-chip" data-target="conversation" style="display:none">
@@ -544,6 +553,10 @@
<div class="agents-detail-label" data-i18n="agents.label_cli_settings">Runtime settings</div>
<div class="agents-detail-cli-settings" id="agents-detail-cli-settings"></div>
</div>
+ <div class="agents-detail-section" id="agents-detail-cli-usage-section" hidden>
+ <div class="agents-detail-label" data-i18n="agents.cli_usage_title">Remaining allowance</div>
+ <div id="agents-detail-cli-usage" aria-live="polite"></div>
+ </div>
<div class="agents-detail-section" id="agents-detail-project-dir-section" style="display:none">
<div class="agents-detail-label" data-i18n="agents.label_project_dir">Project directory</div>
<div class="agents-detail-project-dir" id="agents-detail-project-dir"></div>
@@ -676,6 +689,8 @@
<section class="panel" id="panel-project">
<div class="project-detail-view">
<div class="project-detail-content" id="project-detail-content">
+ <!-- Local rename and delete use the shared header menu. The
+ existing member invite action keeps commercial guidance. -->
<header class="project-detail-header">
<div class="project-detail-header-main">
<div class="project-detail-header-title-row">
@@ -686,8 +701,11 @@
</div>
<div class="project-detail-actions">
<button type="button" class="btn btn-sm" id="project-action-invite" data-i18n="project.menu.invite_members">Invite project members</button>
- <button type="button" class="btn btn-sm" id="project-action-rename" data-i18n="project.action.rename">Rename</button>
- <button type="button" class="btn btn-sm btn-danger" id="project-action-delete" data-i18n="project.action.delete">Delete</button>
+ <button type="button" class="btn btn-sm" id="project-action-rename" data-i18n="project.action.done" hidden>Done</button>
+ <button type="button" class="project-header-icon-btn" id="project-action-more" aria-haspopup="menu"
+ data-i18n-title="project.menu.more_actions" data-i18n-aria-label="project.menu.more_actions" title="More actions" aria-label="More actions">
+ <span data-ui-icon="more-horizontal" data-ui-icon-class="project-header-icon"></span>
+ </button>
</div>
</header>
@@ -710,11 +728,6 @@
<span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
<span class="chat-recipient-name" id="project-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
- <!-- Order toggle sits to the RIGHT of the injected workspace
- chip, same as the other composers. -->
- <button type="button" class="chat-queue-btn" id="project-chat-seq-toggle"
- data-i18n-title="chat.multi_dispatch_toggle_title"
- title="How the mentioned agents run for this message" hidden></button>
<!-- Workspace chip is injected by user-workspace.js right after
the recipient chip — see initUserWorkspace(). -->
<div class="chat-skill-chip" id="project-chat-skill-chip" data-target="project" style="display:none">
@@ -729,8 +742,9 @@
</div>
</div>
- <!-- Tabbed workspace: project tasks and automation. Agents
- and Library live in the right rail. -->
+ <!-- Tabbed workspace: project tasks, automation and to-dos. The
+ active tab's tools share the tab row. Agents and Library
+ live in the right rail. -->
<section class="project-workbench">
<div class="project-detail-tabs">
<div class="project-detail-tab-group" role="tablist">
@@ -747,28 +761,33 @@
<span class="project-detail-tab-count" id="project-todo-count">0</span>
</button>
</div>
+ <!-- _syncProjectDetailTabState shows the active tab's group. -->
+ <div class="project-tab-tools" data-project-tools="auto" hidden>
+ <button type="button" class="btn btn-sm" id="project-auto-add-btn" data-i18n="auto.add_btn">+ Create</button>
+ </div>
+ <div class="project-tab-tools" data-project-tools="todo" hidden>
+ <!-- All / Mine, filled for shared projects by _renderProjectTodosList. -->
+ <div class="project-todo-filter" id="project-todo-filter"></div>
+ <button type="button" class="project-driver-toggle is-switch" id="project-driver-toggle"
+ data-i18n-title="project.driver.toggle_hint"
+ title="AI handles to-dos automatically for you to review when finished. Runs only on the device where you turn it on." aria-pressed="false"><span class="project-driver-switch" aria-hidden="true"></span><span data-i18n="project.driver.toggle">Auto</span><span id="project-driver-device"></span></button>
+ <button type="button" class="project-driver-hint" id="project-driver-hint"
+ data-i18n-aria-label="project.driver.toggle_hint" aria-label="AI handles to-dos automatically for you to review when finished. Runs only on the device where you turn it on."
+ aria-describedby="project-driver-tooltip"><span data-ui-icon="info" data-ui-icon-class="project-driver-hint-icon"></span></button>
+ <button type="button" class="btn btn-sm" id="project-todo-add-btn"
+ data-i18n="todo.add_short" data-i18n-title="project.todo.add" title="Create task">+ Create</button>
+ </div>
</div>
<div class="project-detail-tab-panel" data-project-panel="tasks">
<div class="project-tasks-list" id="project-tasks-list"></div>
<div class="project-tasks-empty empty muted" id="project-tasks-empty" data-i18n="project.tasks_empty">No tasks yet</div>
</div>
<div class="project-detail-tab-panel" data-project-panel="auto" hidden>
- <div class="project-auto-tab-head">
- <div class="auto-sync-note" id="project-auto-sync-note" hidden></div>
- <button type="button" class="btn btn-sm" id="project-auto-add-btn" data-i18n="auto.add_btn">+ Create</button>
- </div>
+ <div class="auto-sync-note" id="project-auto-sync-note" hidden></div>
<div class="auto-list" id="project-auto-list"></div>
<div class="empty muted" id="project-auto-empty" data-i18n="auto.empty">No auto tasks yet</div>
</div>
<div class="project-detail-tab-panel" data-project-panel="todo" hidden>
- <div class="project-todo-tab-head">
- <button type="button" class="btn btn-sm project-driver-toggle" id="project-driver-toggle"
- data-i18n="project.driver.toggle" data-i18n-title="project.driver.toggle_hint"
- title="AI handles to-dos automatically for you to review when finished." aria-pressed="false">Auto</button>
- <span class="form-hint" data-i18n="project.driver.toggle_hint">AI handles to-dos automatically for you to review when finished.</span>
- <button type="button" class="btn btn-sm" id="project-todo-add-btn"
- data-i18n="todo.add_short" data-i18n-title="project.todo.add" title="Create task">+ Create</button>
- </div>
<div class="todo-load-error" id="project-todo-error" role="status" hidden><span data-i18n="todo.load_failed">Could not load tasks. Try again.</span><button class="btn btn-sm" id="project-todo-retry" data-i18n="chat.retry_btn">Retry</button></div>
<div class="project-tasks-list project-todo-list" id="project-todo-list"></div>
</div>
@@ -827,6 +846,8 @@
data-i18n-title="project.memory.add" title="Add memory"
data-i18n-aria-label="project.memory.add" aria-label="Add memory">Add</button>
</div>
+ <p class="project-context-help project-memory-full" id="project-memory-full" role="status" hidden
+ data-i18n="memory.full_notice">Memory is full. Before saving something new, the AI will merge existing entries.</p>
<div class="project-memory-editor" id="project-memory-editor" hidden>
<textarea class="project-memory-editor-input" id="project-memory-editor-input" rows="3" maxlength="2500"
data-i18n-placeholder="project.memory.placeholder" placeholder="Record a durable fact, decision, or project update"></textarea>
@@ -1073,12 +1094,17 @@
<h1 class="apps-page-header-title" data-i18n="apps.title">Apps</h1>
<span class="apps-page-header-count" id="apps-page-header-count"></span>
</div>
+ <div class="apps-header-types">
+ <div class="apps-type-tabs" id="apps-type-tabs" role="tablist" data-i18n-aria-label="apps.title" aria-label="Apps"></div>
+ <span class="apps-type-description" id="apps-type-description"></span>
+ </div>
</div>
<button type="button" class="btn btn-sm" id="apps-create-btn" aria-haspopup="dialog">
<span data-ui-icon="plus" aria-hidden="true"></span><span data-i18n="apps.create">Create</span>
</button>
</div>
- <div class="agents-grid-scroll">
+ <div class="agents-grid-scroll" id="apps-content" role="tabpanel" aria-labelledby="apps-tab-local">
+ <div class="app-publication-quota" id="apps-publication-quota" hidden></div>
<div class="apps-grid" id="apps-grid"></div>
<div class="agents-empty" id="apps-empty" data-i18n="apps.empty">No apps</div>
</div>
@@ -1125,13 +1151,12 @@
<section class="settings-section" id="settings-section-local">
<div class="settings-section-title">
- <h2 data-i18n="settings.section.local">本地</h2>
+ <h2 data-i18n="settings.data_root.title">数据目录</h2>
<span class="settings-section-hint" data-i18n="settings.data.local_hint">仅此设备</span>
</div>
<div class="settings-sheet">
<div class="settings-row settings-data-root-row">
<div class="settings-row-copy">
- <div class="settings-row-title" data-i18n="settings.data_root.title">Data root</div>
<div class="settings-row-desc" data-i18n="settings.data_root.sub">All conversations, agents, skills, and Library content live under this directory. Click the path to open it in the OS file manager.</div>
<span class="settings-mono" id="settings-data-root-path"></span>
</div>
@@ -1140,6 +1165,20 @@
</div>
</section>
+ <section class="settings-section" id="settings-task-cleanup">
+ <div class="settings-section-title"><h2 data-i18n="settings.cleanup.title">Clean up task history</h2></div>
+ <div class="settings-sheet">
+ <div class="settings-row">
+ <div class="settings-row-copy">
+ <div class="settings-row-title" data-i18n="settings.cleanup.age">Last active</div>
+ <div class="settings-row-desc" data-i18n="settings.cleanup.scope">Completed tasks inside and outside projects. Pinned and unread tasks, drafts, and automation runs are kept.</div>
+ </div>
+ <div class="ai-select" id="settings-task-cleanup-age"></div>
+ </div>
+ <div id="settings-task-cleanup-body" aria-live="polite"></div>
+ </div>
+ </section>
+
<section class="settings-section" id="settings-recycle-group">
<div class="settings-section-title">
<div class="settings-section-copy">
@@ -1464,6 +1503,9 @@
</label>
<div class="agent-cli-select-row">
<div class="ai-select" id="agent-modal-ext-cli-select"></div>
+ <div id="agent-modal-ext-cli-upgrades"></div>
+ </div>
+ <div id="agent-modal-ext-cli-upgrade-warning" class="agent-cli-selection-warning" role="status" hidden></div>
<span
class="agent-cli-selection-warning"
id="agent-modal-ext-cli-warning"
@@ -1471,7 +1513,6 @@
aria-live="polite"
hidden
></span>
- </div>
</div>
<div class="form-row">
<label data-i18n="agent_modal.ext_name">Name</label>
@@ -1931,6 +1972,7 @@
<script src="./modules/i18n.js"></script>
<script src="./modules/chat-use.js"></script>
<script src="./modules/user-error.js"></script>
+ <script src="./modules/overlay-manager.js"></script>
<script src="./modules/model-guard.js"></script>
<script src="./modules/dropdown-placement.js"></script>
<script src="./modules/composer-model-picker.js"></script>
@@ -1962,8 +2004,10 @@
<script src="./modules/conversation-view-model.js"></script>
<script src="./vendor/prosemirror/prosemirror.min.js"></script>
<script src="./modules/composer-input.js"></script>
+ <script src="./modules/commercial-entry.js"></script>
<script src="./modules/conversation.js"></script>
<script src="./modules/conversation-to-project.js"></script>
+ <script src="./modules/home.js"></script>
<script src="./modules/conversation-turn-nav.js"></script>
<script src="./modules/web-app-host.js"></script>
<script src="./modules/artifact-security.js"></script>
@@ -1983,6 +2027,7 @@
<!-- DOMPurify must load before utils.js so inline connector SVGs are sanitized, not disabled. -->
<script src="./vendor/dompurify/purify.min.js"></script>
<script src="./modules/pinyin-firstletter.js"></script>
+ <script src="./modules/cli-account-usage.js"></script>
<script src="./modules/agents.js"></script>
<script src="./modules/auto-title.js"></script>
<script src="./modules/auto-events.js"></script>
diff --git a/src/renderer/locales/ar.json b/src/renderer/locales/ar.json
index d5c83999..cbc6b552 100644
--- a/src/renderer/locales/ar.json
+++ b/src/renderer/locales/ar.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "تنزيل",
"web_assist.activity_visit": "زيارة",
"web_assist.download_saved": "تم الحفظ في المرفقات",
- "web_assist.download_needs_grant": "يتطلب إذنًا",
- "web_assist.download_blocked_type": "نوع الملف غير مسموح",
- "web_assist.download_budget": "تم بلوغ حد التنزيلات للمهمة",
"web_assist.download_failed": "فشل",
"web_assist.download_unavailable": "الملف غير متاح. تحقق من اكتمال التنزيل ومن أن الملف لم يُنقل أو يُحذف.",
- "web_assist.download_allow": "السماح لهذا الموقع",
- "web_assist.download_prompt_title": "هل تسمح بالتنزيلات من هذا الموقع؟",
- "web_assist.download_prompt_description": "ستُحفظ الملفات في مرفقات هذه المهمة. بعد السماح، عُد إلى الصفحة وأعد محاولة التنزيل.",
- "web_assist.download_not_now": "ليس الآن",
- "web_assist.download_permission_failed": "تعذّر السماح لهذا الموقع. حاول مجددًا.",
"web_assist.address_placeholder": "ابحث في Bing أو أدخل URL",
"web_assist.empty_title": "تصفّح ضمن هذه المهمة",
"web_assist.empty_hint": "ابحث في Bing أو أدخل URL أعلاه.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "آخر 30 يومًا",
"sidebar.bucket.older": "أقدم",
"sidebar.projects": "المشاريع",
- "sidebar.today_tasks": "مهام اليوم",
- "sidebar.today_empty": "لا توجد مهام اليوم",
+ "sidebar.today_tasks": "المهام الأخيرة",
+ "sidebar.today_empty": "لا توجد مهام في آخر يومين",
"sidebar.section_collapse": "طي {section}",
"sidebar.section_expand": "توسيع {section}",
"sidebar.project_create_title": "مشروع جديد",
"sidebar.project_create_placeholder": "أدخل اسم المشروع",
"sidebar.project_conv_empty": "(لا توجد مهام)",
- "sidebar.load_more_conversations": "تحميل المزيد",
+ "sidebar.load_more_conversations": "عرض المزيد",
"sidebar.connect_agent": "ربط الوكلاء",
"sidebar.connect_agent_sub": "Claude Code · Codex والمزيد",
"sidebar.settings": "الإعدادات",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "جارٍ التحميل…",
"new_chat.model_picker.aria_label": "اختر النموذج",
"new_chat.model_picker.empty": "لا توجد نماذج متاحة",
- "new_chat.model_picker.group_official": "النماذج الرسمية",
- "new_chat.model_picker.group_custom": "نماذج ضبطها المستخدم",
+ "new_chat.model_picker.group_official": "نماذج Orkas المدمجة",
+ "new_chat.model_picker.group_custom": "API Key الخاص بك",
"new_chat.model_picker.configure": "ضبط النماذج",
"new_chat.model_picker.switch_failed": "تعذّر تبديل النموذج. حاول مجددًا.",
"new_chat.model_picker.choose_version": "اختر إصدار نموذج للحساب {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "تمت الإضافة إلى {library}",
"conversation_info.file_add_to_library_failed": "فشلت الإضافة إلى المكتبة: {reason}",
"conversation_info.file_add_to_chat_action": "إضافة إلى محادثة المهمة",
- "conversation_info.file_reveal_failed": "تعذّر فتح المجلد: {reason}",
+ "conversation_info.file_reveal_failed": "تعذّر فتح المجلد. ربما نُقل الملف أو حُذف.",
"conversation_info.file_delete_confirm_title": "حذف ملف",
"conversation_info.file_delete_confirm_msg": "هل تريد حذف \"{name}\"؟",
"conversation_info.file_delete_failed": "تعذّر حذف الملف: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "إرسال الآن",
"chat.queue_sending_now": "جارٍ الإرسال…",
"chat.queue_send_now_failed": "تعذّر إرسال هذه الرسالة المنتظرة الآن: {msg}",
- "chat.multi_dispatch_serial": "تشغيل بالتتابع",
- "chat.multi_dispatch_parallel": "تشغيل معًا",
- "chat.multi_dispatch_toggle_title": "كيفية تشغيل الوكلاء المذكورين لهذه الرسالة؛ انقر للتبديل",
"chat.task_waiting_on": "بانتظار {name}",
"chat.task_status_orchestrating": "جارٍ التنسيق",
"chat.task_dispatched": "أسندها القائد",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "هل تريد حذف الرسائل الـ {count} المحددة؟ لا يمكن التراجع عن ذلك.",
"chat.message_delete_failed": "فشل الحذف: {reason}",
"chat.reference_target_title": "الاستشهاد بـ {count} رسالة في",
- "chat.reference_target_search": "البحث في المهام",
- "chat.reference_new_task": "مهمة جديدة",
- "chat.reference_existing_tasks": "المهام الحالية",
- "chat.reference_area_commander": "القائد",
+ "chat.reference_new_task": "مهمة جديدة…",
"chat.reference_area_project": "المشروع",
- "chat.reference_recent_tasks_hint": "أحدث 5 مهام",
- "chat.reference_search_results_count": "{count} نتيجة",
- "chat.reference_no_tasks": "لا توجد مهام مطابقة",
"chat.reference_unknown_task": "مهمة غير معروفة",
"chat.reference_from_task": "اقتباس من “{title}” @{name}",
"chat.reference_bundle_title": "من “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "إضافة خدمة صور",
"settings.models.add_video": "إضافة خدمة فيديو",
"settings.models.add_tts": "إضافة خدمة صوت",
- "settings.models.order_hint": "اسحب الصفوف لتغيير الأولوية أو استخدم أزرار الأسهم. تُتخطّى النماذج الرسمية المعطّلة.",
+ "settings.models.order_hint": "اسحب الصفوف لتغيير الأولوية أو استخدم أزرار الأسهم. تُتخطّى النماذج المدمجة المعطّلة.",
"settings.general.page_sub": "اضبط التفضيلات وأذونات الوكلاء وتحديثات التطبيق.",
"settings.general.preferences_title": "التفضيلات",
"settings.general.agent_title": "سلوك الوكيل",
@@ -2031,7 +2014,7 @@
"project.review.approve": "موافقة",
"project.review.request_changes": "طلب تغييرات",
"project.driver.toggle": "تلقائي",
- "project.driver.toggle_hint": "يعالج الذكاء الاصطناعي المهام المطلوبة تلقائيًا لتراجعها عند اكتمالها.",
+ "project.driver.toggle_hint": "يعالج الذكاء الاصطناعي المهام المطلوبة تلقائيًا لتراجعها عند اكتمالها. تُنفَّذ فقط على الجهاز الذي تفعّلها عليه.",
"project.driver.enabled_toast": "التقدم التلقائي مفعّل — يختار دوريًا مهمة معلّقة ويعمل عليها؛ وتنتقل المهام إلى قيد التنفيذ.",
"project.driver.disabled_toast": "التقدم التلقائي متوقف.",
"project.recent_convs.view_all": "عرض الكل ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "طي",
"skills.source_external": "حزمة",
"skills.source_global": "عام",
- "web_assist.action_confirm.title": "هل تسمح بهذا الإجراء على الصفحة؟",
"chat.form.boolean_yes": "نعم",
"chat.form.boolean_no": "لا",
"chat.form.invalid_number": "أدخل رقمًا صالحًا",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "إعادة التحميل",
"quality.operator.disabled": "معطل على هذا الجهاز.",
"quality.operator.ready": "جاهز: {count} قواعد.",
- "quality.operator.invalid": "التحقق غير متاح. أصلح operator-policy.json أو أوقف التحقق المخصص، ثم أعد المحاولة."
+ "quality.operator.invalid": "التحقق غير متاح. أصلح operator-policy.json أو أوقف التحقق المخصص، ثم أعد المحاولة.",
+ "chat.app_nav_project_collaboration_target": "أعضاء المشروع: {target}",
+ "new_chat.home.goal_title": "لديك هدف واضح؟ سلّمه إلى القائد.",
+ "new_chat.home.goal_body": "أخبر القائد بما تريد إنجازه، وسينسّق فريق الذكاء الاصطناعي لإتمامه.",
+ "new_chat.home.goal_example": "مثلًا: ابحث في 3 منتجات متشابهة، وقارن ميزاتها وأسعارها، ثم لخّص ذلك في عرض تقديمي.",
+ "new_chat.home.explore_title": "لم تقرر بعد؟ دع Orkas يتعرّف عليك أولًا.",
+ "new_chat.home.explore_body": "تحدّث عن عملك أو تجارتك أو ما يقلقك، وسيساعدك Orkas على إيجاد الأهداف المناسبة ومواصلة التقدّم فيها.",
+ "new_chat.home.explore_context": "شارك الملفات عبر + أو {connect} لتمنح Orkas سياقًا أكبر. ابدأ بما ترتاح لمشاركته.",
+ "new_chat.home.explore_connect_link": "اربط Feishu / DingTalk / البريد الإلكتروني",
+ "new_chat.home.input_placeholder": "صف ما تريد إنجازه، أو أرفق الملفات التي تحتاج إلى معالجة",
+ "new_chat.home.continue_label": "تابع التقدّم في عملك",
+ "new_chat.home.group.todos": "مهام مطلوبة مهمة",
+ "new_chat.home.group.automations": "نتائج الأتمتة",
+ "new_chat.home.group.tasks": "مهام بانتظارك",
+ "new_chat.home.all_automations": "كل الأتمتة ←",
+ "new_chat.home.expand": "عرض {count} أخرى",
+ "new_chat.home.collapse": "عرض أقل",
+ "new_chat.home.view_all_todos": "عرض الكل ←",
+ "new_chat.home.source.project_todo": "{project} · مهمة مطلوبة",
+ "new_chat.home.source.global_todo": "مهمة مطلوبة عامة",
+ "new_chat.home.source.automation": "الأتمتة",
+ "new_chat.home.source.project_task": "{project} · مهمة المشروع",
+ "new_chat.home.source.global_task": "مهمة عامة",
+ "new_chat.home.result.completed": "مكتملة",
+ "new_chat.home.result.failed": "فشلت",
+ "new_chat.home.result.waiting_input": "بانتظار ردّك",
+ "new_chat.home.result.stopped": "متوقفة",
+ "new_chat.home.result.unknown": "نتيجة جديدة",
+ "new_chat.home.action.view": "عرض",
+ "new_chat.home.action.reply": "الرد",
+ "new_chat.home.action.view_reason": "عرض السبب",
+ "new_chat.home.action.view_result": "عرض النتيجة",
+ "new_chat.home.time.updated": "حُدّثت {time}",
+ "new_chat.home.untitled": "مهمة بلا عنوان",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "تم تحديث {name}",
+ "apps.save_root_folder_required": "انقل ملف HTML وموارده إلى مجلد منفصل، ثم احفظه كتطبيق مرة أخرى.",
+ "chat.reference_locate_title": "الانتقال إلى الرسالة الأصلية",
+ "chat.reference_locate_missing": "لم تعد الرسالة الأصلية موجودة.",
+ "agents.cli_usage_title": "الحصة المتبقية",
+ "agents.cli_usage_unavailable": "غير متاحة. تحقق من تسجيل الدخول إلى CLI والاتصال.",
+ "agents.cli_usage_unsupported": "لا يدعم إصدار CLI هذا أو الإعداد المخصص الاستعلام عن الحصة.",
+ "agents.cli_usage_resets": "إعادة التعيين: {time}",
+ "agents.cli_usage_hours": "{count} ساعات",
+ "agents.cli_usage_days": "{count} أيام",
+ "agents.cli_usage_window": "فترة الاستخدام",
+ "memory.full_notice": "الذاكرة ممتلئة. قبل حفظ أي شيء جديد، سيدمج الذكاء الاصطناعي الإدخالات الحالية.",
+ "memory.error_full": "الذاكرة ممتلئة، لذا لا يمكن إضافة هذا الإدخال الآن.",
+ "settings.recycle.clear": "إفراغ",
+ "settings.recycle.clear_title": "إفراغ سلة المحذوفات",
+ "settings.recycle.clear_confirm": "هل تريد حذف جميع السجلات البالغ عددها {count} في {source} نهائيًا؟ لن تتمكن من استعادتها بعد ذلك.",
+ "settings.recycle.clearing": "جارٍ الإفراغ {done}/{total}…",
+ "settings.recycle.cleared": "تم إفراغ سلة المحذوفات",
+ "settings.recycle.clear_failed": "تعذر إفراغ سلة المحذوفات بالكامل. يرجى المحاولة مرة أخرى.",
+ "settings.recycle.automation_count": "الأتمتة · عدد المهام: {count}",
+ "project.todo.move": "نقل",
+ "bash.permission.allow_folder_read": "السماح بقراءة هذا المجلد",
+ "bash.permission.folder_read_scope": "خلال هذه المهمة، يمكن لـ {agent} قراءة الملفات في {folder} دون السؤال مجددًا. ما زالت الكتابة والحذف والملفات السرية تتطلب التأكيد.",
+ "cli_upgrade.action": "ترقية CLI",
+ "cli_upgrade.pending": "جارٍ الترقية…",
+ "cli_upgrade.success": "نجحت الترقية",
+ "cli_upgrade.failed": "فشلت الترقية",
+ "cli_upgrade.named_action": "ترقية {cli} CLI",
+ "web_assist.handback": "إعادة التحكم للذكاء الاصطناعي",
+ "web_assist.permissions": "إعادة ضبط أذونات الموقع",
+ "web_assist.permission_title": "إذن الموقع",
+ "web_assist.permission_allow": "السماح",
+ "web_assist.permission_deny": "رفض",
+ "web_assist.permission_failed": "تعذر حفظ اختيارك. حاول مجددًا.",
+ "apps.view_details": "عرض التفاصيل",
+ "apps.no_local_code": "لا يوجد رمز التطبيق على هذا الجهاز",
+ "apps.publish_commercial": "استخدم نسخة Orkas التجارية للنشر.",
+ "apps.update_original": "تحديث التطبيق الأصلي",
+ "apps.save_new": "حفظ تطبيق جديد",
+ "apps.edit_conflict": "تغيّر التطبيق الأصلي أو حُذف. أعد فتحه للتحرير أو احفظ تطبيقًا جديدًا.",
+ "apps.save_type_mismatch": "نوع هذا الإصدار يختلف عن التطبيق الأصلي، لذا لا يمكنه استبداله. احفظه كتطبيق جديد بدلًا من ذلك.",
+ "apps.type_local": "تطبيق محلي",
+ "apps.type_web": "تطبيق ويب",
+ "apps.type_local_description": "يعمل في Orkas لسطح المكتب مع إمكانية استخدام الذكاء الاصطناعي والملفات والمكتبة والموصلات؛ لا يمكن نشره على الويب.",
+ "apps.type_web_description": "انشر على الويب وافتح عبر رابط، مع جمع البيانات والاستعلام عنها وإحصاءاتها؛ ميزات Orkas لسطح المكتب غير متاحة.",
+ "apps.delete_data_confirm": "هل تريد حذف \"{name}\" وسجلاته المحلية وملفاته الخاصة؟ لا يمكن استعادة البيانات.",
+ "apps.delete_online_retained": "يتم الاحتفاظ بالتطبيق المنشور والبيانات عبر الإنترنت.",
+ "apps.migration_export": "تتغير بنية البيانات. صدّر السجلات المحلية قبل مسحها.",
+ "apps.migration_export_action": "تصدير السجلات",
+ "apps.migration_continue": "متابعة",
+ "apps.migration_clear": "مسح كل السجلات المحلية والتحديث؟ تبقى السجلات عبر الإنترنت مستقلة.",
+ "apps.migration_retry": "مسح وإعادة المحاولة",
+ "chat.reference_scope_label": "نطاق المهام",
+ "chat.reference_scope_all": "كل المهام",
+ "chat.reference_scope_global": "عام (بدون مشروع)",
+ "chat.reference_new_in_global": "مهمة جديدة بدون مشروع",
+ "chat.reference_new_in_project": "مهمة جديدة في «{name}»",
+ "chat.reference_search_all": "البحث في كل المهام",
+ "chat.reference_search_in": "البحث في مهام «{name}»",
+ "chat.reference_count_all": "الإجمالي {count} · الأحدث أولًا",
+ "chat.reference_count_found": "تم العثور على {count} · الأحدث أولًا",
+ "chat.reference_load_more": "تحميل مهام أقدم (متبقٍ {count})",
+ "chat.reference_no_match": "لا توجد مهام مطابقة",
+ "chat.reference_no_match_hint": "جرّب كلمة مفتاحية أخرى، أو اختر نطاقًا آخر من القائمة الجانبية.",
+ "chat.reference_scope_empty": "لا توجد مهام هنا بعد",
+ "chat.reference_scope_empty_hint": "استخدم الزر أعلاه لبدء مهمة جديدة هنا.",
+ "chat.reference_create_back": "العودة إلى المهام",
+ "chat.reference_create_title": "أين تريد إنشاء المهمة الجديدة؟",
+ "chat.reference_create_desc": "تُضاف الاستشهادات بعد اختيار الوجهة. لا يُرسل أي شيء تلقائيًا.",
+ "chat.reference_create_global_desc": "لا تنتمي إلى أي مشروع",
+ "chat.reference_create_project_desc": "بدء مهمة جديدة في هذا المشروع",
+ "chat.reference_target_footer": "عند الاختيار يُفتح حقل إدخال المهمة مع إضافة الاستشهادات. لا يُرسل أي شيء تلقائيًا.",
+ "project.todo.run_busy": "المحادثة الخاصة بهذه المهمة لا تزال قيد المعالجة. شغّلها مرة أخرى بعد انتهائها.",
+ "settings.cleanup.title": "تنظيف المهام القديمة",
+ "settings.cleanup.age": "آخر نشاط",
+ "settings.cleanup.scope": "المهام المكتملة داخل المشاريع وخارجها. تُحفظ المهام المثبتة وغير المقروءة والمسودات وسجلات الأتمتة.",
+ "settings.cleanup.days": "قبل أكثر من {n} يومًا",
+ "settings.cleanup.result": "نُقلت إلى السلة: {deleted}. تم تخطيها: {skipped}. فشلت: {failed}.",
+ "settings.cleanup.progress": "جارٍ التنظيف {done} / {total}",
+ "settings.cleanup.error": "تعذر تحميل المهام أو تنظيفها. حدّث وحاول مجددًا.",
+ "settings.cleanup.count": "تم تحديد {n} مهمة",
+ "settings.cleanup.empty": "لا توجد مهام قديمة للتنظيف.",
+ "settings.cleanup.clean": "تنظيف",
+ "settings.cleanup.confirm": "نقل {n} مهمة ومرفقاتها ونتائجها المضمنة إلى سلة المحذوفات. يمكنك استعادتها أدناه. عند تفعيل المزامنة، يسري الحذف على الأجهزة الأخرى أيضًا. تُحرر مساحة القرص بعد إفراغ السلة.",
+ "settings.cleanup.move": "نقل إلى السلة ({n})",
+ "settings.cleanup.previous": "السابق",
+ "settings.cleanup.next": "التالي",
+ "apps.commercial_required": "تتطلب تطبيقات الويب الإصدار التجاري من Orkas. نزّله للمتابعة.",
+ "apps.commercial_download": "تنزيل الإصدار التجاري",
+ "apps.commercial_open_failed": "تعذّر فتح صفحة التنزيل. يُرجى المحاولة مجددًا."
}
diff --git a/src/renderer/locales/de.json b/src/renderer/locales/de.json
index 3bcc2d28..b01af32a 100644
--- a/src/renderer/locales/de.json
+++ b/src/renderer/locales/de.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Download",
"web_assist.activity_visit": "Besuchen",
"web_assist.download_saved": "in Anhängen gespeichert",
- "web_assist.download_needs_grant": "Berechtigung erforderlich",
- "web_assist.download_blocked_type": "Dateityp nicht erlaubt",
- "web_assist.download_budget": "Downloadlimit der Aufgabe erreicht",
"web_assist.download_failed": "fehlgeschlagen",
"web_assist.download_unavailable": "Datei nicht verfügbar. Prüfen Sie, ob der Download abgeschlossen ist und die Datei nicht verschoben oder gelöscht wurde.",
- "web_assist.download_allow": "Diese Website zulassen",
- "web_assist.download_prompt_title": "Downloads von dieser Website zulassen?",
- "web_assist.download_prompt_description": "Dateien werden in den Anhängen dieser Aufgabe gespeichert. Kehren Sie nach der Freigabe zur Seite zurück und starten Sie den Download erneut.",
- "web_assist.download_not_now": "Jetzt nicht",
- "web_assist.download_permission_failed": "Diese Website konnte nicht zugelassen werden. Versuchen Sie es erneut.",
"web_assist.address_placeholder": "Mit Bing suchen oder URL eingeben",
"web_assist.empty_title": "In dieser Aufgabe surfen",
"web_assist.empty_hint": "Suchen Sie oben mit Bing oder geben Sie eine URL ein.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Letzte 30 Tage",
"sidebar.bucket.older": "Älter",
"sidebar.projects": "Projekte",
- "sidebar.today_tasks": "Heutige Aufgaben",
- "sidebar.today_empty": "Heute keine Aufgaben",
+ "sidebar.today_tasks": "Aktuelle Aufgaben",
+ "sidebar.today_empty": "Keine Aufgaben in den letzten zwei Tagen",
"sidebar.section_collapse": "{section} einklappen",
"sidebar.section_expand": "{section} ausklappen",
"sidebar.project_create_title": "Neues Projekt",
"sidebar.project_create_placeholder": "Projektnamen eingeben",
"sidebar.project_conv_empty": "(keine Aufgaben)",
- "sidebar.load_more_conversations": "Mehr laden",
+ "sidebar.load_more_conversations": "Mehr anzeigen",
"sidebar.connect_agent": "Agenten verbinden",
"sidebar.connect_agent_sub": "Claude Code · Codex und mehr",
"sidebar.settings": "Einstellungen",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Wird geladen…",
"new_chat.model_picker.aria_label": "Modell wählen",
"new_chat.model_picker.empty": "Keine verfügbaren Modelle",
- "new_chat.model_picker.group_official": "Offizielle Modelle",
- "new_chat.model_picker.group_custom": "Vom Nutzer konfigurierte Modelle",
+ "new_chat.model_picker.group_official": "Integrierte Orkas-Modelle",
+ "new_chat.model_picker.group_custom": "Eigener API Key",
"new_chat.model_picker.configure": "Modelle konfigurieren",
"new_chat.model_picker.switch_failed": "Modellwechsel nicht möglich. Versuchen Sie es erneut.",
"new_chat.model_picker.choose_version": "Modellversion für {account} wählen",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Zu {library} hinzugefügt",
"conversation_info.file_add_to_library_failed": "Hinzufügen zur Bibliothek fehlgeschlagen: {reason}",
"conversation_info.file_add_to_chat_action": "Zum Aufgabenchat hinzufügen",
- "conversation_info.file_reveal_failed": "Ordner konnte nicht geöffnet werden: {reason}",
+ "conversation_info.file_reveal_failed": "Ordner konnte nicht geöffnet werden. Die Datei wurde möglicherweise verschoben oder gelöscht.",
"conversation_info.file_delete_confirm_title": "Datei löschen",
"conversation_info.file_delete_confirm_msg": "„{name}“ löschen?",
"conversation_info.file_delete_failed": "Datei konnte nicht gelöscht werden: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Jetzt senden",
"chat.queue_sending_now": "Wird gesendet…",
"chat.queue_send_now_failed": "Diese wartende Nachricht konnte jetzt nicht gesendet werden: {msg}",
- "chat.multi_dispatch_serial": "Nacheinander ausführen",
- "chat.multi_dispatch_parallel": "Gemeinsam ausführen",
- "chat.multi_dispatch_toggle_title": "Ausführungsweise der erwähnten Agenten für diese Nachricht; zum Wechseln klicken",
"chat.task_waiting_on": "Wartet auf {name}",
"chat.task_status_orchestrating": "Wird koordiniert",
"chat.task_dispatched": "Von Commander beauftragt",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Ausgewählte Nachrichten löschen (Anzahl: {count})? Dies kann nicht rückgängig gemacht werden.",
"chat.message_delete_failed": "Löschen fehlgeschlagen: {reason}",
"chat.reference_target_title": "Nachrichten als Referenz verwenden (Anzahl: {count}) in",
- "chat.reference_target_search": "Aufgaben suchen",
- "chat.reference_new_task": "Neue Aufgabe",
- "chat.reference_existing_tasks": "Vorhandene Aufgaben",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Neue Aufgabe…",
"chat.reference_area_project": "Projekt",
- "chat.reference_recent_tasks_hint": "5 neueste Aufgaben",
- "chat.reference_search_results_count": "Ergebnisse: {count}",
- "chat.reference_no_tasks": "Keine passenden Aufgaben",
"chat.reference_unknown_task": "Unbekannte Aufgabe",
"chat.reference_from_task": "Zitat aus „{title}“ @{name}",
"chat.reference_bundle_title": "Aus „{title}“",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Bilddienst hinzufügen",
"settings.models.add_video": "Videodienst hinzufügen",
"settings.models.add_tts": "Sprachdienst hinzufügen",
- "settings.models.order_hint": "Ziehen Sie Zeilen, um die Priorität zu ändern, oder verwenden Sie die Pfeiltasten. Deaktivierte offizielle Modelle werden übersprungen.",
+ "settings.models.order_hint": "Ziehen Sie Zeilen, um die Priorität zu ändern, oder verwenden Sie die Pfeiltasten. Deaktivierte integrierte Modelle werden übersprungen.",
"settings.general.page_sub": "Passen Sie Einstellungen und Agent-Berechtigungen an.",
"settings.general.preferences_title": "Voreinstellungen",
"settings.general.agent_title": "Agent-Verhalten",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Genehmigen",
"project.review.request_changes": "Änderungen anfordern",
"project.driver.toggle": "Auto",
- "project.driver.toggle_hint": "Die KI erledigt offene Aufgaben automatisch, damit Sie die Ergebnisse anschließend prüfen können.",
+ "project.driver.toggle_hint": "Die KI erledigt offene Aufgaben automatisch, damit Sie die Ergebnisse anschließend prüfen können. Die Ausführung erfolgt nur auf dem Gerät, auf dem Sie die Funktion einschalten.",
"project.driver.enabled_toast": "Automatischer Fortschritt aktiv: Regelmäßig wird eine offene Aufgabe ausgewählt und bearbeitet; sie wechselt zu In Bearbeitung.",
"project.driver.disabled_toast": "Automatischer Fortschritt deaktiviert.",
"project.recent_convs.view_all": "Alle anzeigen ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Einklappen",
"skills.source_external": "Paket",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "Diese Aktion auf der Seite erlauben?",
"chat.form.boolean_yes": "Ja",
"chat.form.boolean_no": "Nein",
"chat.form.invalid_number": "Geben Sie eine gültige Zahl ein",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Neu laden",
"quality.operator.disabled": "Auf diesem Gerät deaktiviert.",
"quality.operator.ready": "Bereit: {count} Regeln.",
- "quality.operator.invalid": "Validierung nicht verfügbar. Korrigieren Sie operator-policy.json oder deaktivieren Sie die benutzerdefinierte Validierung und versuchen Sie es erneut."
+ "quality.operator.invalid": "Validierung nicht verfügbar. Korrigieren Sie operator-policy.json oder deaktivieren Sie die benutzerdefinierte Validierung und versuchen Sie es erneut.",
+ "chat.app_nav_project_collaboration_target": "Projektmitglieder: {target}",
+ "new_chat.home.goal_title": "Klares Ziel? Übergeben Sie es dem Commander.",
+ "new_chat.home.goal_body": "Sagen Sie dem Commander, was Sie erreichen möchten – er koordiniert Ihr KI-Team, bis die Aufgabe erledigt ist.",
+ "new_chat.home.goal_example": "Zum Beispiel: 3 ähnliche Produkte recherchieren, Funktionen und Preise vergleichen und das Ergebnis als Präsentation aufbereiten.",
+ "new_chat.home.explore_title": "Noch unsicher? Lassen Sie Orkas Sie zuerst kennenlernen.",
+ "new_chat.home.explore_body": "Erzählen Sie von Ihrer Arbeit, Ihrem Geschäft oder Ihren Herausforderungen – Orkas hilft Ihnen, die richtigen Ziele zu finden und sie voranzubringen.",
+ "new_chat.home.explore_context": "Teilen Sie Dateien über + oder {connect}, damit Orkas mehr Hintergrund hat. Beginnen Sie mit dem, was Sie teilen möchten.",
+ "new_chat.home.explore_connect_link": "verbinden Sie Feishu / DingTalk / E-Mail",
+ "new_chat.home.input_placeholder": "Beschreiben Sie, was Sie erreichen möchten, oder hängen Sie die zu bearbeitenden Dateien an",
+ "new_chat.home.continue_label": "Bringen Sie Ihre Arbeit voran",
+ "new_chat.home.group.todos": "Wichtig zu erledigen",
+ "new_chat.home.group.automations": "Automatisierungen prüfen",
+ "new_chat.home.group.tasks": "Aufgaben warten auf Sie",
+ "new_chat.home.all_automations": "Alle Automatisierungen →",
+ "new_chat.home.expand": "{count} weitere anzeigen",
+ "new_chat.home.collapse": "Weniger anzeigen",
+ "new_chat.home.view_all_todos": "Alle anzeigen →",
+ "new_chat.home.source.project_todo": "{project} · Zu erledigen",
+ "new_chat.home.source.global_todo": "Global zu erledigen",
+ "new_chat.home.source.automation": "Automatisierung",
+ "new_chat.home.source.project_task": "{project} · Projektaufgabe",
+ "new_chat.home.source.global_task": "Globale Aufgabe",
+ "new_chat.home.result.completed": "Abgeschlossen",
+ "new_chat.home.result.failed": "Fehlgeschlagen",
+ "new_chat.home.result.waiting_input": "Wartet auf Sie",
+ "new_chat.home.result.stopped": "Gestoppt",
+ "new_chat.home.result.unknown": "Neues Ergebnis",
+ "new_chat.home.action.view": "Ansehen",
+ "new_chat.home.action.reply": "Antworten",
+ "new_chat.home.action.view_reason": "Ursache ansehen",
+ "new_chat.home.action.view_result": "Ergebnis ansehen",
+ "new_chat.home.time.updated": "Aktualisiert {time}",
+ "new_chat.home.untitled": "Unbenannte Aufgabe",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} aktualisiert",
+ "apps.save_root_folder_required": "Verschiebe die HTML-Datei und ihre Ressourcen in einen eigenen Ordner und speichere sie erneut als App.",
+ "chat.reference_locate_title": "Zur ursprünglichen Nachricht springen",
+ "chat.reference_locate_missing": "Die ursprüngliche Nachricht existiert nicht mehr.",
+ "agents.cli_usage_title": "Verbleibendes Kontingent",
+ "agents.cli_usage_unavailable": "Nicht verfügbar. CLI-Anmeldung und Verbindung prüfen.",
+ "agents.cli_usage_unsupported": "Diese CLI-Version oder benutzerdefinierte Konfiguration unterstützt keine Kontingentabfrage.",
+ "agents.cli_usage_resets": "Zurücksetzung: {time}",
+ "agents.cli_usage_hours": "{count} Stunden",
+ "agents.cli_usage_days": "{count} Tage",
+ "agents.cli_usage_window": "Nutzungszeitraum",
+ "memory.full_notice": "Der Speicher ist voll. Bevor die KI etwas Neues speichert, fasst sie vorhandene Einträge zusammen.",
+ "memory.error_full": "Der Speicher ist voll, daher kann dieser Eintrag gerade nicht hinzugefügt werden.",
+ "settings.recycle.clear": "Leeren",
+ "settings.recycle.clear_title": "Papierkorb leeren",
+ "settings.recycle.clear_confirm": "Alle {count} Einträge in „{source}“ endgültig löschen? Sie können danach nicht wiederhergestellt werden.",
+ "settings.recycle.clearing": "Leeren {done}/{total}…",
+ "settings.recycle.cleared": "Papierkorb geleert",
+ "settings.recycle.clear_failed": "Der Papierkorb konnte nicht vollständig geleert werden. Bitte erneut versuchen.",
+ "settings.recycle.automation_count": "Automatisierung · {count} Aufgaben",
+ "project.todo.move": "Verschieben",
+ "bash.permission.allow_folder_read": "Lesen dieses Ordners erlauben",
+ "bash.permission.folder_read_scope": "In dieser Aufgabe darf {agent} Dateien in {folder} ohne erneute Nachfrage lesen. Schreiben, Löschen und geheime Dateien werden weiterhin abgefragt.",
+ "cli_upgrade.action": "CLI aktualisieren",
+ "cli_upgrade.pending": "Aktualisierung…",
+ "cli_upgrade.success": "Aktualisierung erfolgreich",
+ "cli_upgrade.failed": "Aktualisierung fehlgeschlagen",
+ "cli_upgrade.named_action": "{cli} CLI aktualisieren",
+ "web_assist.handback": "Steuerung an KI zurückgeben",
+ "web_assist.permissions": "Website-Berechtigungen zurücksetzen",
+ "web_assist.permission_title": "Website-Berechtigung",
+ "web_assist.permission_allow": "Erlauben",
+ "web_assist.permission_deny": "Ablehnen",
+ "web_assist.permission_failed": "Ihre Auswahl konnte nicht gespeichert werden. Versuchen Sie es erneut.",
+ "apps.view_details": "Details anzeigen",
+ "apps.no_local_code": "Kein Anwendungscode auf diesem Gerät",
+ "apps.publish_commercial": "Verwenden Sie die kommerzielle Orkas-Version zum Veröffentlichen.",
+ "apps.update_original": "Original-App aktualisieren",
+ "apps.save_new": "Neue App speichern",
+ "apps.edit_conflict": "Die ursprüngliche App wurde geändert oder gelöscht. Erneut bearbeiten oder als neue App speichern.",
+ "apps.save_type_mismatch": "Diese Version hat einen anderen App-Typ als die ursprüngliche App und kann sie nicht ersetzen. Speichern Sie sie stattdessen als neue App.",
+ "apps.type_local": "Lokale App",
+ "apps.type_web": "Web-App",
+ "apps.type_local_description": "Läuft in Orkas auf dem Desktop mit Zugriff auf KI, Dateien, Bibliothek und Konnektoren; kann nicht im Web veröffentlicht werden.",
+ "apps.type_web_description": "Im Web veröffentlichen und per Link öffnen, mit Datenerfassung, Abfragen und Statistiken; Orkas-Desktop-Funktionen sind nicht verfügbar.",
+ "apps.delete_data_confirm": "„{name}“ sowie lokale Datensätze und private Dateien löschen? Die Daten sind nicht wiederherstellbar.",
+ "apps.delete_online_retained": "Die veröffentlichte App und Onlinedaten bleiben erhalten.",
+ "apps.migration_export": "Die Datenstruktur ändert sich. Exportieren Sie lokale Einträge vor dem Löschen.",
+ "apps.migration_export_action": "Einträge exportieren",
+ "apps.migration_continue": "Weiter",
+ "apps.migration_clear": "Alle lokalen Einträge löschen und aktualisieren? Online-Einträge bleiben unabhängig.",
+ "apps.migration_retry": "Löschen und wiederholen",
+ "chat.reference_scope_label": "Aufgabenbereich",
+ "chat.reference_scope_all": "Alle Aufgaben",
+ "chat.reference_scope_global": "Global (ohne Projekt)",
+ "chat.reference_new_in_global": "Neue Aufgabe in Global",
+ "chat.reference_new_in_project": "Neue Aufgabe in „{name}“",
+ "chat.reference_search_all": "Alle Aufgaben durchsuchen",
+ "chat.reference_search_in": "Aufgaben in „{name}“ durchsuchen",
+ "chat.reference_count_all": "{count} insgesamt · zuletzt aktiv zuerst",
+ "chat.reference_count_found": "{count} gefunden · zuletzt aktiv zuerst",
+ "chat.reference_load_more": "Ältere Aufgaben laden (noch {count})",
+ "chat.reference_no_match": "Keine passenden Aufgaben",
+ "chat.reference_no_match_hint": "Versuchen Sie ein anderes Stichwort oder wählen Sie links einen anderen Bereich.",
+ "chat.reference_scope_empty": "Hier gibt es noch keine Aufgaben",
+ "chat.reference_scope_empty_hint": "Über die Schaltfläche oben können Sie hier eine neue Aufgabe anlegen.",
+ "chat.reference_create_back": "Zurück zur Aufgabenliste",
+ "chat.reference_create_title": "Wo soll die neue Aufgabe entstehen?",
+ "chat.reference_create_desc": "Nach der Auswahl werden die Referenzen eingefügt. Es wird nichts automatisch gesendet.",
+ "chat.reference_create_global_desc": "Keinem Projekt zugeordnet",
+ "chat.reference_create_project_desc": "Neue Aufgabe in diesem Projekt anlegen",
+ "chat.reference_target_footer": "Nach der Auswahl werden die Referenzen in das Eingabefeld der Aufgabe eingefügt. Es wird nichts automatisch gesendet.",
+ "project.todo.run_busy": "Die Unterhaltung dieser Aufgabe läuft noch. Führe sie erneut aus, sobald sie fertig ist.",
+ "settings.cleanup.title": "Alte Aufgaben bereinigen",
+ "settings.cleanup.age": "Zuletzt aktiv",
+ "settings.cleanup.scope": "Abgeschlossene Aufgaben innerhalb und außerhalb von Projekten. Angeheftete und ungelesene Aufgaben, Entwürfe und Automatisierungsläufe bleiben erhalten.",
+ "settings.cleanup.days": "Vor mehr als {n} Tagen",
+ "settings.cleanup.result": "Im Papierkorb: {deleted}. Übersprungen: {skipped}. Fehlgeschlagen: {failed}.",
+ "settings.cleanup.progress": "Bereinigung {done} / {total}",
+ "settings.cleanup.error": "Aufgaben konnten nicht geladen oder bereinigt werden. Aktualisieren Sie die Ansicht und versuchen Sie es erneut.",
+ "settings.cleanup.count": "{n} Aufgaben ausgewählt",
+ "settings.cleanup.empty": "Keine alten Aufgaben zum Bereinigen.",
+ "settings.cleanup.clean": "Bereinigen",
+ "settings.cleanup.confirm": "{n} Aufgaben mit Anhängen und eingebetteten Ergebnissen in den Papierkorb verschieben. Sie können sie unten wiederherstellen. Bei aktivierter Synchronisierung werden sie auch auf anderen Geräten gelöscht. Speicherplatz wird erst beim Leeren des Papierkorbs frei.",
+ "settings.cleanup.move": "In den Papierkorb ({n})",
+ "settings.cleanup.previous": "Zurück",
+ "settings.cleanup.next": "Weiter",
+ "apps.commercial_required": "Web-Apps erfordern die kommerzielle Version von Orkas. Laden Sie sie herunter, um fortzufahren.",
+ "apps.commercial_download": "Kommerzielle Version herunterladen",
+ "apps.commercial_open_failed": "Die Downloadseite konnte nicht geöffnet werden. Bitte versuchen Sie es erneut."
}
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index cbf577c9..f59b28d9 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Download",
"web_assist.activity_visit": "Visit",
"web_assist.download_saved": "saved to attachments",
- "web_assist.download_needs_grant": "needs permission",
- "web_assist.download_blocked_type": "file type not allowed",
- "web_assist.download_budget": "task download limit reached",
"web_assist.download_failed": "failed",
"web_assist.download_unavailable": "File unavailable. Check that the download finished and the file has not been moved or deleted.",
- "web_assist.download_allow": "Allow this site",
- "web_assist.download_prompt_title": "Allow downloads from this site?",
- "web_assist.download_prompt_description": "Files will be saved to this task’s attachments. After allowing, return to the page and retry the download.",
- "web_assist.download_not_now": "Not now",
- "web_assist.download_permission_failed": "Could not allow this site. Try again.",
"web_assist.address_placeholder": "Search Bing or enter a URL",
"web_assist.empty_title": "Browse in this task",
"web_assist.empty_hint": "Search Bing or enter a URL above.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Last 30 days",
"sidebar.bucket.older": "Older",
"sidebar.projects": "Projects",
- "sidebar.today_tasks": "Today's Tasks",
- "sidebar.today_empty": "No tasks today",
+ "sidebar.today_tasks": "Recent Tasks",
+ "sidebar.today_empty": "No tasks in the last two days",
"sidebar.section_collapse": "Collapse {section}",
"sidebar.section_expand": "Expand {section}",
"sidebar.project_create_title": "New project",
"sidebar.project_create_placeholder": "Enter project name",
"sidebar.project_conv_empty": "(no tasks)",
- "sidebar.load_more_conversations": "Load more",
+ "sidebar.load_more_conversations": "Show more",
"sidebar.connect_agent": "Connect agents",
"sidebar.connect_agent_sub": "Claude Code · Codex & more",
"sidebar.settings": "Settings",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Loading…",
"new_chat.model_picker.aria_label": "Choose model",
"new_chat.model_picker.empty": "No available models",
- "new_chat.model_picker.group_official": "Official models",
- "new_chat.model_picker.group_custom": "User-configured models",
+ "new_chat.model_picker.group_official": "Orkas built-in models",
+ "new_chat.model_picker.group_custom": "Bring your own API Key",
"new_chat.model_picker.configure": "Configure models",
"new_chat.model_picker.switch_failed": "Could not switch models. Try again.",
"new_chat.model_picker.choose_version": "Choose a model version for {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Added to {library}",
"conversation_info.file_add_to_library_failed": "Add to Library failed: {reason}",
"conversation_info.file_add_to_chat_action": "Add to task chat",
- "conversation_info.file_reveal_failed": "Could not open folder: {reason}",
+ "conversation_info.file_reveal_failed": "Could not open the folder. The file may have been moved or deleted.",
"conversation_info.file_delete_confirm_title": "Delete file",
"conversation_info.file_delete_confirm_msg": "Delete \"{name}\"?",
"conversation_info.file_delete_failed": "Could not delete file: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Send now",
"chat.queue_sending_now": "Sending…",
"chat.queue_send_now_failed": "Could not send this queued message now: {msg}",
- "chat.multi_dispatch_serial": "Run in order",
- "chat.multi_dispatch_parallel": "Run together",
- "chat.multi_dispatch_toggle_title": "How the mentioned agents run for this message; click to switch",
"chat.task_waiting_on": "Waiting on {name}",
"chat.task_status_orchestrating": "Orchestrating",
"chat.task_dispatched": "Dispatched by Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Delete the selected {count} messages? This cannot be undone.",
"chat.message_delete_failed": "Delete failed: {reason}",
"chat.reference_target_title": "Reference {count} messages in",
- "chat.reference_target_search": "Search tasks",
- "chat.reference_new_task": "New task",
- "chat.reference_existing_tasks": "Existing tasks",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "New task…",
"chat.reference_area_project": "Project",
- "chat.reference_recent_tasks_hint": "5 most recent tasks",
- "chat.reference_search_results_count": "{count} results",
- "chat.reference_no_tasks": "No matching tasks",
"chat.reference_unknown_task": "Unknown task",
"chat.reference_from_task": "Quoted from “{title}” @{name}",
"chat.reference_bundle_title": "From “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Add image service",
"settings.models.add_video": "Add video service",
"settings.models.add_tts": "Add speech service",
- "settings.models.order_hint": "Drag rows to change priority, or use the arrow buttons. Disabled official models are skipped.",
+ "settings.models.order_hint": "Drag rows to change priority, or use the arrow buttons. Disabled built-in models are skipped.",
"settings.general.page_sub": "Adjust preferences and agent permissions.",
"settings.general.preferences_title": "Preferences",
"settings.general.agent_title": "Agent behavior",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Approve",
"project.review.request_changes": "Request changes",
"project.driver.toggle": "Auto",
- "project.driver.toggle_hint": "AI handles to-dos automatically for you to review when finished.",
+ "project.driver.toggle_hint": "AI handles to-dos automatically for you to review when finished. Runs only on the device where you turn it on.",
"project.driver.enabled_toast": "Auto-advance on — it periodically picks a backlog task and works it; tasks move to In progress.",
"project.driver.disabled_toast": "Auto-advance off.",
"project.recent_convs.view_all": "View all ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Collapse",
"skills.source_external": "Package",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "Allow this action on the page?",
"chat.form.boolean_yes": "Yes",
"chat.form.boolean_no": "No",
"chat.form.invalid_number": "Enter a valid number",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Reload",
"quality.operator.disabled": "Disabled on this device.",
"quality.operator.ready": "Ready: {count} rules.",
- "quality.operator.invalid": "Validation unavailable. Fix operator-policy.json or turn off custom validation, then retry."
+ "quality.operator.invalid": "Validation unavailable. Fix operator-policy.json or turn off custom validation, then retry.",
+ "chat.app_nav_project_collaboration_target": "Project members: {target}",
+ "new_chat.home.goal_title": "Have a clear goal? Hand it to Commander.",
+ "new_chat.home.goal_body": "Tell Commander what you want to accomplish, and it will coordinate your AI team to get it done.",
+ "new_chat.home.goal_example": "For example: research 3 similar products, compare their features and pricing, and turn the findings into a presentation.",
+ "new_chat.home.explore_title": "Not sure yet? Let Orkas get to know you first.",
+ "new_chat.home.explore_body": "Talk about your work, your business, or what's on your mind, and Orkas will help you find the right goals and keep them moving.",
+ "new_chat.home.explore_context": "Share files with +, or {connect}, to give Orkas more background. Start with whatever you're comfortable sharing.",
+ "new_chat.home.explore_connect_link": "connect Feishu / DingTalk / email",
+ "new_chat.home.input_placeholder": "Describe what you want to accomplish, or attach the files to work on",
+ "new_chat.home.continue_label": "Keep things moving",
+ "new_chat.home.group.todos": "Important to-dos",
+ "new_chat.home.group.automations": "Automation results",
+ "new_chat.home.group.tasks": "Tasks waiting on you",
+ "new_chat.home.all_automations": "All automations →",
+ "new_chat.home.expand": "Show {count} more",
+ "new_chat.home.collapse": "Show less",
+ "new_chat.home.view_all_todos": "View all →",
+ "new_chat.home.source.project_todo": "{project} · To-do",
+ "new_chat.home.source.global_todo": "Global to-do",
+ "new_chat.home.source.automation": "Automation",
+ "new_chat.home.source.project_task": "{project} · Project task",
+ "new_chat.home.source.global_task": "Global task",
+ "new_chat.home.result.completed": "Completed",
+ "new_chat.home.result.failed": "Failed",
+ "new_chat.home.result.waiting_input": "Needs your input",
+ "new_chat.home.result.stopped": "Stopped",
+ "new_chat.home.result.unknown": "New result",
+ "new_chat.home.action.view": "View",
+ "new_chat.home.action.reply": "Reply",
+ "new_chat.home.action.view_reason": "See why",
+ "new_chat.home.action.view_result": "View result",
+ "new_chat.home.time.updated": "Updated {time}",
+ "new_chat.home.untitled": "Untitled task",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "Updated {name}",
+ "apps.save_root_folder_required": "Move the HTML and its resources into a separate folder, then save as an app again.",
+ "chat.reference_locate_title": "Go to the original message",
+ "chat.reference_locate_missing": "The original message no longer exists.",
+ "agents.cli_usage_title": "Remaining allowance",
+ "agents.cli_usage_unavailable": "Unavailable. Check your CLI sign-in and connection.",
+ "agents.cli_usage_unsupported": "Allowance lookup is not supported by this CLI version or custom configuration.",
+ "agents.cli_usage_resets": "Resets {time}",
+ "agents.cli_usage_hours": "{count} hours",
+ "agents.cli_usage_days": "{count} days",
+ "agents.cli_usage_window": "Usage window",
+ "memory.full_notice": "Memory is full. Before saving something new, the AI will merge existing entries.",
+ "memory.error_full": "Memory is full, so this entry can't be added right now.",
+ "settings.recycle.clear": "Empty",
+ "settings.recycle.clear_title": "Empty Recycle Bin",
+ "settings.recycle.clear_confirm": "Permanently delete all {count} records in {source}? They cannot be restored afterward.",
+ "settings.recycle.clearing": "Emptying {done}/{total}…",
+ "settings.recycle.cleared": "Recycle bin emptied",
+ "settings.recycle.clear_failed": "Could not finish emptying the recycle bin. Please try again.",
+ "settings.recycle.automation_count": "Automation · {count} tasks",
+ "project.todo.move": "Move",
+ "bash.permission.allow_folder_read": "Allow reading this folder",
+ "bash.permission.folder_read_scope": "For this task, {agent} can read files in {folder} without asking again. Writing, deleting and secret files still ask.",
+ "cli_upgrade.action": "Upgrade CLI",
+ "cli_upgrade.pending": "Upgrading…",
+ "cli_upgrade.success": "Upgrade successful",
+ "cli_upgrade.failed": "Upgrade failed",
+ "cli_upgrade.named_action": "Upgrade {cli} CLI",
+ "web_assist.handback": "Let AI continue",
+ "web_assist.permissions": "Reset site permissions",
+ "web_assist.permission_title": "Website permission",
+ "web_assist.permission_allow": "Allow",
+ "web_assist.permission_deny": "Deny",
+ "web_assist.permission_failed": "Could not save your choice. Try again.",
+ "apps.view_details": "View details",
+ "apps.no_local_code": "No app code on this device",
+ "apps.publish_commercial": "Use the commercial version of Orkas to publish apps.",
+ "apps.update_original": "Update original app",
+ "apps.save_new": "Save new app",
+ "apps.edit_conflict": "The original app changed or was deleted. Reopen it to edit, or save a new app.",
+ "apps.save_type_mismatch": "This version is a different app type from the original app, so it can’t replace it. Save it as a new app instead.",
+ "apps.type_local": "Local app",
+ "apps.type_web": "Web app",
+ "apps.type_local_description": "Runs in Orkas desktop with access to AI, files, the library and connectors; cannot be published to the web.",
+ "apps.type_web_description": "Publish to the web and access via a link, with data collection, queries and statistics; Orkas desktop capabilities are unavailable.",
+ "apps.delete_data_confirm": "Delete \"{name}\" and its local records and private files? Data cannot be recovered.",
+ "apps.delete_online_retained": "The published app and online data are retained.",
+ "apps.migration_export": "The update changes the data structure. Export local records before clearing.",
+ "apps.migration_export_action": "Export records",
+ "apps.migration_continue": "Continue",
+ "apps.migration_clear": "Clear all local records and apply this update? Online records stay independent.",
+ "apps.migration_retry": "Clear and retry",
+ "chat.reference_scope_label": "Task scope",
+ "chat.reference_scope_all": "All tasks",
+ "chat.reference_scope_global": "Global (no project)",
+ "chat.reference_new_in_global": "New task in Global",
+ "chat.reference_new_in_project": "New task in “{name}”",
+ "chat.reference_search_all": "Search all tasks",
+ "chat.reference_search_in": "Search tasks in “{name}”",
+ "chat.reference_count_all": "{count} total · most recent first",
+ "chat.reference_count_found": "{count} found · most recent first",
+ "chat.reference_load_more": "Load earlier tasks ({count} more)",
+ "chat.reference_no_match": "No matching tasks",
+ "chat.reference_no_match_hint": "Try another keyword, or pick a different scope on the left.",
+ "chat.reference_scope_empty": "No tasks here yet",
+ "chat.reference_scope_empty_hint": "Use the button above to start a new task here.",
+ "chat.reference_create_back": "Back to tasks",
+ "chat.reference_create_title": "Where should the new task go?",
+ "chat.reference_create_desc": "The references are added once you choose. Nothing is sent automatically.",
+ "chat.reference_create_global_desc": "Not part of any project",
+ "chat.reference_create_project_desc": "Start a new task in this project",
+ "chat.reference_target_footer": "Your choice opens that task’s input with the references added. Nothing is sent automatically.",
+ "project.todo.run_busy": "This to-do's conversation is still working. Run it again once it finishes.",
+ "settings.cleanup.title": "Clean up task history",
+ "settings.cleanup.age": "Last active",
+ "settings.cleanup.scope": "Completed tasks inside and outside projects. Pinned and unread tasks, drafts, and automation runs are kept.",
+ "settings.cleanup.days": "Over {n} days ago",
+ "settings.cleanup.result": "Moved to recycle bin: {deleted}. Skipped: {skipped}. Failed: {failed}.",
+ "settings.cleanup.progress": "Cleaning {done} / {total}",
+ "settings.cleanup.error": "Could not finish loading or cleaning tasks. Refresh and try again.",
+ "settings.cleanup.count": "Selected tasks: {n}",
+ "settings.cleanup.empty": "No historical tasks to clean up.",
+ "settings.cleanup.clean": "Clean up",
+ "settings.cleanup.confirm": "Move the selected tasks ({n}), their attachments and embedded results to the recycle bin. You can restore them below. With sync enabled, deletion also applies to other devices. Disk space is not freed until the recycle bin is emptied.",
+ "settings.cleanup.move": "Move to recycle bin ({n})",
+ "settings.cleanup.previous": "Previous",
+ "settings.cleanup.next": "Next",
+ "apps.commercial_required": "Web apps require the commercial version of Orkas. Download it to continue.",
+ "apps.commercial_download": "Download commercial version",
+ "apps.commercial_open_failed": "Could not open the download page. Please try again."
}
diff --git a/src/renderer/locales/es-419.json b/src/renderer/locales/es-419.json
index e248e763..a1f0927f 100644
--- a/src/renderer/locales/es-419.json
+++ b/src/renderer/locales/es-419.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Descarga",
"web_assist.activity_visit": "Visita",
"web_assist.download_saved": "guardado en adjuntos",
- "web_assist.download_needs_grant": "requiere permiso",
- "web_assist.download_blocked_type": "tipo de archivo no permitido",
- "web_assist.download_budget": "se alcanzó el límite de descargas de la tarea",
"web_assist.download_failed": "falló",
"web_assist.download_unavailable": "Archivo no disponible. Verifica que la descarga haya terminado y que el archivo no se haya movido ni eliminado.",
- "web_assist.download_allow": "Permitir este sitio",
- "web_assist.download_prompt_title": "¿Permitir descargas de este sitio?",
- "web_assist.download_prompt_description": "Los archivos se guardarán en los adjuntos de esta tarea. Tras permitirlas, vuelve a la página y reintenta la descarga.",
- "web_assist.download_not_now": "Ahora no",
- "web_assist.download_permission_failed": "No se pudo permitir este sitio. Inténtalo de nuevo.",
"web_assist.address_placeholder": "Buscar en Bing o ingresar una URL",
"web_assist.empty_title": "Navega en esta tarea",
"web_assist.empty_hint": "Busca en Bing o ingresa una URL arriba.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Últimos 30 días",
"sidebar.bucket.older": "Anteriores",
"sidebar.projects": "Proyectos",
- "sidebar.today_tasks": "Tareas de hoy",
- "sidebar.today_empty": "No hay tareas hoy",
+ "sidebar.today_tasks": "Tareas recientes",
+ "sidebar.today_empty": "No hay tareas en los últimos dos días",
"sidebar.section_collapse": "Contraer {section}",
"sidebar.section_expand": "Expandir {section}",
"sidebar.project_create_title": "Nuevo proyecto",
"sidebar.project_create_placeholder": "Ingresa el nombre del proyecto",
"sidebar.project_conv_empty": "(sin tareas)",
- "sidebar.load_more_conversations": "Cargar más",
+ "sidebar.load_more_conversations": "Mostrar más",
"sidebar.connect_agent": "Conectar agentes",
"sidebar.connect_agent_sub": "Claude Code · Codex y más",
"sidebar.settings": "Configuración",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Cargando…",
"new_chat.model_picker.aria_label": "Elegir modelo",
"new_chat.model_picker.empty": "No hay modelos disponibles",
- "new_chat.model_picker.group_official": "Modelos oficiales",
- "new_chat.model_picker.group_custom": "Modelos configurados por el usuario",
+ "new_chat.model_picker.group_official": "Modelos integrados de Orkas",
+ "new_chat.model_picker.group_custom": "Tu propia API Key",
"new_chat.model_picker.configure": "Configurar modelos",
"new_chat.model_picker.switch_failed": "No se pudo cambiar de modelo. Inténtalo de nuevo.",
"new_chat.model_picker.choose_version": "Elegir una versión del modelo para {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Agregado a {library}",
"conversation_info.file_add_to_library_failed": "Error al agregar a la biblioteca: {reason}",
"conversation_info.file_add_to_chat_action": "Agregar al chat de la tarea",
- "conversation_info.file_reveal_failed": "No se pudo abrir la carpeta: {reason}",
+ "conversation_info.file_reveal_failed": "No se pudo abrir la carpeta. Es posible que el archivo se haya movido o eliminado.",
"conversation_info.file_delete_confirm_title": "Eliminar archivo",
"conversation_info.file_delete_confirm_msg": "¿Eliminar \"{name}\"?",
"conversation_info.file_delete_failed": "No se pudo eliminar el archivo: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Enviar ahora",
"chat.queue_sending_now": "Enviando…",
"chat.queue_send_now_failed": "No se pudo enviar ahora este mensaje en cola: {msg}",
- "chat.multi_dispatch_serial": "Ejecutar en orden",
- "chat.multi_dispatch_parallel": "Ejecutar juntos",
- "chat.multi_dispatch_toggle_title": "Cómo se ejecutan los agentes mencionados para este mensaje; haz clic para cambiar",
"chat.task_waiting_on": "Esperando a {name}",
"chat.task_status_orchestrating": "Coordinando",
"chat.task_dispatched": "Asignada por Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "¿Eliminar los mensajes seleccionados (total: {count})? Esta acción no se puede deshacer.",
"chat.message_delete_failed": "Error al eliminar: {reason}",
"chat.reference_target_title": "Referenciar mensajes ({count}) en",
- "chat.reference_target_search": "Buscar tareas",
- "chat.reference_new_task": "Nueva tarea",
- "chat.reference_existing_tasks": "Tareas existentes",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nueva tarea…",
"chat.reference_area_project": "Proyecto",
- "chat.reference_recent_tasks_hint": "Las 5 tareas más recientes",
- "chat.reference_search_results_count": "Resultados: {count}",
- "chat.reference_no_tasks": "No hay tareas coincidentes",
"chat.reference_unknown_task": "Tarea desconocida",
"chat.reference_from_task": "Cita de “{title}” @{name}",
"chat.reference_bundle_title": "De “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Agregar servicio de imágenes",
"settings.models.add_video": "Agregar servicio de video",
"settings.models.add_tts": "Agregar servicio de voz",
- "settings.models.order_hint": "Arrastra las filas para cambiar la prioridad o usa los botones de flecha. Los modelos oficiales desactivados se omiten.",
+ "settings.models.order_hint": "Arrastra las filas para cambiar la prioridad o usa los botones de flecha. Los modelos integrados desactivados se omiten.",
"settings.general.page_sub": "Ajusta las preferencias, los permisos de agentes y las actualizaciones de la aplicación.",
"settings.general.preferences_title": "Preferencias",
"settings.general.agent_title": "Comportamiento de los agentes",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Aprobar",
"project.review.request_changes": "Solicitar cambios",
"project.driver.toggle": "Automático",
- "project.driver.toggle_hint": "La IA atiende automáticamente las tareas pendientes para que las revises al terminar.",
+ "project.driver.toggle_hint": "La IA atiende automáticamente las tareas pendientes para que las revises al terminar. Solo se ejecuta en el dispositivo donde la activas.",
"project.driver.enabled_toast": "Avance automático activado: elige periódicamente una tarea pendiente y trabaja en ella; las tareas pasan a En curso.",
"project.driver.disabled_toast": "Avance automático desactivado.",
"project.recent_convs.view_all": "Ver todo ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Contraer",
"skills.source_external": "Paquete",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "¿Permitir esta acción en la página?",
"chat.form.boolean_yes": "Sí",
"chat.form.boolean_no": "No",
"chat.form.invalid_number": "Ingresa un número válido",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Recargar",
"quality.operator.disabled": "Desactivada en este dispositivo.",
"quality.operator.ready": "Lista: {count} reglas.",
- "quality.operator.invalid": "Validación no disponible. Corrige operator-policy.json o desactiva la validación personalizada y vuelve a intentarlo."
+ "quality.operator.invalid": "Validación no disponible. Corrige operator-policy.json o desactiva la validación personalizada y vuelve a intentarlo.",
+ "chat.app_nav_project_collaboration_target": "Miembros del proyecto: {target}",
+ "new_chat.home.goal_title": "¿Tienes un objetivo claro? Déjalo en manos del Commander.",
+ "new_chat.home.goal_body": "Dile al Commander qué quieres conseguir y coordinará a tu equipo de IA para lograrlo.",
+ "new_chat.home.goal_example": "Por ejemplo: investiga 3 productos similares, compara sus funciones y precios y resúmelo en una presentación.",
+ "new_chat.home.explore_title": "¿Todavía no lo tienes claro? Deja que Orkas te conozca primero.",
+ "new_chat.home.explore_body": "Habla de tu trabajo, tu negocio o tus dificultades, y Orkas te ayudará a encontrar los objetivos adecuados y a avanzar en ellos.",
+ "new_chat.home.explore_context": "Comparte archivos con + o {connect} para darle más contexto a Orkas. Empieza por lo que te sientas cómodo compartiendo.",
+ "new_chat.home.explore_connect_link": "conecta Feishu / DingTalk / tu correo",
+ "new_chat.home.input_placeholder": "Describe lo que quieres conseguir o adjunta los archivos que hay que procesar",
+ "new_chat.home.continue_label": "Sigue avanzando",
+ "new_chat.home.group.todos": "Pendientes importantes",
+ "new_chat.home.group.automations": "Automatizaciones por revisar",
+ "new_chat.home.group.tasks": "Tareas que te esperan",
+ "new_chat.home.all_automations": "Todas las automatizaciones →",
+ "new_chat.home.expand": "Mostrar {count} más",
+ "new_chat.home.collapse": "Mostrar menos",
+ "new_chat.home.view_all_todos": "Ver todo →",
+ "new_chat.home.source.project_todo": "{project} · Pendiente",
+ "new_chat.home.source.global_todo": "Pendiente global",
+ "new_chat.home.source.automation": "Automatización",
+ "new_chat.home.source.project_task": "{project} · Tarea del proyecto",
+ "new_chat.home.source.global_task": "Tarea global",
+ "new_chat.home.result.completed": "Completada",
+ "new_chat.home.result.failed": "Fallida",
+ "new_chat.home.result.waiting_input": "Espera tu respuesta",
+ "new_chat.home.result.stopped": "Detenida",
+ "new_chat.home.result.unknown": "Nuevo resultado",
+ "new_chat.home.action.view": "Ver",
+ "new_chat.home.action.reply": "Responder",
+ "new_chat.home.action.view_reason": "Ver el motivo",
+ "new_chat.home.action.view_result": "Ver resultado",
+ "new_chat.home.time.updated": "Actualizado {time}",
+ "new_chat.home.untitled": "Tarea sin título",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} actualizado",
+ "apps.save_root_folder_required": "Mueve el HTML y sus recursos a una carpeta aparte y vuelve a guardar como aplicación.",
+ "chat.reference_locate_title": "Ir al mensaje original",
+ "chat.reference_locate_missing": "El mensaje original ya no existe.",
+ "agents.cli_usage_title": "Cuota restante",
+ "agents.cli_usage_unavailable": "No disponible. Revisa el inicio de sesión de la CLI y la conexión.",
+ "agents.cli_usage_unsupported": "Esta versión de la CLI o configuración personalizada no permite consultar la cuota.",
+ "agents.cli_usage_resets": "Se restablece: {time}",
+ "agents.cli_usage_hours": "{count} horas",
+ "agents.cli_usage_days": "{count} días",
+ "agents.cli_usage_window": "Período de uso",
+ "memory.full_notice": "La memoria está llena. Antes de guardar algo nuevo, la IA combinará las entradas existentes.",
+ "memory.error_full": "La memoria está llena, así que esta entrada no se puede agregar ahora.",
+ "settings.recycle.clear": "Vaciar",
+ "settings.recycle.clear_title": "Vaciar la papelera",
+ "settings.recycle.clear_confirm": "¿Eliminar permanentemente los {count} registros de {source}? No podrán restaurarse después.",
+ "settings.recycle.clearing": "Vaciando {done}/{total}…",
+ "settings.recycle.cleared": "Papelera vaciada",
+ "settings.recycle.clear_failed": "No se pudo vaciar toda la papelera. Inténtalo de nuevo.",
+ "settings.recycle.automation_count": "Automatización · {count} tareas",
+ "project.todo.move": "Mover",
+ "bash.permission.allow_folder_read": "Permitir leer esta carpeta",
+ "bash.permission.folder_read_scope": "Durante esta tarea, {agent} puede leer archivos de {folder} sin volver a preguntar. Escribir, eliminar y los archivos secretos seguirán pidiendo confirmación.",
+ "cli_upgrade.action": "Actualizar CLI",
+ "cli_upgrade.pending": "Actualizando…",
+ "cli_upgrade.success": "Actualización completada",
+ "cli_upgrade.failed": "Error al actualizar",
+ "cli_upgrade.named_action": "Actualizar {cli} CLI",
+ "web_assist.handback": "Devolver el control a la IA",
+ "web_assist.permissions": "Restablecer permisos del sitio",
+ "web_assist.permission_title": "Permiso del sitio",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Denegar",
+ "web_assist.permission_failed": "No se pudo guardar tu elección. Inténtalo de nuevo.",
+ "apps.view_details": "Ver detalles",
+ "apps.no_local_code": "No hay código de la aplicación en este dispositivo",
+ "apps.publish_commercial": "Usa la versión comercial de Orkas para publicar.",
+ "apps.update_original": "Actualizar aplicación original",
+ "apps.save_new": "Guardar nueva aplicación",
+ "apps.edit_conflict": "La aplicación original cambió o se eliminó. Vuelve a editarla o guarda una nueva.",
+ "apps.save_type_mismatch": "Esta versión es de un tipo distinto al de la aplicación original y no puede reemplazarla. Guárdala como una nueva aplicación.",
+ "apps.type_local": "Aplicación local",
+ "apps.type_web": "Aplicación web",
+ "apps.type_local_description": "Se ejecuta en Orkas para escritorio con acceso a IA, archivos, biblioteca y conectores; no se puede publicar en la web.",
+ "apps.type_web_description": "Publica en la web y accede mediante un enlace, con recopilación, consultas y estadísticas de datos; las funciones de Orkas para escritorio no están disponibles.",
+ "apps.delete_data_confirm": "¿Eliminar \"{name}\", sus registros locales y archivos privados? Los datos no se pueden recuperar.",
+ "apps.delete_online_retained": "La aplicación publicada y sus datos en línea se conservan.",
+ "apps.migration_export": "Cambia la estructura de los datos. Exporta los registros locales antes de borrarlos.",
+ "apps.migration_export_action": "Exportar registros",
+ "apps.migration_continue": "Continuar",
+ "apps.migration_clear": "¿Borrar todos los registros locales y actualizar? Los registros en línea son independientes.",
+ "apps.migration_retry": "Borrar y reintentar",
+ "chat.reference_scope_label": "Ámbito de tareas",
+ "chat.reference_scope_all": "Todas las tareas",
+ "chat.reference_scope_global": "Global (sin proyecto)",
+ "chat.reference_new_in_global": "Nueva tarea en Global",
+ "chat.reference_new_in_project": "Nueva tarea en “{name}”",
+ "chat.reference_search_all": "Buscar en todas las tareas",
+ "chat.reference_search_in": "Buscar tareas en “{name}”",
+ "chat.reference_count_all": "{count} en total · más recientes primero",
+ "chat.reference_count_found": "{count} encontradas · más recientes primero",
+ "chat.reference_load_more": "Cargar tareas anteriores (quedan {count})",
+ "chat.reference_no_match": "No hay tareas coincidentes",
+ "chat.reference_no_match_hint": "Prueba con otra palabra clave o elige otro ámbito a la izquierda.",
+ "chat.reference_scope_empty": "Aún no hay tareas aquí",
+ "chat.reference_scope_empty_hint": "Usa el botón de arriba para iniciar una tarea aquí.",
+ "chat.reference_create_back": "Volver a las tareas",
+ "chat.reference_create_title": "¿Dónde quieres crear la nueva tarea?",
+ "chat.reference_create_desc": "Las referencias se agregan al elegir el destino. No se envía nada automáticamente.",
+ "chat.reference_create_global_desc": "No pertenece a ningún proyecto",
+ "chat.reference_create_project_desc": "Iniciar una tarea en este proyecto",
+ "chat.reference_target_footer": "Al elegir, se abre el cuadro de entrada de la tarea con las referencias agregadas. No se envía nada automáticamente.",
+ "project.todo.run_busy": "La conversación de esta tarea todavía está en curso. Vuelve a ejecutarla cuando termine.",
+ "settings.cleanup.title": "Limpiar tareas antiguas",
+ "settings.cleanup.age": "Última actividad",
+ "settings.cleanup.scope": "Tareas completadas dentro y fuera de proyectos. Se conservan las fijadas, no leídas, los borradores y las ejecuciones automatizadas.",
+ "settings.cleanup.days": "Hace más de {n} días",
+ "settings.cleanup.result": "En la papelera: {deleted}. Omitidas: {skipped}. Fallidas: {failed}.",
+ "settings.cleanup.progress": "Limpiando {done} / {total}",
+ "settings.cleanup.error": "No se pudieron cargar o limpiar las tareas. Actualiza e inténtalo de nuevo.",
+ "settings.cleanup.count": "{n} tareas seleccionadas",
+ "settings.cleanup.empty": "No hay tareas antiguas para limpiar.",
+ "settings.cleanup.clean": "Limpiar",
+ "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Puedes restaurarlas abajo. Con la sincronización activa, también se eliminan de otros dispositivos. El espacio se libera al vaciar la papelera.",
+ "settings.cleanup.move": "Mover a la papelera ({n})",
+ "settings.cleanup.previous": "Anterior",
+ "settings.cleanup.next": "Siguiente",
+ "apps.commercial_required": "Las aplicaciones web requieren la versión comercial de Orkas. Descárgala para continuar.",
+ "apps.commercial_download": "Descargar versión comercial",
+ "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo."
}
diff --git a/src/renderer/locales/es.json b/src/renderer/locales/es.json
index b0813e5e..30b499b8 100644
--- a/src/renderer/locales/es.json
+++ b/src/renderer/locales/es.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Descarga",
"web_assist.activity_visit": "Visita",
"web_assist.download_saved": "guardado en adjuntos",
- "web_assist.download_needs_grant": "requiere permiso",
- "web_assist.download_blocked_type": "tipo de archivo no permitido",
- "web_assist.download_budget": "se alcanzó el límite de descargas de la tarea",
"web_assist.download_failed": "falló",
"web_assist.download_unavailable": "Archivo no disponible. Comprueba que la descarga haya terminado y que el archivo no se haya movido ni eliminado.",
- "web_assist.download_allow": "Permitir este sitio",
- "web_assist.download_prompt_title": "¿Permitir descargas de este sitio?",
- "web_assist.download_prompt_description": "Los archivos se guardarán en los adjuntos de esta tarea. Tras permitirlas, vuelve a la página y reintenta la descarga.",
- "web_assist.download_not_now": "Ahora no",
- "web_assist.download_permission_failed": "No se pudo permitir este sitio. Inténtalo de nuevo.",
"web_assist.address_placeholder": "Buscar en Bing o introducir una URL",
"web_assist.empty_title": "Navega en esta tarea",
"web_assist.empty_hint": "Busca en Bing o introduce una URL arriba.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Últimos 30 días",
"sidebar.bucket.older": "Anteriores",
"sidebar.projects": "Proyectos",
- "sidebar.today_tasks": "Tareas de hoy",
- "sidebar.today_empty": "No hay tareas hoy",
+ "sidebar.today_tasks": "Tareas recientes",
+ "sidebar.today_empty": "No hay tareas en los últimos dos días",
"sidebar.section_collapse": "Contraer {section}",
"sidebar.section_expand": "Expandir {section}",
"sidebar.project_create_title": "Nuevo proyecto",
"sidebar.project_create_placeholder": "Introduce el nombre del proyecto",
"sidebar.project_conv_empty": "(sin tareas)",
- "sidebar.load_more_conversations": "Cargar más",
+ "sidebar.load_more_conversations": "Mostrar más",
"sidebar.connect_agent": "Conectar agentes",
"sidebar.connect_agent_sub": "Claude Code · Codex y más",
"sidebar.settings": "Configuración",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Cargando…",
"new_chat.model_picker.aria_label": "Elegir modelo",
"new_chat.model_picker.empty": "No hay modelos disponibles",
- "new_chat.model_picker.group_official": "Modelos oficiales",
- "new_chat.model_picker.group_custom": "Modelos configurados por el usuario",
+ "new_chat.model_picker.group_official": "Modelos integrados de Orkas",
+ "new_chat.model_picker.group_custom": "Tu propia API Key",
"new_chat.model_picker.configure": "Configurar modelos",
"new_chat.model_picker.switch_failed": "No se pudo cambiar de modelo. Inténtalo de nuevo.",
"new_chat.model_picker.choose_version": "Elegir una versión del modelo para {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Añadido a {library}",
"conversation_info.file_add_to_library_failed": "Error al añadir a la biblioteca: {reason}",
"conversation_info.file_add_to_chat_action": "Añadir al chat de la tarea",
- "conversation_info.file_reveal_failed": "No se pudo abrir la carpeta: {reason}",
+ "conversation_info.file_reveal_failed": "No se pudo abrir la carpeta. Es posible que el archivo se haya movido o eliminado.",
"conversation_info.file_delete_confirm_title": "Eliminar archivo",
"conversation_info.file_delete_confirm_msg": "¿Eliminar \"{name}\"?",
"conversation_info.file_delete_failed": "No se pudo eliminar el archivo: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Enviar ahora",
"chat.queue_sending_now": "Enviando…",
"chat.queue_send_now_failed": "No se pudo enviar ahora este mensaje en cola: {msg}",
- "chat.multi_dispatch_serial": "Ejecutar en orden",
- "chat.multi_dispatch_parallel": "Ejecutar juntos",
- "chat.multi_dispatch_toggle_title": "Cómo se ejecutan los agentes mencionados para este mensaje; haz clic para cambiar",
"chat.task_waiting_on": "Esperando a {name}",
"chat.task_status_orchestrating": "Coordinando",
"chat.task_dispatched": "Asignada por Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "¿Eliminar los mensajes seleccionados (total: {count})? Esta acción no se puede deshacer.",
"chat.message_delete_failed": "Error al eliminar: {reason}",
"chat.reference_target_title": "Referenciar mensajes ({count}) en",
- "chat.reference_target_search": "Buscar tareas",
- "chat.reference_new_task": "Nueva tarea",
- "chat.reference_existing_tasks": "Tareas existentes",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nueva tarea…",
"chat.reference_area_project": "Proyecto",
- "chat.reference_recent_tasks_hint": "Las 5 tareas más recientes",
- "chat.reference_search_results_count": "Resultados: {count}",
- "chat.reference_no_tasks": "No hay tareas coincidentes",
"chat.reference_unknown_task": "Tarea desconocida",
"chat.reference_from_task": "Cita de “{title}” @{name}",
"chat.reference_bundle_title": "De “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Añadir servicio de imágenes",
"settings.models.add_video": "Añadir servicio de video",
"settings.models.add_tts": "Añadir servicio de voz",
- "settings.models.order_hint": "Arrastra las filas para cambiar la prioridad o usa los botones de flecha. Los modelos oficiales desactivados se omiten.",
+ "settings.models.order_hint": "Arrastra las filas para cambiar la prioridad o usa los botones de flecha. Los modelos integrados desactivados se omiten.",
"settings.general.page_sub": "Ajusta las preferencias y los permisos de agentes.",
"settings.general.preferences_title": "Preferencias",
"settings.general.agent_title": "Comportamiento de los agentes",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Aprobar",
"project.review.request_changes": "Solicitar cambios",
"project.driver.toggle": "Automático",
- "project.driver.toggle_hint": "La IA atiende automáticamente las tareas pendientes para que las revises al terminar.",
+ "project.driver.toggle_hint": "La IA atiende automáticamente las tareas pendientes para que las revises al terminar. Solo se ejecuta en el dispositivo donde la activas.",
"project.driver.enabled_toast": "Avance automático activado: elige periódicamente una tarea pendiente y trabaja en ella; las tareas pasan a En curso.",
"project.driver.disabled_toast": "Avance automático desactivado.",
"project.recent_convs.view_all": "Ver todo ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Contraer",
"skills.source_external": "Paquete",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "¿Permitir esta acción en la página?",
"chat.form.boolean_yes": "Sí",
"chat.form.boolean_no": "No",
"chat.form.invalid_number": "Introduce un número válido",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Recargar",
"quality.operator.disabled": "Desactivada en este dispositivo.",
"quality.operator.ready": "Lista: {count} reglas.",
- "quality.operator.invalid": "Validación no disponible. Corrige operator-policy.json o desactiva la validación personalizada e inténtalo de nuevo."
+ "quality.operator.invalid": "Validación no disponible. Corrige operator-policy.json o desactiva la validación personalizada e inténtalo de nuevo.",
+ "chat.app_nav_project_collaboration_target": "Miembros del proyecto: {target}",
+ "new_chat.home.goal_title": "¿Tienes un objetivo claro? Déjalo en manos del Commander.",
+ "new_chat.home.goal_body": "Dile al Commander qué quieres conseguir y coordinará a tu equipo de IA para lograrlo.",
+ "new_chat.home.goal_example": "Por ejemplo: investiga 3 productos similares, compara sus funciones y precios y resúmelo en una presentación.",
+ "new_chat.home.explore_title": "¿Aún no lo tienes claro? Deja que Orkas te conozca primero.",
+ "new_chat.home.explore_body": "Habla de tu trabajo, tu negocio o tus dificultades, y Orkas te ayudará a encontrar los objetivos adecuados y a avanzar en ellos.",
+ "new_chat.home.explore_context": "Comparte archivos con + o {connect} para darle más contexto a Orkas. Empieza por lo que te sientas cómodo compartiendo.",
+ "new_chat.home.explore_connect_link": "conecta Feishu / DingTalk / tu correo",
+ "new_chat.home.input_placeholder": "Describe lo que quieres conseguir o adjunta los archivos que hay que procesar",
+ "new_chat.home.continue_label": "Sigue avanzando",
+ "new_chat.home.group.todos": "Pendientes importantes",
+ "new_chat.home.group.automations": "Automatizaciones por revisar",
+ "new_chat.home.group.tasks": "Tareas que te esperan",
+ "new_chat.home.all_automations": "Todas las automatizaciones →",
+ "new_chat.home.expand": "Mostrar {count} más",
+ "new_chat.home.collapse": "Mostrar menos",
+ "new_chat.home.view_all_todos": "Ver todo →",
+ "new_chat.home.source.project_todo": "{project} · Pendiente",
+ "new_chat.home.source.global_todo": "Pendiente global",
+ "new_chat.home.source.automation": "Automatización",
+ "new_chat.home.source.project_task": "{project} · Tarea del proyecto",
+ "new_chat.home.source.global_task": "Tarea global",
+ "new_chat.home.result.completed": "Completada",
+ "new_chat.home.result.failed": "Fallida",
+ "new_chat.home.result.waiting_input": "Espera tu respuesta",
+ "new_chat.home.result.stopped": "Detenida",
+ "new_chat.home.result.unknown": "Nuevo resultado",
+ "new_chat.home.action.view": "Ver",
+ "new_chat.home.action.reply": "Responder",
+ "new_chat.home.action.view_reason": "Ver el motivo",
+ "new_chat.home.action.view_result": "Ver resultado",
+ "new_chat.home.time.updated": "Actualizado {time}",
+ "new_chat.home.untitled": "Tarea sin título",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} actualizado",
+ "apps.save_root_folder_required": "Mueve el HTML y sus recursos a una carpeta aparte y vuelve a guardar como aplicación.",
+ "chat.reference_locate_title": "Ir al mensaje original",
+ "chat.reference_locate_missing": "El mensaje original ya no existe.",
+ "agents.cli_usage_title": "Cuota restante",
+ "agents.cli_usage_unavailable": "No disponible. Comprueba el inicio de sesión de la CLI y la conexión.",
+ "agents.cli_usage_unsupported": "Esta versión de la CLI o configuración personalizada no admite consultar la cuota.",
+ "agents.cli_usage_resets": "Se restablece: {time}",
+ "agents.cli_usage_hours": "{count} horas",
+ "agents.cli_usage_days": "{count} días",
+ "agents.cli_usage_window": "Período de uso",
+ "memory.full_notice": "La memoria está llena. Antes de guardar algo nuevo, la IA fusionará las entradas existentes.",
+ "memory.error_full": "La memoria está llena, así que esta entrada no se puede añadir ahora.",
+ "settings.recycle.clear": "Vaciar",
+ "settings.recycle.clear_title": "Vaciar la papelera",
+ "settings.recycle.clear_confirm": "¿Eliminar permanentemente los {count} registros de {source}? No podrán restaurarse después.",
+ "settings.recycle.clearing": "Vaciando {done}/{total}…",
+ "settings.recycle.cleared": "Papelera vaciada",
+ "settings.recycle.clear_failed": "No se pudo vaciar toda la papelera. Inténtalo de nuevo.",
+ "settings.recycle.automation_count": "Automatización · {count} tareas",
+ "project.todo.move": "Mover",
+ "bash.permission.allow_folder_read": "Permitir leer esta carpeta",
+ "bash.permission.folder_read_scope": "Durante esta tarea, {agent} puede leer archivos de {folder} sin volver a preguntar. Escribir, eliminar y los archivos secretos seguirán pidiendo confirmación.",
+ "cli_upgrade.action": "Actualizar CLI",
+ "cli_upgrade.pending": "Actualizando…",
+ "cli_upgrade.success": "Actualización completada",
+ "cli_upgrade.failed": "Error al actualizar",
+ "cli_upgrade.named_action": "Actualizar {cli} CLI",
+ "web_assist.handback": "Devolver el control a la IA",
+ "web_assist.permissions": "Restablecer permisos del sitio",
+ "web_assist.permission_title": "Permiso del sitio",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Denegar",
+ "web_assist.permission_failed": "No se pudo guardar tu elección. Inténtalo de nuevo.",
+ "apps.view_details": "Ver detalles",
+ "apps.no_local_code": "No hay código de la aplicación en este dispositivo",
+ "apps.publish_commercial": "Usa la versión comercial de Orkas para publicar.",
+ "apps.update_original": "Actualizar aplicación original",
+ "apps.save_new": "Guardar nueva aplicación",
+ "apps.edit_conflict": "La aplicación original cambió o se eliminó. Vuelve a editarla o guarda una nueva.",
+ "apps.save_type_mismatch": "Esta versión es de un tipo distinto al de la aplicación original y no puede reemplazarla. Guárdala como una nueva aplicación.",
+ "apps.type_local": "Aplicación local",
+ "apps.type_web": "Aplicación web",
+ "apps.type_local_description": "Se ejecuta en Orkas para escritorio con acceso a IA, archivos, biblioteca y conectores; no se puede publicar en la web.",
+ "apps.type_web_description": "Publica en la web y accede mediante un enlace, con recopilación, consultas y estadísticas de datos; las funciones de Orkas para escritorio no están disponibles.",
+ "apps.delete_data_confirm": "¿Eliminar \"{name}\", sus registros locales y archivos privados? Los datos no se pueden recuperar.",
+ "apps.delete_online_retained": "La aplicación publicada y sus datos en línea se conservan.",
+ "apps.migration_export": "Cambia la estructura de los datos. Exporte los registros locales antes de borrarlos.",
+ "apps.migration_export_action": "Exportar registros",
+ "apps.migration_continue": "Continuar",
+ "apps.migration_clear": "¿Borrar todos los registros locales y actualizar? Los registros en línea son independientes.",
+ "apps.migration_retry": "Borrar y reintentar",
+ "chat.reference_scope_label": "Ámbito de tareas",
+ "chat.reference_scope_all": "Todas las tareas",
+ "chat.reference_scope_global": "Global (sin proyecto)",
+ "chat.reference_new_in_global": "Nueva tarea en Global",
+ "chat.reference_new_in_project": "Nueva tarea en «{name}»",
+ "chat.reference_search_all": "Buscar en todas las tareas",
+ "chat.reference_search_in": "Buscar tareas en «{name}»",
+ "chat.reference_count_all": "{count} en total · más recientes primero",
+ "chat.reference_count_found": "{count} encontradas · más recientes primero",
+ "chat.reference_load_more": "Cargar tareas anteriores (quedan {count})",
+ "chat.reference_no_match": "No hay tareas coincidentes",
+ "chat.reference_no_match_hint": "Prueba con otra palabra clave o elige otro ámbito a la izquierda.",
+ "chat.reference_scope_empty": "Aún no hay tareas aquí",
+ "chat.reference_scope_empty_hint": "Usa el botón de arriba para iniciar una tarea aquí.",
+ "chat.reference_create_back": "Volver a las tareas",
+ "chat.reference_create_title": "¿Dónde quieres crear la nueva tarea?",
+ "chat.reference_create_desc": "Las referencias se añaden al elegir el destino. No se envía nada automáticamente.",
+ "chat.reference_create_global_desc": "No pertenece a ningún proyecto",
+ "chat.reference_create_project_desc": "Iniciar una tarea en este proyecto",
+ "chat.reference_target_footer": "Al elegir, se abre el cuadro de entrada de la tarea con las referencias añadidas. No se envía nada automáticamente.",
+ "project.todo.run_busy": "La conversación de esta tarea todavía está en curso. Vuelve a ejecutarla cuando termine.",
+ "settings.cleanup.title": "Limpiar tareas antiguas",
+ "settings.cleanup.age": "Última actividad",
+ "settings.cleanup.scope": "Tareas completadas dentro y fuera de proyectos. Se conservan las fijadas, no leídas, los borradores y las ejecuciones automatizadas.",
+ "settings.cleanup.days": "Hace más de {n} días",
+ "settings.cleanup.result": "En la papelera: {deleted}. Omitidas: {skipped}. Fallidas: {failed}.",
+ "settings.cleanup.progress": "Limpiando {done} / {total}",
+ "settings.cleanup.error": "No se pudieron cargar o limpiar las tareas. Actualiza e inténtalo de nuevo.",
+ "settings.cleanup.count": "{n} tareas seleccionadas",
+ "settings.cleanup.empty": "No hay tareas antiguas para limpiar.",
+ "settings.cleanup.clean": "Limpiar",
+ "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Puedes restaurarlas abajo. Con la sincronización activa, también se eliminan de otros dispositivos. El espacio se libera al vaciar la papelera.",
+ "settings.cleanup.move": "Mover a la papelera ({n})",
+ "settings.cleanup.previous": "Anterior",
+ "settings.cleanup.next": "Siguiente",
+ "apps.commercial_required": "Las aplicaciones web requieren la versión comercial de Orkas. Descárgala para continuar.",
+ "apps.commercial_download": "Descargar versión comercial",
+ "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo."
}
diff --git a/src/renderer/locales/fr.json b/src/renderer/locales/fr.json
index 07f3fcf5..09b951bd 100644
--- a/src/renderer/locales/fr.json
+++ b/src/renderer/locales/fr.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Téléchargement",
"web_assist.activity_visit": "Visiter",
"web_assist.download_saved": "enregistré dans les pièces jointes",
- "web_assist.download_needs_grant": "autorisation requise",
- "web_assist.download_blocked_type": "type de fichier non autorisé",
- "web_assist.download_budget": "limite de téléchargement de la tâche atteinte",
"web_assist.download_failed": "échec",
"web_assist.download_unavailable": "Fichier indisponible. Vérifiez que le téléchargement est terminé et que le fichier n’a pas été déplacé ou supprimé.",
- "web_assist.download_allow": "Autoriser ce site",
- "web_assist.download_prompt_title": "Autoriser les téléchargements de ce site ?",
- "web_assist.download_prompt_description": "Les fichiers seront enregistrés dans les pièces jointes de cette tâche. Après autorisation, revenez à la page et relancez le téléchargement.",
- "web_assist.download_not_now": "Pas maintenant",
- "web_assist.download_permission_failed": "Impossible d’autoriser ce site. Réessayez.",
"web_assist.address_placeholder": "Rechercher avec Bing ou saisir une URL",
"web_assist.empty_title": "Naviguer dans cette tâche",
"web_assist.empty_hint": "Recherchez avec Bing ou saisissez une URL ci-dessus.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 derniers jours",
"sidebar.bucket.older": "Plus ancien",
"sidebar.projects": "Projets",
- "sidebar.today_tasks": "Tâches du jour",
- "sidebar.today_empty": "Aucune tâche aujourd’hui",
+ "sidebar.today_tasks": "Tâches récentes",
+ "sidebar.today_empty": "Aucune tâche ces deux derniers jours",
"sidebar.section_collapse": "Réduire {section}",
"sidebar.section_expand": "Développer {section}",
"sidebar.project_create_title": "Nouveau projet",
"sidebar.project_create_placeholder": "Saisir le nom du projet",
"sidebar.project_conv_empty": "(aucune tâche)",
- "sidebar.load_more_conversations": "Charger la suite",
+ "sidebar.load_more_conversations": "Afficher plus",
"sidebar.connect_agent": "Connecter des Agents",
"sidebar.connect_agent_sub": "Claude Code · Codex et plus",
"sidebar.settings": "Paramètres",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Chargement…",
"new_chat.model_picker.aria_label": "Choisir le modèle",
"new_chat.model_picker.empty": "Aucun modèle disponible",
- "new_chat.model_picker.group_official": "Modèles officiels",
- "new_chat.model_picker.group_custom": "Modèles configurés par l’utilisateur",
+ "new_chat.model_picker.group_official": "Modèles intégrés Orkas",
+ "new_chat.model_picker.group_custom": "Votre propre API Key",
"new_chat.model_picker.configure": "Configurer les modèles",
"new_chat.model_picker.switch_failed": "Impossible de changer de modèle. Réessayez.",
"new_chat.model_picker.choose_version": "Choisir une version de modèle pour {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Ajouté à {library}",
"conversation_info.file_add_to_library_failed": "Échec de l’ajout à la bibliothèque : {reason}",
"conversation_info.file_add_to_chat_action": "Ajouter à la conversation de tâche",
- "conversation_info.file_reveal_failed": "Impossible d’ouvrir le dossier : {reason}",
+ "conversation_info.file_reveal_failed": "Impossible d’ouvrir le dossier. Le fichier a peut-être été déplacé ou supprimé.",
"conversation_info.file_delete_confirm_title": "Supprimer le fichier",
"conversation_info.file_delete_confirm_msg": "Supprimer « {name} » ?",
"conversation_info.file_delete_failed": "Impossible de supprimer le fichier : {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Envoyer maintenant",
"chat.queue_sending_now": "Envoi…",
"chat.queue_send_now_failed": "Impossible d’envoyer maintenant ce message en attente : {msg}",
- "chat.multi_dispatch_serial": "Exécuter dans l’ordre",
- "chat.multi_dispatch_parallel": "Exécuter ensemble",
- "chat.multi_dispatch_toggle_title": "Mode d’exécution des Agents mentionnés pour ce message ; cliquer pour changer",
"chat.task_waiting_on": "En attente de {name}",
"chat.task_status_orchestrating": "Coordination",
"chat.task_dispatched": "Délégué par Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Supprimer les messages sélectionnés ({count}) ? Cette action est irréversible.",
"chat.message_delete_failed": "Échec de la suppression : {reason}",
"chat.reference_target_title": "Référencer les messages ({count}) dans",
- "chat.reference_target_search": "Rechercher des tâches",
- "chat.reference_new_task": "Nouvelle tâche",
- "chat.reference_existing_tasks": "Tâches existantes",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nouvelle tâche…",
"chat.reference_area_project": "Projet",
- "chat.reference_recent_tasks_hint": "5 tâches les plus récentes",
- "chat.reference_search_results_count": "Résultats : {count}",
- "chat.reference_no_tasks": "Aucune tâche correspondante",
"chat.reference_unknown_task": "Tâche inconnue",
"chat.reference_from_task": "Citation de « {title} » @{name}",
"chat.reference_bundle_title": "De « {title} »",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Ajouter un service d’images",
"settings.models.add_video": "Ajouter un service vidéo",
"settings.models.add_tts": "Ajouter un service vocal",
- "settings.models.order_hint": "Glissez les lignes pour modifier la priorité ou utilisez les flèches. Les modèles officiels désactivés sont ignorés.",
+ "settings.models.order_hint": "Glissez les lignes pour modifier la priorité ou utilisez les flèches. Les modèles intégrés désactivés sont ignorés.",
"settings.general.page_sub": "Réglez les préférences et les autorisations des Agents.",
"settings.general.preferences_title": "Préférences",
"settings.general.agent_title": "Comportement des Agents",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Approuver",
"project.review.request_changes": "Demander des modifications",
"project.driver.toggle": "Auto",
- "project.driver.toggle_hint": "L’IA traite automatiquement les tâches à faire, puis vous les soumet pour vérification.",
+ "project.driver.toggle_hint": "L’IA traite automatiquement les tâches à faire, puis vous les soumet pour vérification. L’exécution a lieu uniquement sur l’appareil où vous l’activez.",
"project.driver.enabled_toast": "Progression automatique activée : une tâche en attente est régulièrement sélectionnée et traitée ; elle passe à l’état En cours.",
"project.driver.disabled_toast": "Progression automatique désactivée.",
"project.recent_convs.view_all": "Tout voir ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Réduire",
"skills.source_external": "Paquet",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "Autoriser cette action sur la page ?",
"chat.form.boolean_yes": "Oui",
"chat.form.boolean_no": "Non",
"chat.form.invalid_number": "Saisissez un nombre valide",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Recharger",
"quality.operator.disabled": "Désactivée sur cet appareil.",
"quality.operator.ready": "Prête : {count} règles.",
- "quality.operator.invalid": "Validation indisponible. Corrigez operator-policy.json ou désactivez la validation personnalisée, puis réessayez."
+ "quality.operator.invalid": "Validation indisponible. Corrigez operator-policy.json ou désactivez la validation personnalisée, puis réessayez.",
+ "chat.app_nav_project_collaboration_target": "Membres du projet : {target}",
+ "new_chat.home.goal_title": "Un objectif précis ? Confiez-le au Commander.",
+ "new_chat.home.goal_body": "Dites au Commander ce que vous voulez accomplir : il coordonne votre équipe IA pour y parvenir.",
+ "new_chat.home.goal_example": "Par exemple : étudier 3 produits similaires, comparer leurs fonctionnalités et leurs prix, puis en faire une présentation.",
+ "new_chat.home.explore_title": "Pas encore d’idée précise ? Laissez d’abord Orkas apprendre à vous connaître.",
+ "new_chat.home.explore_body": "Parlez de votre travail, de votre activité ou de vos difficultés : Orkas vous aide à trouver les bons objectifs et à les faire avancer.",
+ "new_chat.home.explore_context": "Partagez des fichiers avec +, ou {connect}, pour donner plus de contexte à Orkas. Commencez par ce que vous êtes prêt à partager.",
+ "new_chat.home.explore_connect_link": "connectez Feishu / DingTalk / votre e-mail",
+ "new_chat.home.input_placeholder": "Décrivez ce que vous voulez accomplir, ou joignez les fichiers à traiter",
+ "new_chat.home.continue_label": "Faites avancer les choses",
+ "new_chat.home.group.todos": "À faire en priorité",
+ "new_chat.home.group.automations": "Automatisations à examiner",
+ "new_chat.home.group.tasks": "Tâches qui vous attendent",
+ "new_chat.home.all_automations": "Toutes les automatisations →",
+ "new_chat.home.expand": "Afficher les {count} autres",
+ "new_chat.home.collapse": "Réduire",
+ "new_chat.home.view_all_todos": "Tout voir →",
+ "new_chat.home.source.project_todo": "{project} · À faire",
+ "new_chat.home.source.global_todo": "À faire global",
+ "new_chat.home.source.automation": "Automatisation",
+ "new_chat.home.source.project_task": "{project} · Tâche de projet",
+ "new_chat.home.source.global_task": "Tâche globale",
+ "new_chat.home.result.completed": "Terminé",
+ "new_chat.home.result.failed": "Échec",
+ "new_chat.home.result.waiting_input": "En attente de votre réponse",
+ "new_chat.home.result.stopped": "Arrêté",
+ "new_chat.home.result.unknown": "Nouveau résultat",
+ "new_chat.home.action.view": "Voir",
+ "new_chat.home.action.reply": "Répondre",
+ "new_chat.home.action.view_reason": "Voir la cause",
+ "new_chat.home.action.view_result": "Voir le résultat",
+ "new_chat.home.time.updated": "Mis à jour {time}",
+ "new_chat.home.untitled": "Tâche sans titre",
+ "artifact.failure_detail": "{action} : {detail}",
+ "apps.updated_toast": "{name} mis à jour",
+ "apps.save_root_folder_required": "Déplacez le HTML et ses ressources dans un dossier dédié, puis enregistrez à nouveau l’application.",
+ "chat.reference_locate_title": "Aller au message d’origine",
+ "chat.reference_locate_missing": "Le message d’origine n’existe plus.",
+ "agents.cli_usage_title": "Quota restant",
+ "agents.cli_usage_unavailable": "Indisponible. Vérifiez la connexion au compte CLI et au réseau.",
+ "agents.cli_usage_unsupported": "Cette version de la CLI ou cette configuration personnalisée ne permet pas de consulter le quota.",
+ "agents.cli_usage_resets": "Réinitialisation : {time}",
+ "agents.cli_usage_hours": "{count} heures",
+ "agents.cli_usage_days": "{count} jours",
+ "agents.cli_usage_window": "Période d’utilisation",
+ "memory.full_notice": "La mémoire est pleine. Avant d'enregistrer quelque chose de nouveau, l'IA fusionnera les entrées existantes.",
+ "memory.error_full": "La mémoire est pleine : cette entrée ne peut pas être ajoutée pour le moment.",
+ "settings.recycle.clear": "Vider",
+ "settings.recycle.clear_title": "Vider la corbeille",
+ "settings.recycle.clear_confirm": "Supprimer définitivement les {count} éléments de « {source} » ? Ils ne pourront plus être restaurés.",
+ "settings.recycle.clearing": "Suppression {done}/{total}…",
+ "settings.recycle.cleared": "Corbeille vidée",
+ "settings.recycle.clear_failed": "La corbeille n’a pas pu être entièrement vidée. Veuillez réessayer.",
+ "settings.recycle.automation_count": "Automatisation · {count} tâches",
+ "project.todo.move": "Déplacer",
+ "bash.permission.allow_folder_read": "Autoriser la lecture de ce dossier",
+ "bash.permission.folder_read_scope": "Pour cette tâche, {agent} peut lire les fichiers de {folder} sans redemander. L’écriture, la suppression et les fichiers secrets restent soumis à confirmation.",
+ "cli_upgrade.action": "Mettre à jour le CLI",
+ "cli_upgrade.pending": "Mise à jour…",
+ "cli_upgrade.success": "Mise à jour réussie",
+ "cli_upgrade.failed": "Échec de la mise à jour",
+ "cli_upgrade.named_action": "Mettre à jour {cli} CLI",
+ "web_assist.handback": "Rendre le contrôle à l’IA",
+ "web_assist.permissions": "Réinitialiser les autorisations du site",
+ "web_assist.permission_title": "Autorisation du site",
+ "web_assist.permission_allow": "Autoriser",
+ "web_assist.permission_deny": "Refuser",
+ "web_assist.permission_failed": "Impossible d’enregistrer votre choix. Réessayez.",
+ "apps.view_details": "Voir les détails",
+ "apps.no_local_code": "Aucun code de l’application sur cet appareil",
+ "apps.publish_commercial": "Utilisez la version commerciale d’Orkas pour publier.",
+ "apps.update_original": "Mettre à jour l’application originale",
+ "apps.save_new": "Enregistrer une nouvelle application",
+ "apps.edit_conflict": "L’application originale a changé ou a été supprimée. Rouvrez-la ou enregistrez une nouvelle application.",
+ "apps.save_type_mismatch": "Cette version n’est pas du même type que l’application originale et ne peut pas la remplacer. Enregistrez-la plutôt comme nouvelle application.",
+ "apps.type_local": "Application locale",
+ "apps.type_web": "Application web",
+ "apps.type_local_description": "Fonctionne dans Orkas sur ordinateur avec accès à l’IA, aux fichiers, à la bibliothèque et aux connecteurs ; ne peut pas être publié sur le Web.",
+ "apps.type_web_description": "Publiez sur le Web et accédez via un lien, avec collecte, requêtes et statistiques de données ; les fonctionnalités d’Orkas sur ordinateur sont indisponibles.",
+ "apps.delete_data_confirm": "Supprimer « {name} », ses données locales et ses fichiers privés ? Les données sont irrécupérables.",
+ "apps.delete_online_retained": "L’application publiée et ses données en ligne sont conservées.",
+ "apps.migration_export": "La structure des données change. Exportez les données locales avant de les effacer.",
+ "apps.migration_export_action": "Exporter les données",
+ "apps.migration_continue": "Continuer",
+ "apps.migration_clear": "Effacer toutes les données locales et mettre à jour ? Les données en ligne restent indépendantes.",
+ "apps.migration_retry": "Effacer et réessayer",
+ "chat.reference_scope_label": "Portée des tâches",
+ "chat.reference_scope_all": "Toutes les tâches",
+ "chat.reference_scope_global": "Global (sans projet)",
+ "chat.reference_new_in_global": "Nouvelle tâche dans Global",
+ "chat.reference_new_in_project": "Nouvelle tâche dans « {name} »",
+ "chat.reference_search_all": "Rechercher dans toutes les tâches",
+ "chat.reference_search_in": "Rechercher les tâches de « {name} »",
+ "chat.reference_count_all": "{count} au total · plus récentes d’abord",
+ "chat.reference_count_found": "{count} trouvée(s) · plus récentes d’abord",
+ "chat.reference_load_more": "Charger des tâches plus anciennes (encore {count})",
+ "chat.reference_no_match": "Aucune tâche correspondante",
+ "chat.reference_no_match_hint": "Essayez un autre mot-clé ou choisissez une autre portée à gauche.",
+ "chat.reference_scope_empty": "Aucune tâche ici pour le moment",
+ "chat.reference_scope_empty_hint": "Utilisez le bouton ci-dessus pour démarrer une tâche ici.",
+ "chat.reference_create_back": "Retour aux tâches",
+ "chat.reference_create_title": "Où créer la nouvelle tâche ?",
+ "chat.reference_create_desc": "Les références sont ajoutées une fois la destination choisie. Rien n’est envoyé automatiquement.",
+ "chat.reference_create_global_desc": "Rattachée à aucun projet",
+ "chat.reference_create_project_desc": "Démarrer une tâche dans ce projet",
+ "chat.reference_target_footer": "Votre choix ouvre la zone de saisie de la tâche avec les références ajoutées. Rien n’est envoyé automatiquement.",
+ "project.todo.run_busy": "La conversation de cette tâche est encore en cours. Relancez-la une fois terminée.",
+ "settings.cleanup.title": "Nettoyer les anciennes tâches",
+ "settings.cleanup.age": "Dernière activité",
+ "settings.cleanup.scope": "Tâches terminées dans et hors des projets. Les tâches épinglées, non lues, les brouillons et les exécutions automatisées sont conservés.",
+ "settings.cleanup.days": "Il y a plus de {n} jours",
+ "settings.cleanup.result": "Dans la corbeille : {deleted}. Ignorées : {skipped}. Échecs : {failed}.",
+ "settings.cleanup.progress": "Nettoyage {done} / {total}",
+ "settings.cleanup.error": "Impossible de charger ou nettoyer les tâches. Actualisez et réessayez.",
+ "settings.cleanup.count": "{n} tâches sélectionnées",
+ "settings.cleanup.empty": "Aucune ancienne tâche à nettoyer.",
+ "settings.cleanup.clean": "Nettoyer",
+ "settings.cleanup.confirm": "Déplacer {n} tâches, leurs pièces jointes et résultats intégrés dans la corbeille. Vous pourrez les restaurer ci-dessous. Si la synchronisation est activée, la suppression concerne aussi les autres appareils. Videz la corbeille pour libérer l’espace disque.",
+ "settings.cleanup.move": "Mettre à la corbeille ({n})",
+ "settings.cleanup.previous": "Précédent",
+ "settings.cleanup.next": "Suivant",
+ "apps.commercial_required": "Les applications web nécessitent la version commerciale d’Orkas. Téléchargez-la pour continuer.",
+ "apps.commercial_download": "Télécharger la version commerciale",
+ "apps.commercial_open_failed": "Impossible d’ouvrir la page de téléchargement. Réessayez."
}
diff --git a/src/renderer/locales/hi.json b/src/renderer/locales/hi.json
index f7518067..cf53214b 100644
--- a/src/renderer/locales/hi.json
+++ b/src/renderer/locales/hi.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "डाउनलोड करें",
"web_assist.activity_visit": "देखें",
"web_assist.download_saved": "अटैचमेंट में सहेजा गया",
- "web_assist.download_needs_grant": "अनुमति चाहिए",
- "web_assist.download_blocked_type": "फ़ाइल प्रकार की अनुमति नहीं है",
- "web_assist.download_budget": "कार्य की डाउनलोड सीमा पूरी हुई",
"web_assist.download_failed": "विफल",
"web_assist.download_unavailable": "फ़ाइल उपलब्ध नहीं है। जाँचें कि डाउनलोड पूरा हुआ है और फ़ाइल हटाई या स्थानांतरित नहीं की गई है।",
- "web_assist.download_allow": "इस साइट को अनुमति दें",
- "web_assist.download_prompt_title": "इस साइट से डाउनलोड की अनुमति दें?",
- "web_assist.download_prompt_description": "फ़ाइलें इस कार्य के अटैचमेंट में सहेजी जाएँगी। अनुमति देने के बाद पृष्ठ पर लौटें और डाउनलोड फिर करें।",
- "web_assist.download_not_now": "अभी नहीं",
- "web_assist.download_permission_failed": "इस साइट को अनुमति नहीं दी जा सकी। फिर कोशिश करें।",
"web_assist.address_placeholder": "Bing पर खोजें या URL डालें",
"web_assist.empty_title": "इस कार्य में ब्राउज़ करें",
"web_assist.empty_hint": "ऊपर Bing पर खोजें या URL डालें।",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "पिछले 30 दिन",
"sidebar.bucket.older": "पुराने",
"sidebar.projects": "प्रोजेक्ट",
- "sidebar.today_tasks": "आज के कार्य",
- "sidebar.today_empty": "आज कोई कार्य नहीं है",
+ "sidebar.today_tasks": "हाल के कार्य",
+ "sidebar.today_empty": "पिछले दो दिनों में कोई कार्य नहीं है",
"sidebar.section_collapse": "{section} समेटें",
"sidebar.section_expand": "{section} फैलाएँ",
"sidebar.project_create_title": "नया प्रोजेक्ट",
"sidebar.project_create_placeholder": "प्रोजेक्ट का नाम डालें",
"sidebar.project_conv_empty": "(कोई कार्य नहीं)",
- "sidebar.load_more_conversations": "और लोड करें",
+ "sidebar.load_more_conversations": "और दिखाएँ",
"sidebar.connect_agent": "एजेंट जोड़ें",
"sidebar.connect_agent_sub": "Claude Code · Codex और अन्य",
"sidebar.settings": "सेटिंग",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "लोड हो रहा है…",
"new_chat.model_picker.aria_label": "मॉडल चुनें",
"new_chat.model_picker.empty": "कोई मॉडल उपलब्ध नहीं",
- "new_chat.model_picker.group_official": "आधिकारिक मॉडल",
- "new_chat.model_picker.group_custom": "उपयोगकर्ता द्वारा कॉन्फ़िगर किए गए मॉडल",
+ "new_chat.model_picker.group_official": "Orkas के अंतर्निहित मॉडल",
+ "new_chat.model_picker.group_custom": "आपकी अपनी API Key",
"new_chat.model_picker.configure": "मॉडल कॉन्फ़िगर करें",
"new_chat.model_picker.switch_failed": "मॉडल नहीं बदला जा सका। फिर कोशिश करें।",
"new_chat.model_picker.choose_version": "{account} के लिए मॉडल संस्करण चुनें",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "{library} में जोड़ा गया",
"conversation_info.file_add_to_library_failed": "लाइब्रेरी में जोड़ना विफल रहा: {reason}",
"conversation_info.file_add_to_chat_action": "कार्य चैट में जोड़ें",
- "conversation_info.file_reveal_failed": "फ़ोल्डर नहीं खुल सका: {reason}",
+ "conversation_info.file_reveal_failed": "फ़ोल्डर नहीं खुल सका। फ़ाइल को शायद हटाया या स्थानांतरित किया गया है।",
"conversation_info.file_delete_confirm_title": "फ़ाइल हटाएँ",
"conversation_info.file_delete_confirm_msg": "\"{name}\" हटाएँ?",
"conversation_info.file_delete_failed": "फ़ाइल नहीं हट सकी: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "अभी भेजें",
"chat.queue_sending_now": "भेजा जा रहा है…",
"chat.queue_send_now_failed": "कतार का यह संदेश अभी नहीं भेजा जा सका: {msg}",
- "chat.multi_dispatch_serial": "क्रम से चलाएँ",
- "chat.multi_dispatch_parallel": "साथ चलाएँ",
- "chat.multi_dispatch_toggle_title": "इस संदेश के लिए उल्लेखित एजेंट कैसे चलेंगे; बदलने के लिए क्लिक करें",
"chat.task_waiting_on": "{name} की प्रतीक्षा में",
"chat.task_status_orchestrating": "समन्वय जारी है",
"chat.task_dispatched": "Commander ने सौंपा",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "चुने गए {count} संदेश हटाएँ? इसे वापस नहीं किया जा सकता।",
"chat.message_delete_failed": "हटाना विफल रहा: {reason}",
"chat.reference_target_title": "{count} संदेशों का संदर्भ इसमें दें",
- "chat.reference_target_search": "कार्य खोजें",
- "chat.reference_new_task": "नया कार्य",
- "chat.reference_existing_tasks": "मौजूदा कार्य",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "नया कार्य…",
"chat.reference_area_project": "प्रोजेक्ट",
- "chat.reference_recent_tasks_hint": "5 सबसे हाल के कार्य",
- "chat.reference_search_results_count": "{count} परिणाम",
- "chat.reference_no_tasks": "कोई मेल खाता कार्य नहीं",
"chat.reference_unknown_task": "अज्ञात कार्य",
"chat.reference_from_task": "“{title}” @{name} से उद्धृत",
"chat.reference_bundle_title": "“{title}” से",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "चित्र सेवा जोड़ें",
"settings.models.add_video": "वीडियो सेवा जोड़ें",
"settings.models.add_tts": "वाणी सेवा जोड़ें",
- "settings.models.order_hint": "प्राथमिकता बदलने के लिए पंक्तियाँ खींचें या तीर बटन इस्तेमाल करें। अक्षम आधिकारिक मॉडल छोड़ दिए जाते हैं।",
+ "settings.models.order_hint": "प्राथमिकता बदलने के लिए पंक्तियाँ खींचें या तीर बटन इस्तेमाल करें। अक्षम अंतर्निहित मॉडल छोड़ दिए जाते हैं।",
"settings.general.page_sub": "पसंद, एजेंट अनुमतियाँ और ऐप अपडेट समायोजित करें।",
"settings.general.preferences_title": "पसंद",
"settings.general.agent_title": "एजेंट व्यवहार",
@@ -2031,7 +2014,7 @@
"project.review.approve": "मंज़ूर करें",
"project.review.request_changes": "बदलाव माँगें",
"project.driver.toggle": "स्वचालित",
- "project.driver.toggle_hint": "AI लंबित कार्य अपने आप सँभालता है, पूरे होने पर आप समीक्षा कर सकते हैं।",
+ "project.driver.toggle_hint": "AI लंबित कार्य अपने आप सँभालता है, पूरे होने पर आप समीक्षा कर सकते हैं। यह केवल उसी डिवाइस पर चलता है जहाँ आप इसे चालू करते हैं।",
"project.driver.enabled_toast": "स्वचालित प्रगति चालू — समय-समय पर लंबित कार्य चुनकर उस पर काम करता है; कार्य प्रगति में चले जाते हैं।",
"project.driver.disabled_toast": "स्वचालित प्रगति बंद है।",
"project.recent_convs.view_all": "सभी देखें ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "समेटें",
"skills.source_external": "पैकेज",
"skills.source_global": "वैश्विक",
- "web_assist.action_confirm.title": "पृष्ठ पर इस कार्रवाई की अनुमति दें?",
"chat.form.boolean_yes": "हाँ",
"chat.form.boolean_no": "नहीं",
"chat.form.invalid_number": "मान्य संख्या डालें",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "फिर से लोड करें",
"quality.operator.disabled": "इस डिवाइस पर बंद है।",
"quality.operator.ready": "तैयार: {count} नियम।",
- "quality.operator.invalid": "सत्यापन उपलब्ध नहीं है। operator-policy.json ठीक करें या कस्टम सत्यापन बंद करके फिर कोशिश करें।"
+ "quality.operator.invalid": "सत्यापन उपलब्ध नहीं है। operator-policy.json ठीक करें या कस्टम सत्यापन बंद करके फिर कोशिश करें।",
+ "chat.app_nav_project_collaboration_target": "परियोजना के सदस्य: {target}",
+ "new_chat.home.goal_title": "लक्ष्य साफ़ है? Commander को सौंप दें।",
+ "new_chat.home.goal_body": "Commander को बताएँ कि आप क्या पूरा करना चाहते हैं — वह आपकी AI टीम का तालमेल बिठाकर काम पूरा करवाएगा।",
+ "new_chat.home.goal_example": "उदाहरण: 3 मिलते-जुलते उत्पादों पर रिसर्च करें, उनकी सुविधाओं और कीमतों की तुलना करें और एक प्रेज़ेंटेशन बनाएँ।",
+ "new_chat.home.explore_title": "अभी तय नहीं? पहले Orkas को आपको जानने दें।",
+ "new_chat.home.explore_body": "अपने काम, कारोबार या परेशानियों के बारे में बताएँ — Orkas सही लक्ष्य ढूँढने और उन्हें आगे बढ़ाते रहने में मदद करेगा।",
+ "new_chat.home.explore_context": "+ से फ़ाइलें शेयर करें या {connect}, ताकि Orkas को ज़्यादा संदर्भ मिले। वहीं से शुरू करें जो आप शेयर करना चाहें।",
+ "new_chat.home.explore_connect_link": "Feishu / DingTalk / ईमेल जोड़ें",
+ "new_chat.home.input_placeholder": "बताएँ कि आप क्या पूरा करना चाहते हैं, या जिन फ़ाइलों पर काम करना है उन्हें अटैच करें",
+ "new_chat.home.continue_label": "काम आगे बढ़ाते रहें",
+ "new_chat.home.group.todos": "ज़रूरी करने वाले काम",
+ "new_chat.home.group.automations": "देखने लायक स्वचालन",
+ "new_chat.home.group.tasks": "आपका इंतज़ार कर रहे कार्य",
+ "new_chat.home.all_automations": "सभी स्वचालन →",
+ "new_chat.home.expand": "{count} और दिखाएँ",
+ "new_chat.home.collapse": "कम दिखाएँ",
+ "new_chat.home.view_all_todos": "सभी देखें →",
+ "new_chat.home.source.project_todo": "{project} · करना है",
+ "new_chat.home.source.global_todo": "वैश्विक करने वाला काम",
+ "new_chat.home.source.automation": "स्वचालन",
+ "new_chat.home.source.project_task": "{project} · प्रोजेक्ट कार्य",
+ "new_chat.home.source.global_task": "वैश्विक कार्य",
+ "new_chat.home.result.completed": "पूरा हुआ",
+ "new_chat.home.result.failed": "विफल",
+ "new_chat.home.result.waiting_input": "आपके इनपुट का इंतज़ार",
+ "new_chat.home.result.stopped": "रोका गया",
+ "new_chat.home.result.unknown": "नया नतीजा",
+ "new_chat.home.action.view": "देखें",
+ "new_chat.home.action.reply": "जवाब दें",
+ "new_chat.home.action.view_reason": "कारण देखें",
+ "new_chat.home.action.view_result": "नतीजा देखें",
+ "new_chat.home.time.updated": "{time} अपडेट किया गया",
+ "new_chat.home.untitled": "बिना नाम का कार्य",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} अपडेट हुआ",
+ "apps.save_root_folder_required": "HTML और उससे जुड़े संसाधनों को अलग फ़ोल्डर में ले जाएँ, फिर दोबारा ऐप के रूप में सेव करें।",
+ "chat.reference_locate_title": "मूल संदेश पर जाएँ",
+ "chat.reference_locate_missing": "मूल संदेश अब मौजूद नहीं है।",
+ "agents.cli_usage_title": "शेष सीमा",
+ "agents.cli_usage_unavailable": "उपलब्ध नहीं है। CLI साइन-इन और कनेक्शन जाँचें।",
+ "agents.cli_usage_unsupported": "यह CLI संस्करण या कस्टम कॉन्फ़िगरेशन सीमा की जानकारी प्राप्त करने का समर्थन नहीं करता।",
+ "agents.cli_usage_resets": "रीसेट: {time}",
+ "agents.cli_usage_hours": "{count} घंटे",
+ "agents.cli_usage_days": "{count} दिन",
+ "agents.cli_usage_window": "उपयोग अवधि",
+ "memory.full_notice": "मेमोरी भर गई है। कुछ नया सहेजने से पहले AI मौजूदा प्रविष्टियों को मिला देगा।",
+ "memory.error_full": "मेमोरी भर गई है, इसलिए यह प्रविष्टि अभी नहीं जोड़ी जा सकती।",
+ "settings.recycle.clear": "खाली करें",
+ "settings.recycle.clear_title": "रीसायकल बिन खाली करें",
+ "settings.recycle.clear_confirm": "क्या {source} के सभी {count} रिकॉर्ड स्थायी रूप से हटाएं? बाद में इन्हें बहाल नहीं किया जा सकेगा।",
+ "settings.recycle.clearing": "खाली किया जा रहा है {done}/{total}…",
+ "settings.recycle.cleared": "रीसायकल बिन खाली कर दिया गया",
+ "settings.recycle.clear_failed": "रीसायकल बिन पूरी तरह खाली नहीं हो सका। कृपया फिर से प्रयास करें।",
+ "settings.recycle.automation_count": "स्वचालन · {count} कार्य",
+ "project.todo.move": "स्थानांतरित करें",
+ "bash.permission.allow_folder_read": "इस फ़ोल्डर को पढ़ने की अनुमति दें",
+ "bash.permission.folder_read_scope": "इस कार्य के दौरान {agent} बिना दोबारा पूछे {folder} की फ़ाइलें पढ़ सकता है। लिखने, हटाने और गोपनीय फ़ाइलों के लिए अब भी पुष्टि माँगी जाएगी।",
+ "cli_upgrade.action": "CLI अपग्रेड करें",
+ "cli_upgrade.pending": "अपग्रेड हो रहा है…",
+ "cli_upgrade.success": "अपग्रेड सफल",
+ "cli_upgrade.failed": "अपग्रेड विफल",
+ "cli_upgrade.named_action": "{cli} CLI अपग्रेड करें",
+ "web_assist.handback": "AI को नियंत्रण लौटाएँ",
+ "web_assist.permissions": "साइट की अनुमतियाँ रीसेट करें",
+ "web_assist.permission_title": "वेबसाइट की अनुमति",
+ "web_assist.permission_allow": "अनुमति दें",
+ "web_assist.permission_deny": "मना करें",
+ "web_assist.permission_failed": "आपका चयन सहेजा नहीं जा सका। फिर से कोशिश करें।",
+ "apps.view_details": "विवरण देखें",
+ "apps.no_local_code": "इस डिवाइस पर ऐप का कोड नहीं है",
+ "apps.publish_commercial": "प्रकाशन के लिए Orkas का व्यावसायिक संस्करण उपयोग करें।",
+ "apps.update_original": "मूल ऐप अपडेट करें",
+ "apps.save_new": "नया ऐप सहेजें",
+ "apps.edit_conflict": "मूल ऐप बदल गया या हट गया है। फिर संपादित करें या नया ऐप सहेजें।",
+ "apps.save_type_mismatch": "यह संस्करण मूल ऐप से अलग प्रकार का है, इसलिए उसे बदल नहीं सकता। इसके बजाय इसे नए ऐप के रूप में सहेजें।",
+ "apps.type_local": "स्थानीय ऐप",
+ "apps.type_web": "वेब ऐप",
+ "apps.type_local_description": "Orkas डेस्कटॉप में चलता है और AI, फ़ाइलें, लाइब्रेरी व कनेक्टर जैसी सुविधाएँ इस्तेमाल कर सकता है; वेब पर प्रकाशित नहीं किया जा सकता।",
+ "apps.type_web_description": "वेब पर प्रकाशित करें और लिंक से खोलें; डेटा संग्रह, क्वेरी और आँकड़े उपलब्ध हैं, लेकिन Orkas डेस्कटॉप की सुविधाएँ उपलब्ध नहीं हैं।",
+ "apps.delete_data_confirm": "\"{name}\", उसके स्थानीय रिकॉर्ड और निजी फ़ाइलें हटाएँ? डेटा वापस नहीं मिलेगा।",
+ "apps.delete_online_retained": "प्रकाशित ऐप और ऑनलाइन डेटा सुरक्षित रहते हैं।",
+ "apps.migration_export": "डेटा संरचना बदलती है। मिटाने से पहले स्थानीय रिकॉर्ड निर्यात करें।",
+ "apps.migration_export_action": "रिकॉर्ड निर्यात करें",
+ "apps.migration_continue": "जारी रखें",
+ "apps.migration_clear": "सभी स्थानीय रिकॉर्ड मिटाकर अपडेट करें? ऑनलाइन रिकॉर्ड अलग रहते हैं।",
+ "apps.migration_retry": "मिटाएँ और फिर कोशिश करें",
+ "chat.reference_scope_label": "कार्यों का दायरा",
+ "chat.reference_scope_all": "सभी कार्य",
+ "chat.reference_scope_global": "ग्लोबल (कोई प्रोजेक्ट नहीं)",
+ "chat.reference_new_in_global": "ग्लोबल में नया कार्य",
+ "chat.reference_new_in_project": "“{name}” में नया कार्य",
+ "chat.reference_search_all": "सभी कार्य खोजें",
+ "chat.reference_search_in": "“{name}” के कार्य खोजें",
+ "chat.reference_count_all": "कुल {count} · हाल में सक्रिय पहले",
+ "chat.reference_count_found": "{count} मिलीं · हाल में सक्रिय पहले",
+ "chat.reference_load_more": "पुराने कार्य लोड करें ({count} और)",
+ "chat.reference_no_match": "कोई मेल खाता कार्य नहीं",
+ "chat.reference_no_match_hint": "कोई दूसरा कीवर्ड आज़माएँ, या बाईं ओर कोई दूसरा दायरा चुनें।",
+ "chat.reference_scope_empty": "यहाँ अभी कोई कार्य नहीं है",
+ "chat.reference_scope_empty_hint": "ऊपर दिए बटन से यहाँ नया कार्य शुरू करें।",
+ "chat.reference_create_back": "कार्य सूची पर वापस जाएँ",
+ "chat.reference_create_title": "नया कार्य कहाँ बनाना है?",
+ "chat.reference_create_desc": "चुनने के बाद संदर्भ जोड़ दिए जाएँगे। कुछ भी अपने-आप नहीं भेजा जाएगा।",
+ "chat.reference_create_global_desc": "किसी प्रोजेक्ट का हिस्सा नहीं",
+ "chat.reference_create_project_desc": "इस प्रोजेक्ट में नया कार्य शुरू करें",
+ "chat.reference_target_footer": "चुनने पर लक्ष्य कार्य का इनपुट बॉक्स संदर्भों के साथ खुलेगा। कुछ भी अपने-आप नहीं भेजा जाएगा।",
+ "project.todo.run_busy": "इस कार्य की बातचीत अभी चल रही है। पूरा होने के बाद इसे फिर से चलाएँ।",
+ "settings.cleanup.title": "पुराने कार्य साफ़ करें",
+ "settings.cleanup.age": "अंतिम गतिविधि",
+ "settings.cleanup.scope": "प्रोजेक्ट के अंदर और बाहर के पूरे हुए कार्य। पिन किए गए, अपठित कार्य, ड्राफ़्ट और स्वचालन का इतिहास रखा जाता है।",
+ "settings.cleanup.days": "{n} दिन से पहले",
+ "settings.cleanup.result": "ट्रैश में भेजे: {deleted}। छोड़े: {skipped}। विफल: {failed}।",
+ "settings.cleanup.progress": "साफ़ हो रहा है {done} / {total}",
+ "settings.cleanup.error": "कार्य लोड या साफ़ नहीं हो सके। रीफ़्रेश करके फिर कोशिश करें।",
+ "settings.cleanup.count": "{n} कार्य चुने गए",
+ "settings.cleanup.empty": "साफ़ करने के लिए कोई पुराना कार्य नहीं है।",
+ "settings.cleanup.clean": "साफ़ करें",
+ "settings.cleanup.confirm": "{n} कार्य, उनके अटैचमेंट और एम्बेड किए गए परिणाम ट्रैश में भेजें। नीचे से इन्हें बहाल कर सकते हैं। सिंक चालू होने पर अन्य डिवाइस से भी हटेंगे। ट्रैश खाली करने पर डिस्क स्थान खाली होगा।",
+ "settings.cleanup.move": "ट्रैश में भेजें ({n})",
+ "settings.cleanup.previous": "पिछला",
+ "settings.cleanup.next": "अगला",
+ "apps.commercial_required": "वेब ऐप्स के लिए Orkas का व्यावसायिक संस्करण आवश्यक है। जारी रखने के लिए इसे डाउनलोड करें।",
+ "apps.commercial_download": "व्यावसायिक संस्करण डाउनलोड करें",
+ "apps.commercial_open_failed": "डाउनलोड पृष्ठ नहीं खुल सका। कृपया फिर प्रयास करें।"
}
diff --git a/src/renderer/locales/id.json b/src/renderer/locales/id.json
index 4dd11a5b..4439593c 100644
--- a/src/renderer/locales/id.json
+++ b/src/renderer/locales/id.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Download",
"web_assist.activity_visit": "Kunjungan",
"web_assist.download_saved": "Disimpan ke lampiran",
- "web_assist.download_needs_grant": "Butuh izin",
- "web_assist.download_blocked_type": "Jenis berkas tidak diizinkan",
- "web_assist.download_budget": "Batas unduhan tugas tercapai",
"web_assist.download_failed": "Gagal",
"web_assist.download_unavailable": "File tidak tersedia. Periksa apakah unduhan telah selesai dan file belum dipindahkan atau dihapus.",
- "web_assist.download_allow": "Izinkan situs ini",
- "web_assist.download_prompt_title": "Mengizinkan unduhan dari situs ini?",
- "web_assist.download_prompt_description": "File akan disimpan ke lampiran tugas ini. Setelah mengizinkan, kembali ke halaman dan coba lagi unduhan.",
- "web_assist.download_not_now": "Tidak sekarang",
- "web_assist.download_permission_failed": "Tidak dapat mengizinkan situs ini. Coba lagi.",
"web_assist.address_placeholder": "Cari Bing atau masukkan URL",
"web_assist.empty_title": "Jelajahi dalam tugas ini",
"web_assist.empty_hint": "Cari Bing atau masukkan URL di atas.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 hari terakhir",
"sidebar.bucket.older": "Lebih tua",
"sidebar.projects": "Proyek",
- "sidebar.today_tasks": "Tugas Hari Ini",
- "sidebar.today_empty": "Tidak ada tugas hari ini",
+ "sidebar.today_tasks": "Tugas Terbaru",
+ "sidebar.today_empty": "Tidak ada tugas dalam dua hari terakhir",
"sidebar.section_collapse": "Runtuh {section}",
"sidebar.section_expand": "Perluas {section}",
"sidebar.project_create_title": "Proyek baru",
"sidebar.project_create_placeholder": "Masukkan nama proyek",
"sidebar.project_conv_empty": "(Tidak ada tugas)",
- "sidebar.load_more_conversations": "Muat lebih banyak",
+ "sidebar.load_more_conversations": "Tampilkan lebih banyak",
"sidebar.connect_agent": "Agen penghubung",
"sidebar.connect_agent_sub": "Claude Code · Codex & lainnya",
"sidebar.settings": "Pengaturan",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Memuat...",
"new_chat.model_picker.aria_label": "Pilih model",
"new_chat.model_picker.empty": "Tidak ada model yang tersedia",
- "new_chat.model_picker.group_official": "Model resmi",
- "new_chat.model_picker.group_custom": "Model yang dikonfigurasi pengguna",
+ "new_chat.model_picker.group_official": "Model bawaan Orkas",
+ "new_chat.model_picker.group_custom": "API Key Anda sendiri",
"new_chat.model_picker.configure": "Konfigurasikan model",
"new_chat.model_picker.switch_failed": "Tidak dapat mengganti model. Coba lagi.",
"new_chat.model_picker.choose_version": "Pilih versi model untuk {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Ditambahkan ke {library}",
"conversation_info.file_add_to_library_failed": "Menambahkan ke Perpustakaan gagal: {reason}",
"conversation_info.file_add_to_chat_action": "Tambahkan ke obrolan tugas",
- "conversation_info.file_reveal_failed": "Tidak dapat membuka folder: {reason}",
+ "conversation_info.file_reveal_failed": "Tidak dapat membuka folder. File mungkin telah dipindahkan atau dihapus.",
"conversation_info.file_delete_confirm_title": "Hapus berkas",
"conversation_info.file_delete_confirm_msg": "Hapus \"{name}\"?",
"conversation_info.file_delete_failed": "Tidak dapat menghapus file: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Kirim sekarang",
"chat.queue_sending_now": "Mengirim...",
"chat.queue_send_now_failed": "Tidak dapat mengirim pesan antrian ini sekarang: {msg}",
- "chat.multi_dispatch_serial": "Jalankan secara berurutan",
- "chat.multi_dispatch_parallel": "Jalankan bersama",
- "chat.multi_dispatch_toggle_title": "Bagaimana agen yang disebutkan berjalan untuk pesan ini; klik untuk beralih",
"chat.task_waiting_on": "Menunggu {name}",
"chat.task_status_orchestrating": "Mengatur",
"chat.task_dispatched": "Dikirim oleh Komandan",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Hapus pesan {count} yang dipilih? Ini tidak bisa dibatalkan.",
"chat.message_delete_failed": "Gagal menghapus: {reason}",
"chat.reference_target_title": "Referensi pesan {count} di",
- "chat.reference_target_search": "Cari tugas",
- "chat.reference_new_task": "Tugas baru",
- "chat.reference_existing_tasks": "Tugas yang ada",
- "chat.reference_area_commander": "Komandan",
+ "chat.reference_new_task": "Tugas baru…",
"chat.reference_area_project": "Proyek",
- "chat.reference_recent_tasks_hint": "5 tugas terbaru",
- "chat.reference_search_results_count": "Hasil {count}",
- "chat.reference_no_tasks": "Tidak ada tugas yang cocok",
"chat.reference_unknown_task": "Tugas yang tidak diketahui",
"chat.reference_from_task": "Dikutip dari \"{title}\" @{name}",
"chat.reference_bundle_title": "Dari \"{title}\"",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Tambahkan layanan gambar",
"settings.models.add_video": "Tambahkan layanan video",
"settings.models.add_tts": "Tambahkan layanan pidato",
- "settings.models.order_hint": "Seret baris untuk mengubah prioritas, atau gunakan tombol panah. Model resmi yang dinonaktifkan dilewati.",
+ "settings.models.order_hint": "Seret baris untuk mengubah prioritas, atau gunakan tombol panah. Model bawaan yang dinonaktifkan dilewati.",
"settings.general.page_sub": "Sesuaikan preferensi, izin agen, dan pembaruan aplikasi.",
"settings.general.preferences_title": "Preferensi",
"settings.general.agent_title": "Perilaku agen",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Menyetujui",
"project.review.request_changes": "Meminta perubahan",
"project.driver.toggle": "Otomatis",
- "project.driver.toggle_hint": "AI menangani tugas-tugas secara otomatis untuk Anda tinjau setelah selesai.",
+ "project.driver.toggle_hint": "AI menangani tugas-tugas secara otomatis untuk Anda tinjau setelah selesai. Hanya berjalan di perangkat tempat Anda mengaktifkannya.",
"project.driver.enabled_toast": "Kemajuan otomatis aktif — secara berkala mengambil tugas yang tertunda dan mengerjakannya; tugas pindah ke Sedang berlangsung.",
"project.driver.disabled_toast": "Otomatis-manati.",
"project.recent_convs.view_all": "Lihat semua ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Runtuh",
"skills.source_external": "Bungkus",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "Izinkan tindakan ini di halaman?",
"chat.form.boolean_yes": "Ya",
"chat.form.boolean_no": "Tidak",
"chat.form.invalid_number": "Masukkan nomor yang valid",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Muat ulang",
"quality.operator.disabled": "Dinonaktifkan di perangkat ini.",
"quality.operator.ready": "Siap: {count} aturan.",
- "quality.operator.invalid": "Validasi tidak tersedia. Perbaiki operator-policy.json atau nonaktifkan validasi kustom, lalu coba lagi."
+ "quality.operator.invalid": "Validasi tidak tersedia. Perbaiki operator-policy.json atau nonaktifkan validasi kustom, lalu coba lagi.",
+ "chat.app_nav_project_collaboration_target": "Anggota proyek: {target}",
+ "new_chat.home.goal_title": "Punya tujuan yang jelas? Serahkan ke Komandan.",
+ "new_chat.home.goal_body": "Beri tahu Komandan apa yang ingin kamu capai, dan Komandan akan mengoordinasikan tim AI untuk menyelesaikannya.",
+ "new_chat.home.goal_example": "Misalnya: riset 3 produk sejenis, bandingkan fitur dan harganya, lalu rangkum menjadi presentasi.",
+ "new_chat.home.explore_title": "Belum yakin? Biarkan Orkas mengenalmu dulu.",
+ "new_chat.home.explore_body": "Ceritakan pekerjaan, bisnis, atau kendalamu, dan Orkas akan membantumu menemukan tujuan yang tepat serta terus menjalankannya.",
+ "new_chat.home.explore_context": "Bagikan file dengan + atau {connect} agar Orkas punya lebih banyak konteks. Mulailah dari hal yang nyaman kamu bagikan.",
+ "new_chat.home.explore_connect_link": "hubungkan Feishu / DingTalk / email",
+ "new_chat.home.input_placeholder": "Ceritakan apa yang ingin kamu capai, atau lampirkan file yang perlu diproses",
+ "new_chat.home.continue_label": "Lanjutkan pekerjaanmu",
+ "new_chat.home.group.todos": "Hal penting yang harus dilakukan",
+ "new_chat.home.group.automations": "Hasil otomatisasi",
+ "new_chat.home.group.tasks": "Tugas yang menunggumu",
+ "new_chat.home.all_automations": "Semua otomatisasi →",
+ "new_chat.home.expand": "Tampilkan {count} lainnya",
+ "new_chat.home.collapse": "Tampilkan lebih sedikit",
+ "new_chat.home.view_all_todos": "Lihat semua →",
+ "new_chat.home.source.project_todo": "{project} · Yang harus dilakukan",
+ "new_chat.home.source.global_todo": "Yang harus dilakukan (global)",
+ "new_chat.home.source.automation": "Otomatisasi",
+ "new_chat.home.source.project_task": "{project} · Tugas proyek",
+ "new_chat.home.source.global_task": "Tugas global",
+ "new_chat.home.result.completed": "Selesai",
+ "new_chat.home.result.failed": "Gagal",
+ "new_chat.home.result.waiting_input": "Menunggu masukanmu",
+ "new_chat.home.result.stopped": "Dihentikan",
+ "new_chat.home.result.unknown": "Ada hasil baru",
+ "new_chat.home.action.view": "Lihat",
+ "new_chat.home.action.reply": "Balas",
+ "new_chat.home.action.view_reason": "Lihat penyebab",
+ "new_chat.home.action.view_result": "Lihat hasil",
+ "new_chat.home.time.updated": "Diperbarui {time}",
+ "new_chat.home.untitled": "Tugas tanpa judul",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "Diperbarui {name}",
+ "apps.save_root_folder_required": "Pindahkan HTML dan sumber dayanya ke folder terpisah, lalu simpan kembali sebagai aplikasi.",
+ "chat.reference_locate_title": "Buka pesan asli",
+ "chat.reference_locate_missing": "Pesan asli tidak ada lagi.",
+ "agents.cli_usage_title": "Sisa kuota",
+ "agents.cli_usage_unavailable": "Tidak tersedia. Periksa login CLI dan koneksi.",
+ "agents.cli_usage_unsupported": "Versi CLI atau konfigurasi khusus ini tidak mendukung pemeriksaan kuota.",
+ "agents.cli_usage_resets": "Direset {time}",
+ "agents.cli_usage_hours": "{count} jam",
+ "agents.cli_usage_days": "{count} hari",
+ "agents.cli_usage_window": "Periode penggunaan",
+ "memory.full_notice": "Memori penuh. Sebelum menyimpan hal baru, AI akan menggabungkan entri yang ada.",
+ "memory.error_full": "Memori penuh, jadi entri ini belum dapat ditambahkan sekarang.",
+ "settings.recycle.clear": "Kosongkan",
+ "settings.recycle.clear_title": "Kosongkan Tempat Sampah",
+ "settings.recycle.clear_confirm": "Hapus permanen semua {count} catatan di {source}? Catatan tidak dapat dipulihkan setelahnya.",
+ "settings.recycle.clearing": "Mengosongkan {done}/{total}…",
+ "settings.recycle.cleared": "Tempat sampah dikosongkan",
+ "settings.recycle.clear_failed": "Tempat sampah belum sepenuhnya dikosongkan. Silakan coba lagi.",
+ "settings.recycle.automation_count": "Otomatisasi · {count} tugas",
+ "project.todo.move": "Pindah",
+ "bash.permission.allow_folder_read": "Izinkan membaca folder ini",
+ "bash.permission.folder_read_scope": "Selama tugas ini, {agent} dapat membaca file di {folder} tanpa bertanya lagi. Menulis, menghapus, dan file rahasia tetap meminta konfirmasi.",
+ "cli_upgrade.action": "Perbarui CLI",
+ "cli_upgrade.pending": "Memperbarui…",
+ "cli_upgrade.success": "Pembaruan berhasil",
+ "cli_upgrade.failed": "Pembaruan gagal",
+ "cli_upgrade.named_action": "Perbarui {cli} CLI",
+ "web_assist.handback": "Kembalikan kontrol ke AI",
+ "web_assist.permissions": "Reset izin situs",
+ "web_assist.permission_title": "Izin situs",
+ "web_assist.permission_allow": "Izinkan",
+ "web_assist.permission_deny": "Tolak",
+ "web_assist.permission_failed": "Pilihan tidak dapat disimpan. Coba lagi.",
+ "apps.view_details": "Lihat detail",
+ "apps.no_local_code": "Tidak ada kode aplikasi di perangkat ini",
+ "apps.publish_commercial": "Gunakan Orkas versi komersial untuk menerbitkan.",
+ "apps.update_original": "Perbarui aplikasi asli",
+ "apps.save_new": "Simpan aplikasi baru",
+ "apps.edit_conflict": "Aplikasi asli berubah atau dihapus. Buka ulang untuk mengedit atau simpan aplikasi baru.",
+ "apps.save_type_mismatch": "Versi ini memiliki jenis aplikasi yang berbeda dari aplikasi asli sehingga tidak dapat menggantikannya. Simpan sebagai aplikasi baru.",
+ "apps.type_local": "Aplikasi lokal",
+ "apps.type_web": "Aplikasi web",
+ "apps.type_local_description": "Berjalan di Orkas desktop dengan akses ke AI, file, pustaka, dan konektor; tidak dapat dipublikasikan ke web.",
+ "apps.type_web_description": "Publikasikan ke web dan akses melalui tautan, dengan pengumpulan, kueri, dan statistik data; fitur Orkas desktop tidak tersedia.",
+ "apps.delete_data_confirm": "Hapus \"{name}\", catatan lokal dan file pribadinya? Data tidak dapat dipulihkan.",
+ "apps.delete_online_retained": "Aplikasi yang diterbitkan dan data online tetap disimpan.",
+ "apps.migration_export": "Struktur data berubah. Ekspor catatan lokal sebelum menghapusnya.",
+ "apps.migration_export_action": "Ekspor catatan",
+ "apps.migration_continue": "Lanjutkan",
+ "apps.migration_clear": "Hapus semua catatan lokal dan perbarui? Catatan online tetap terpisah.",
+ "apps.migration_retry": "Hapus dan coba lagi",
+ "chat.reference_scope_label": "Cakupan tugas",
+ "chat.reference_scope_all": "Semua tugas",
+ "chat.reference_scope_global": "Global (tanpa proyek)",
+ "chat.reference_new_in_global": "Tugas baru di Global",
+ "chat.reference_new_in_project": "Tugas baru di “{name}”",
+ "chat.reference_search_all": "Cari di semua tugas",
+ "chat.reference_search_in": "Cari tugas di “{name}”",
+ "chat.reference_count_all": "Total {count} · terbaru dulu",
+ "chat.reference_count_found": "{count} ditemukan · terbaru dulu",
+ "chat.reference_load_more": "Muat tugas sebelumnya ({count} lagi)",
+ "chat.reference_no_match": "Tidak ada tugas yang cocok",
+ "chat.reference_no_match_hint": "Coba kata kunci lain, atau pilih cakupan lain di sebelah kiri.",
+ "chat.reference_scope_empty": "Belum ada tugas di sini",
+ "chat.reference_scope_empty_hint": "Gunakan tombol di atas untuk memulai tugas baru di sini.",
+ "chat.reference_create_back": "Kembali ke daftar tugas",
+ "chat.reference_create_title": "Di mana tugas baru akan dibuat?",
+ "chat.reference_create_desc": "Referensi ditambahkan setelah Anda memilih. Tidak ada yang dikirim otomatis.",
+ "chat.reference_create_global_desc": "Tidak termasuk proyek mana pun",
+ "chat.reference_create_project_desc": "Mulai tugas baru di proyek ini",
+ "chat.reference_target_footer": "Pilihan Anda membuka kolom input tugas dengan referensi ditambahkan. Tidak ada yang dikirim otomatis.",
+ "project.todo.run_busy": "Percakapan untuk tugas ini masih berjalan. Jalankan lagi setelah selesai.",
+ "settings.cleanup.title": "Bersihkan tugas lama",
+ "settings.cleanup.age": "Aktivitas terakhir",
+ "settings.cleanup.scope": "Tugas selesai di dalam maupun di luar proyek. Tugas disematkan, belum dibaca, draf, dan riwayat otomatisasi tetap disimpan.",
+ "settings.cleanup.days": "Lebih dari {n} hari lalu",
+ "settings.cleanup.result": "Dipindahkan ke sampah: {deleted}. Dilewati: {skipped}. Gagal: {failed}.",
+ "settings.cleanup.progress": "Membersihkan {done} / {total}",
+ "settings.cleanup.error": "Tidak dapat memuat atau membersihkan tugas. Muat ulang dan coba lagi.",
+ "settings.cleanup.count": "{n} tugas dipilih",
+ "settings.cleanup.empty": "Tidak ada tugas lama untuk dibersihkan.",
+ "settings.cleanup.clean": "Bersihkan",
+ "settings.cleanup.confirm": "Pindahkan {n} tugas, lampiran, dan hasil tertanam ke sampah. Anda dapat memulihkannya di bawah. Jika sinkronisasi aktif, penghapusan juga berlaku di perangkat lain. Ruang disk dibebaskan setelah sampah dikosongkan.",
+ "settings.cleanup.move": "Pindahkan ke sampah ({n})",
+ "settings.cleanup.previous": "Sebelumnya",
+ "settings.cleanup.next": "Berikutnya",
+ "apps.commercial_required": "Aplikasi web memerlukan Orkas versi komersial. Unduh untuk melanjutkan.",
+ "apps.commercial_download": "Unduh versi komersial",
+ "apps.commercial_open_failed": "Halaman unduhan tidak dapat dibuka. Coba lagi."
}
diff --git a/src/renderer/locales/it.json b/src/renderer/locales/it.json
index 1d08659d..80ce1f15 100644
--- a/src/renderer/locales/it.json
+++ b/src/renderer/locales/it.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Download",
"web_assist.activity_visit": "Visita",
"web_assist.download_saved": "salvato negli allegati",
- "web_assist.download_needs_grant": "richiede un permesso",
- "web_assist.download_blocked_type": "tipo di file non consentito",
- "web_assist.download_budget": "limite di download dell'attività raggiunto",
"web_assist.download_failed": "non riuscito",
"web_assist.download_unavailable": "File non disponibile. Verifica che il download sia terminato e che il file non sia stato spostato o eliminato.",
- "web_assist.download_allow": "Consenti questo sito",
- "web_assist.download_prompt_title": "Consentire i download da questo sito?",
- "web_assist.download_prompt_description": "I file verranno salvati negli allegati di questa attività. Dopo aver dato il consenso, torna alla pagina e riprova il download.",
- "web_assist.download_not_now": "Non ora",
- "web_assist.download_permission_failed": "Impossibile consentire questo sito. Riprova.",
"web_assist.address_placeholder": "Cerca con Bing o inserisci un URL",
"web_assist.empty_title": "Naviga in questa attività",
"web_assist.empty_hint": "Cerca con Bing o inserisci un URL qui sopra.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Ultimi 30 giorni",
"sidebar.bucket.older": "Precedenti",
"sidebar.projects": "Progetti",
- "sidebar.today_tasks": "Attività di oggi",
- "sidebar.today_empty": "Nessuna attività oggi",
+ "sidebar.today_tasks": "Attività recenti",
+ "sidebar.today_empty": "Nessuna attività negli ultimi due giorni",
"sidebar.section_collapse": "Comprimi {section}",
"sidebar.section_expand": "Espandi {section}",
"sidebar.project_create_title": "Nuovo progetto",
"sidebar.project_create_placeholder": "Inserisci il nome del progetto",
"sidebar.project_conv_empty": "(nessuna attività)",
- "sidebar.load_more_conversations": "Carica altro",
+ "sidebar.load_more_conversations": "Mostra altro",
"sidebar.connect_agent": "Connetti agenti",
"sidebar.connect_agent_sub": "Claude Code · Codex e altri",
"sidebar.settings": "Impostazioni",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Caricamento…",
"new_chat.model_picker.aria_label": "Scegli modello",
"new_chat.model_picker.empty": "Nessun modello disponibile",
- "new_chat.model_picker.group_official": "Modelli ufficiali",
- "new_chat.model_picker.group_custom": "Modelli configurati dall'utente",
+ "new_chat.model_picker.group_official": "Modelli integrati Orkas",
+ "new_chat.model_picker.group_custom": "La tua API Key",
"new_chat.model_picker.configure": "Configura modelli",
"new_chat.model_picker.switch_failed": "Impossibile cambiare modello. Riprova.",
"new_chat.model_picker.choose_version": "Scegli una versione del modello per {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Aggiunto a {library}",
"conversation_info.file_add_to_library_failed": "Aggiunta alla biblioteca non riuscita: {reason}",
"conversation_info.file_add_to_chat_action": "Aggiungi alla chat dell'attività",
- "conversation_info.file_reveal_failed": "Impossibile aprire la cartella: {reason}",
+ "conversation_info.file_reveal_failed": "Impossibile aprire la cartella. Il file potrebbe essere stato spostato o eliminato.",
"conversation_info.file_delete_confirm_title": "Elimina file",
"conversation_info.file_delete_confirm_msg": "Eliminare \"{name}\"?",
"conversation_info.file_delete_failed": "Impossibile eliminare il file: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Invia ora",
"chat.queue_sending_now": "Invio…",
"chat.queue_send_now_failed": "Impossibile inviare ora questo messaggio in coda: {msg}",
- "chat.multi_dispatch_serial": "Esegui in sequenza",
- "chat.multi_dispatch_parallel": "Esegui insieme",
- "chat.multi_dispatch_toggle_title": "Come vengono eseguiti gli agenti menzionati in questo messaggio; fai clic per cambiare",
"chat.task_waiting_on": "In attesa di {name}",
"chat.task_status_orchestrating": "Coordinamento",
"chat.task_dispatched": "Assegnata da Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Eliminare i messaggi selezionati ({count})? L'operazione è irreversibile.",
"chat.message_delete_failed": "Eliminazione non riuscita: {reason}",
"chat.reference_target_title": "Richiama i messaggi ({count}) in",
- "chat.reference_target_search": "Cerca attività",
- "chat.reference_new_task": "Nuova attività",
- "chat.reference_existing_tasks": "Attività esistenti",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nuova attività…",
"chat.reference_area_project": "Progetto",
- "chat.reference_recent_tasks_hint": "Le 5 attività più recenti",
- "chat.reference_search_results_count": "Risultati: {count}",
- "chat.reference_no_tasks": "Nessuna attività corrispondente",
"chat.reference_unknown_task": "Attività sconosciuta",
"chat.reference_from_task": "Citazione da “{title}” @{name}",
"chat.reference_bundle_title": "Da “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Aggiungi servizio di immagini",
"settings.models.add_video": "Aggiungi servizio video",
"settings.models.add_tts": "Aggiungi servizio vocale",
- "settings.models.order_hint": "Trascina le righe per cambiare priorità oppure usa i pulsanti freccia. I modelli ufficiali disabilitati vengono saltati.",
+ "settings.models.order_hint": "Trascina le righe per cambiare priorità oppure usa i pulsanti freccia. I modelli integrati disabilitati vengono saltati.",
"settings.general.page_sub": "Regola preferenze e permessi degli agenti.",
"settings.general.preferences_title": "Preferenze",
"settings.general.agent_title": "Comportamento degli agenti",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Approva",
"project.review.request_changes": "Richiedi modifiche",
"project.driver.toggle": "Auto",
- "project.driver.toggle_hint": "L'IA gestisce automaticamente le attività da fare; potrai esaminarle quando saranno completate.",
+ "project.driver.toggle_hint": "L'IA gestisce automaticamente le attività da fare; potrai esaminarle quando saranno completate. Viene eseguito solo sul dispositivo su cui lo attivi.",
"project.driver.enabled_toast": "Avanzamento automatico attivo: seleziona periodicamente un'attività arretrata e la svolge; le attività passano a In corso.",
"project.driver.disabled_toast": "Avanzamento automatico disattivato.",
"project.recent_convs.view_all": "Vedi tutto ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Comprimi",
"skills.source_external": "Pacchetto",
"skills.source_global": "Globale",
- "web_assist.action_confirm.title": "Consentire questa azione sulla pagina?",
"chat.form.boolean_yes": "Sì",
"chat.form.boolean_no": "No",
"chat.form.invalid_number": "Inserisci un numero valido",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Ricarica",
"quality.operator.disabled": "Disattivata su questo dispositivo.",
"quality.operator.ready": "Pronta: {count} regole.",
- "quality.operator.invalid": "Validazione non disponibile. Correggi operator-policy.json o disattiva la validazione personalizzata, quindi riprova."
+ "quality.operator.invalid": "Validazione non disponibile. Correggi operator-policy.json o disattiva la validazione personalizzata, quindi riprova.",
+ "chat.app_nav_project_collaboration_target": "Membri del progetto: {target}",
+ "new_chat.home.goal_title": "Hai un obiettivo chiaro? Affidalo al Commander.",
+ "new_chat.home.goal_body": "Di’ al Commander cosa vuoi realizzare: coordinerà il tuo team di IA per portarlo a termine.",
+ "new_chat.home.goal_example": "Ad esempio: analizza 3 prodotti simili, confronta funzionalità e prezzi e riassumi tutto in una presentazione.",
+ "new_chat.home.explore_title": "Non hai ancora le idee chiare? Lascia prima che Orkas ti conosca.",
+ "new_chat.home.explore_body": "Parla del tuo lavoro, della tua attività o delle tue difficoltà: Orkas ti aiuterà a trovare gli obiettivi giusti e a portarli avanti.",
+ "new_chat.home.explore_context": "Condividi file con + oppure {connect} per dare più contesto a Orkas. Inizia da ciò che ti senti di condividere.",
+ "new_chat.home.explore_connect_link": "collega Feishu / DingTalk / email",
+ "new_chat.home.input_placeholder": "Descrivi cosa vuoi realizzare oppure allega i file da elaborare",
+ "new_chat.home.continue_label": "Porta avanti il lavoro",
+ "new_chat.home.group.todos": "Da fare importanti",
+ "new_chat.home.group.automations": "Automazioni da controllare",
+ "new_chat.home.group.tasks": "Attività che ti aspettano",
+ "new_chat.home.all_automations": "Tutte le automazioni →",
+ "new_chat.home.expand": "Mostra altri {count}",
+ "new_chat.home.collapse": "Mostra meno",
+ "new_chat.home.view_all_todos": "Vedi tutto →",
+ "new_chat.home.source.project_todo": "{project} · Da fare",
+ "new_chat.home.source.global_todo": "Da fare globale",
+ "new_chat.home.source.automation": "Automazione",
+ "new_chat.home.source.project_task": "{project} · Attività di progetto",
+ "new_chat.home.source.global_task": "Attività globale",
+ "new_chat.home.result.completed": "Completata",
+ "new_chat.home.result.failed": "Non riuscita",
+ "new_chat.home.result.waiting_input": "In attesa di te",
+ "new_chat.home.result.stopped": "Interrotta",
+ "new_chat.home.result.unknown": "Nuovo risultato",
+ "new_chat.home.action.view": "Apri",
+ "new_chat.home.action.reply": "Rispondi",
+ "new_chat.home.action.view_reason": "Vedi il motivo",
+ "new_chat.home.action.view_result": "Vedi il risultato",
+ "new_chat.home.time.updated": "Aggiornato {time}",
+ "new_chat.home.untitled": "Attività senza titolo",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "Aggiornato {name}",
+ "apps.save_root_folder_required": "Sposta il file HTML e le relative risorse in una cartella dedicata, poi salva di nuovo come app.",
+ "chat.reference_locate_title": "Vai al messaggio originale",
+ "chat.reference_locate_missing": "Il messaggio originale non esiste più.",
+ "agents.cli_usage_title": "Quota residua",
+ "agents.cli_usage_unavailable": "Non disponibile. Verifica accesso alla CLI e connessione.",
+ "agents.cli_usage_unsupported": "Questa versione della CLI o configurazione personalizzata non supporta la verifica della quota.",
+ "agents.cli_usage_resets": "Ripristino: {time}",
+ "agents.cli_usage_hours": "{count} ore",
+ "agents.cli_usage_days": "{count} giorni",
+ "agents.cli_usage_window": "Periodo di utilizzo",
+ "memory.full_notice": "La memoria è piena. Prima di salvare qualcosa di nuovo, l'IA unirà le voci esistenti.",
+ "memory.error_full": "La memoria è piena, quindi questa voce non può essere aggiunta ora.",
+ "settings.recycle.clear": "Svuota",
+ "settings.recycle.clear_title": "Svuota il cestino",
+ "settings.recycle.clear_confirm": "Eliminare definitivamente tutti i {count} elementi in {source}? Non potranno più essere ripristinati.",
+ "settings.recycle.clearing": "Svuotamento {done}/{total}…",
+ "settings.recycle.cleared": "Cestino svuotato",
+ "settings.recycle.clear_failed": "Non è stato possibile svuotare tutto il cestino. Riprova.",
+ "settings.recycle.automation_count": "Automazione · {count} attività",
+ "project.todo.move": "Sposta",
+ "bash.permission.allow_folder_read": "Consenti la lettura di questa cartella",
+ "bash.permission.folder_read_scope": "Per questa attività, {agent} può leggere i file in {folder} senza chiedere di nuovo. Scrittura, eliminazione e file segreti richiedono ancora conferma.",
+ "cli_upgrade.action": "Aggiorna CLI",
+ "cli_upgrade.pending": "Aggiornamento…",
+ "cli_upgrade.success": "Aggiornamento riuscito",
+ "cli_upgrade.failed": "Aggiornamento non riuscito",
+ "cli_upgrade.named_action": "Aggiorna {cli} CLI",
+ "web_assist.handback": "Restituisci il controllo all’IA",
+ "web_assist.permissions": "Reimposta autorizzazioni del sito",
+ "web_assist.permission_title": "Autorizzazione del sito",
+ "web_assist.permission_allow": "Consenti",
+ "web_assist.permission_deny": "Nega",
+ "web_assist.permission_failed": "Impossibile salvare la scelta. Riprova.",
+ "apps.view_details": "Vedi dettagli",
+ "apps.no_local_code": "Nessun codice dell’app su questo dispositivo",
+ "apps.publish_commercial": "Usa la versione commerciale di Orkas per pubblicare.",
+ "apps.update_original": "Aggiorna app originale",
+ "apps.save_new": "Salva nuova app",
+ "apps.edit_conflict": "L’app originale è cambiata o è stata eliminata. Riaprila o salva una nuova app.",
+ "apps.save_type_mismatch": "Questa versione è di un tipo diverso dall’app originale e non può sostituirla. Salvala invece come nuova app.",
+ "apps.type_local": "App locale",
+ "apps.type_web": "App web",
+ "apps.type_local_description": "Funziona in Orkas desktop con accesso a IA, file, libreria e connettori; non può essere pubblicata sul web.",
+ "apps.type_web_description": "Pubblica sul web e accedi tramite un link, con raccolta, query e statistiche dei dati; le funzionalità di Orkas desktop non sono disponibili.",
+ "apps.delete_data_confirm": "Eliminare \"{name}\", i suoi dati locali e file privati? I dati non sono recuperabili.",
+ "apps.delete_online_retained": "L’app pubblicata e i dati online vengono conservati.",
+ "apps.migration_export": "La struttura dei dati cambia. Esporta i record locali prima di eliminarli.",
+ "apps.migration_export_action": "Esporta record",
+ "apps.migration_continue": "Continua",
+ "apps.migration_clear": "Eliminare tutti i record locali e aggiornare? I record online sono indipendenti.",
+ "apps.migration_retry": "Elimina e riprova",
+ "chat.reference_scope_label": "Ambito delle attività",
+ "chat.reference_scope_all": "Tutte le attività",
+ "chat.reference_scope_global": "Globale (nessun progetto)",
+ "chat.reference_new_in_global": "Nuova attività in Globale",
+ "chat.reference_new_in_project": "Nuova attività in «{name}»",
+ "chat.reference_search_all": "Cerca in tutte le attività",
+ "chat.reference_search_in": "Cerca attività in «{name}»",
+ "chat.reference_count_all": "{count} in totale · più recenti prima",
+ "chat.reference_count_found": "{count} trovate · più recenti prima",
+ "chat.reference_load_more": "Carica attività precedenti (altre {count})",
+ "chat.reference_no_match": "Nessuna attività corrispondente",
+ "chat.reference_no_match_hint": "Prova un’altra parola chiave o scegli un altro ambito a sinistra.",
+ "chat.reference_scope_empty": "Ancora nessuna attività qui",
+ "chat.reference_scope_empty_hint": "Usa il pulsante in alto per avviare un’attività qui.",
+ "chat.reference_create_back": "Torna alle attività",
+ "chat.reference_create_title": "Dove vuoi creare la nuova attività?",
+ "chat.reference_create_desc": "I riferimenti vengono aggiunti dopo la scelta. Nulla viene inviato automaticamente.",
+ "chat.reference_create_global_desc": "Non appartiene a nessun progetto",
+ "chat.reference_create_project_desc": "Avvia un’attività in questo progetto",
+ "chat.reference_target_footer": "La scelta apre il campo di input dell’attività con i riferimenti aggiunti. Nulla viene inviato automaticamente.",
+ "project.todo.run_busy": "La conversazione di questa attività è ancora in corso. Eseguila di nuovo al termine.",
+ "settings.cleanup.title": "Pulisci le attività precedenti",
+ "settings.cleanup.age": "Ultima attività",
+ "settings.cleanup.scope": "Attività completate dentro e fuori dai progetti. Restano le attività fissate, non lette, le bozze e le esecuzioni automatiche.",
+ "settings.cleanup.days": "Più di {n} giorni fa",
+ "settings.cleanup.result": "Nel cestino: {deleted}. Ignorate: {skipped}. Non riuscite: {failed}.",
+ "settings.cleanup.progress": "Pulizia {done} / {total}",
+ "settings.cleanup.error": "Impossibile caricare o pulire le attività. Aggiorna e riprova.",
+ "settings.cleanup.count": "{n} attività selezionate",
+ "settings.cleanup.empty": "Nessuna attività precedente da pulire.",
+ "settings.cleanup.clean": "Pulisci",
+ "settings.cleanup.confirm": "Sposta {n} attività, allegati e risultati incorporati nel cestino. Potrai ripristinarli qui sotto. Con la sincronizzazione attiva, la rimozione si applica anche agli altri dispositivi. Lo spazio viene liberato svuotando il cestino.",
+ "settings.cleanup.move": "Sposta nel cestino ({n})",
+ "settings.cleanup.previous": "Precedente",
+ "settings.cleanup.next": "Successivo",
+ "apps.commercial_required": "Le app web richiedono la versione commerciale di Orkas. Scaricala per continuare.",
+ "apps.commercial_download": "Scarica la versione commerciale",
+ "apps.commercial_open_failed": "Impossibile aprire la pagina di download. Riprova."
}
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index 7144b547..1b2c1996 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "ダウンロード",
"web_assist.activity_visit": "アクセス",
"web_assist.download_saved": "添付に保存しました",
- "web_assist.download_needs_grant": "許可が必要",
- "web_assist.download_blocked_type": "この種類は許可されていません",
- "web_assist.download_budget": "このタスクのダウンロード上限に達しました",
"web_assist.download_failed": "失敗",
"web_assist.download_unavailable": "ファイルにアクセスできません。ダウンロードが完了し、ファイルが移動または削除されていないか確認してください。",
- "web_assist.download_allow": "このサイトを許可",
- "web_assist.download_prompt_title": "このサイトからのダウンロードを許可しますか?",
- "web_assist.download_prompt_description": "ファイルはこのタスクの添付に保存されます。許可後、ページに戻ってダウンロードをやり直してください。",
- "web_assist.download_not_now": "今は許可しない",
- "web_assist.download_permission_failed": "許可できませんでした。もう一度お試しください。",
"web_assist.address_placeholder": "Bing で検索または URL を入力",
"web_assist.empty_title": "このタスクでウェブを閲覧",
"web_assist.empty_hint": "上で Bing 検索または URL を入力してください。",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30日以内",
"sidebar.bucket.older": "それ以前",
"sidebar.projects": "プロジェクト",
- "sidebar.today_tasks": "本日のタスク",
- "sidebar.today_empty": "本日のタスクはありません",
+ "sidebar.today_tasks": "最近のタスク",
+ "sidebar.today_empty": "直近2日間のタスクはありません",
"sidebar.section_collapse": "{section}を折りたたむ",
"sidebar.section_expand": "{section}を展開",
"sidebar.project_create_title": "新規プロジェクト",
"sidebar.project_create_placeholder": "プロジェクト名を入力",
"sidebar.project_conv_empty": "(タスクなし)",
- "sidebar.load_more_conversations": "さらに読み込む",
+ "sidebar.load_more_conversations": "さらに表示",
"sidebar.connect_agent": "エージェントを接続",
"sidebar.connect_agent_sub": "Claude Code · Codex など",
"sidebar.settings": "設定",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "読み込み中…",
"new_chat.model_picker.aria_label": "モデルを選択",
"new_chat.model_picker.empty": "利用可能なモデルがありません",
- "new_chat.model_picker.group_official": "公式モデル",
- "new_chat.model_picker.group_custom": "ユーザー設定モデル",
+ "new_chat.model_picker.group_official": "Orkas 内蔵モデル",
+ "new_chat.model_picker.group_custom": "自分の API Key",
"new_chat.model_picker.configure": "モデルを設定",
"new_chat.model_picker.switch_failed": "モデルを切り替えられませんでした。もう一度お試しください。",
"new_chat.model_picker.choose_version": "{account} のモデルバージョンを選択",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "{library}に追加しました",
"conversation_info.file_add_to_library_failed": "ライブラリへの追加に失敗しました: {reason}",
"conversation_info.file_add_to_chat_action": "タスクチャットに追加",
- "conversation_info.file_reveal_failed": "フォルダを開けませんでした: {reason}",
+ "conversation_info.file_reveal_failed": "フォルダを開けませんでした。ファイルが移動または削除された可能性があります。",
"conversation_info.file_delete_confirm_title": "ファイルを削除",
"conversation_info.file_delete_confirm_msg": "「{name}」を削除しますか?",
"conversation_info.file_delete_failed": "ファイルを削除できませんでした: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "今すぐ送信",
"chat.queue_sending_now": "送信中…",
"chat.queue_send_now_failed": "キュー内のメッセージを今すぐ送信できませんでした:{msg}",
- "chat.multi_dispatch_serial": "順番に実行",
- "chat.multi_dispatch_parallel": "同時に実行",
- "chat.multi_dispatch_toggle_title": "このメッセージでメンションした複数エージェントの実行方式。クリックで切り替え",
"chat.task_waiting_on": "{name} の完了待ち",
"chat.task_status_orchestrating": "編成中",
"chat.task_dispatched": "指揮官が派遣",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "選択した{count}件のメッセージを削除しますか?この操作は取り消せません。",
"chat.message_delete_failed": "削除に失敗しました:{reason}",
"chat.reference_target_title": "{count}件のメッセージの参照先",
- "chat.reference_target_search": "タスクを検索",
- "chat.reference_new_task": "新しいタスク",
- "chat.reference_existing_tasks": "既存のタスク",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "新しいタスク…",
"chat.reference_area_project": "プロジェクト",
- "chat.reference_recent_tasks_hint": "最近の5件のタスク",
- "chat.reference_search_results_count": "{count}件の結果",
- "chat.reference_no_tasks": "一致するタスクはありません",
"chat.reference_unknown_task": "不明なタスク",
"chat.reference_from_task": "「{title}」の @{name} からの引用",
"chat.reference_bundle_title": "「{title}」より",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "画像サービスを追加",
"settings.models.add_video": "動画サービスを追加",
"settings.models.add_tts": "音声サービスを追加",
- "settings.models.order_hint": "行をドラッグするか矢印ボタンで優先順位を変更できます。無効化した公式モデルは使用されません。",
+ "settings.models.order_hint": "行をドラッグするか矢印ボタンで優先順位を変更できます。無効化した内蔵モデルは使用されません。",
"settings.general.page_sub": "利用設定とエージェント権限を調整します。",
"settings.general.preferences_title": "利用設定",
"settings.general.agent_title": "エージェントの動作",
@@ -2031,7 +2014,7 @@
"project.review.approve": "承認",
"project.review.request_changes": "修正を依頼",
"project.driver.toggle": "自動推進",
- "project.driver.toggle_hint": "AI がTo-doを自動で処理し、完了後にあなたが確認します。",
+ "project.driver.toggle_hint": "AI がTo-doを自動で処理し、完了後にあなたが確認します。オンにしたデバイスでのみ実行されます。",
"project.driver.enabled_toast": "自動推進をオンにしました —— バックログからタスクを定期的に選んで進めます。タスクは「進行中」になります。",
"project.driver.disabled_toast": "自動推進をオフにしました。",
"project.recent_convs.view_all": "すべて表示 ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "折りたたむ",
"skills.source_external": "パッケージ",
"skills.source_global": "グローバル",
- "web_assist.action_confirm.title": "このページでこの操作を許可しますか?",
"chat.form.boolean_yes": "はい",
"chat.form.boolean_no": "いいえ",
"chat.form.invalid_number": "有効な数値を入力してください",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "再読み込み",
"quality.operator.disabled": "このデバイスでは無効です。",
"quality.operator.ready": "準備完了:{count} 件のルール。",
- "quality.operator.invalid": "検証を利用できません。operator-policy.json を修正するか、カスタム検証を無効にしてから再試行してください。"
+ "quality.operator.invalid": "検証を利用できません。operator-policy.json を修正するか、カスタム検証を無効にしてから再試行してください。",
+ "chat.app_nav_project_collaboration_target": "プロジェクトメンバー:{target}",
+ "new_chat.home.goal_title": "目標が決まっている? Commander に任せましょう。",
+ "new_chat.home.goal_body": "達成したいことを Commander に伝えると、AI チームを指揮して仕上げます。",
+ "new_chat.home.goal_example": "例:同類製品を 3 つ調査し、機能と価格を比較して、プレゼン資料にまとめる。",
+ "new_chat.home.explore_title": "まだ決まっていない? まずは Orkas にあなたのことを伝えましょう。",
+ "new_chat.home.explore_body": "仕事やビジネス、困っていることを話してください。Orkas が合った目標を見つけ、継続的に進めるお手伝いをします。",
+ "new_chat.home.explore_context": "+ で資料を共有するか、{connect}して背景を補うと、Orkas があなたをより深く理解できます。共有してもよい内容から始めてください。",
+ "new_chat.home.explore_connect_link": "Feishu / DingTalk / メールを接続",
+ "new_chat.home.input_placeholder": "達成したいことを書くか、処理したい資料を添付してください",
+ "new_chat.home.continue_label": "やりかけの仕事を進めましょう",
+ "new_chat.home.group.todos": "重要な ToDo",
+ "new_chat.home.group.automations": "確認待ちの自動化",
+ "new_chat.home.group.tasks": "対応が必要なタスク",
+ "new_chat.home.all_automations": "すべての自動化 →",
+ "new_chat.home.expand": "残り {count} 件を表示",
+ "new_chat.home.collapse": "折りたたむ",
+ "new_chat.home.view_all_todos": "すべて表示 →",
+ "new_chat.home.source.project_todo": "{project} · ToDo",
+ "new_chat.home.source.global_todo": "グローバル ToDo",
+ "new_chat.home.source.automation": "自動化",
+ "new_chat.home.source.project_task": "{project} · プロジェクトタスク",
+ "new_chat.home.source.global_task": "グローバルタスク",
+ "new_chat.home.result.completed": "完了",
+ "new_chat.home.result.failed": "失敗",
+ "new_chat.home.result.waiting_input": "入力待ち",
+ "new_chat.home.result.stopped": "停止済み",
+ "new_chat.home.result.unknown": "新しい結果",
+ "new_chat.home.action.view": "表示",
+ "new_chat.home.action.reply": "返信する",
+ "new_chat.home.action.view_reason": "原因を見る",
+ "new_chat.home.action.view_result": "結果を見る",
+ "new_chat.home.time.updated": "更新: {time}",
+ "new_chat.home.untitled": "無題のタスク",
+ "artifact.failure_detail": "{action}:{detail}",
+ "apps.updated_toast": "{name} を更新しました",
+ "apps.save_root_folder_required": "HTML と関連リソースを専用フォルダーに移してから、もう一度アプリとして保存してください。",
+ "chat.reference_locate_title": "元のメッセージへ移動",
+ "chat.reference_locate_missing": "元のメッセージはもう存在しません。",
+ "agents.cli_usage_title": "残り利用枠",
+ "agents.cli_usage_unavailable": "取得できません。CLI のログインと接続を確認してください。",
+ "agents.cli_usage_unsupported": "この CLI バージョンまたはカスタム設定では利用枠を取得できません。",
+ "agents.cli_usage_resets": "リセット:{time}",
+ "agents.cli_usage_hours": "{count} 時間",
+ "agents.cli_usage_days": "{count} 日",
+ "agents.cli_usage_window": "利用期間",
+ "memory.full_notice": "メモリがいっぱいです。新しい内容を保存する前に、AI が既存の項目を整理して統合します。",
+ "memory.error_full": "メモリがいっぱいのため、この項目は今は追加できません。",
+ "settings.recycle.clear": "空にする",
+ "settings.recycle.clear_title": "ごみ箱を空にする",
+ "settings.recycle.clear_confirm": "「{source}」の全 {count} 件を完全に削除しますか?削除後は復元できません。",
+ "settings.recycle.clearing": "削除中 {done}/{total}…",
+ "settings.recycle.cleared": "ごみ箱を空にしました",
+ "settings.recycle.clear_failed": "ごみ箱を空にできませんでした。もう一度お試しください。",
+ "settings.recycle.automation_count": "自動化 · {count} 件のタスク",
+ "project.todo.move": "移動",
+ "bash.permission.allow_folder_read": "このフォルダの読み取りを許可",
+ "bash.permission.folder_read_scope": "このタスク中、{agent} は「{folder}」内のファイルを確認なしで読み取れます。書き込み、削除、秘密情報のファイルは引き続き確認します。",
+ "cli_upgrade.action": "CLI を更新",
+ "cli_upgrade.pending": "更新中…",
+ "cli_upgrade.success": "更新しました",
+ "cli_upgrade.failed": "更新に失敗しました",
+ "cli_upgrade.named_action": "{cli} CLI を更新",
+ "web_assist.handback": "AI に操作を戻す",
+ "web_assist.permissions": "サイトの権限をリセット",
+ "web_assist.permission_title": "サイトの権限",
+ "web_assist.permission_allow": "許可",
+ "web_assist.permission_deny": "拒否",
+ "web_assist.permission_failed": "選択を保存できませんでした。もう一度お試しください。",
+ "apps.view_details": "詳細を表示",
+ "apps.no_local_code": "この端末にアプリのコードがありません",
+ "apps.publish_commercial": "アプリの公開には Orkas 商用版をご利用ください。",
+ "apps.update_original": "元のアプリを更新",
+ "apps.save_new": "新しいアプリとして保存",
+ "apps.edit_conflict": "元のアプリが変更または削除されました。再度編集を開くか、新しいアプリとして保存してください。",
+ "apps.save_type_mismatch": "このバージョンは元のアプリと種類が異なるため、置き換えられません。新しいアプリとして保存してください。",
+ "apps.type_local": "ローカルアプリ",
+ "apps.type_web": "Webアプリ",
+ "apps.type_local_description": "Orkas デスクトップで動作し、AI、ファイル、ライブラリ、コネクタなどを利用できます。Web には公開できません。",
+ "apps.type_web_description": "Web に公開してリンクからアクセスでき、データの収集・検索・集計に対応しています。Orkas デスクトップの機能は利用できません。",
+ "apps.delete_data_confirm": "「{name}」とローカルの記録・専用ファイルを削除しますか?データは復元できません。",
+ "apps.delete_online_retained": "公開アプリとオンラインデータは保持されます。",
+ "apps.migration_export": "データ構造が変わります。削除前にローカル記録をエクスポートできます。",
+ "apps.migration_export_action": "記録をエクスポート",
+ "apps.migration_continue": "続ける",
+ "apps.migration_clear": "ローカル記録をすべて削除して更新しますか?オンライン記録は独立しています。",
+ "apps.migration_retry": "削除して再試行",
+ "chat.reference_scope_label": "タスクの範囲",
+ "chat.reference_scope_all": "すべてのタスク",
+ "chat.reference_scope_global": "全体(プロジェクトなし)",
+ "chat.reference_new_in_global": "全体に新しいタスクを作成",
+ "chat.reference_new_in_project": "「{name}」に新しいタスクを作成",
+ "chat.reference_search_all": "すべてのタスクを検索",
+ "chat.reference_search_in": "「{name}」のタスクを検索",
+ "chat.reference_count_all": "全{count}件 · 最近のアクティブ順",
+ "chat.reference_count_found": "{count}件見つかりました · 最近のアクティブ順",
+ "chat.reference_load_more": "以前のタスクを読み込む(残り{count}件)",
+ "chat.reference_no_match": "一致するタスクはありません",
+ "chat.reference_no_match_hint": "別のキーワードを試すか、左側で別の範囲を選択してください。",
+ "chat.reference_scope_empty": "まだタスクがありません",
+ "chat.reference_scope_empty_hint": "上のボタンからここに新しいタスクを作成できます。",
+ "chat.reference_create_back": "タスク一覧に戻る",
+ "chat.reference_create_title": "新しいタスクをどこに作成しますか?",
+ "chat.reference_create_desc": "作成先を選ぶと参照が追加されます。自動では送信されません。",
+ "chat.reference_create_global_desc": "どのプロジェクトにも属しません",
+ "chat.reference_create_project_desc": "このプロジェクトに新しいタスクを作成",
+ "chat.reference_target_footer": "選択すると対象のタスクの入力欄に参照が追加されます。自動では送信されません。",
+ "project.todo.run_busy": "このタスクの会話はまだ処理中です。終わってからもう一度実行してください。",
+ "settings.cleanup.title": "過去のタスクを整理",
+ "settings.cleanup.age": "最終アクティビティ",
+ "settings.cleanup.scope": "プロジェクト内外の完了済みタスクが対象です。固定済み・未読・下書きのあるタスクと自動化の実行履歴は保持されます。",
+ "settings.cleanup.days": "{n} 日より前",
+ "settings.cleanup.result": "ごみ箱へ移動:{deleted} 件。スキップ:{skipped} 件。失敗:{failed} 件。",
+ "settings.cleanup.progress": "整理中 {done} / {total}",
+ "settings.cleanup.error": "タスクの読み込みまたは整理ができませんでした。更新して再試行してください。",
+ "settings.cleanup.count": "{n} 件を選択中",
+ "settings.cleanup.empty": "整理できる過去のタスクはありません。",
+ "settings.cleanup.clean": "整理",
+ "settings.cleanup.confirm": "{n} 件のタスクと添付ファイル、埋め込み結果をごみ箱へ移動します。下から復元できます。同期が有効な場合、他のデバイスにも削除が反映されます。ディスク容量はごみ箱を空にすると解放されます。",
+ "settings.cleanup.move": "ごみ箱へ移動({n})",
+ "settings.cleanup.previous": "前へ",
+ "settings.cleanup.next": "次へ",
+ "apps.commercial_required": "Web アプリには Orkas 商用版が必要です。商用版をダウンロードして続けてください。",
+ "apps.commercial_download": "商用版をダウンロード",
+ "apps.commercial_open_failed": "ダウンロードページを開けませんでした。もう一度お試しください。"
}
diff --git a/src/renderer/locales/ko.json b/src/renderer/locales/ko.json
index 939446e7..22725f28 100644
--- a/src/renderer/locales/ko.json
+++ b/src/renderer/locales/ko.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "다운로드",
"web_assist.activity_visit": "방문",
"web_assist.download_saved": "첨부 파일에 저장됨",
- "web_assist.download_needs_grant": "권한 필요",
- "web_assist.download_blocked_type": "허용되지 않는 파일 형식",
- "web_assist.download_budget": "작업 다운로드 한도 도달",
"web_assist.download_failed": "실패",
"web_assist.download_unavailable": "파일을 사용할 수 없습니다. 다운로드가 완료되었고 파일이 이동되거나 삭제되지 않았는지 확인해 주세요.",
- "web_assist.download_allow": "이 사이트 허용",
- "web_assist.download_prompt_title": "이 사이트의 다운로드를 허용할까요?",
- "web_assist.download_prompt_description": "파일이 이 작업의 첨부 파일에 저장됩니다. 허용한 후 페이지로 돌아가 다운로드를 다시 시도해 주세요.",
- "web_assist.download_not_now": "나중에",
- "web_assist.download_permission_failed": "이 사이트를 허용할 수 없습니다. 다시 시도해 주세요.",
"web_assist.address_placeholder": "Bing 검색 또는 URL 입력",
"web_assist.empty_title": "이 작업에서 웹 탐색",
"web_assist.empty_hint": "위에서 Bing을 검색하거나 URL을 입력하세요.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "최근 30일",
"sidebar.bucket.older": "이전",
"sidebar.projects": "프로젝트",
- "sidebar.today_tasks": "오늘의 작업",
- "sidebar.today_empty": "오늘 작업이 없습니다",
+ "sidebar.today_tasks": "최근 작업",
+ "sidebar.today_empty": "최근 이틀간 작업이 없습니다",
"sidebar.section_collapse": "{section} 접기",
"sidebar.section_expand": "{section} 펼치기",
"sidebar.project_create_title": "새 프로젝트",
"sidebar.project_create_placeholder": "프로젝트 이름 입력",
"sidebar.project_conv_empty": "(작업 없음)",
- "sidebar.load_more_conversations": "더 불러오기",
+ "sidebar.load_more_conversations": "더 보기",
"sidebar.connect_agent": "에이전트 연결",
"sidebar.connect_agent_sub": "Claude Code · Codex 등",
"sidebar.settings": "설정",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "불러오는 중…",
"new_chat.model_picker.aria_label": "모델 선택",
"new_chat.model_picker.empty": "사용 가능한 모델이 없습니다",
- "new_chat.model_picker.group_official": "공식 모델",
- "new_chat.model_picker.group_custom": "사용자 설정 모델",
+ "new_chat.model_picker.group_official": "Orkas 내장 모델",
+ "new_chat.model_picker.group_custom": "직접 가져온 API Key",
"new_chat.model_picker.configure": "모델 설정",
"new_chat.model_picker.switch_failed": "모델을 전환할 수 없습니다. 다시 시도해 주세요.",
"new_chat.model_picker.choose_version": "{account}의 모델 버전 선택",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "{library}에 추가됨",
"conversation_info.file_add_to_library_failed": "라이브러리에 추가 실패: {reason}",
"conversation_info.file_add_to_chat_action": "작업 채팅에 추가",
- "conversation_info.file_reveal_failed": "폴더를 열 수 없습니다: {reason}",
+ "conversation_info.file_reveal_failed": "폴더를 열 수 없습니다. 파일이 이동되었거나 삭제되었을 수 있습니다.",
"conversation_info.file_delete_confirm_title": "파일 삭제",
"conversation_info.file_delete_confirm_msg": "\"{name}\"을(를) 삭제할까요?",
"conversation_info.file_delete_failed": "파일을 삭제할 수 없습니다: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "지금 보내기",
"chat.queue_sending_now": "전송 중…",
"chat.queue_send_now_failed": "대기 중인 이 메시지를 지금 보낼 수 없습니다: {msg}",
- "chat.multi_dispatch_serial": "순서대로 실행",
- "chat.multi_dispatch_parallel": "함께 실행",
- "chat.multi_dispatch_toggle_title": "이 메시지에서 언급한 에이전트의 실행 방식입니다. 클릭하여 전환하세요",
"chat.task_waiting_on": "{name} 대기 중",
"chat.task_status_orchestrating": "조율 중",
"chat.task_dispatched": "지휘 에이전트가 배정함",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "선택한 메시지 {count}개를 삭제할까요? 되돌릴 수 없습니다.",
"chat.message_delete_failed": "삭제 실패: {reason}",
"chat.reference_target_title": "메시지 {count}개를 참조할 위치",
- "chat.reference_target_search": "작업 검색",
- "chat.reference_new_task": "새 작업",
- "chat.reference_existing_tasks": "기존 작업",
- "chat.reference_area_commander": "지휘 에이전트",
+ "chat.reference_new_task": "새 작업…",
"chat.reference_area_project": "프로젝트",
- "chat.reference_recent_tasks_hint": "최근 작업 5개",
- "chat.reference_search_results_count": "결과 {count}개",
- "chat.reference_no_tasks": "일치하는 작업 없음",
"chat.reference_unknown_task": "알 수 없는 작업",
"chat.reference_from_task": "“{title}”의 @{name} 메시지 인용",
"chat.reference_bundle_title": "“{title}”에서 가져옴",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "이미지 서비스 추가",
"settings.models.add_video": "동영상 서비스 추가",
"settings.models.add_tts": "음성 서비스 추가",
- "settings.models.order_hint": "행을 드래그하거나 화살표 버튼을 사용하여 우선순위를 변경하세요. 비활성화된 공식 모델은 건너뜁니다.",
+ "settings.models.order_hint": "행을 드래그하거나 화살표 버튼을 사용하여 우선순위를 변경하세요. 비활성화된 내장 모델은 건너뜁니다.",
"settings.general.page_sub": "환경설정과 에이전트 권한을 조정하세요.",
"settings.general.preferences_title": "환경설정",
"settings.general.agent_title": "에이전트 동작",
@@ -2031,7 +2014,7 @@
"project.review.approve": "승인",
"project.review.request_changes": "변경 요청",
"project.driver.toggle": "자동",
- "project.driver.toggle_hint": "AI가 할 일을 자동으로 처리하며 완료 후 검토할 수 있습니다.",
+ "project.driver.toggle_hint": "AI가 할 일을 자동으로 처리하며 완료 후 검토할 수 있습니다. 이 기능을 켠 기기에서만 실행됩니다.",
"project.driver.enabled_toast": "자동 진행 켜짐 — 대기 작업을 주기적으로 선택하여 처리하고 진행 중 상태로 변경합니다.",
"project.driver.disabled_toast": "자동 진행 꺼짐.",
"project.recent_convs.view_all": "모두 보기 ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "접기",
"skills.source_external": "패키지",
"skills.source_global": "전역",
- "web_assist.action_confirm.title": "페이지에서 이 동작을 허용할까요?",
"chat.form.boolean_yes": "예",
"chat.form.boolean_no": "아니요",
"chat.form.invalid_number": "유효한 숫자를 입력해 주세요",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "다시 로드",
"quality.operator.disabled": "이 기기에서 비활성화되어 있습니다.",
"quality.operator.ready": "준비 완료: 규칙 {count}개.",
- "quality.operator.invalid": "검증을 사용할 수 없습니다. operator-policy.json을 수정하거나 사용자 지정 검증을 끈 후 다시 시도하세요."
+ "quality.operator.invalid": "검증을 사용할 수 없습니다. operator-policy.json을 수정하거나 사용자 지정 검증을 끈 후 다시 시도하세요.",
+ "chat.app_nav_project_collaboration_target": "프로젝트 구성원: {target}",
+ "new_chat.home.goal_title": "목표가 분명한가요? 지휘 에이전트에게 맡기세요.",
+ "new_chat.home.goal_body": "이루고 싶은 일을 지휘 에이전트에게 알려 주면 AI 팀을 조율해 완성합니다.",
+ "new_chat.home.goal_example": "예: 비슷한 제품 3개를 조사해 기능과 가격을 비교하고 프레젠테이션으로 정리하기.",
+ "new_chat.home.explore_title": "아직 정하지 못했나요? 먼저 Orkas가 당신을 알게 해 주세요.",
+ "new_chat.home.explore_body": "하는 일, 사업, 고민을 이야기해 주세요. Orkas가 알맞은 목표를 찾고 꾸준히 진행하도록 돕습니다.",
+ "new_chat.home.explore_context": "+로 자료를 공유하거나 {connect}해 배경을 더해 주면 Orkas가 당신을 더 잘 이해합니다. 공유해도 괜찮은 것부터 시작하세요.",
+ "new_chat.home.explore_connect_link": "Feishu / DingTalk / 이메일 연결",
+ "new_chat.home.input_placeholder": "이루고 싶은 일을 적거나 처리할 자료를 첨부하세요",
+ "new_chat.home.continue_label": "하던 일을 이어서 진행하세요",
+ "new_chat.home.group.todos": "중요한 할 일",
+ "new_chat.home.group.automations": "확인할 자동화",
+ "new_chat.home.group.tasks": "응답이 필요한 작업",
+ "new_chat.home.all_automations": "모든 자동화 →",
+ "new_chat.home.expand": "나머지 {count}개 펼치기",
+ "new_chat.home.collapse": "접기",
+ "new_chat.home.view_all_todos": "모두 보기 →",
+ "new_chat.home.source.project_todo": "{project} · 할 일",
+ "new_chat.home.source.global_todo": "전체 할 일",
+ "new_chat.home.source.automation": "자동화",
+ "new_chat.home.source.project_task": "{project} · 프로젝트 작업",
+ "new_chat.home.source.global_task": "전체 작업",
+ "new_chat.home.result.completed": "완료됨",
+ "new_chat.home.result.failed": "실패",
+ "new_chat.home.result.waiting_input": "입력 대기 중",
+ "new_chat.home.result.stopped": "중지됨",
+ "new_chat.home.result.unknown": "새 결과",
+ "new_chat.home.action.view": "보기",
+ "new_chat.home.action.reply": "답장하기",
+ "new_chat.home.action.view_reason": "원인 보기",
+ "new_chat.home.action.view_result": "결과 보기",
+ "new_chat.home.time.updated": "{time} 업데이트",
+ "new_chat.home.untitled": "제목 없는 작업",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} 업데이트됨",
+ "apps.save_root_folder_required": "HTML과 관련 리소스를 별도 폴더로 옮긴 후 다시 앱으로 저장하세요.",
+ "chat.reference_locate_title": "원본 메시지로 이동",
+ "chat.reference_locate_missing": "원본 메시지가 더 이상 존재하지 않습니다.",
+ "agents.cli_usage_title": "잔여 사용량",
+ "agents.cli_usage_unavailable": "불러올 수 없습니다. CLI 로그인과 연결을 확인하세요.",
+ "agents.cli_usage_unsupported": "이 CLI 버전 또는 사용자 설정에서는 사용량 조회를 지원하지 않습니다.",
+ "agents.cli_usage_resets": "초기화: {time}",
+ "agents.cli_usage_hours": "{count}시간",
+ "agents.cli_usage_days": "{count}일",
+ "agents.cli_usage_window": "사용량 기간",
+ "memory.full_notice": "메모리가 가득 찼습니다. 새 내용을 저장하기 전에 AI가 기존 항목을 정리해 합칩니다.",
+ "memory.error_full": "메모리가 가득 차서 지금은 이 항목을 추가할 수 없습니다.",
+ "settings.recycle.clear": "비우기",
+ "settings.recycle.clear_title": "휴지통 비우기",
+ "settings.recycle.clear_confirm": "{source}의 기록 {count}개를 모두 영구 삭제할까요? 삭제 후에는 복원할 수 없습니다.",
+ "settings.recycle.clearing": "비우는 중 {done}/{total}…",
+ "settings.recycle.cleared": "휴지통을 비웠습니다",
+ "settings.recycle.clear_failed": "휴지통을 모두 비우지 못했습니다. 다시 시도해 주세요.",
+ "settings.recycle.automation_count": "자동화 · 작업 {count}개",
+ "project.todo.move": "이동",
+ "bash.permission.allow_folder_read": "이 폴더 읽기 허용",
+ "bash.permission.folder_read_scope": "이 작업 동안 {agent}은(는) “{folder}”의 파일을 다시 묻지 않고 읽을 수 있습니다. 쓰기, 삭제, 비밀 파일은 계속 확인합니다.",
+ "cli_upgrade.action": "CLI 업그레이드",
+ "cli_upgrade.pending": "업그레이드 중…",
+ "cli_upgrade.success": "업그레이드 성공",
+ "cli_upgrade.failed": "업그레이드 실패",
+ "cli_upgrade.named_action": "{cli} CLI 업그레이드",
+ "web_assist.handback": "AI에 제어권 넘기기",
+ "web_assist.permissions": "사이트 권한 초기화",
+ "web_assist.permission_title": "웹사이트 권한",
+ "web_assist.permission_allow": "허용",
+ "web_assist.permission_deny": "거부",
+ "web_assist.permission_failed": "선택을 저장하지 못했습니다. 다시 시도하세요.",
+ "apps.view_details": "세부 정보 보기",
+ "apps.no_local_code": "이 기기에 앱 코드가 없습니다",
+ "apps.publish_commercial": "앱을 게시하려면 Orkas 상용 버전을 사용하세요.",
+ "apps.update_original": "원래 앱 업데이트",
+ "apps.save_new": "새 앱으로 저장",
+ "apps.edit_conflict": "원래 앱이 변경되었거나 삭제되었습니다. 다시 편집하거나 새 앱으로 저장하세요.",
+ "apps.save_type_mismatch": "이 버전은 원래 앱과 앱 유형이 달라 원래 앱을 대체할 수 없습니다. 대신 새 앱으로 저장하세요.",
+ "apps.type_local": "로컬 앱",
+ "apps.type_web": "웹 앱",
+ "apps.type_local_description": "Orkas 데스크톱에서 실행되며 AI, 파일, 라이브러리, 커넥터 등을 사용할 수 있습니다. 웹에 게시할 수 없습니다.",
+ "apps.type_web_description": "웹에 게시하고 링크로 접속할 수 있으며 데이터 수집, 조회, 통계를 지원합니다. Orkas 데스크톱 기능은 사용할 수 없습니다.",
+ "apps.delete_data_confirm": "\"{name}\" 및 로컬 기록과 전용 파일을 삭제할까요? 데이터는 복구할 수 없습니다.",
+ "apps.delete_online_retained": "게시된 앱과 온라인 데이터는 유지됩니다.",
+ "apps.migration_export": "데이터 구조가 변경됩니다. 삭제 전에 로컬 기록을 내보낼 수 있습니다.",
+ "apps.migration_export_action": "기록 내보내기",
+ "apps.migration_continue": "계속",
+ "apps.migration_clear": "모든 로컬 기록을 삭제하고 업데이트할까요? 온라인 기록은 별도로 저장됩니다.",
+ "apps.migration_retry": "삭제 후 재시도",
+ "chat.reference_scope_label": "작업 범위",
+ "chat.reference_scope_all": "모든 작업",
+ "chat.reference_scope_global": "전체(프로젝트 없음)",
+ "chat.reference_new_in_global": "전체에 새 작업 만들기",
+ "chat.reference_new_in_project": "‘{name}’에 새 작업 만들기",
+ "chat.reference_search_all": "모든 작업 검색",
+ "chat.reference_search_in": "‘{name}’의 작업 검색",
+ "chat.reference_count_all": "총 {count}개 · 최근 활동순",
+ "chat.reference_count_found": "{count}개 찾음 · 최근 활동순",
+ "chat.reference_load_more": "이전 작업 더 불러오기({count}개 남음)",
+ "chat.reference_no_match": "일치하는 작업 없음",
+ "chat.reference_no_match_hint": "다른 키워드를 입력하거나 왼쪽에서 다른 범위를 선택하세요.",
+ "chat.reference_scope_empty": "아직 작업이 없습니다",
+ "chat.reference_scope_empty_hint": "위의 버튼으로 여기에 새 작업을 만들 수 있습니다.",
+ "chat.reference_create_back": "작업 목록으로 돌아가기",
+ "chat.reference_create_title": "새 작업을 어디에 만들까요?",
+ "chat.reference_create_desc": "위치를 선택하면 참조가 추가됩니다. 자동으로 전송되지 않습니다.",
+ "chat.reference_create_global_desc": "어떤 프로젝트에도 속하지 않음",
+ "chat.reference_create_project_desc": "이 프로젝트에 새 작업 만들기",
+ "chat.reference_target_footer": "선택하면 대상 작업의 입력란에 참조가 추가됩니다. 자동으로 전송되지 않습니다.",
+ "project.todo.run_busy": "이 작업의 대화가 아직 진행 중입니다. 끝난 후 다시 실행하세요.",
+ "settings.cleanup.title": "이전 작업 정리",
+ "settings.cleanup.age": "마지막 활동",
+ "settings.cleanup.scope": "프로젝트 안팎의 완료된 작업을 정리합니다. 고정된 작업, 읽지 않은 작업, 초안과 자동화 실행 기록은 유지됩니다.",
+ "settings.cleanup.days": "{n}일 이전",
+ "settings.cleanup.result": "휴지통으로 이동: {deleted}개. 건너뜀: {skipped}개. 실패: {failed}개.",
+ "settings.cleanup.progress": "정리 중 {done} / {total}",
+ "settings.cleanup.error": "작업을 불러오거나 정리하지 못했습니다. 새로 고침 후 다시 시도하세요.",
+ "settings.cleanup.count": "작업 {n}개 선택됨",
+ "settings.cleanup.empty": "정리할 이전 작업이 없습니다.",
+ "settings.cleanup.clean": "정리",
+ "settings.cleanup.confirm": "작업 {n}개와 첨부 파일, 내장 결과를 휴지통으로 이동합니다. 아래에서 복원할 수 있습니다. 동기화가 켜져 있으면 다른 기기에서도 삭제됩니다. 휴지통을 비워야 디스크 공간이 확보됩니다.",
+ "settings.cleanup.move": "휴지통으로 이동({n})",
+ "settings.cleanup.previous": "이전",
+ "settings.cleanup.next": "다음",
+ "apps.commercial_required": "웹 앱을 사용하려면 Orkas 상용 버전이 필요합니다. 다운로드하여 계속하세요.",
+ "apps.commercial_download": "상용 버전 다운로드",
+ "apps.commercial_open_failed": "다운로드 페이지를 열 수 없습니다. 다시 시도하세요."
}
diff --git a/src/renderer/locales/pt-pt.json b/src/renderer/locales/pt-pt.json
index a5bebc06..c9f82225 100644
--- a/src/renderer/locales/pt-pt.json
+++ b/src/renderer/locales/pt-pt.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Transferência",
"web_assist.activity_visit": "Visita",
"web_assist.download_saved": "guardado nos anexos",
- "web_assist.download_needs_grant": "precisa de permissão",
- "web_assist.download_blocked_type": "tipo de ficheiro não permitido",
- "web_assist.download_budget": "limite de transferências da tarefa atingido",
"web_assist.download_failed": "falhou",
"web_assist.download_unavailable": "Ficheiro indisponível. Verifique se a transferência terminou e se o ficheiro foi movido ou eliminado.",
- "web_assist.download_allow": "Permitir este site",
- "web_assist.download_prompt_title": "Permitir transferências deste site?",
- "web_assist.download_prompt_description": "Os ficheiros serão guardados nos anexos desta tarefa. Após permitir, volte à página e tente transferir novamente.",
- "web_assist.download_not_now": "Agora não",
- "web_assist.download_permission_failed": "Não foi possível permitir este site. Tente novamente.",
"web_assist.address_placeholder": "Pesquise no Bing ou introduza um URL",
"web_assist.empty_title": "Navegue nesta tarefa",
"web_assist.empty_hint": "Pesquise no Bing ou introduza um URL acima.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Últimos 30 dias",
"sidebar.bucket.older": "Mais antigas",
"sidebar.projects": "Projetos",
- "sidebar.today_tasks": "Tarefas de hoje",
- "sidebar.today_empty": "Nenhuma tarefa hoje",
+ "sidebar.today_tasks": "Tarefas recentes",
+ "sidebar.today_empty": "Nenhuma tarefa nos últimos dois dias",
"sidebar.section_collapse": "Recolher {section}",
"sidebar.section_expand": "Expandir {section}",
"sidebar.project_create_title": "Novo projeto",
"sidebar.project_create_placeholder": "Introduza o nome do projeto",
"sidebar.project_conv_empty": "(sem tarefas)",
- "sidebar.load_more_conversations": "Carregar mais",
+ "sidebar.load_more_conversations": "Mostrar mais",
"sidebar.connect_agent": "Ligar agentes",
"sidebar.connect_agent_sub": "Claude Code · Codex e mais",
"sidebar.settings": "Definições",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "A carregar…",
"new_chat.model_picker.aria_label": "Escolher modelo",
"new_chat.model_picker.empty": "Nenhum modelo disponível",
- "new_chat.model_picker.group_official": "Modelos oficiais",
- "new_chat.model_picker.group_custom": "Modelos configurados pelo utilizador",
+ "new_chat.model_picker.group_official": "Modelos integrados do Orkas",
+ "new_chat.model_picker.group_custom": "A sua API Key",
"new_chat.model_picker.configure": "Configurar modelos",
"new_chat.model_picker.switch_failed": "Não foi possível trocar de modelo. Tente novamente.",
"new_chat.model_picker.choose_version": "Escolher uma versão do modelo para {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Adicionado a {library}",
"conversation_info.file_add_to_library_failed": "Falha ao adicionar à biblioteca: {reason}",
"conversation_info.file_add_to_chat_action": "Adicionar à conversa da tarefa",
- "conversation_info.file_reveal_failed": "Não foi possível abrir a pasta: {reason}",
+ "conversation_info.file_reveal_failed": "Não foi possível abrir a pasta. O ficheiro pode ter sido movido ou eliminado.",
"conversation_info.file_delete_confirm_title": "Eliminar ficheiro",
"conversation_info.file_delete_confirm_msg": "Eliminar \"{name}\"?",
"conversation_info.file_delete_failed": "Não foi possível eliminar o ficheiro: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Enviar agora",
"chat.queue_sending_now": "A enviar…",
"chat.queue_send_now_failed": "Não foi possível enviar esta mensagem da fila agora: {msg}",
- "chat.multi_dispatch_serial": "Executar em ordem",
- "chat.multi_dispatch_parallel": "Executar juntos",
- "chat.multi_dispatch_toggle_title": "Como os agentes mencionados executam esta mensagem; clique para alternar",
"chat.task_waiting_on": "A aguardar {name}",
"chat.task_status_orchestrating": "A coordenar",
"chat.task_dispatched": "Atribuída pelo Commander",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Eliminar as {count} mensagens selecionadas? Esta ação não pode ser desfeita.",
"chat.message_delete_failed": "Falha ao eliminar: {reason}",
"chat.reference_target_title": "Referenciar {count} mensagens em",
- "chat.reference_target_search": "Pesquisar tarefas",
- "chat.reference_new_task": "Nova tarefa",
- "chat.reference_existing_tasks": "Tarefas existentes",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nova tarefa…",
"chat.reference_area_project": "Projeto",
- "chat.reference_recent_tasks_hint": "5 tarefas mais recentes",
- "chat.reference_search_results_count": "{count} resultados",
- "chat.reference_no_tasks": "Nenhuma tarefa correspondente",
"chat.reference_unknown_task": "Tarefa desconhecida",
"chat.reference_from_task": "Citado de “{title}” @{name}",
"chat.reference_bundle_title": "De “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Adicionar serviço de imagem",
"settings.models.add_video": "Adicionar serviço de vídeo",
"settings.models.add_tts": "Adicionar serviço de voz",
- "settings.models.order_hint": "Arraste as linhas para alterar a prioridade ou use os botões de seta. Modelos oficiais desativados são ignorados.",
+ "settings.models.order_hint": "Arraste as linhas para alterar a prioridade ou use os botões de seta. Modelos integrados desativados são ignorados.",
"settings.general.page_sub": "Ajuste preferências, permissões dos agentes e atualizações da aplicação.",
"settings.general.preferences_title": "Preferências",
"settings.general.agent_title": "Comportamento dos agentes",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Aprovar",
"project.review.request_changes": "Solicitar alterações",
"project.driver.toggle": "Automático",
- "project.driver.toggle_hint": "A IA executa automaticamente as tarefas, para que possa rever o trabalho concluído.",
+ "project.driver.toggle_hint": "A IA executa automaticamente as tarefas, para que possa rever o trabalho concluído. Só é executada no dispositivo em que ativa a função.",
"project.driver.enabled_toast": "Avanço automático ativo — seleciona periodicamente uma tarefa pendente e executa-a; as tarefas passam para Em curso.",
"project.driver.disabled_toast": "Avanço automático desligado.",
"project.recent_convs.view_all": "Ver tudo ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Recolher",
"skills.source_external": "Pacote",
"skills.source_global": "Global",
- "web_assist.action_confirm.title": "Permitir esta ação na página?",
"chat.form.boolean_yes": "Sim",
"chat.form.boolean_no": "Não",
"chat.form.invalid_number": "Insira um número válido",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Recarregar",
"quality.operator.disabled": "Desativada neste dispositivo.",
"quality.operator.ready": "Pronta: {count} regras.",
- "quality.operator.invalid": "Validação indisponível. Corrija operator-policy.json ou desative a validação personalizada e tente novamente."
+ "quality.operator.invalid": "Validação indisponível. Corrija operator-policy.json ou desative a validação personalizada e tente novamente.",
+ "chat.app_nav_project_collaboration_target": "Membros do projeto: {target}",
+ "new_chat.home.goal_title": "Tem um objetivo claro? Entregue-o ao Commander.",
+ "new_chat.home.goal_body": "Diga ao Commander o que pretende fazer e ele coordena a sua equipa de IA para o concretizar.",
+ "new_chat.home.goal_example": "Por exemplo: pesquise 3 produtos semelhantes, compare funcionalidades e preços e organize tudo numa apresentação.",
+ "new_chat.home.explore_title": "Ainda não sabe? Deixe primeiro o Orkas conhecê-lo.",
+ "new_chat.home.explore_body": "Fale sobre o seu trabalho, o seu negócio ou as suas dificuldades, e o Orkas ajuda-o a encontrar os objetivos certos e a fazê-los avançar.",
+ "new_chat.home.explore_context": "Partilhe ficheiros com + ou {connect} para dar mais contexto ao Orkas. Comece pelo que se sentir à vontade para partilhar.",
+ "new_chat.home.explore_connect_link": "ligue o Feishu / DingTalk / e-mail",
+ "new_chat.home.input_placeholder": "Descreva o que pretende fazer ou anexe os ficheiros a tratar",
+ "new_chat.home.continue_label": "Continue a avançar",
+ "new_chat.home.group.todos": "A fazer importantes",
+ "new_chat.home.group.automations": "Automações para rever",
+ "new_chat.home.group.tasks": "Tarefas à sua espera",
+ "new_chat.home.all_automations": "Todas as automações →",
+ "new_chat.home.expand": "Mostrar mais {count}",
+ "new_chat.home.collapse": "Mostrar menos",
+ "new_chat.home.view_all_todos": "Ver tudo →",
+ "new_chat.home.source.project_todo": "{project} · A fazer",
+ "new_chat.home.source.global_todo": "A fazer global",
+ "new_chat.home.source.automation": "Automação",
+ "new_chat.home.source.project_task": "{project} · Tarefa do projeto",
+ "new_chat.home.source.global_task": "Tarefa global",
+ "new_chat.home.result.completed": "Concluída",
+ "new_chat.home.result.failed": "Falhou",
+ "new_chat.home.result.waiting_input": "À sua espera",
+ "new_chat.home.result.stopped": "Interrompida",
+ "new_chat.home.result.unknown": "Novo resultado",
+ "new_chat.home.action.view": "Ver",
+ "new_chat.home.action.reply": "Responder",
+ "new_chat.home.action.view_reason": "Ver motivo",
+ "new_chat.home.action.view_result": "Ver resultado",
+ "new_chat.home.time.updated": "Atualizado {time}",
+ "new_chat.home.untitled": "Tarefa sem título",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} atualizado",
+ "apps.save_root_folder_required": "Mova o HTML e os respetivos recursos para uma pasta separada e volte a guardar como aplicação.",
+ "chat.reference_locate_title": "Ir para a mensagem original",
+ "chat.reference_locate_missing": "A mensagem original já não existe.",
+ "agents.cli_usage_title": "Quota restante",
+ "agents.cli_usage_unavailable": "Indisponível. Verifique o início de sessão da CLI e a ligação.",
+ "agents.cli_usage_unsupported": "Esta versão da CLI ou configuração personalizada não permite consultar a quota.",
+ "agents.cli_usage_resets": "Repõe a {time}",
+ "agents.cli_usage_hours": "{count} horas",
+ "agents.cli_usage_days": "{count} dias",
+ "agents.cli_usage_window": "Período de utilização",
+ "memory.full_notice": "A memória está cheia. Antes de guardar algo novo, a IA vai juntar as entradas existentes.",
+ "memory.error_full": "A memória está cheia, por isso esta entrada não pode ser adicionada agora.",
+ "settings.recycle.clear": "Esvaziar",
+ "settings.recycle.clear_title": "Esvaziar reciclagem",
+ "settings.recycle.clear_confirm": "Eliminar permanentemente todos os {count} registos em {source}? Não poderão ser restaurados depois.",
+ "settings.recycle.clearing": "A esvaziar {done}/{total}…",
+ "settings.recycle.cleared": "Reciclagem esvaziada",
+ "settings.recycle.clear_failed": "Não foi possível esvaziar toda a reciclagem. Tente novamente.",
+ "settings.recycle.automation_count": "Automação · {count} tarefas",
+ "project.todo.move": "Mover",
+ "bash.permission.allow_folder_read": "Permitir ler esta pasta",
+ "bash.permission.folder_read_scope": "Nesta tarefa, {agent} pode ler ficheiros em {folder} sem voltar a perguntar. Escrita, eliminação e ficheiros secretos continuam a pedir confirmação.",
+ "cli_upgrade.action": "Atualizar CLI",
+ "cli_upgrade.pending": "A atualizar…",
+ "cli_upgrade.success": "Atualização concluída",
+ "cli_upgrade.failed": "Falha na atualização",
+ "cli_upgrade.named_action": "Atualizar {cli} CLI",
+ "web_assist.handback": "Devolver controlo à IA",
+ "web_assist.permissions": "Repor permissões do site",
+ "web_assist.permission_title": "Permissão do site",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Recusar",
+ "web_assist.permission_failed": "Não foi possível guardar a sua escolha. Tente novamente.",
+ "apps.view_details": "Ver detalhes",
+ "apps.no_local_code": "Não há código da aplicação neste dispositivo",
+ "apps.publish_commercial": "Use a versão comercial do Orkas para publicar.",
+ "apps.update_original": "Atualizar aplicação original",
+ "apps.save_new": "Guardar novo aplicação",
+ "apps.edit_conflict": "O aplicação original mudou ou foi excluído. Reabra para editar ou guarde um novo.",
+ "apps.save_type_mismatch": "Esta versão é de um tipo diferente da aplicação original e não a pode substituir. Guarde-a como uma nova aplicação.",
+ "apps.type_local": "Aplicação local",
+ "apps.type_web": "Aplicação web",
+ "apps.type_local_description": "É executada no Orkas para computador com acesso a IA, ficheiros, biblioteca e conectores; não pode ser publicada na Web.",
+ "apps.type_web_description": "Publique na Web e aceda através de uma ligação, com recolha, consultas e estatísticas de dados; as funcionalidades do Orkas para computador não estão disponíveis.",
+ "apps.delete_data_confirm": "Eliminar \"{name}\", os seus registos locais e ficheiros privados? Os dados não podem ser recuperados.",
+ "apps.delete_online_retained": "A aplicação publicada e os dados online são mantidos.",
+ "apps.migration_export": "A estrutura dos dados muda. Exporte os registos locais antes de os apagar.",
+ "apps.migration_export_action": "Exportar registos",
+ "apps.migration_continue": "Continuar",
+ "apps.migration_clear": "Apagar todos os registos locais e atualizar? Os registos online são independentes.",
+ "apps.migration_retry": "Apagar e tentar novamente",
+ "chat.reference_scope_label": "Âmbito das tarefas",
+ "chat.reference_scope_all": "Todas as tarefas",
+ "chat.reference_scope_global": "Global (sem projeto)",
+ "chat.reference_new_in_global": "Nova tarefa em Global",
+ "chat.reference_new_in_project": "Nova tarefa em «{name}»",
+ "chat.reference_search_all": "Pesquisar em todas as tarefas",
+ "chat.reference_search_in": "Pesquisar tarefas em «{name}»",
+ "chat.reference_count_all": "{count} no total · mais recentes primeiro",
+ "chat.reference_count_found": "{count} encontradas · mais recentes primeiro",
+ "chat.reference_load_more": "Carregar tarefas anteriores (mais {count})",
+ "chat.reference_no_match": "Nenhuma tarefa correspondente",
+ "chat.reference_no_match_hint": "Experimente outra palavra-chave ou escolha outro âmbito à esquerda.",
+ "chat.reference_scope_empty": "Ainda não existem tarefas aqui",
+ "chat.reference_scope_empty_hint": "Utilize o botão acima para iniciar uma tarefa aqui.",
+ "chat.reference_create_back": "Voltar às tarefas",
+ "chat.reference_create_title": "Onde criar a nova tarefa?",
+ "chat.reference_create_desc": "As referências são adicionadas depois de escolher. Nada é enviado automaticamente.",
+ "chat.reference_create_global_desc": "Não pertence a nenhum projeto",
+ "chat.reference_create_project_desc": "Iniciar uma tarefa neste projeto",
+ "chat.reference_target_footer": "A escolha abre o campo de introdução da tarefa com as referências adicionadas. Nada é enviado automaticamente.",
+ "project.todo.run_busy": "A conversa desta tarefa ainda está em curso. Execute-a novamente quando terminar.",
+ "settings.cleanup.title": "Limpar tarefas antigas",
+ "settings.cleanup.age": "Última atividade",
+ "settings.cleanup.scope": "Tarefas concluídas dentro e fora de projetos. São mantidas as tarefas afixadas, não lidas, os rascunhos e as execuções de automatizações.",
+ "settings.cleanup.days": "Há mais de {n} dias",
+ "settings.cleanup.result": "Na reciclagem: {deleted}. Ignoradas: {skipped}. Falhas: {failed}.",
+ "settings.cleanup.progress": "A limpar {done} / {total}",
+ "settings.cleanup.error": "Não foi possível carregar ou limpar as tarefas. Atualize e tente novamente.",
+ "settings.cleanup.count": "{n} tarefas selecionadas",
+ "settings.cleanup.empty": "Não há tarefas antigas para limpar.",
+ "settings.cleanup.clean": "Limpar",
+ "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a reciclagem. Pode restaurá-los abaixo. Com a sincronização ativa, a eliminação também se aplica a outros dispositivos. O espaço é libertado ao esvaziar a reciclagem.",
+ "settings.cleanup.move": "Mover para a reciclagem ({n})",
+ "settings.cleanup.previous": "Anterior",
+ "settings.cleanup.next": "Seguinte",
+ "apps.commercial_required": "As aplicações Web requerem a versão comercial do Orkas. Transfira-a para continuar.",
+ "apps.commercial_download": "Transferir versão comercial",
+ "apps.commercial_open_failed": "Não foi possível abrir a página de transferência. Tente novamente."
}
diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.json
index 78e6ee9a..12d78cc1 100644
--- a/src/renderer/locales/pt.json
+++ b/src/renderer/locales/pt.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Download",
"web_assist.activity_visit": "Visita",
"web_assist.download_saved": "salvo nos anexos",
- "web_assist.download_needs_grant": "precisa de permissão",
- "web_assist.download_blocked_type": "tipo de arquivo não permitido",
- "web_assist.download_budget": "limite de downloads da tarefa atingido",
"web_assist.download_failed": "falhou",
"web_assist.download_unavailable": "Arquivo indisponível. Verifique se o download terminou e se o arquivo não foi movido ou excluído.",
- "web_assist.download_allow": "Permitir este site",
- "web_assist.download_prompt_title": "Permitir downloads deste site?",
- "web_assist.download_prompt_description": "Os arquivos serão salvos nos anexos desta tarefa. Após permitir, volte à página e tente baixar novamente.",
- "web_assist.download_not_now": "Agora não",
- "web_assist.download_permission_failed": "Não foi possível permitir este site. Tente novamente.",
"web_assist.address_placeholder": "Pesquise no Bing ou digite uma URL",
"web_assist.empty_title": "Navegue nesta tarefa",
"web_assist.empty_hint": "Pesquise no Bing ou digite uma URL acima.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Últimos 30 dias",
"sidebar.bucket.older": "Mais velho",
"sidebar.projects": "Projetos",
- "sidebar.today_tasks": "Tarefas de hoje",
- "sidebar.today_empty": "Nenhuma tarefa hoje",
+ "sidebar.today_tasks": "Tarefas recentes",
+ "sidebar.today_empty": "Nenhuma tarefa nos últimos dois dias",
"sidebar.section_collapse": "Recolher {section}",
"sidebar.section_expand": "Expandir {section}",
"sidebar.project_create_title": "Novo projeto",
"sidebar.project_create_placeholder": "Digite o nome do projeto",
"sidebar.project_conv_empty": "(sem tarefas)",
- "sidebar.load_more_conversations": "Carregar mais",
+ "sidebar.load_more_conversations": "Mostrar mais",
"sidebar.connect_agent": "Conectar agentes",
"sidebar.connect_agent_sub": "Claude Code · Codex e mais",
"sidebar.settings": "Configurações",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Carregando…",
"new_chat.model_picker.aria_label": "Escolher modelo",
"new_chat.model_picker.empty": "Nenhum modelo disponível",
- "new_chat.model_picker.group_official": "Modelos oficiais",
- "new_chat.model_picker.group_custom": "Modelos configurados pelo usuário",
+ "new_chat.model_picker.group_official": "Modelos integrados do Orkas",
+ "new_chat.model_picker.group_custom": "Sua própria API Key",
"new_chat.model_picker.configure": "Configurar modelos",
"new_chat.model_picker.switch_failed": "Não foi possível trocar de modelo. Tente novamente.",
"new_chat.model_picker.choose_version": "Escolher uma versão do modelo para {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Adicionado à {library}",
"conversation_info.file_add_to_library_failed": "Falha ao adicionar à biblioteca: {reason}",
"conversation_info.file_add_to_chat_action": "Adicionar ao chat de tarefas",
- "conversation_info.file_reveal_failed": "Não foi possível abrir a pasta: {reason}",
+ "conversation_info.file_reveal_failed": "Não foi possível abrir a pasta. O arquivo pode ter sido movido ou excluído.",
"conversation_info.file_delete_confirm_title": "Excluir arquivo",
"conversation_info.file_delete_confirm_msg": "Excluir \"{name}\"?",
"conversation_info.file_delete_failed": "Não foi possível excluir o arquivo: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Enviar agora",
"chat.queue_sending_now": "Enviando…",
"chat.queue_send_now_failed": "Não foi possível enviar esta mensagem da fila agora: {msg}",
- "chat.multi_dispatch_serial": "Executar em ordem",
- "chat.multi_dispatch_parallel": "Executar juntos",
- "chat.multi_dispatch_toggle_title": "Como os agentes mencionados executam esta mensagem; clique para alternar",
"chat.task_waiting_on": "Aguardando {name}",
"chat.task_status_orchestrating": "Orquestrando",
"chat.task_dispatched": "Despachada pelo Comandante",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Excluir as {count} mensagens selecionadas? Esta ação não pode ser desfeita.",
"chat.message_delete_failed": "Falha ao excluir: {reason}",
"chat.reference_target_title": "Referenciar {count} mensagens em",
- "chat.reference_target_search": "Pesquisar tarefas",
- "chat.reference_new_task": "Nova tarefa",
- "chat.reference_existing_tasks": "Tarefas existentes",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Nova tarefa…",
"chat.reference_area_project": "Projeto",
- "chat.reference_recent_tasks_hint": "5 tarefas mais recentes",
- "chat.reference_search_results_count": "{count} resultados",
- "chat.reference_no_tasks": "Nenhuma tarefa correspondente",
"chat.reference_unknown_task": "Tarefa desconhecida",
"chat.reference_from_task": "Citado de “{title}” @{name}",
"chat.reference_bundle_title": "De “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Adicionar serviço de imagem",
"settings.models.add_video": "Adicionar serviço de vídeo",
"settings.models.add_tts": "Adicionar serviço de voz",
- "settings.models.order_hint": "Arraste as linhas para alterar a prioridade ou use os botões de seta. Modelos oficiais desativados são ignorados.",
+ "settings.models.order_hint": "Arraste as linhas para alterar a prioridade ou use os botões de seta. Modelos integrados desativados são ignorados.",
"settings.general.page_sub": "Ajuste preferências e permissões dos agentes.",
"settings.general.preferences_title": "Preferências",
"settings.general.agent_title": "Comportamento dos agentes",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Aprovar",
"project.review.request_changes": "Solicitar alterações",
"project.driver.toggle": "Auto",
- "project.driver.toggle_hint": "A IA executa as tarefas automaticamente para você confirmar ao final.",
+ "project.driver.toggle_hint": "A IA executa as tarefas automaticamente para você confirmar ao final. Só funciona no dispositivo em que você ativa a função.",
"project.driver.enabled_toast": "Avanço automático ligado — seleciona periodicamente uma tarefa do backlog e a executa; as tarefas passam para Em andamento.",
"project.driver.disabled_toast": "Avanço automático desligado.",
"project.recent_convs.view_all": "Ver tudo ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Recolher",
"skills.source_external": "Pacote",
"skills.source_global": "Globais",
- "web_assist.action_confirm.title": "Permitir esta ação na página?",
"chat.form.boolean_yes": "Sim",
"chat.form.boolean_no": "Não",
"chat.form.invalid_number": "Insira um número válido",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Recarregar",
"quality.operator.disabled": "Desativada neste dispositivo.",
"quality.operator.ready": "Pronta: {count} regras.",
- "quality.operator.invalid": "Validação indisponível. Corrija operator-policy.json ou desative a validação personalizada e tente novamente."
+ "quality.operator.invalid": "Validação indisponível. Corrija operator-policy.json ou desative a validação personalizada e tente novamente.",
+ "chat.app_nav_project_collaboration_target": "Membros do projeto: {target}",
+ "new_chat.home.goal_title": "Tem um objetivo claro? Entregue ao Commander.",
+ "new_chat.home.goal_body": "Diga ao Commander o que você quer realizar, e ele coordena sua equipe de IA para concluir.",
+ "new_chat.home.goal_example": "Por exemplo: pesquise 3 produtos semelhantes, compare recursos e preços e organize tudo em uma apresentação.",
+ "new_chat.home.explore_title": "Ainda não sabe? Deixe o Orkas conhecer você primeiro.",
+ "new_chat.home.explore_body": "Fale sobre seu trabalho, seu negócio ou suas dificuldades, e o Orkas ajuda você a encontrar os objetivos certos e a avançar com eles.",
+ "new_chat.home.explore_context": "Compartilhe arquivos com + ou {connect} para dar mais contexto ao Orkas. Comece pelo que você se sentir à vontade para compartilhar.",
+ "new_chat.home.explore_connect_link": "conecte Feishu / DingTalk / e-mail",
+ "new_chat.home.input_placeholder": "Descreva o que você quer realizar ou anexe os arquivos a serem trabalhados",
+ "new_chat.home.continue_label": "Continue avançando",
+ "new_chat.home.group.todos": "A fazer importantes",
+ "new_chat.home.group.automations": "Automações para revisar",
+ "new_chat.home.group.tasks": "Tarefas aguardando você",
+ "new_chat.home.all_automations": "Todas as automações →",
+ "new_chat.home.expand": "Mostrar mais {count}",
+ "new_chat.home.collapse": "Mostrar menos",
+ "new_chat.home.view_all_todos": "Ver tudo →",
+ "new_chat.home.source.project_todo": "{project} · A fazer",
+ "new_chat.home.source.global_todo": "A fazer global",
+ "new_chat.home.source.automation": "Automação",
+ "new_chat.home.source.project_task": "{project} · Tarefa do projeto",
+ "new_chat.home.source.global_task": "Tarefa global",
+ "new_chat.home.result.completed": "Concluída",
+ "new_chat.home.result.failed": "Falhou",
+ "new_chat.home.result.waiting_input": "Aguardando você",
+ "new_chat.home.result.stopped": "Interrompida",
+ "new_chat.home.result.unknown": "Novo resultado",
+ "new_chat.home.action.view": "Ver",
+ "new_chat.home.action.reply": "Responder",
+ "new_chat.home.action.view_reason": "Ver motivo",
+ "new_chat.home.action.view_result": "Ver resultado",
+ "new_chat.home.time.updated": "Atualizado {time}",
+ "new_chat.home.untitled": "Tarefa sem título",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} atualizado",
+ "apps.save_root_folder_required": "Mova o HTML e seus recursos para uma pasta separada e salve como aplicativo novamente.",
+ "chat.reference_locate_title": "Ir para a mensagem original",
+ "chat.reference_locate_missing": "A mensagem original não existe mais.",
+ "agents.cli_usage_title": "Cota restante",
+ "agents.cli_usage_unavailable": "Indisponível. Verifique o login da CLI e a conexão.",
+ "agents.cli_usage_unsupported": "Esta versão da CLI ou configuração personalizada não permite consultar a cota.",
+ "agents.cli_usage_resets": "Redefine em {time}",
+ "agents.cli_usage_hours": "{count} horas",
+ "agents.cli_usage_days": "{count} dias",
+ "agents.cli_usage_window": "Período de uso",
+ "memory.full_notice": "A memória está cheia. Antes de salvar algo novo, a IA vai mesclar as entradas existentes.",
+ "memory.error_full": "A memória está cheia, então esta entrada não pode ser adicionada agora.",
+ "settings.recycle.clear": "Esvaziar",
+ "settings.recycle.clear_title": "Esvaziar lixeira",
+ "settings.recycle.clear_confirm": "Excluir permanentemente todos os {count} registros em {source}? Eles não poderão ser restaurados depois.",
+ "settings.recycle.clearing": "Esvaziando {done}/{total}…",
+ "settings.recycle.cleared": "Lixeira esvaziada",
+ "settings.recycle.clear_failed": "Não foi possível esvaziar toda a lixeira. Tente novamente.",
+ "settings.recycle.automation_count": "Automação · {count} tarefas",
+ "project.todo.move": "Mover",
+ "bash.permission.allow_folder_read": "Permitir ler esta pasta",
+ "bash.permission.folder_read_scope": "Nesta tarefa, {agent} pode ler arquivos em {folder} sem perguntar de novo. Gravação, exclusão e arquivos secretos continuam pedindo confirmação.",
+ "cli_upgrade.action": "Atualizar CLI",
+ "cli_upgrade.pending": "Atualizando…",
+ "cli_upgrade.success": "Atualização concluída",
+ "cli_upgrade.failed": "Falha na atualização",
+ "cli_upgrade.named_action": "Atualizar {cli} CLI",
+ "web_assist.handback": "Devolver controle à IA",
+ "web_assist.permissions": "Redefinir permissões do site",
+ "web_assist.permission_title": "Permissão do site",
+ "web_assist.permission_allow": "Permitir",
+ "web_assist.permission_deny": "Negar",
+ "web_assist.permission_failed": "Não foi possível salvar sua escolha. Tente novamente.",
+ "apps.view_details": "Ver detalhes",
+ "apps.no_local_code": "Não há código do aplicativo neste dispositivo",
+ "apps.publish_commercial": "Use a versão comercial do Orkas para publicar.",
+ "apps.update_original": "Atualizar aplicativo original",
+ "apps.save_new": "Salvar novo aplicativo",
+ "apps.edit_conflict": "O aplicativo original mudou ou foi excluído. Reabra para editar ou salve um novo.",
+ "apps.save_type_mismatch": "Esta versão é de um tipo diferente do aplicativo original e não pode substituí-lo. Salve-a como um novo aplicativo.",
+ "apps.type_local": "Aplicativo local",
+ "apps.type_web": "Aplicativo web",
+ "apps.type_local_description": "Executa no Orkas para desktop com acesso a IA, arquivos, biblioteca e conectores; não pode ser publicado na web.",
+ "apps.type_web_description": "Publique na web e acesse por um link, com coleta, consultas e estatísticas de dados; os recursos do Orkas para desktop não estão disponíveis.",
+ "apps.delete_data_confirm": "Excluir \"{name}\", seus registros locais e arquivos privados? Os dados não podem ser recuperados.",
+ "apps.delete_online_retained": "O aplicativo publicado e os dados online são mantidos.",
+ "apps.migration_export": "A estrutura dos dados muda. Exporte os registros locais antes de apagá-los.",
+ "apps.migration_export_action": "Exportar registros",
+ "apps.migration_continue": "Continuar",
+ "apps.migration_clear": "Apagar todos os registros locais e atualizar? Os registros online são independentes.",
+ "apps.migration_retry": "Apagar e tentar novamente",
+ "chat.reference_scope_label": "Escopo das tarefas",
+ "chat.reference_scope_all": "Todas as tarefas",
+ "chat.reference_scope_global": "Global (sem projeto)",
+ "chat.reference_new_in_global": "Nova tarefa em Global",
+ "chat.reference_new_in_project": "Nova tarefa em “{name}”",
+ "chat.reference_search_all": "Pesquisar em todas as tarefas",
+ "chat.reference_search_in": "Pesquisar tarefas em “{name}”",
+ "chat.reference_count_all": "{count} no total · mais recentes primeiro",
+ "chat.reference_count_found": "{count} encontradas · mais recentes primeiro",
+ "chat.reference_load_more": "Carregar tarefas anteriores (mais {count})",
+ "chat.reference_no_match": "Nenhuma tarefa correspondente",
+ "chat.reference_no_match_hint": "Tente outra palavra-chave ou escolha outro escopo à esquerda.",
+ "chat.reference_scope_empty": "Ainda não há tarefas aqui",
+ "chat.reference_scope_empty_hint": "Use o botão acima para iniciar uma tarefa aqui.",
+ "chat.reference_create_back": "Voltar às tarefas",
+ "chat.reference_create_title": "Onde criar a nova tarefa?",
+ "chat.reference_create_desc": "As referências são adicionadas após a escolha. Nada é enviado automaticamente.",
+ "chat.reference_create_global_desc": "Não pertence a nenhum projeto",
+ "chat.reference_create_project_desc": "Iniciar uma tarefa neste projeto",
+ "chat.reference_target_footer": "A escolha abre o campo de entrada da tarefa com as referências adicionadas. Nada é enviado automaticamente.",
+ "project.todo.run_busy": "A conversa desta tarefa ainda está em andamento. Execute-a novamente quando terminar.",
+ "settings.cleanup.title": "Limpar tarefas antigas",
+ "settings.cleanup.age": "Última atividade",
+ "settings.cleanup.scope": "Tarefas concluídas dentro e fora de projetos. Tarefas fixadas, não lidas, rascunhos e execuções de automações são mantidos.",
+ "settings.cleanup.days": "Há mais de {n} dias",
+ "settings.cleanup.result": "Na lixeira: {deleted}. Ignoradas: {skipped}. Falhas: {failed}.",
+ "settings.cleanup.progress": "Limpando {done} / {total}",
+ "settings.cleanup.error": "Não foi possível carregar ou limpar as tarefas. Atualize e tente novamente.",
+ "settings.cleanup.count": "{n} tarefas selecionadas",
+ "settings.cleanup.empty": "Nenhuma tarefa antiga para limpar.",
+ "settings.cleanup.clean": "Limpar",
+ "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a lixeira. Você pode restaurá-los abaixo. Com a sincronização ativa, a exclusão também se aplica a outros dispositivos. O espaço é liberado ao esvaziar a lixeira.",
+ "settings.cleanup.move": "Mover para a lixeira ({n})",
+ "settings.cleanup.previous": "Anterior",
+ "settings.cleanup.next": "Próxima",
+ "apps.commercial_required": "Os aplicativos web exigem a versão comercial do Orkas. Baixe-a para continuar.",
+ "apps.commercial_download": "Baixar versão comercial",
+ "apps.commercial_open_failed": "Não foi possível abrir a página de download. Tente novamente."
}
diff --git a/src/renderer/locales/ru.json b/src/renderer/locales/ru.json
index f6bc26c4..2a74744e 100644
--- a/src/renderer/locales/ru.json
+++ b/src/renderer/locales/ru.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Загрузка",
"web_assist.activity_visit": "Посещение",
"web_assist.download_saved": "сохранено во вложениях",
- "web_assist.download_needs_grant": "нужно разрешение",
- "web_assist.download_blocked_type": "тип файла не разрешён",
- "web_assist.download_budget": "достигнут лимит загрузок для задачи",
"web_assist.download_failed": "ошибка",
"web_assist.download_unavailable": "Файл недоступен. Убедитесь, что загрузка завершена, а файл не перемещён и не удалён.",
- "web_assist.download_allow": "Разрешить этому сайту",
- "web_assist.download_prompt_title": "Разрешить загрузки с этого сайта?",
- "web_assist.download_prompt_description": "Файлы будут сохранены во вложениях этой задачи. После предоставления разрешения вернитесь на страницу и повторите загрузку.",
- "web_assist.download_not_now": "Не сейчас",
- "web_assist.download_permission_failed": "Не удалось разрешить загрузки с этого сайта. Повторите попытку.",
"web_assist.address_placeholder": "Поиск в Bing или ввод URL",
"web_assist.empty_title": "Браузер в этой задаче",
"web_assist.empty_hint": "Введите поисковый запрос Bing или URL выше.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Последние 30 дней",
"sidebar.bucket.older": "Ранее",
"sidebar.projects": "Проекты",
- "sidebar.today_tasks": "Задачи на сегодня",
- "sidebar.today_empty": "На сегодня задач нет",
+ "sidebar.today_tasks": "Недавние задачи",
+ "sidebar.today_empty": "За последние два дня задач нет",
"sidebar.section_collapse": "Свернуть {section}",
"sidebar.section_expand": "Развернуть {section}",
"sidebar.project_create_title": "Новый проект",
"sidebar.project_create_placeholder": "Введите название проекта",
"sidebar.project_conv_empty": "(нет задач)",
- "sidebar.load_more_conversations": "Загрузить ещё",
+ "sidebar.load_more_conversations": "Показать ещё",
"sidebar.connect_agent": "Подключить агентов",
"sidebar.connect_agent_sub": "Claude Code · Codex и другие",
"sidebar.settings": "Настройки",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Загрузка…",
"new_chat.model_picker.aria_label": "Выбрать модель",
"new_chat.model_picker.empty": "Нет доступных моделей",
- "new_chat.model_picker.group_official": "Официальные модели",
- "new_chat.model_picker.group_custom": "Модели пользователя",
+ "new_chat.model_picker.group_official": "Встроенные модели Orkas",
+ "new_chat.model_picker.group_custom": "Свой API Key",
"new_chat.model_picker.configure": "Настроить модели",
"new_chat.model_picker.switch_failed": "Не удалось сменить модель. Повторите попытку.",
"new_chat.model_picker.choose_version": "Выберите версию модели для {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Добавлено в {library}",
"conversation_info.file_add_to_library_failed": "Не удалось добавить в библиотеку: {reason}",
"conversation_info.file_add_to_chat_action": "Добавить в чат задачи",
- "conversation_info.file_reveal_failed": "Не удалось открыть папку: {reason}",
+ "conversation_info.file_reveal_failed": "Не удалось открыть папку. Возможно, файл перемещён или удалён.",
"conversation_info.file_delete_confirm_title": "Удалить файл",
"conversation_info.file_delete_confirm_msg": "Удалить «{name}»?",
"conversation_info.file_delete_failed": "Не удалось удалить файл: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Отправить сейчас",
"chat.queue_sending_now": "Отправка…",
"chat.queue_send_now_failed": "Не удалось сейчас отправить это сообщение из очереди: {msg}",
- "chat.multi_dispatch_serial": "Выполнять по порядку",
- "chat.multi_dispatch_parallel": "Выполнять вместе",
- "chat.multi_dispatch_toggle_title": "Порядок работы упомянутых агентов для этого сообщения; нажмите для переключения",
"chat.task_waiting_on": "Ожидание {name}",
"chat.task_status_orchestrating": "Координация",
"chat.task_dispatched": "Передано командиром",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Удалить выбранные сообщения? Количество: {count}. Это действие нельзя отменить.",
"chat.message_delete_failed": "Ошибка удаления: {reason}",
"chat.reference_target_title": "Сослаться на сообщения ({count}) в",
- "chat.reference_target_search": "Поиск задач",
- "chat.reference_new_task": "Новая задача",
- "chat.reference_existing_tasks": "Существующие задачи",
- "chat.reference_area_commander": "Командир",
+ "chat.reference_new_task": "Новая задача…",
"chat.reference_area_project": "Проект",
- "chat.reference_recent_tasks_hint": "5 последних задач",
- "chat.reference_search_results_count": "Результатов: {count}",
- "chat.reference_no_tasks": "Нет подходящих задач",
"chat.reference_unknown_task": "Неизвестная задача",
"chat.reference_from_task": "Цитата из «{title}» @{name}",
"chat.reference_bundle_title": "Из «{title}»",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Добавить сервис изображений",
"settings.models.add_video": "Добавить видеосервис",
"settings.models.add_tts": "Добавить речевой сервис",
- "settings.models.order_hint": "Перетаскивайте строки или используйте кнопки со стрелками для изменения приоритета. Отключённые официальные модели пропускаются.",
+ "settings.models.order_hint": "Перетаскивайте строки или используйте кнопки со стрелками для изменения приоритета. Отключённые встроенные модели пропускаются.",
"settings.general.page_sub": "Настройте предпочтения и разрешения агентов.",
"settings.general.preferences_title": "Предпочтения",
"settings.general.agent_title": "Поведение агентов",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Одобрить",
"project.review.request_changes": "Запросить изменения",
"project.driver.toggle": "Авто",
- "project.driver.toggle_hint": "ИИ автоматически выполняет задачи, а вы проверяете готовый результат.",
+ "project.driver.toggle_hint": "ИИ автоматически выполняет задачи, а вы проверяете готовый результат. Выполняется только на устройстве, на котором вы включили эту функцию.",
"project.driver.enabled_toast": "Автопродвижение включено — оно периодически выбирает задачу из очереди и выполняет её; задачи переходят в статус «В работе».",
"project.driver.disabled_toast": "Автопродвижение отключено.",
"project.recent_convs.view_all": "Посмотреть все ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Свернуть",
"skills.source_external": "Пакет",
"skills.source_global": "Общий",
- "web_assist.action_confirm.title": "Разрешить это действие на странице?",
"chat.form.boolean_yes": "Да",
"chat.form.boolean_no": "Нет",
"chat.form.invalid_number": "Введите корректное число",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Перезагрузить",
"quality.operator.disabled": "Отключена на этом устройстве.",
"quality.operator.ready": "Готово: {count} правил.",
- "quality.operator.invalid": "Проверка недоступна. Исправьте operator-policy.json или отключите пользовательскую проверку, затем повторите попытку."
+ "quality.operator.invalid": "Проверка недоступна. Исправьте operator-policy.json или отключите пользовательскую проверку, затем повторите попытку.",
+ "chat.app_nav_project_collaboration_target": "Участники проекта: {target}",
+ "new_chat.home.goal_title": "Есть чёткая цель? Поручите её Командиру.",
+ "new_chat.home.goal_body": "Расскажите Командиру, чего хотите добиться, — он организует работу вашей ИИ-команды.",
+ "new_chat.home.goal_example": "Например: изучить 3 похожих продукта, сравнить функции и цены и оформить всё в презентацию.",
+ "new_chat.home.explore_title": "Пока не решили? Сначала позвольте Orkas узнать вас.",
+ "new_chat.home.explore_body": "Расскажите о своей работе, бизнесе или трудностях — Orkas поможет найти подходящие цели и продвигаться к ним.",
+ "new_chat.home.explore_context": "Поделитесь файлами через + или {connect}, чтобы дать Orkas больше контекста. Начните с того, чем готовы поделиться.",
+ "new_chat.home.explore_connect_link": "подключите Feishu / DingTalk / почту",
+ "new_chat.home.input_placeholder": "Опишите, чего хотите добиться, или приложите файлы для обработки",
+ "new_chat.home.continue_label": "Продолжим начатое",
+ "new_chat.home.group.todos": "Важные дела",
+ "new_chat.home.group.automations": "Результаты автоматизаций",
+ "new_chat.home.group.tasks": "Задачи ждут вас",
+ "new_chat.home.all_automations": "Все автоматизации →",
+ "new_chat.home.expand": "Показать ещё {count}",
+ "new_chat.home.collapse": "Свернуть",
+ "new_chat.home.view_all_todos": "Посмотреть все →",
+ "new_chat.home.source.project_todo": "{project} · Дело",
+ "new_chat.home.source.global_todo": "Общее дело",
+ "new_chat.home.source.automation": "Автоматизация",
+ "new_chat.home.source.project_task": "{project} · Задача проекта",
+ "new_chat.home.source.global_task": "Общая задача",
+ "new_chat.home.result.completed": "Выполнено",
+ "new_chat.home.result.failed": "Ошибка",
+ "new_chat.home.result.waiting_input": "Ждёт вашего ответа",
+ "new_chat.home.result.stopped": "Остановлено",
+ "new_chat.home.result.unknown": "Новый результат",
+ "new_chat.home.action.view": "Открыть",
+ "new_chat.home.action.reply": "Ответить",
+ "new_chat.home.action.view_reason": "Узнать причину",
+ "new_chat.home.action.view_result": "Посмотреть результат",
+ "new_chat.home.time.updated": "Обновлено {time}",
+ "new_chat.home.untitled": "Задача без названия",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "Обновлено: {name}",
+ "apps.save_root_folder_required": "Переместите HTML и связанные ресурсы в отдельную папку, затем снова сохраните как приложение.",
+ "chat.reference_locate_title": "Перейти к исходному сообщению",
+ "chat.reference_locate_missing": "Исходное сообщение больше не существует.",
+ "agents.cli_usage_title": "Оставшийся лимит",
+ "agents.cli_usage_unavailable": "Недоступно. Проверьте вход в CLI и подключение.",
+ "agents.cli_usage_unsupported": "Эта версия CLI или пользовательская конфигурация не поддерживает запрос лимита.",
+ "agents.cli_usage_resets": "Сброс: {time}",
+ "agents.cli_usage_hours": "{count} ч",
+ "agents.cli_usage_days": "{count} дн.",
+ "agents.cli_usage_window": "Период использования",
+ "memory.full_notice": "Память заполнена. Прежде чем сохранить что-то новое, ИИ объединит существующие записи.",
+ "memory.error_full": "Память заполнена, поэтому сейчас эту запись добавить нельзя.",
+ "settings.recycle.clear": "Очистить",
+ "settings.recycle.clear_title": "Очистить корзину",
+ "settings.recycle.clear_confirm": "Удалить навсегда все записи ({count}) в разделе «{source}»? Их нельзя будет восстановить.",
+ "settings.recycle.clearing": "Очистка {done}/{total}…",
+ "settings.recycle.cleared": "Корзина очищена",
+ "settings.recycle.clear_failed": "Не удалось полностью очистить корзину. Повторите попытку.",
+ "settings.recycle.automation_count": "Автоматизация · Задач: {count}",
+ "project.todo.move": "Переместить",
+ "bash.permission.allow_folder_read": "Разрешить чтение этой папки",
+ "bash.permission.folder_read_scope": "В этой задаче {agent} может читать файлы в {folder} без повторного запроса. Запись, удаление и секретные файлы по-прежнему требуют подтверждения.",
+ "cli_upgrade.action": "Обновить CLI",
+ "cli_upgrade.pending": "Обновление…",
+ "cli_upgrade.success": "Обновление выполнено",
+ "cli_upgrade.failed": "Не удалось обновить",
+ "cli_upgrade.named_action": "Обновить {cli} CLI",
+ "web_assist.handback": "Вернуть управление ИИ",
+ "web_assist.permissions": "Сбросить разрешения сайта",
+ "web_assist.permission_title": "Разрешение сайта",
+ "web_assist.permission_allow": "Разрешить",
+ "web_assist.permission_deny": "Запретить",
+ "web_assist.permission_failed": "Не удалось сохранить выбор. Попробуйте ещё раз.",
+ "apps.view_details": "Подробнее",
+ "apps.no_local_code": "На этом устройстве нет кода приложения",
+ "apps.publish_commercial": "Для публикации используйте коммерческую версию Orkas.",
+ "apps.update_original": "Обновить исходное приложение",
+ "apps.save_new": "Сохранить новое приложение",
+ "apps.edit_conflict": "Исходное приложение изменено или удалено. Откройте его заново или сохраните новое.",
+ "apps.save_type_mismatch": "Эта версия имеет другой тип, чем исходное приложение, и не может его заменить. Сохраните её как новое приложение.",
+ "apps.type_local": "Локальное приложение",
+ "apps.type_web": "Веб-приложение",
+ "apps.type_local_description": "Работает в настольном Orkas с доступом к ИИ, файлам, библиотеке и коннекторам; публикация в интернете недоступна.",
+ "apps.type_web_description": "Публикуйте в интернете и открывайте по ссылке: доступны сбор, запросы и статистика данных, но не функции настольного Orkas.",
+ "apps.delete_data_confirm": "Удалить «{name}», локальные записи и личные файлы приложения? Данные не восстановить.",
+ "apps.delete_online_retained": "Опубликованное приложение и онлайн-данные сохранятся.",
+ "apps.migration_export": "Структура данных меняется. Экспортируйте локальные записи перед удалением.",
+ "apps.migration_export_action": "Экспорт записей",
+ "apps.migration_continue": "Продолжить",
+ "apps.migration_clear": "Удалить все локальные записи и обновить? Онлайн-записи хранятся отдельно.",
+ "apps.migration_retry": "Удалить и повторить",
+ "chat.reference_scope_label": "Область задач",
+ "chat.reference_scope_all": "Все задачи",
+ "chat.reference_scope_global": "Общие (без проекта)",
+ "chat.reference_new_in_global": "Новая задача без проекта",
+ "chat.reference_new_in_project": "Новая задача в «{name}»",
+ "chat.reference_search_all": "Искать во всех задачах",
+ "chat.reference_search_in": "Искать задачи в «{name}»",
+ "chat.reference_count_all": "Всего: {count} · сначала недавние",
+ "chat.reference_count_found": "Найдено: {count} · сначала недавние",
+ "chat.reference_load_more": "Загрузить более ранние задачи (ещё {count})",
+ "chat.reference_no_match": "Нет подходящих задач",
+ "chat.reference_no_match_hint": "Попробуйте другое ключевое слово или выберите другую область слева.",
+ "chat.reference_scope_empty": "Здесь пока нет задач",
+ "chat.reference_scope_empty_hint": "Создайте здесь новую задачу с помощью кнопки выше.",
+ "chat.reference_create_back": "Назад к списку задач",
+ "chat.reference_create_title": "Где создать новую задачу?",
+ "chat.reference_create_desc": "Ссылки добавятся после выбора. Ничего не отправляется автоматически.",
+ "chat.reference_create_global_desc": "Не относится ни к одному проекту",
+ "chat.reference_create_project_desc": "Создать новую задачу в этом проекте",
+ "chat.reference_target_footer": "После выбора ссылки добавятся в поле ввода задачи. Ничего не отправляется автоматически.",
+ "project.todo.run_busy": "Беседа этой задачи ещё выполняется. Запустите её снова, когда она завершится.",
+ "settings.cleanup.title": "Очистить старые задачи",
+ "settings.cleanup.age": "Последняя активность",
+ "settings.cleanup.scope": "Завершённые задачи внутри и вне проектов. Закреплённые, непрочитанные задачи, черновики и запуски автоматизаций сохраняются.",
+ "settings.cleanup.days": "Более {n} дней назад",
+ "settings.cleanup.result": "В корзине: {deleted}. Пропущено: {skipped}. Ошибки: {failed}.",
+ "settings.cleanup.progress": "Очистка {done} / {total}",
+ "settings.cleanup.error": "Не удалось загрузить или очистить задачи. Обновите и повторите попытку.",
+ "settings.cleanup.count": "Выбрано задач: {n}",
+ "settings.cleanup.empty": "Нет старых задач для очистки.",
+ "settings.cleanup.clean": "Очистить",
+ "settings.cleanup.confirm": "Переместить {n} задач, вложения и встроенные результаты в корзину. Их можно восстановить ниже. При включённой синхронизации удаление затронет другие устройства. Место освободится после очистки корзины.",
+ "settings.cleanup.move": "В корзину ({n})",
+ "settings.cleanup.previous": "Назад",
+ "settings.cleanup.next": "Далее",
+ "apps.commercial_required": "Для веб-приложений нужна коммерческая версия Orkas. Скачайте её, чтобы продолжить.",
+ "apps.commercial_download": "Скачать коммерческую версию",
+ "apps.commercial_open_failed": "Не удалось открыть страницу загрузки. Повторите попытку."
}
diff --git a/src/renderer/locales/th.json b/src/renderer/locales/th.json
index d0cedaa9..fc832ff8 100644
--- a/src/renderer/locales/th.json
+++ b/src/renderer/locales/th.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "ดาวน์โหลด",
"web_assist.activity_visit": "เข้าชม",
"web_assist.download_saved": "บันทึกเป็นไฟล์แนบแล้ว",
- "web_assist.download_needs_grant": "ต้องได้รับอนุญาต",
- "web_assist.download_blocked_type": "ไม่อนุญาตไฟล์ประเภทนี้",
- "web_assist.download_budget": "ถึงขีดจำกัดการดาวน์โหลดของงานแล้ว",
"web_assist.download_failed": "ล้มเหลว",
"web_assist.download_unavailable": "ไฟล์ไม่พร้อมใช้งาน ตรวจสอบว่าดาวน์โหลดเสร็จแล้วและไฟล์ไม่ได้ถูกย้ายหรือลบ",
- "web_assist.download_allow": "อนุญาตเว็บไซต์นี้",
- "web_assist.download_prompt_title": "อนุญาตให้ดาวน์โหลดจากเว็บไซต์นี้หรือไม่?",
- "web_assist.download_prompt_description": "ไฟล์จะถูกบันทึกเป็นไฟล์แนบของงานนี้ หลังอนุญาตแล้ว ให้กลับไปที่หน้าเว็บแล้วลองดาวน์โหลดอีกครั้ง",
- "web_assist.download_not_now": "ยังไม่ใช่ตอนนี้",
- "web_assist.download_permission_failed": "อนุญาตเว็บไซต์นี้ไม่ได้ ลองอีกครั้ง",
"web_assist.address_placeholder": "ค้นหา Bing หรือป้อน URL",
"web_assist.empty_title": "ท่องเว็บในงานนี้",
"web_assist.empty_hint": "ค้นหา Bing หรือป้อน URL ด้านบน",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 วันที่ผ่านมา",
"sidebar.bucket.older": "ก่อนหน้านี้",
"sidebar.projects": "โปรเจกต์",
- "sidebar.today_tasks": "งานวันนี้",
- "sidebar.today_empty": "วันนี้ไม่มีงาน",
+ "sidebar.today_tasks": "งานล่าสุด",
+ "sidebar.today_empty": "ไม่มีงานในสองวันที่ผ่านมา",
"sidebar.section_collapse": "ยุบ {section}",
"sidebar.section_expand": "ขยาย {section}",
"sidebar.project_create_title": "โปรเจกต์ใหม่",
"sidebar.project_create_placeholder": "ป้อนชื่อโปรเจกต์",
"sidebar.project_conv_empty": "(ไม่มีงาน)",
- "sidebar.load_more_conversations": "โหลดเพิ่มเติม",
+ "sidebar.load_more_conversations": "แสดงเพิ่มเติม",
"sidebar.connect_agent": "เชื่อมต่อเอเจนต์",
"sidebar.connect_agent_sub": "Claude Code · Codex และอีกมากมาย",
"sidebar.settings": "การตั้งค่า",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "กำลังโหลด…",
"new_chat.model_picker.aria_label": "เลือกโมเดล",
"new_chat.model_picker.empty": "ไม่มีโมเดลที่พร้อมใช้งาน",
- "new_chat.model_picker.group_official": "โมเดลทางการ",
- "new_chat.model_picker.group_custom": "โมเดลที่ผู้ใช้ตั้งค่า",
+ "new_chat.model_picker.group_official": "โมเดลในตัว Orkas",
+ "new_chat.model_picker.group_custom": "API Key ของคุณเอง",
"new_chat.model_picker.configure": "ตั้งค่าโมเดล",
"new_chat.model_picker.switch_failed": "เปลี่ยนโมเดลไม่ได้ ลองอีกครั้ง",
"new_chat.model_picker.choose_version": "เลือกเวอร์ชันโมเดลสำหรับ {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "เพิ่มใน {library} แล้ว",
"conversation_info.file_add_to_library_failed": "เพิ่มเข้าคลังข้อมูลไม่สำเร็จ: {reason}",
"conversation_info.file_add_to_chat_action": "เพิ่มในแชตงาน",
- "conversation_info.file_reveal_failed": "เปิดโฟลเดอร์ไม่ได้: {reason}",
+ "conversation_info.file_reveal_failed": "เปิดโฟลเดอร์ไม่ได้ ไฟล์อาจถูกย้ายหรือลบไปแล้ว",
"conversation_info.file_delete_confirm_title": "ลบไฟล์",
"conversation_info.file_delete_confirm_msg": "ลบ \"{name}\" หรือไม่?",
"conversation_info.file_delete_failed": "ลบไฟล์ไม่ได้: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "ส่งตอนนี้",
"chat.queue_sending_now": "กำลังส่ง…",
"chat.queue_send_now_failed": "ส่งข้อความในคิวนี้ตอนนี้ไม่ได้: {msg}",
- "chat.multi_dispatch_serial": "ทำงานตามลำดับ",
- "chat.multi_dispatch_parallel": "ทำงานพร้อมกัน",
- "chat.multi_dispatch_toggle_title": "วิธีทำงานของเอเจนต์ที่กล่าวถึงในข้อความนี้ คลิกเพื่อสลับ",
"chat.task_waiting_on": "กำลังรอ {name}",
"chat.task_status_orchestrating": "กำลังประสานงาน",
"chat.task_dispatched": "มอบหมายโดยผู้บัญชาการ",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "ลบข้อความที่เลือก {count} ข้อความหรือไม่? การดำเนินการนี้ย้อนกลับไม่ได้",
"chat.message_delete_failed": "ลบไม่สำเร็จ: {reason}",
"chat.reference_target_title": "อ้างอิง {count} ข้อความใน",
- "chat.reference_target_search": "ค้นหางาน",
- "chat.reference_new_task": "งานใหม่",
- "chat.reference_existing_tasks": "งานที่มีอยู่",
- "chat.reference_area_commander": "ผู้บัญชาการ",
+ "chat.reference_new_task": "งานใหม่…",
"chat.reference_area_project": "โปรเจกต์",
- "chat.reference_recent_tasks_hint": "5 งานล่าสุด",
- "chat.reference_search_results_count": "{count} ผลลัพธ์",
- "chat.reference_no_tasks": "ไม่พบงานที่ตรงกัน",
"chat.reference_unknown_task": "ไม่ทราบงาน",
"chat.reference_from_task": "อ้างอิงจาก “{title}” @{name}",
"chat.reference_bundle_title": "จาก “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "เพิ่มบริการภาพ",
"settings.models.add_video": "เพิ่มบริการวิดีโอ",
"settings.models.add_tts": "เพิ่มบริการเสียงพูด",
- "settings.models.order_hint": "ลากแถวเพื่อเปลี่ยนลำดับความสำคัญ หรือใช้ปุ่มลูกศร โมเดลทางการที่ปิดใช้งานจะถูกข้าม",
+ "settings.models.order_hint": "ลากแถวเพื่อเปลี่ยนลำดับความสำคัญ หรือใช้ปุ่มลูกศร โมเดลในตัวที่ปิดใช้งานจะถูกข้าม",
"settings.general.page_sub": "ปรับการตั้งค่าส่วนตัว สิทธิ์เอเจนต์ และการอัปเดตแอป",
"settings.general.preferences_title": "การตั้งค่าส่วนตัว",
"settings.general.agent_title": "พฤติกรรมเอเจนต์",
@@ -2031,7 +2014,7 @@
"project.review.approve": "อนุมัติ",
"project.review.request_changes": "ขอให้แก้ไข",
"project.driver.toggle": "อัตโนมัติ",
- "project.driver.toggle_hint": "AI จัดการสิ่งที่ต้องทำโดยอัตโนมัติให้คุณตรวจสอบเมื่อเสร็จ",
+ "project.driver.toggle_hint": "AI จัดการสิ่งที่ต้องทำโดยอัตโนมัติให้คุณตรวจสอบเมื่อเสร็จ ทำงานเฉพาะบนอุปกรณ์ที่คุณเปิดใช้งานเท่านั้น",
"project.driver.enabled_toast": "เปิดการเดินหน้าต่ออัตโนมัติ — ระบบจะเลือกงานค้างมาทำเป็นระยะ และย้ายงานไปเป็นกำลังดำเนินการ",
"project.driver.disabled_toast": "ปิดการเดินหน้าต่ออัตโนมัติ",
"project.recent_convs.view_all": "ดูทั้งหมด ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "ยุบ",
"skills.source_external": "แพ็กเกจ",
"skills.source_global": "ส่วนกลาง",
- "web_assist.action_confirm.title": "อนุญาตการดำเนินการนี้บนหน้าเว็บหรือไม่?",
"chat.form.boolean_yes": "ใช่",
"chat.form.boolean_no": "ไม่",
"chat.form.invalid_number": "ป้อนตัวเลขที่ถูกต้อง",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "โหลดใหม่",
"quality.operator.disabled": "ปิดใช้งานบนอุปกรณ์นี้",
"quality.operator.ready": "พร้อม: {count} กฎ",
- "quality.operator.invalid": "ไม่สามารถตรวจสอบได้ แก้ไข operator-policy.json หรือปิดการตรวจสอบแบบกำหนดเอง แล้วลองอีกครั้ง"
+ "quality.operator.invalid": "ไม่สามารถตรวจสอบได้ แก้ไข operator-policy.json หรือปิดการตรวจสอบแบบกำหนดเอง แล้วลองอีกครั้ง",
+ "chat.app_nav_project_collaboration_target": "สมาชิกโปรเจกต์: {target}",
+ "new_chat.home.goal_title": "มีเป้าหมายชัดเจนแล้ว? มอบให้ผู้บัญชาการ",
+ "new_chat.home.goal_body": "บอกผู้บัญชาการว่าคุณอยากทำอะไรให้สำเร็จ แล้วผู้บัญชาการจะประสานทีม AI ให้ทำงานจนเสร็จ",
+ "new_chat.home.goal_example": "เช่น: สำรวจผลิตภัณฑ์ที่คล้ายกัน 3 ตัว เปรียบเทียบฟีเจอร์และราคา แล้วสรุปเป็นงานนำเสนอ",
+ "new_chat.home.explore_title": "ยังไม่แน่ใจ? ให้ Orkas ได้รู้จักคุณก่อน",
+ "new_chat.home.explore_body": "เล่าเรื่องงาน ธุรกิจ หรือปัญหาที่เจออยู่ แล้ว Orkas จะช่วยหาเป้าหมายที่เหมาะสมและผลักดันต่อไปอย่างต่อเนื่อง",
+ "new_chat.home.explore_context": "แชร์ไฟล์ด้วย + หรือ{connect} เพื่อให้ Orkas เข้าใจบริบทของคุณมากขึ้น เริ่มจากสิ่งที่คุณสะดวกใจจะแชร์",
+ "new_chat.home.explore_connect_link": "เชื่อมต่อ Feishu / DingTalk / อีเมล",
+ "new_chat.home.input_placeholder": "บอกสิ่งที่คุณอยากทำให้สำเร็จ หรือแนบไฟล์ที่ต้องจัดการ",
+ "new_chat.home.continue_label": "ทำงานต่อให้คืบหน้า",
+ "new_chat.home.group.todos": "สิ่งที่ต้องทำที่สำคัญ",
+ "new_chat.home.group.automations": "งานอัตโนมัติที่ต้องตรวจ",
+ "new_chat.home.group.tasks": "งานที่รอคุณ",
+ "new_chat.home.all_automations": "งานอัตโนมัติทั้งหมด →",
+ "new_chat.home.expand": "แสดงอีก {count} รายการ",
+ "new_chat.home.collapse": "ย่อ",
+ "new_chat.home.view_all_todos": "ดูทั้งหมด →",
+ "new_chat.home.source.project_todo": "{project} · สิ่งที่ต้องทำ",
+ "new_chat.home.source.global_todo": "สิ่งที่ต้องทำส่วนกลาง",
+ "new_chat.home.source.automation": "งานอัตโนมัติ",
+ "new_chat.home.source.project_task": "{project} · งานในโปรเจกต์",
+ "new_chat.home.source.global_task": "งานส่วนกลาง",
+ "new_chat.home.result.completed": "เสร็จแล้ว",
+ "new_chat.home.result.failed": "ล้มเหลว",
+ "new_chat.home.result.waiting_input": "รอคุณตอบ",
+ "new_chat.home.result.stopped": "หยุดแล้ว",
+ "new_chat.home.result.unknown": "มีผลลัพธ์ใหม่",
+ "new_chat.home.action.view": "ดู",
+ "new_chat.home.action.reply": "ตอบกลับ",
+ "new_chat.home.action.view_reason": "ดูสาเหตุ",
+ "new_chat.home.action.view_result": "ดูผลลัพธ์",
+ "new_chat.home.time.updated": "อัปเดต {time}",
+ "new_chat.home.untitled": "งานที่ไม่มีชื่อ",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "อัปเดต {name} แล้ว",
+ "apps.save_root_folder_required": "ย้าย HTML และทรัพยากรที่เกี่ยวข้องไปไว้ในโฟลเดอร์แยก แล้วบันทึกเป็นแอปอีกครั้ง",
+ "chat.reference_locate_title": "ไปที่ข้อความต้นฉบับ",
+ "chat.reference_locate_missing": "ข้อความต้นฉบับไม่มีอยู่แล้ว",
+ "agents.cli_usage_title": "โควตาคงเหลือ",
+ "agents.cli_usage_unavailable": "ไม่พร้อมใช้งาน ตรวจสอบการเข้าสู่ระบบ CLI และการเชื่อมต่อ",
+ "agents.cli_usage_unsupported": "CLI เวอร์ชันนี้หรือการตั้งค่าแบบกำหนดเองไม่รองรับการดูโควตา",
+ "agents.cli_usage_resets": "รีเซ็ต: {time}",
+ "agents.cli_usage_hours": "{count} ชั่วโมง",
+ "agents.cli_usage_days": "{count} วัน",
+ "agents.cli_usage_window": "รอบการใช้งาน",
+ "memory.full_notice": "หน่วยความจำเต็มแล้ว ก่อนบันทึกสิ่งใหม่ AI จะรวมรายการที่มีอยู่เข้าด้วยกัน",
+ "memory.error_full": "หน่วยความจำเต็มแล้ว จึงยังเพิ่มรายการนี้ไม่ได้ในตอนนี้",
+ "settings.recycle.clear": "ล้าง",
+ "settings.recycle.clear_title": "ล้างถังขยะ",
+ "settings.recycle.clear_confirm": "ลบทั้ง {count} รายการใน {source} อย่างถาวรหรือไม่? หลังจากลบจะไม่สามารถกู้คืนได้",
+ "settings.recycle.clearing": "กำลังล้าง {done}/{total}…",
+ "settings.recycle.cleared": "ล้างถังขยะแล้ว",
+ "settings.recycle.clear_failed": "ไม่สามารถล้างถังขยะได้ทั้งหมด โปรดลองอีกครั้ง",
+ "settings.recycle.automation_count": "ระบบอัตโนมัติ · {count} งาน",
+ "project.todo.move": "ย้าย",
+ "bash.permission.allow_folder_read": "อนุญาตให้อ่านโฟลเดอร์นี้",
+ "bash.permission.folder_read_scope": "ระหว่างงานนี้ {agent} อ่านไฟล์ใน {folder} ได้โดยไม่ต้องถามอีก การเขียน การลบ และไฟล์ลับยังคงต้องยืนยัน",
+ "cli_upgrade.action": "อัปเกรด CLI",
+ "cli_upgrade.pending": "กำลังอัปเกรด…",
+ "cli_upgrade.success": "อัปเกรดสำเร็จ",
+ "cli_upgrade.failed": "อัปเกรดไม่สำเร็จ",
+ "cli_upgrade.named_action": "อัปเกรด {cli} CLI",
+ "web_assist.handback": "คืนการควบคุมให้ AI",
+ "web_assist.permissions": "รีเซ็ตสิทธิ์เว็บไซต์",
+ "web_assist.permission_title": "สิทธิ์เว็บไซต์",
+ "web_assist.permission_allow": "อนุญาต",
+ "web_assist.permission_deny": "ปฏิเสธ",
+ "web_assist.permission_failed": "บันทึกตัวเลือกไม่ได้ โปรดลองอีกครั้ง",
+ "apps.view_details": "ดูรายละเอียด",
+ "apps.no_local_code": "ไม่มีโค้ดแอปบนอุปกรณ์นี้",
+ "apps.publish_commercial": "ใช้ Orkas รุ่นเชิงพาณิชย์เพื่อเผยแพร่",
+ "apps.update_original": "อัปเดตแอปเดิม",
+ "apps.save_new": "บันทึกแอปใหม่",
+ "apps.edit_conflict": "แอปเดิมเปลี่ยนหรือถูกลบ โปรดเปิดแก้ไขใหม่หรือบันทึกเป็นแอปใหม่",
+ "apps.save_type_mismatch": "เวอร์ชันนี้เป็นแอปคนละประเภทกับแอปเดิม จึงแทนที่แอปเดิมไม่ได้ โปรดบันทึกเป็นแอปใหม่แทน",
+ "apps.type_local": "แอปในเครื่อง",
+ "apps.type_web": "เว็บแอป",
+ "apps.type_local_description": "ทำงานใน Orkas บนเดสก์ท็อป ใช้ AI ไฟล์ คลังความรู้ และตัวเชื่อมต่อได้ แต่ไม่สามารถเผยแพร่เป็นเว็บได้",
+ "apps.type_web_description": "เผยแพร่เป็นเว็บและเข้าถึงผ่านลิงก์ได้ รองรับการเก็บรวบรวม ค้นหา และสถิติข้อมูล แต่ไม่รองรับฟังก์ชันของ Orkas บนเดสก์ท็อป",
+ "apps.delete_data_confirm": "ลบ \"{name}\" พร้อมข้อมูลในเครื่องและไฟล์ส่วนตัวหรือไม่? กู้คืนข้อมูลไม่ได้",
+ "apps.delete_online_retained": "แอปที่เผยแพร่และข้อมูลออนไลน์ยังคงอยู่",
+ "apps.migration_export": "โครงสร้างข้อมูลจะเปลี่ยน ส่งออกระเบียนในเครื่องก่อนล้างได้",
+ "apps.migration_export_action": "ส่งออกระเบียน",
+ "apps.migration_continue": "ดำเนินการต่อ",
+ "apps.migration_clear": "ล้างระเบียนในเครื่องทั้งหมดและอัปเดตหรือไม่? ระเบียนออนไลน์เก็บแยกกัน",
+ "apps.migration_retry": "ล้างและลองใหม่",
+ "chat.reference_scope_label": "ขอบเขตงาน",
+ "chat.reference_scope_all": "งานทั้งหมด",
+ "chat.reference_scope_global": "ทั่วไป (ไม่มีโปรเจกต์)",
+ "chat.reference_new_in_global": "งานใหม่แบบไม่มีโปรเจกต์",
+ "chat.reference_new_in_project": "งานใหม่ใน “{name}”",
+ "chat.reference_search_all": "ค้นหางานทั้งหมด",
+ "chat.reference_search_in": "ค้นหางานใน “{name}”",
+ "chat.reference_count_all": "ทั้งหมด {count} · ล่าสุดก่อน",
+ "chat.reference_count_found": "พบ {count} · ล่าสุดก่อน",
+ "chat.reference_load_more": "โหลดงานก่อนหน้า (เหลืออีก {count})",
+ "chat.reference_no_match": "ไม่พบงานที่ตรงกัน",
+ "chat.reference_no_match_hint": "ลองใช้คำค้นอื่น หรือเลือกขอบเขตอื่นทางซ้าย",
+ "chat.reference_scope_empty": "ยังไม่มีงานที่นี่",
+ "chat.reference_scope_empty_hint": "ใช้ปุ่มด้านบนเพื่อเริ่มงานใหม่ที่นี่",
+ "chat.reference_create_back": "กลับไปที่รายการงาน",
+ "chat.reference_create_title": "จะสร้างงานใหม่ไว้ที่ไหน",
+ "chat.reference_create_desc": "ระบบจะเพิ่มข้อความอ้างอิงหลังจากเลือก และจะไม่ส่งอัตโนมัติ",
+ "chat.reference_create_global_desc": "ไม่อยู่ในโปรเจกต์ใด",
+ "chat.reference_create_project_desc": "เริ่มงานใหม่ในโปรเจกต์นี้",
+ "chat.reference_target_footer": "เมื่อเลือกแล้ว ข้อความอ้างอิงจะถูกเพิ่มในช่องพิมพ์ของงาน และจะไม่ส่งอัตโนมัติ",
+ "project.todo.run_busy": "บทสนทนาของงานนี้ยังทำงานอยู่ เรียกใช้อีกครั้งเมื่อเสร็จแล้ว",
+ "settings.cleanup.title": "ล้างงานเก่า",
+ "settings.cleanup.age": "ใช้งานล่าสุด",
+ "settings.cleanup.scope": "งานที่เสร็จแล้วทั้งในและนอกโครงการ โดยเก็บงานที่ปักหมุด ยังไม่อ่าน ฉบับร่าง และประวัติระบบอัตโนมัติไว้",
+ "settings.cleanup.days": "มากกว่า {n} วันที่แล้ว",
+ "settings.cleanup.result": "ย้ายไปถังขยะ {deleted} รายการ ข้าม {skipped} รายการ ล้มเหลว {failed} รายการ",
+ "settings.cleanup.progress": "กำลังล้าง {done} / {total}",
+ "settings.cleanup.error": "โหลดหรือล้างงานไม่สำเร็จ โปรดรีเฟรชแล้วลองอีกครั้ง",
+ "settings.cleanup.count": "เลือก {n} งาน",
+ "settings.cleanup.empty": "ไม่มีงานเก่าที่ล้างได้",
+ "settings.cleanup.clean": "ล้าง",
+ "settings.cleanup.confirm": "ย้าย {n} งาน พร้อมไฟล์แนบและผลลัพธ์ที่ฝังไว้ไปยังถังขยะ โดยกู้คืนได้ด้านล่าง หากเปิดการซิงค์ การลบจะมีผลกับอุปกรณ์อื่นด้วย พื้นที่ดิสก์จะว่างเมื่อเทถังขยะ",
+ "settings.cleanup.move": "ย้ายไปถังขยะ ({n})",
+ "settings.cleanup.previous": "ก่อนหน้า",
+ "settings.cleanup.next": "ถัดไป",
+ "apps.commercial_required": "แอปเว็บต้องใช้ Orkas เวอร์ชันเชิงพาณิชย์ ดาวน์โหลดเพื่อดำเนินการต่อ",
+ "apps.commercial_download": "ดาวน์โหลดเวอร์ชันเชิงพาณิชย์",
+ "apps.commercial_open_failed": "เปิดหน้าดาวน์โหลดไม่ได้ โปรดลองอีกครั้ง"
}
diff --git a/src/renderer/locales/tr.json b/src/renderer/locales/tr.json
index e1348126..d759fc75 100644
--- a/src/renderer/locales/tr.json
+++ b/src/renderer/locales/tr.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "İndir",
"web_assist.activity_visit": "Ziyaret et",
"web_assist.download_saved": "eklere kaydedildi",
- "web_assist.download_needs_grant": "izin gerekiyor",
- "web_assist.download_blocked_type": "dosya türüne izin verilmiyor",
- "web_assist.download_budget": "görev indirme sınırına ulaşıldı",
"web_assist.download_failed": "başarısız",
"web_assist.download_unavailable": "Dosya kullanılamıyor. İndirmenin tamamlandığını ve dosyanın taşınmadığını veya silinmediğini kontrol edin.",
- "web_assist.download_allow": "Bu siteye izin ver",
- "web_assist.download_prompt_title": "Bu siteden indirmelere izin verilsin mi?",
- "web_assist.download_prompt_description": "Dosyalar bu görevin eklerine kaydedilecek. İzin verdikten sonra sayfaya dönüp indirmeyi tekrar deneyin.",
- "web_assist.download_not_now": "Şimdi değil",
- "web_assist.download_permission_failed": "Bu siteye izin verilemedi. Tekrar deneyin.",
"web_assist.address_placeholder": "Bing'de arayın veya URL girin",
"web_assist.empty_title": "Bu görevde web'de gezinin",
"web_assist.empty_hint": "Bing'de arayın veya yukarıya URL girin.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "Son 30 gün",
"sidebar.bucket.older": "Daha eski",
"sidebar.projects": "Projeler",
- "sidebar.today_tasks": "Bugünün görevleri",
- "sidebar.today_empty": "Bugün görev yok",
+ "sidebar.today_tasks": "Son görevler",
+ "sidebar.today_empty": "Son iki günde görev yok",
"sidebar.section_collapse": "{section} bölümünü daralt",
"sidebar.section_expand": "{section} bölümünü genişlet",
"sidebar.project_create_title": "Yeni proje",
"sidebar.project_create_placeholder": "Proje adını girin",
"sidebar.project_conv_empty": "(görev yok)",
- "sidebar.load_more_conversations": "Daha fazla yükle",
+ "sidebar.load_more_conversations": "Daha fazla göster",
"sidebar.connect_agent": "Ajanları bağla",
"sidebar.connect_agent_sub": "Claude Code · Codex ve daha fazlası",
"sidebar.settings": "Ayarlar",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Yükleniyor…",
"new_chat.model_picker.aria_label": "Model seç",
"new_chat.model_picker.empty": "Kullanılabilir model yok",
- "new_chat.model_picker.group_official": "Resmî modeller",
- "new_chat.model_picker.group_custom": "Kullanıcının yapılandırdığı modeller",
+ "new_chat.model_picker.group_official": "Orkas yerleşik modelleri",
+ "new_chat.model_picker.group_custom": "Kendi API Key’iniz",
"new_chat.model_picker.configure": "Modelleri yapılandır",
"new_chat.model_picker.switch_failed": "Model değiştirilemedi. Tekrar deneyin.",
"new_chat.model_picker.choose_version": "{account} için model sürümü seçin",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "{library} konumuna eklendi",
"conversation_info.file_add_to_library_failed": "Kütüphane'ye eklenemedi: {reason}",
"conversation_info.file_add_to_chat_action": "Görev sohbetine ekle",
- "conversation_info.file_reveal_failed": "Klasör açılamadı: {reason}",
+ "conversation_info.file_reveal_failed": "Klasör açılamadı. Dosya taşınmış veya silinmiş olabilir.",
"conversation_info.file_delete_confirm_title": "Dosyayı sil",
"conversation_info.file_delete_confirm_msg": "\"{name}\" silinsin mi?",
"conversation_info.file_delete_failed": "Dosya silinemedi: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Şimdi gönder",
"chat.queue_sending_now": "Gönderiliyor…",
"chat.queue_send_now_failed": "Sıradaki bu mesaj şimdi gönderilemedi: {msg}",
- "chat.multi_dispatch_serial": "Sırayla çalıştır",
- "chat.multi_dispatch_parallel": "Birlikte çalıştır",
- "chat.multi_dispatch_toggle_title": "Bu mesajda bahsedilen ajanların çalışma biçimi; değiştirmek için tıklayın",
"chat.task_waiting_on": "{name} bekleniyor",
"chat.task_status_orchestrating": "Koordine ediliyor",
"chat.task_dispatched": "Commander tarafından atandı",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Seçilen {count} mesaj silinsin mi? Bu işlem geri alınamaz.",
"chat.message_delete_failed": "Silinemedi: {reason}",
"chat.reference_target_title": "{count} mesaja referans verilecek yer",
- "chat.reference_target_search": "Görevlerde ara",
- "chat.reference_new_task": "Yeni görev",
- "chat.reference_existing_tasks": "Mevcut görevler",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Yeni görev…",
"chat.reference_area_project": "Proje",
- "chat.reference_recent_tasks_hint": "En son 5 görev",
- "chat.reference_search_results_count": "{count} sonuç",
- "chat.reference_no_tasks": "Eşleşen görev yok",
"chat.reference_unknown_task": "Bilinmeyen görev",
"chat.reference_from_task": "“{title}” görevindeki @{name} kişisinden alıntı",
"chat.reference_bundle_title": "“{title}” görevinden",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Görsel hizmeti ekle",
"settings.models.add_video": "Video hizmeti ekle",
"settings.models.add_tts": "Konuşma hizmeti ekle",
- "settings.models.order_hint": "Önceliği değiştirmek için satırları sürükleyin veya ok düğmelerini kullanın. Devre dışı resmî modeller atlanır.",
+ "settings.models.order_hint": "Önceliği değiştirmek için satırları sürükleyin veya ok düğmelerini kullanın. Devre dışı yerleşik modeller atlanır.",
"settings.general.page_sub": "Tercihleri, ajan izinlerini ve uygulama güncellemelerini ayarlayın.",
"settings.general.preferences_title": "Tercihler",
"settings.general.agent_title": "Ajan davranışı",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Onayla",
"project.review.request_changes": "Değişiklik iste",
"project.driver.toggle": "Otomatik",
- "project.driver.toggle_hint": "Yapay zekâ yapılacakları otomatik tamamlar; bittiğinde siz incelersiniz.",
+ "project.driver.toggle_hint": "Yapay zekâ yapılacakları otomatik tamamlar; bittiğinde siz incelersiniz. Yalnızca açtığınız cihazda çalışır.",
"project.driver.enabled_toast": "Otomatik ilerleme açık; düzenli olarak bekleyen bir görev seçip üzerinde çalışır. Görevler Devam ediyor durumuna geçer.",
"project.driver.disabled_toast": "Otomatik ilerleme kapalı.",
"project.recent_convs.view_all": "Tümünü görüntüle ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Daralt",
"skills.source_external": "Paket",
"skills.source_global": "Genel",
- "web_assist.action_confirm.title": "Sayfadaki bu işleme izin verilsin mi?",
"chat.form.boolean_yes": "Evet",
"chat.form.boolean_no": "Hayır",
"chat.form.invalid_number": "Geçerli bir sayı girin",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Yeniden yükle",
"quality.operator.disabled": "Bu cihazda devre dışı.",
"quality.operator.ready": "Hazır: {count} kural.",
- "quality.operator.invalid": "Doğrulama kullanılamıyor. operator-policy.json dosyasını düzeltin veya özel doğrulamayı kapatıp yeniden deneyin."
+ "quality.operator.invalid": "Doğrulama kullanılamıyor. operator-policy.json dosyasını düzeltin veya özel doğrulamayı kapatıp yeniden deneyin.",
+ "chat.app_nav_project_collaboration_target": "Proje üyeleri: {target}",
+ "new_chat.home.goal_title": "Net bir hedefiniz mi var? Commander'a bırakın.",
+ "new_chat.home.goal_body": "Neyi başarmak istediğinizi Commander'a söyleyin; yapay zekâ ekibinizi yönlendirerek işi tamamlasın.",
+ "new_chat.home.goal_example": "Örneğin: 3 benzer ürünü araştır, özelliklerini ve fiyatlarını karşılaştır ve bir sunuma dönüştür.",
+ "new_chat.home.explore_title": "Henüz emin değil misiniz? Önce Orkas sizi tanısın.",
+ "new_chat.home.explore_body": "İşinizden, şirketinizden veya zorluklarınızdan bahsedin; Orkas doğru hedefleri bulmanıza ve ilerletmenize yardımcı olsun.",
+ "new_chat.home.explore_context": "+ ile dosya paylaşın veya {connect}; böylece Orkas sizi daha iyi anlasın. Paylaşmaktan rahatsız olmadığınız şeylerle başlayın.",
+ "new_chat.home.explore_connect_link": "Feishu / DingTalk / e-postanızı bağlayın",
+ "new_chat.home.input_placeholder": "Neyi başarmak istediğinizi yazın veya işlenecek dosyaları ekleyin",
+ "new_chat.home.continue_label": "İşleri ilerletmeye devam edin",
+ "new_chat.home.group.todos": "Önemli yapılacaklar",
+ "new_chat.home.group.automations": "İncelenecek otomasyonlar",
+ "new_chat.home.group.tasks": "Sizi bekleyen görevler",
+ "new_chat.home.all_automations": "Tüm otomasyonlar →",
+ "new_chat.home.expand": "{count} tane daha göster",
+ "new_chat.home.collapse": "Daha az göster",
+ "new_chat.home.view_all_todos": "Tümünü görüntüle →",
+ "new_chat.home.source.project_todo": "{project} · Yapılacak",
+ "new_chat.home.source.global_todo": "Genel yapılacak",
+ "new_chat.home.source.automation": "Otomasyon",
+ "new_chat.home.source.project_task": "{project} · Proje görevi",
+ "new_chat.home.source.global_task": "Genel görev",
+ "new_chat.home.result.completed": "Tamamlandı",
+ "new_chat.home.result.failed": "Başarısız",
+ "new_chat.home.result.waiting_input": "Yanıtınızı bekliyor",
+ "new_chat.home.result.stopped": "Durduruldu",
+ "new_chat.home.result.unknown": "Yeni sonuç",
+ "new_chat.home.action.view": "Görüntüle",
+ "new_chat.home.action.reply": "Yanıtla",
+ "new_chat.home.action.view_reason": "Nedenini gör",
+ "new_chat.home.action.view_result": "Sonucu gör",
+ "new_chat.home.time.updated": "{time} güncellendi",
+ "new_chat.home.untitled": "Adsız görev",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "{name} güncellendi",
+ "apps.save_root_folder_required": "HTML ve ilgili kaynakları ayrı bir klasöre taşıyıp yeniden uygulama olarak kaydedin.",
+ "chat.reference_locate_title": "Özgün mesaja git",
+ "chat.reference_locate_missing": "Özgün mesaj artık mevcut değil.",
+ "agents.cli_usage_title": "Kalan kota",
+ "agents.cli_usage_unavailable": "Kullanılamıyor. CLI oturumunu ve bağlantıyı kontrol edin.",
+ "agents.cli_usage_unsupported": "Bu CLI sürümü veya özel yapılandırma kota sorgulamayı desteklemiyor.",
+ "agents.cli_usage_resets": "Sıfırlanma: {time}",
+ "agents.cli_usage_hours": "{count} saat",
+ "agents.cli_usage_days": "{count} gün",
+ "agents.cli_usage_window": "Kullanım dönemi",
+ "memory.full_notice": "Bellek dolu. Yapay zekâ yeni bir şey kaydetmeden önce mevcut kayıtları birleştirecek.",
+ "memory.error_full": "Bellek dolu, bu yüzden bu kayıt şu anda eklenemiyor.",
+ "settings.recycle.clear": "Boşalt",
+ "settings.recycle.clear_title": "Geri Dönüşüm Kutusunu Boşalt",
+ "settings.recycle.clear_confirm": "{source} içindeki {count} kaydın tümü kalıcı olarak silinsin mi? Daha sonra geri yüklenemezler.",
+ "settings.recycle.clearing": "Boşaltılıyor {done}/{total}…",
+ "settings.recycle.cleared": "Geri dönüşüm kutusu boşaltıldı",
+ "settings.recycle.clear_failed": "Geri dönüşüm kutusu tamamen boşaltılamadı. Lütfen tekrar deneyin.",
+ "settings.recycle.automation_count": "Otomasyon · {count} görev",
+ "project.todo.move": "Taşı",
+ "bash.permission.allow_folder_read": "Bu klasörü okumaya izin ver",
+ "bash.permission.folder_read_scope": "Bu görev boyunca {agent}, {folder} içindeki dosyaları yeniden sormadan okuyabilir. Yazma, silme ve gizli dosyalar için onay istenmeye devam eder.",
+ "cli_upgrade.action": "CLI’ı yükselt",
+ "cli_upgrade.pending": "Yükseltiliyor…",
+ "cli_upgrade.success": "Yükseltme başarılı",
+ "cli_upgrade.failed": "Yükseltme başarısız",
+ "cli_upgrade.named_action": "{cli} CLI’ı yükselt",
+ "web_assist.handback": "Kontrolü yapay zekâya ver",
+ "web_assist.permissions": "Site izinlerini sıfırla",
+ "web_assist.permission_title": "Site izni",
+ "web_assist.permission_allow": "İzin ver",
+ "web_assist.permission_deny": "Reddet",
+ "web_assist.permission_failed": "Seçiminiz kaydedilemedi. Tekrar deneyin.",
+ "apps.view_details": "Ayrıntıları görüntüle",
+ "apps.no_local_code": "Bu cihazda uygulama kodu yok",
+ "apps.publish_commercial": "Yayımlamak için ticari Orkas sürümünü kullanın.",
+ "apps.update_original": "Özgün uygulamayı güncelle",
+ "apps.save_new": "Yeni uygulama kaydet",
+ "apps.edit_conflict": "Özgün uygulama değişti veya silindi. Yeniden düzenleyin ya da yeni uygulama kaydedin.",
+ "apps.save_type_mismatch": "Bu sürüm özgün uygulamadan farklı türde olduğu için onun yerini alamaz. Bunun yerine yeni uygulama olarak kaydedin.",
+ "apps.type_local": "Yerel uygulama",
+ "apps.type_web": "Web uygulaması",
+ "apps.type_local_description": "Orkas masaüstünde çalışır; yapay zekâ, dosyalar, kitaplık ve bağlayıcıları kullanabilir, ancak web üzerinde yayınlanamaz.",
+ "apps.type_web_description": "Web üzerinde yayınlayın ve bağlantıyla erişin; veri toplama, sorgulama ve istatistik desteklenir, ancak Orkas masaüstü özellikleri kullanılamaz.",
+ "apps.delete_data_confirm": "\"{name}\", yerel kayıtları ve özel dosyaları silinsin mi? Veriler kurtarılamaz.",
+ "apps.delete_online_retained": "Yayınlanan uygulama ve çevrimiçi veriler korunur.",
+ "apps.migration_export": "Veri yapısı değişir. Silmeden önce yerel kayıtları dışa aktarın.",
+ "apps.migration_export_action": "Kayıtları dışa aktar",
+ "apps.migration_continue": "Devam",
+ "apps.migration_clear": "Tüm yerel kayıtlar silinip güncellensin mi? Çevrimiçi kayıtlar bağımsızdır.",
+ "apps.migration_retry": "Sil ve yeniden dene",
+ "chat.reference_scope_label": "Görev kapsamı",
+ "chat.reference_scope_all": "Tüm görevler",
+ "chat.reference_scope_global": "Genel (projesiz)",
+ "chat.reference_new_in_global": "Genel’de yeni görev",
+ "chat.reference_new_in_project": "“{name}” içinde yeni görev",
+ "chat.reference_search_all": "Tüm görevlerde ara",
+ "chat.reference_search_in": "“{name}” içindeki görevlerde ara",
+ "chat.reference_count_all": "Toplam {count} · en son etkin önce",
+ "chat.reference_count_found": "{count} bulundu · en son etkin önce",
+ "chat.reference_load_more": "Daha eski görevleri yükle ({count} kaldı)",
+ "chat.reference_no_match": "Eşleşen görev yok",
+ "chat.reference_no_match_hint": "Başka bir anahtar kelime deneyin veya soldan başka bir kapsam seçin.",
+ "chat.reference_scope_empty": "Burada henüz görev yok",
+ "chat.reference_scope_empty_hint": "Burada yeni bir görev başlatmak için yukarıdaki düğmeyi kullanın.",
+ "chat.reference_create_back": "Görev listesine dön",
+ "chat.reference_create_title": "Yeni görev nerede oluşturulsun?",
+ "chat.reference_create_desc": "Seçimden sonra referanslar eklenir. Hiçbir şey otomatik gönderilmez.",
+ "chat.reference_create_global_desc": "Hiçbir projeye ait değil",
+ "chat.reference_create_project_desc": "Bu projede yeni görev başlat",
+ "chat.reference_target_footer": "Seçiminiz, referanslar eklenmiş olarak görevin giriş alanını açar. Hiçbir şey otomatik gönderilmez.",
+ "project.todo.run_busy": "Bu görevin sohbeti hâlâ çalışıyor. Bittiğinde tekrar çalıştırın.",
+ "settings.cleanup.title": "Eski görevleri temizle",
+ "settings.cleanup.age": "Son etkinlik",
+ "settings.cleanup.scope": "Projelerin içindeki ve dışındaki tamamlanmış görevler. Sabitlenen, okunmamış görevler, taslaklar ve otomasyon geçmişi korunur.",
+ "settings.cleanup.days": "{n} günden önce",
+ "settings.cleanup.result": "Çöp kutusuna taşınan: {deleted}. Atlanan: {skipped}. Başarısız: {failed}.",
+ "settings.cleanup.progress": "Temizleniyor {done} / {total}",
+ "settings.cleanup.error": "Görevler yüklenemedi veya temizlenemedi. Yenileyip tekrar deneyin.",
+ "settings.cleanup.count": "{n} görev seçildi",
+ "settings.cleanup.empty": "Temizlenecek eski görev yok.",
+ "settings.cleanup.clean": "Temizle",
+ "settings.cleanup.confirm": "{n} görevi, eklerini ve gömülü sonuçlarını çöp kutusuna taşıyın. Aşağıdan geri yükleyebilirsiniz. Eşitleme açıksa silme diğer cihazlara da uygulanır. Disk alanı çöp kutusu boşaltıldığında açılır.",
+ "settings.cleanup.move": "Çöp kutusuna taşı ({n})",
+ "settings.cleanup.previous": "Önceki",
+ "settings.cleanup.next": "Sonraki",
+ "apps.commercial_required": "Web uygulamaları için Orkas’ın ticari sürümü gerekir. Devam etmek için indirin.",
+ "apps.commercial_download": "Ticari sürümü indir",
+ "apps.commercial_open_failed": "İndirme sayfası açılamadı. Lütfen tekrar deneyin."
}
diff --git a/src/renderer/locales/vi.json b/src/renderer/locales/vi.json
index 121d5ebd..740c6d7f 100644
--- a/src/renderer/locales/vi.json
+++ b/src/renderer/locales/vi.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "Tải xuống",
"web_assist.activity_visit": "Truy cập",
"web_assist.download_saved": "đã lưu vào tệp đính kèm",
- "web_assist.download_needs_grant": "cần quyền",
- "web_assist.download_blocked_type": "loại tệp không được phép",
- "web_assist.download_budget": "đã đạt giới hạn tải xuống của tác vụ",
"web_assist.download_failed": "thất bại",
"web_assist.download_unavailable": "Tệp không khả dụng. Hãy kiểm tra việc tải xuống đã hoàn tất và tệp chưa bị di chuyển hoặc xóa.",
- "web_assist.download_allow": "Cho phép trang này",
- "web_assist.download_prompt_title": "Cho phép tải xuống từ trang này?",
- "web_assist.download_prompt_description": "Tệp sẽ được lưu vào tệp đính kèm của tác vụ này. Sau khi cho phép, hãy trở lại trang và thử tải xuống lần nữa.",
- "web_assist.download_not_now": "Để sau",
- "web_assist.download_permission_failed": "Không thể cho phép trang này. Hãy thử lại.",
"web_assist.address_placeholder": "Tìm trên Bing hoặc nhập URL",
"web_assist.empty_title": "Duyệt web trong tác vụ này",
"web_assist.empty_hint": "Tìm trên Bing hoặc nhập URL ở trên.",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 ngày gần nhất",
"sidebar.bucket.older": "Cũ hơn",
"sidebar.projects": "Dự án",
- "sidebar.today_tasks": "Tác vụ hôm nay",
- "sidebar.today_empty": "Hôm nay chưa có tác vụ",
+ "sidebar.today_tasks": "Tác vụ gần đây",
+ "sidebar.today_empty": "Hai ngày qua chưa có tác vụ",
"sidebar.section_collapse": "Thu gọn {section}",
"sidebar.section_expand": "Mở rộng {section}",
"sidebar.project_create_title": "Dự án mới",
"sidebar.project_create_placeholder": "Nhập tên dự án",
"sidebar.project_conv_empty": "(không có tác vụ)",
- "sidebar.load_more_conversations": "Tải thêm",
+ "sidebar.load_more_conversations": "Hiển thị thêm",
"sidebar.connect_agent": "Kết nối tác tử",
"sidebar.connect_agent_sub": "Claude Code · Codex và nhiều hơn nữa",
"sidebar.settings": "Cài đặt",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "Đang tải…",
"new_chat.model_picker.aria_label": "Chọn mô hình",
"new_chat.model_picker.empty": "Không có mô hình khả dụng",
- "new_chat.model_picker.group_official": "Mô hình chính thức",
- "new_chat.model_picker.group_custom": "Mô hình do người dùng cấu hình",
+ "new_chat.model_picker.group_official": "Mô hình tích hợp Orkas",
+ "new_chat.model_picker.group_custom": "API Key của bạn",
"new_chat.model_picker.configure": "Cấu hình mô hình",
"new_chat.model_picker.switch_failed": "Không thể đổi mô hình. Hãy thử lại.",
"new_chat.model_picker.choose_version": "Chọn phiên bản mô hình cho {account}",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "Đã thêm vào {library}",
"conversation_info.file_add_to_library_failed": "Thêm vào thư viện thất bại: {reason}",
"conversation_info.file_add_to_chat_action": "Thêm vào trò chuyện tác vụ",
- "conversation_info.file_reveal_failed": "Không thể mở thư mục: {reason}",
+ "conversation_info.file_reveal_failed": "Không thể mở thư mục. Tệp có thể đã bị di chuyển hoặc xóa.",
"conversation_info.file_delete_confirm_title": "Xóa tệp",
"conversation_info.file_delete_confirm_msg": "Xóa \"{name}\"?",
"conversation_info.file_delete_failed": "Không thể xóa tệp: {reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "Gửi ngay",
"chat.queue_sending_now": "Đang gửi…",
"chat.queue_send_now_failed": "Không thể gửi tin nhắn trong hàng chờ này ngay: {msg}",
- "chat.multi_dispatch_serial": "Chạy lần lượt",
- "chat.multi_dispatch_parallel": "Chạy đồng thời",
- "chat.multi_dispatch_toggle_title": "Cách các tác tử được nhắc đến chạy cho tin nhắn này; nhấn để đổi",
"chat.task_waiting_on": "Đang chờ {name}",
"chat.task_status_orchestrating": "Đang điều phối",
"chat.task_dispatched": "Do Commander phân công",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "Xóa {count} tin nhắn đã chọn? Không thể hoàn tác.",
"chat.message_delete_failed": "Xóa thất bại: {reason}",
"chat.reference_target_title": "Tham chiếu {count} tin nhắn trong",
- "chat.reference_target_search": "Tìm tác vụ",
- "chat.reference_new_task": "Tác vụ mới",
- "chat.reference_existing_tasks": "Tác vụ hiện có",
- "chat.reference_area_commander": "Commander",
+ "chat.reference_new_task": "Tác vụ mới…",
"chat.reference_area_project": "Dự án",
- "chat.reference_recent_tasks_hint": "5 tác vụ gần nhất",
- "chat.reference_search_results_count": "{count} kết quả",
- "chat.reference_no_tasks": "Không có tác vụ phù hợp",
"chat.reference_unknown_task": "Tác vụ không xác định",
"chat.reference_from_task": "Trích từ “{title}” @{name}",
"chat.reference_bundle_title": "Từ “{title}”",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "Thêm dịch vụ ảnh",
"settings.models.add_video": "Thêm dịch vụ video",
"settings.models.add_tts": "Thêm dịch vụ giọng nói",
- "settings.models.order_hint": "Kéo hàng để đổi mức ưu tiên hoặc dùng nút mũi tên. Mô hình chính thức bị tắt sẽ được bỏ qua.",
+ "settings.models.order_hint": "Kéo hàng để đổi mức ưu tiên hoặc dùng nút mũi tên. Mô hình tích hợp bị tắt sẽ được bỏ qua.",
"settings.general.page_sub": "Điều chỉnh tùy chọn, quyền tác tử và cập nhật ứng dụng.",
"settings.general.preferences_title": "Tùy chọn",
"settings.general.agent_title": "Hành vi tác tử",
@@ -2031,7 +2014,7 @@
"project.review.approve": "Phê duyệt",
"project.review.request_changes": "Yêu cầu thay đổi",
"project.driver.toggle": "Tự động",
- "project.driver.toggle_hint": "AI tự động xử lý việc cần làm để bạn xem xét khi hoàn tất.",
+ "project.driver.toggle_hint": "AI tự động xử lý việc cần làm để bạn xem xét khi hoàn tất. Chỉ chạy trên thiết bị mà bạn bật tính năng này.",
"project.driver.enabled_toast": "Đã bật tự động tiến hành — định kỳ chọn một việc tồn đọng và thực hiện; tác vụ chuyển sang Đang thực hiện.",
"project.driver.disabled_toast": "Đã tắt tự động tiến hành.",
"project.recent_convs.view_all": "Xem tất cả ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "Thu gọn",
"skills.source_external": "Gói",
"skills.source_global": "Toàn cục",
- "web_assist.action_confirm.title": "Cho phép thao tác này trên trang?",
"chat.form.boolean_yes": "Có",
"chat.form.boolean_no": "Không",
"chat.form.invalid_number": "Nhập số hợp lệ",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "Tải lại",
"quality.operator.disabled": "Đã tắt trên thiết bị này.",
"quality.operator.ready": "Sẵn sàng: {count} quy tắc.",
- "quality.operator.invalid": "Không thể kiểm tra. Sửa operator-policy.json hoặc tắt kiểm tra tùy chỉnh rồi thử lại."
+ "quality.operator.invalid": "Không thể kiểm tra. Sửa operator-policy.json hoặc tắt kiểm tra tùy chỉnh rồi thử lại.",
+ "chat.app_nav_project_collaboration_target": "Thành viên dự án: {target}",
+ "new_chat.home.goal_title": "Đã có mục tiêu rõ ràng? Hãy giao cho Commander.",
+ "new_chat.home.goal_body": "Cho Commander biết bạn muốn hoàn thành điều gì, Commander sẽ điều phối đội ngũ AI để làm xong.",
+ "new_chat.home.goal_example": "Ví dụ: nghiên cứu 3 sản phẩm tương tự, so sánh tính năng và giá, rồi tổng hợp thành một bài thuyết trình.",
+ "new_chat.home.explore_title": "Chưa nghĩ ra? Hãy để Orkas hiểu bạn trước.",
+ "new_chat.home.explore_body": "Hãy chia sẻ về công việc, việc kinh doanh hay khó khăn của bạn; Orkas sẽ giúp bạn tìm mục tiêu phù hợp và tiếp tục thúc đẩy.",
+ "new_chat.home.explore_context": "Chia sẻ tài liệu bằng + hoặc {connect} để Orkas có thêm bối cảnh. Hãy bắt đầu từ những gì bạn sẵn sàng chia sẻ.",
+ "new_chat.home.explore_connect_link": "kết nối Feishu / DingTalk / email",
+ "new_chat.home.input_placeholder": "Mô tả điều bạn muốn hoàn thành, hoặc đính kèm tài liệu cần xử lý",
+ "new_chat.home.continue_label": "Tiếp tục đẩy công việc",
+ "new_chat.home.group.todos": "Việc cần làm quan trọng",
+ "new_chat.home.group.automations": "Tự động hóa cần xem",
+ "new_chat.home.group.tasks": "Tác vụ chờ bạn xử lý",
+ "new_chat.home.all_automations": "Tất cả tự động hóa →",
+ "new_chat.home.expand": "Hiện thêm {count} mục",
+ "new_chat.home.collapse": "Thu gọn",
+ "new_chat.home.view_all_todos": "Xem tất cả →",
+ "new_chat.home.source.project_todo": "{project} · Việc cần làm",
+ "new_chat.home.source.global_todo": "Việc cần làm toàn cục",
+ "new_chat.home.source.automation": "Tự động hóa",
+ "new_chat.home.source.project_task": "{project} · Tác vụ dự án",
+ "new_chat.home.source.global_task": "Tác vụ toàn cục",
+ "new_chat.home.result.completed": "Đã hoàn thành",
+ "new_chat.home.result.failed": "Thất bại",
+ "new_chat.home.result.waiting_input": "Đang chờ bạn",
+ "new_chat.home.result.stopped": "Đã dừng",
+ "new_chat.home.result.unknown": "Có kết quả mới",
+ "new_chat.home.action.view": "Xem",
+ "new_chat.home.action.reply": "Trả lời",
+ "new_chat.home.action.view_reason": "Xem nguyên nhân",
+ "new_chat.home.action.view_result": "Xem kết quả",
+ "new_chat.home.time.updated": "Cập nhật {time}",
+ "new_chat.home.untitled": "Tác vụ chưa đặt tên",
+ "artifact.failure_detail": "{action}: {detail}",
+ "apps.updated_toast": "Đã cập nhật {name}",
+ "apps.save_root_folder_required": "Chuyển HTML và các tài nguyên liên quan vào thư mục riêng, rồi lưu lại thành ứng dụng.",
+ "chat.reference_locate_title": "Đi tới tin nhắn gốc",
+ "chat.reference_locate_missing": "Tin nhắn gốc không còn tồn tại.",
+ "agents.cli_usage_title": "Hạn mức còn lại",
+ "agents.cli_usage_unavailable": "Không khả dụng. Kiểm tra đăng nhập CLI và kết nối.",
+ "agents.cli_usage_unsupported": "Phiên bản CLI hoặc cấu hình tùy chỉnh này không hỗ trợ tra cứu hạn mức.",
+ "agents.cli_usage_resets": "Đặt lại: {time}",
+ "agents.cli_usage_hours": "{count} giờ",
+ "agents.cli_usage_days": "{count} ngày",
+ "agents.cli_usage_window": "Chu kỳ sử dụng",
+ "memory.full_notice": "Bộ nhớ đã đầy. Trước khi lưu nội dung mới, AI sẽ gộp các mục hiện có.",
+ "memory.error_full": "Bộ nhớ đã đầy nên hiện chưa thể thêm mục này.",
+ "settings.recycle.clear": "Dọn sạch",
+ "settings.recycle.clear_title": "Dọn sạch thùng rác",
+ "settings.recycle.clear_confirm": "Xóa vĩnh viễn toàn bộ {count} bản ghi trong {source}? Sau đó không thể khôi phục.",
+ "settings.recycle.clearing": "Đang dọn {done}/{total}…",
+ "settings.recycle.cleared": "Đã dọn sạch thùng rác",
+ "settings.recycle.clear_failed": "Không thể dọn sạch toàn bộ thùng rác. Vui lòng thử lại.",
+ "settings.recycle.automation_count": "Tự động hóa · {count} tác vụ",
+ "project.todo.move": "Di chuyển",
+ "bash.permission.allow_folder_read": "Cho phép đọc thư mục này",
+ "bash.permission.folder_read_scope": "Trong tác vụ này, {agent} có thể đọc tệp trong {folder} mà không hỏi lại. Ghi, xóa và tệp bí mật vẫn cần xác nhận.",
+ "cli_upgrade.action": "Nâng cấp CLI",
+ "cli_upgrade.pending": "Đang nâng cấp…",
+ "cli_upgrade.success": "Nâng cấp thành công",
+ "cli_upgrade.failed": "Nâng cấp thất bại",
+ "cli_upgrade.named_action": "Nâng cấp {cli} CLI",
+ "web_assist.handback": "Trả quyền điều khiển cho AI",
+ "web_assist.permissions": "Đặt lại quyền trang web",
+ "web_assist.permission_title": "Quyền của trang web",
+ "web_assist.permission_allow": "Cho phép",
+ "web_assist.permission_deny": "Từ chối",
+ "web_assist.permission_failed": "Không thể lưu lựa chọn của bạn. Hãy thử lại.",
+ "apps.view_details": "Xem chi tiết",
+ "apps.no_local_code": "Không có mã ứng dụng trên thiết bị này",
+ "apps.publish_commercial": "Dùng phiên bản Orkas thương mại để xuất bản.",
+ "apps.update_original": "Cập nhật ứng dụng gốc",
+ "apps.save_new": "Lưu ứng dụng mới",
+ "apps.edit_conflict": "Ứng dụng gốc đã thay đổi hoặc bị xóa. Mở lại để sửa hoặc lưu ứng dụng mới.",
+ "apps.save_type_mismatch": "Phiên bản này khác loại với ứng dụng gốc nên không thể thay thế ứng dụng đó. Hãy lưu thành ứng dụng mới.",
+ "apps.type_local": "Ứng dụng cục bộ",
+ "apps.type_web": "Ứng dụng web",
+ "apps.type_local_description": "Chạy trong Orkas trên máy tính, có thể sử dụng AI, tệp, thư viện và trình kết nối; không thể xuất bản lên web.",
+ "apps.type_web_description": "Xuất bản lên web và truy cập qua liên kết, hỗ trợ thu thập, truy vấn và thống kê dữ liệu; không hỗ trợ các tính năng Orkas trên máy tính.",
+ "apps.delete_data_confirm": "Xóa \"{name}\", bản ghi cục bộ và tệp riêng? Không thể khôi phục dữ liệu.",
+ "apps.delete_online_retained": "Ứng dụng đã xuất bản và dữ liệu trực tuyến được giữ lại.",
+ "apps.migration_export": "Cấu trúc dữ liệu thay đổi. Xuất bản ghi cục bộ trước khi xóa.",
+ "apps.migration_export_action": "Xuất bản ghi",
+ "apps.migration_continue": "Tiếp tục",
+ "apps.migration_clear": "Xóa mọi bản ghi cục bộ và cập nhật? Bản ghi trực tuyến được lưu riêng.",
+ "apps.migration_retry": "Xóa và thử lại",
+ "chat.reference_scope_label": "Phạm vi tác vụ",
+ "chat.reference_scope_all": "Tất cả tác vụ",
+ "chat.reference_scope_global": "Chung (không thuộc dự án)",
+ "chat.reference_new_in_global": "Tác vụ mới không thuộc dự án",
+ "chat.reference_new_in_project": "Tác vụ mới trong “{name}”",
+ "chat.reference_search_all": "Tìm trong tất cả tác vụ",
+ "chat.reference_search_in": "Tìm tác vụ trong “{name}”",
+ "chat.reference_count_all": "Tổng {count} · mới hoạt động trước",
+ "chat.reference_count_found": "Tìm thấy {count} · mới hoạt động trước",
+ "chat.reference_load_more": "Tải tác vụ cũ hơn (còn {count})",
+ "chat.reference_no_match": "Không có tác vụ phù hợp",
+ "chat.reference_no_match_hint": "Hãy thử từ khóa khác hoặc chọn phạm vi khác ở bên trái.",
+ "chat.reference_scope_empty": "Chưa có tác vụ nào ở đây",
+ "chat.reference_scope_empty_hint": "Dùng nút phía trên để bắt đầu tác vụ mới tại đây.",
+ "chat.reference_create_back": "Quay lại danh sách tác vụ",
+ "chat.reference_create_title": "Tạo tác vụ mới ở đâu?",
+ "chat.reference_create_desc": "Tham chiếu sẽ được thêm sau khi bạn chọn. Không có gì được gửi tự động.",
+ "chat.reference_create_global_desc": "Không thuộc dự án nào",
+ "chat.reference_create_project_desc": "Bắt đầu tác vụ mới trong dự án này",
+ "chat.reference_target_footer": "Lựa chọn của bạn mở ô nhập của tác vụ với tham chiếu đã thêm. Không có gì được gửi tự động.",
+ "project.todo.run_busy": "Cuộc trò chuyện của tác vụ này vẫn đang chạy. Hãy chạy lại khi hoàn tất.",
+ "settings.cleanup.title": "Dọn dẹp tác vụ cũ",
+ "settings.cleanup.age": "Hoạt động gần nhất",
+ "settings.cleanup.scope": "Tác vụ đã hoàn thành trong và ngoài dự án. Giữ lại tác vụ đã ghim, chưa đọc, bản nháp và lịch sử tự động hóa.",
+ "settings.cleanup.days": "Hơn {n} ngày trước",
+ "settings.cleanup.result": "Đã chuyển vào thùng rác: {deleted}. Bỏ qua: {skipped}. Lỗi: {failed}.",
+ "settings.cleanup.progress": "Đang dọn dẹp {done} / {total}",
+ "settings.cleanup.error": "Không thể tải hoặc dọn dẹp tác vụ. Hãy làm mới và thử lại.",
+ "settings.cleanup.count": "Đã chọn {n} tác vụ",
+ "settings.cleanup.empty": "Không có tác vụ cũ để dọn dẹp.",
+ "settings.cleanup.clean": "Dọn dẹp",
+ "settings.cleanup.confirm": "Chuyển {n} tác vụ, tệp đính kèm và kết quả nhúng vào thùng rác. Có thể khôi phục bên dưới. Khi bật đồng bộ, thao tác xóa cũng áp dụng trên thiết bị khác. Dung lượng được giải phóng sau khi dọn sạch thùng rác.",
+ "settings.cleanup.move": "Chuyển vào thùng rác ({n})",
+ "settings.cleanup.previous": "Trước",
+ "settings.cleanup.next": "Tiếp",
+ "apps.commercial_required": "Ứng dụng web yêu cầu phiên bản thương mại của Orkas. Hãy tải xuống để tiếp tục.",
+ "apps.commercial_download": "Tải phiên bản thương mại",
+ "apps.commercial_open_failed": "Không thể mở trang tải xuống. Vui lòng thử lại."
}
diff --git a/src/renderer/locales/zh-tw.json b/src/renderer/locales/zh-tw.json
index b2526309..c6400f94 100644
--- a/src/renderer/locales/zh-tw.json
+++ b/src/renderer/locales/zh-tw.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "下載",
"web_assist.activity_visit": "存取",
"web_assist.download_saved": "已存入附件",
- "web_assist.download_needs_grant": "需要授權",
- "web_assist.download_blocked_type": "該檔案類型不允許",
- "web_assist.download_budget": "已達本任務下載上限",
"web_assist.download_failed": "失敗",
"web_assist.download_unavailable": "無法存取檔案,請確認下載已完成,且檔案未被移動或刪除。",
- "web_assist.download_allow": "允許此網站",
- "web_assist.download_prompt_title": "允許此網站下載檔案?",
- "web_assist.download_prompt_description": "檔案將儲存到目前任務的附件。允許後,請回到網頁重新點選下載。",
- "web_assist.download_not_now": "暫不允許",
- "web_assist.download_permission_failed": "授權失敗,請重試。",
"web_assist.address_placeholder": "搜尋 Bing 或輸入網址",
"web_assist.empty_title": "在目前任務中瀏覽網頁",
"web_assist.empty_hint": "在上方搜尋 Bing 或輸入網址。",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 天內",
"sidebar.bucket.older": "更早",
"sidebar.projects": "專案",
- "sidebar.today_tasks": "今日任務",
- "sidebar.today_empty": "今天還沒有任務",
+ "sidebar.today_tasks": "近期任務",
+ "sidebar.today_empty": "最近兩天沒有任務",
"sidebar.section_collapse": "收合{section}",
"sidebar.section_expand": "展開{section}",
"sidebar.project_create_title": "建立專案",
"sidebar.project_create_placeholder": "輸入專案名",
"sidebar.project_conv_empty": "(暫無任務)",
- "sidebar.load_more_conversations": "載入更多",
+ "sidebar.load_more_conversations": "顯示更多",
"sidebar.connect_agent": "接入智慧代理",
"sidebar.connect_agent_sub": "Claude Code · Codex 等",
"sidebar.settings": "設定",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "載入中…",
"new_chat.model_picker.aria_label": "選擇模型",
"new_chat.model_picker.empty": "暫無可用模型",
- "new_chat.model_picker.group_official": "官方模型",
- "new_chat.model_picker.group_custom": "使用者設定模型",
+ "new_chat.model_picker.group_official": "Orkas 內建模型",
+ "new_chat.model_picker.group_custom": "自備 API Key",
"new_chat.model_picker.configure": "設定模型",
"new_chat.model_picker.switch_failed": "切換模型失敗,請稍後重試。",
"new_chat.model_picker.choose_version": "選擇 {account} 的模型版本",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "已新增到{library}",
"conversation_info.file_add_to_library_failed": "新增到資料庫失敗:{reason}",
"conversation_info.file_add_to_chat_action": "新增到任務對話",
- "conversation_info.file_reveal_failed": "開啟資料夾失敗:{reason}",
+ "conversation_info.file_reveal_failed": "無法開啟所在資料夾,檔案可能已被移動或刪除。",
"conversation_info.file_delete_confirm_title": "刪除檔案",
"conversation_info.file_delete_confirm_msg": "刪除「{name}」?",
"conversation_info.file_delete_failed": "刪除檔案失敗:{reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "立即傳送",
"chat.queue_sending_now": "傳送中…",
"chat.queue_send_now_failed": "無法立即傳送這條待傳送訊息:{msg}",
- "chat.multi_dispatch_serial": "按序執行",
- "chat.multi_dispatch_parallel": "同時執行",
- "chat.multi_dispatch_toggle_title": "此訊息提及的多個智慧代理的執行方式,點選可切換",
"chat.task_waiting_on": "等待:{name}",
"chat.task_status_orchestrating": "編排中",
"chat.task_dispatched": "指揮官派發",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "刪除選中的 {count} 條訊息?此操作無法復原。",
"chat.message_delete_failed": "刪除失敗:{reason}",
"chat.reference_target_title": "引用 {count} 條訊息到",
- "chat.reference_target_search": "搜尋任務",
- "chat.reference_new_task": "新任務",
- "chat.reference_existing_tasks": "已有任務",
- "chat.reference_area_commander": "指揮官",
+ "chat.reference_new_task": "新增任務…",
"chat.reference_area_project": "專案",
- "chat.reference_recent_tasks_hint": "最近 5 個任務",
- "chat.reference_search_results_count": "{count} 個結果",
- "chat.reference_no_tasks": "沒有相符的任務",
"chat.reference_unknown_task": "未知任務",
"chat.reference_from_task": "引用自《{title}》@{name}",
"chat.reference_bundle_title": "來自《{title}》",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "新增圖片服務",
"settings.models.add_video": "新增影片服務",
"settings.models.add_tts": "新增語音服務",
- "settings.models.order_hint": "拖曳清單調整優先順序,也可使用上下箭頭。已停用的官方模型不參與輪轉。",
+ "settings.models.order_hint": "拖曳清單調整優先順序,也可使用上下箭頭。已停用的內建模型不參與輪轉。",
"settings.general.page_sub": "調整使用偏好、智慧代理權限與應用程式更新。",
"settings.general.preferences_title": "使用偏好",
"settings.general.agent_title": "智慧代理行為",
@@ -2031,7 +2014,7 @@
"project.review.approve": "核准",
"project.review.request_changes": "要求修改",
"project.driver.toggle": "自動推進",
- "project.driver.toggle_hint": "AI 自動處理待辦,完成後由你確認。",
+ "project.driver.toggle_hint": "AI 自動處理待辦,完成後由你確認。僅在開啟開關的裝置上執行。",
"project.driver.enabled_toast": "已開啟自動推進,會定期選取待辦任務並執行,任務將變為「進行中」。",
"project.driver.disabled_toast": "已關閉自動推進。",
"project.recent_convs.view_all": "查看全部 ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "收起",
"skills.source_external": "套件",
"skills.source_global": "全域",
- "web_assist.action_confirm.title": "允許在該頁面執行此操作嗎?",
"chat.form.boolean_yes": "是",
"chat.form.boolean_no": "否",
"chat.form.invalid_number": "請輸入有效數字",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "重新載入",
"quality.operator.disabled": "已在此裝置停用。",
"quality.operator.ready": "已就緒:{count} 條規則。",
- "quality.operator.invalid": "驗證無法使用。請修正 operator-policy.json 或停用自訂驗證後重試。"
+ "quality.operator.invalid": "驗證無法使用。請修正 operator-policy.json 或停用自訂驗證後重試。",
+ "chat.app_nav_project_collaboration_target": "專案成員:{target}",
+ "new_chat.home.goal_title": "有明確目標?交給指揮官。",
+ "new_chat.home.goal_body": "告訴指揮官你想完成什麼,它會調度 AI 團隊協作完成任務。",
+ "new_chat.home.goal_example": "例如:調研 3 款同類產品,比較功能與定價,整理成一份簡報。",
+ "new_chat.home.explore_title": "還沒想好?先讓 Orkas 了解你。",
+ "new_chat.home.explore_body": "聊聊你的工作、生意或困擾,讓 Orkas 幫你找到合適的目標,並持續推進。",
+ "new_chat.home.explore_context": "用 + 分享資料,或{connect},補充背景,讓 Orkas 更了解你。從你願意分享的內容開始。",
+ "new_chat.home.explore_connect_link": "連接飛書 / 釘釘 / 電子郵件",
+ "new_chat.home.input_placeholder": "說說你想完成什麼,或附上需要處理的資料",
+ "new_chat.home.continue_label": "接著把事情推進",
+ "new_chat.home.group.todos": "重要待辦",
+ "new_chat.home.group.automations": "自動化待處理",
+ "new_chat.home.group.tasks": "任務待你處理",
+ "new_chat.home.all_automations": "全部自動化 →",
+ "new_chat.home.expand": "展開其餘 {count} 項",
+ "new_chat.home.collapse": "收起",
+ "new_chat.home.view_all_todos": "查看全部 →",
+ "new_chat.home.source.project_todo": "{project} · 待辦",
+ "new_chat.home.source.global_todo": "全域待辦",
+ "new_chat.home.source.automation": "自動化",
+ "new_chat.home.source.project_task": "{project} · 專案任務",
+ "new_chat.home.source.global_task": "全域任務",
+ "new_chat.home.result.completed": "已完成",
+ "new_chat.home.result.failed": "失敗",
+ "new_chat.home.result.waiting_input": "等你輸入",
+ "new_chat.home.result.stopped": "已停止",
+ "new_chat.home.result.unknown": "有新結果",
+ "new_chat.home.action.view": "查看",
+ "new_chat.home.action.reply": "去回覆",
+ "new_chat.home.action.view_reason": "查看原因",
+ "new_chat.home.action.view_result": "查看結果",
+ "new_chat.home.time.updated": "{time}更新",
+ "new_chat.home.untitled": "未命名任務",
+ "artifact.failure_detail": "{action}:{detail}",
+ "apps.updated_toast": "已更新 {name}",
+ "apps.save_root_folder_required": "請將 HTML 和相關資源移入獨立資料夾,再儲存為應用程式。",
+ "chat.reference_locate_title": "定位到原始訊息",
+ "chat.reference_locate_missing": "原始訊息已不存在。",
+ "agents.cli_usage_title": "剩餘額度",
+ "agents.cli_usage_unavailable": "暫時無法取得。請檢查 CLI 登入和網路。",
+ "agents.cli_usage_unsupported": "目前 CLI 版本或自訂設定不支援額度查詢。",
+ "agents.cli_usage_resets": "重設時間:{time}",
+ "agents.cli_usage_hours": "{count} 小時",
+ "agents.cli_usage_days": "{count} 天",
+ "agents.cli_usage_window": "額度週期",
+ "memory.full_notice": "記憶已滿。AI 儲存新記憶前會先整理合併現有條目。",
+ "memory.error_full": "記憶已滿,暫時無法新增這則內容。",
+ "settings.recycle.clear": "清空",
+ "settings.recycle.clear_title": "清空回收站",
+ "settings.recycle.clear_confirm": "永久刪除「{source}」中的全部 {count} 筆記錄?刪除後無法還原。",
+ "settings.recycle.clearing": "正在清空 {done}/{total}…",
+ "settings.recycle.cleared": "回收站已清空",
+ "settings.recycle.clear_failed": "回收站未能全部清空,請重試。",
+ "settings.recycle.automation_count": "自動化 · {count} 個任務",
+ "project.todo.move": "移動",
+ "bash.permission.allow_folder_read": "允許讀取此資料夾",
+ "bash.permission.folder_read_scope": "本任務內,{agent} 讀取「{folder}」中的檔案不再詢問;寫入、刪除和金鑰類檔案仍會詢問。",
+ "cli_upgrade.action": "升級 CLI",
+ "cli_upgrade.pending": "升級中…",
+ "cli_upgrade.success": "升級成功",
+ "cli_upgrade.failed": "升級失敗",
+ "cli_upgrade.named_action": "升級 {cli} CLI",
+ "web_assist.handback": "交還給 AI",
+ "web_assist.permissions": "重設網站權限",
+ "web_assist.permission_title": "網站權限",
+ "web_assist.permission_allow": "允許",
+ "web_assist.permission_deny": "拒絕",
+ "web_assist.permission_failed": "未能儲存你的選擇,請重試。",
+ "apps.view_details": "查看詳細資訊",
+ "apps.no_local_code": "本機沒有應用程式碼",
+ "apps.publish_commercial": "請使用 Orkas 商業版發布應用。",
+ "apps.update_original": "更新原應用",
+ "apps.save_new": "儲存新應用",
+ "apps.edit_conflict": "原應用已變更或被刪除。請重新開啟編輯,或儲存新應用。",
+ "apps.save_type_mismatch": "此版本與原應用的類型不同,無法更新原應用。請改為儲存新應用。",
+ "apps.type_local": "本機應用",
+ "apps.type_web": "網頁應用",
+ "apps.type_local_description": "在 Orkas 桌面端執行,可使用 AI、檔案、知識庫和連接器等功能,不支援發布為網頁。",
+ "apps.type_web_description": "可發布為網頁,透過連結存取,支援資料收集、查詢和統計,不支援 Orkas 桌面端功能。",
+ "apps.delete_data_confirm": "刪除「{name}」及其本機記錄和私人檔案?資料無法復原。",
+ "apps.delete_online_retained": "已發佈應用及線上資料將保留。",
+ "apps.migration_export": "更新會改變資料結構,清理前可匯出本機記錄。",
+ "apps.migration_export_action": "匯出記錄",
+ "apps.migration_continue": "繼續",
+ "apps.migration_clear": "清空全部本機記錄並更新?線上記錄獨立儲存。",
+ "apps.migration_retry": "清空並重試",
+ "chat.reference_scope_label": "任務範圍",
+ "chat.reference_scope_all": "全部任務",
+ "chat.reference_scope_global": "全域(無專案)",
+ "chat.reference_new_in_global": "在全域新增任務",
+ "chat.reference_new_in_project": "在「{name}」中新增任務",
+ "chat.reference_search_all": "搜尋全部任務",
+ "chat.reference_search_in": "搜尋「{name}」中的任務",
+ "chat.reference_count_all": "共 {count} 個 · 最近活躍",
+ "chat.reference_count_found": "找到 {count} 個 · 最近活躍",
+ "chat.reference_load_more": "載入更早的任務(還有 {count} 個)",
+ "chat.reference_no_match": "找不到相符的任務",
+ "chat.reference_no_match_hint": "換個關鍵字,或選擇左側其他範圍。",
+ "chat.reference_scope_empty": "這裡還沒有任務",
+ "chat.reference_scope_empty_hint": "可使用上方入口在這裡新增任務。",
+ "chat.reference_create_back": "返回任務列表",
+ "chat.reference_create_title": "新任務要建在哪裡?",
+ "chat.reference_create_desc": "選定歸屬後帶入引用,不會自動傳送。",
+ "chat.reference_create_global_desc": "不歸屬任何專案",
+ "chat.reference_create_project_desc": "在此專案中新增任務",
+ "chat.reference_target_footer": "選擇後帶入目標任務的輸入區,不會自動傳送。",
+ "project.todo.run_busy": "這個待辦所在的對話仍在處理中,結束後再執行。",
+ "settings.cleanup.title": "清理歷史任務",
+ "settings.cleanup.age": "最後活動時間",
+ "settings.cleanup.scope": "清理專案內外的已完成任務。保留置頂、未讀、有草稿的任務和自動化執行記錄。",
+ "settings.cleanup.days": "{n} 天以前",
+ "settings.cleanup.result": "已移入資源回收筒 {deleted} 項,略過 {skipped} 項,失敗 {failed} 項。",
+ "settings.cleanup.progress": "正在清理 {done} / {total}",
+ "settings.cleanup.error": "未能完成任務載入或清理,請重新整理後重試。",
+ "settings.cleanup.count": "已選 {n} 項任務",
+ "settings.cleanup.empty": "暫無可清理的歷史任務。",
+ "settings.cleanup.clean": "清理",
+ "settings.cleanup.confirm": "將 {n} 項任務及其附件、內嵌產物移入資源回收筒,可在下方還原。啟用同步後,刪除也會同步至其他裝置。清空資源回收筒後才會釋放相應磁碟空間。",
+ "settings.cleanup.move": "移入資源回收筒({n})",
+ "settings.cleanup.previous": "上一頁",
+ "settings.cleanup.next": "下一頁",
+ "apps.commercial_required": "網頁應用需要 Orkas 商業版。下載商業版即可繼續。",
+ "apps.commercial_download": "下載商業版",
+ "apps.commercial_open_failed": "無法開啟下載頁面,請重試。"
}
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 0e1e6f3c..7c40d07e 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -168,16 +168,8 @@
"web_assist.activity_download": "下载",
"web_assist.activity_visit": "访问",
"web_assist.download_saved": "已存入附件",
- "web_assist.download_needs_grant": "需要授权",
- "web_assist.download_blocked_type": "该文件类型不允许",
- "web_assist.download_budget": "已达本任务下载上限",
"web_assist.download_failed": "失败",
"web_assist.download_unavailable": "无法访问文件,请确认下载已完成,且文件未被移动或删除。",
- "web_assist.download_allow": "允许此站点",
- "web_assist.download_prompt_title": "允许此站点下载文件?",
- "web_assist.download_prompt_description": "文件将保存到当前任务的附件。允许后,请回到网页重新点击下载。",
- "web_assist.download_not_now": "暂不允许",
- "web_assist.download_permission_failed": "授权失败,请重试。",
"web_assist.address_placeholder": "搜索 Bing 或输入网址",
"web_assist.empty_title": "在当前任务中浏览网页",
"web_assist.empty_hint": "在上方搜索 Bing 或输入网址。",
@@ -275,14 +267,14 @@
"sidebar.bucket.last30": "30 天内",
"sidebar.bucket.older": "更早",
"sidebar.projects": "项目",
- "sidebar.today_tasks": "当天任务",
- "sidebar.today_empty": "今天还没有任务",
+ "sidebar.today_tasks": "近期任务",
+ "sidebar.today_empty": "最近两天没有任务",
"sidebar.section_collapse": "折叠{section}",
"sidebar.section_expand": "展开{section}",
"sidebar.project_create_title": "新建项目",
"sidebar.project_create_placeholder": "输入项目名",
"sidebar.project_conv_empty": "(暂无任务)",
- "sidebar.load_more_conversations": "加载更多",
+ "sidebar.load_more_conversations": "显示更多",
"sidebar.connect_agent": "接入智能体",
"sidebar.connect_agent_sub": "Claude Code · Codex 等",
"sidebar.settings": "设置",
@@ -375,8 +367,8 @@
"new_chat.model_picker.loading": "加载中…",
"new_chat.model_picker.aria_label": "选择模型",
"new_chat.model_picker.empty": "暂无可用模型",
- "new_chat.model_picker.group_official": "官方模型",
- "new_chat.model_picker.group_custom": "用户配置模型",
+ "new_chat.model_picker.group_official": "Orkas 内置模型",
+ "new_chat.model_picker.group_custom": "自带 API Key",
"new_chat.model_picker.configure": "配置模型",
"new_chat.model_picker.switch_failed": "切换模型失败,请稍后重试。",
"new_chat.model_picker.choose_version": "为 {account} 选择模型版本",
@@ -551,7 +543,7 @@
"conversation_info.file_add_to_library_done": "已添加到{library}",
"conversation_info.file_add_to_library_failed": "添加到资料库失败:{reason}",
"conversation_info.file_add_to_chat_action": "添加到任务对话",
- "conversation_info.file_reveal_failed": "打开文件夹失败:{reason}",
+ "conversation_info.file_reveal_failed": "无法打开所在文件夹,文件可能已被移动或删除。",
"conversation_info.file_delete_confirm_title": "删除文件",
"conversation_info.file_delete_confirm_msg": "删除「{name}」?",
"conversation_info.file_delete_failed": "删除文件失败:{reason}",
@@ -746,9 +738,6 @@
"chat.queue_send_now": "立即发送",
"chat.queue_sending_now": "发送中…",
"chat.queue_send_now_failed": "无法立即发送这条待发送消息:{msg}",
- "chat.multi_dispatch_serial": "按序执行",
- "chat.multi_dispatch_parallel": "同时执行",
- "chat.multi_dispatch_toggle_title": "这条消息提及的多个 Agent 的执行方式,点击切换",
"chat.task_waiting_on": "等待:{name}",
"chat.task_status_orchestrating": "编排中",
"chat.task_dispatched": "指挥官派发",
@@ -783,14 +772,8 @@
"chat.message_delete_confirm": "删除选中的 {count} 条消息?此操作无法撤销。",
"chat.message_delete_failed": "删除失败:{reason}",
"chat.reference_target_title": "引用 {count} 条消息到",
- "chat.reference_target_search": "搜索任务",
- "chat.reference_new_task": "新任务",
- "chat.reference_existing_tasks": "已有任务",
- "chat.reference_area_commander": "指挥官",
+ "chat.reference_new_task": "新建任务…",
"chat.reference_area_project": "项目",
- "chat.reference_recent_tasks_hint": "最近 5 个任务",
- "chat.reference_search_results_count": "{count} 个结果",
- "chat.reference_no_tasks": "没有匹配的任务",
"chat.reference_unknown_task": "未知任务",
"chat.reference_from_task": "引用自《{title}》@{name}",
"chat.reference_bundle_title": "来自《{title}》",
@@ -1376,7 +1359,7 @@
"settings.models.add_image": "添加图片服务",
"settings.models.add_video": "添加视频服务",
"settings.models.add_tts": "添加语音服务",
- "settings.models.order_hint": "拖动列表调整优先级,也可使用上下箭头。已停用的官方模型不参与轮转。",
+ "settings.models.order_hint": "拖动列表调整优先级,也可使用上下箭头。已停用的 Orkas 内置模型不参与轮转。",
"settings.general.page_sub": "调整使用偏好与智能体权限。",
"settings.general.preferences_title": "使用偏好",
"settings.general.agent_title": "智能体行为",
@@ -2031,7 +2014,7 @@
"project.review.approve": "通过",
"project.review.request_changes": "打回",
"project.driver.toggle": "自动推进",
- "project.driver.toggle_hint": "AI 自动处理待办,完成后由你确认。",
+ "project.driver.toggle_hint": "AI 自动处理待办,完成后由你确认。仅在开启开关的设备上执行。",
"project.driver.enabled_toast": "已开启自动推进 —— 会定期从待办里挑任务自动推进,任务会进入「进行中」。",
"project.driver.disabled_toast": "已关闭自动推进。",
"project.recent_convs.view_all": "查看全部 ›",
@@ -2289,7 +2272,6 @@
"skills.global_group_collapse": "收起",
"skills.source_external": "包",
"skills.source_global": "全局",
- "web_assist.action_confirm.title": "允许在该页面执行此操作吗?",
"chat.form.boolean_yes": "是",
"chat.form.boolean_no": "否",
"chat.form.invalid_number": "请输入有效数字",
@@ -2532,5 +2514,129 @@
"quality.operator.reload": "重新加载",
"quality.operator.disabled": "本机已停用。",
"quality.operator.ready": "已加载 {count} 条规则。",
- "quality.operator.invalid": "校验不可用。请修复 operator-policy.json,或停用自定义校验后重试。"
+ "quality.operator.invalid": "校验不可用。请修复 operator-policy.json,或停用自定义校验后重试。",
+ "chat.app_nav_project_collaboration_target": "项目成员:{target}",
+ "new_chat.home.goal_title": "有明确目标?交给指挥官。",
+ "new_chat.home.goal_body": "告诉指挥官你想完成什么,它会调度 AI 团队协作完成任务。",
+ "new_chat.home.goal_example": "例如:调研 3 款同类产品,对比功能与定价,整理成一份演示文稿。",
+ "new_chat.home.explore_title": "还没想好?先让 Orkas 了解你。",
+ "new_chat.home.explore_body": "聊聊你的工作、生意或困扰,让 Orkas 帮你找到合适的目标,并持续推进。",
+ "new_chat.home.explore_context": "用 + 分享资料,或{connect},补充背景,让 Orkas 更了解你。从你愿意分享的内容开始。",
+ "new_chat.home.explore_connect_link": "连接飞书 / 钉钉 / 邮箱",
+ "new_chat.home.input_placeholder": "说说你想完成什么,或附上需要处理的资料",
+ "new_chat.home.continue_label": "接着把事情推进",
+ "new_chat.home.group.todos": "重要待办",
+ "new_chat.home.group.automations": "自动化待处理",
+ "new_chat.home.group.tasks": "任务待你处理",
+ "new_chat.home.all_automations": "全部自动化 →",
+ "new_chat.home.expand": "展开其余 {count} 条",
+ "new_chat.home.collapse": "收起",
+ "new_chat.home.view_all_todos": "查看全部 →",
+ "new_chat.home.source.project_todo": "{project} · 待办",
+ "new_chat.home.source.global_todo": "全局待办",
+ "new_chat.home.source.automation": "自动化",
+ "new_chat.home.source.project_task": "{project} · 项目任务",
+ "new_chat.home.source.global_task": "全局任务",
+ "new_chat.home.result.completed": "已完成",
+ "new_chat.home.result.failed": "失败",
+ "new_chat.home.result.waiting_input": "等你输入",
+ "new_chat.home.result.stopped": "已停止",
+ "new_chat.home.result.unknown": "有新结果",
+ "new_chat.home.action.view": "查看",
+ "new_chat.home.action.reply": "去回复",
+ "new_chat.home.action.view_reason": "查看原因",
+ "new_chat.home.action.view_result": "查看结果",
+ "new_chat.home.time.updated": "{time}更新",
+ "new_chat.home.untitled": "未命名任务",
+ "artifact.failure_detail": "{action}:{detail}",
+ "apps.updated_toast": "已更新 {name}",
+ "apps.save_root_folder_required": "请将 HTML 和相关资源移入独立文件夹,再保存为应用。",
+ "chat.reference_locate_title": "定位到原消息",
+ "chat.reference_locate_missing": "原消息已不存在。",
+ "agents.cli_usage_title": "剩余额度",
+ "agents.cli_usage_unavailable": "暂不可获取。请检查 CLI 登录和网络。",
+ "agents.cli_usage_unsupported": "当前 CLI 版本或自定义配置不支持额度查询。",
+ "agents.cli_usage_resets": "重置时间:{time}",
+ "agents.cli_usage_hours": "{count} 小时",
+ "agents.cli_usage_days": "{count} 天",
+ "agents.cli_usage_window": "额度周期",
+ "memory.full_notice": "记忆已满。AI 保存新记忆前会先整理合并现有条目。",
+ "memory.error_full": "记忆已满,暂时无法添加这条内容。",
+ "settings.recycle.clear": "清空",
+ "settings.recycle.clear_title": "清空回收站",
+ "settings.recycle.clear_confirm": "彻底删除“{source}”中的全部 {count} 条记录?删除后无法恢复。",
+ "settings.recycle.clearing": "正在清空 {done}/{total}…",
+ "settings.recycle.cleared": "回收站已清空",
+ "settings.recycle.clear_failed": "回收站未能全部清空,请重试。",
+ "settings.recycle.automation_count": "自动化 · {count} 个任务",
+ "project.todo.move": "移动",
+ "bash.permission.allow_folder_read": "允许读取此文件夹",
+ "bash.permission.folder_read_scope": "本任务内,{agent} 读取「{folder}」里的文件不再询问;写入、删除和密钥类文件仍会询问。",
+ "cli_upgrade.action": "升级 CLI",
+ "cli_upgrade.pending": "升级中…",
+ "cli_upgrade.success": "升级成功",
+ "cli_upgrade.failed": "升级失败",
+ "cli_upgrade.named_action": "升级 {cli} CLI",
+ "web_assist.handback": "交还给 AI",
+ "web_assist.permissions": "重置网站权限",
+ "web_assist.permission_title": "网站权限",
+ "web_assist.permission_allow": "允许",
+ "web_assist.permission_deny": "拒绝",
+ "web_assist.permission_failed": "未能保存你的选择,请重试。",
+ "apps.view_details": "查看详情",
+ "apps.no_local_code": "本机没有应用代码",
+ "apps.publish_commercial": "请使用 Orkas 商业版发布应用。",
+ "apps.update_original": "更新原应用",
+ "apps.save_new": "保存新应用",
+ "apps.edit_conflict": "原应用已变化或被删除。请重新打开编辑,或保存新应用。",
+ "apps.save_type_mismatch": "此版本与原应用的类型不同,无法更新原应用。请改为保存新应用。",
+ "apps.type_local": "本地应用",
+ "apps.type_web": "网页应用",
+ "apps.type_local_description": "在 Orkas 桌面端运行,可使用 AI、文件、知识库和连接器等能力,不支持发布为网页。",
+ "apps.type_web_description": "可发布为网页,通过链接访问,支持数据收集、查询和统计,不支持 Orkas 桌面端能力。",
+ "apps.delete_data_confirm": "删除「{name}」及其本地记录和私有文件?数据无法恢复。",
+ "apps.delete_online_retained": "已发布应用及线上数据将保留。",
+ "apps.migration_export": "更新会改变数据结构,清理前可导出本地记录。",
+ "apps.migration_export_action": "导出记录",
+ "apps.migration_continue": "继续",
+ "apps.migration_clear": "清空全部本地记录并更新?线上记录独立保存。",
+ "apps.migration_retry": "清空并重试",
+ "chat.reference_scope_label": "任务范围",
+ "chat.reference_scope_all": "全部任务",
+ "chat.reference_scope_global": "全局(无项目)",
+ "chat.reference_new_in_global": "在全局新建任务",
+ "chat.reference_new_in_project": "在「{name}」中新建任务",
+ "chat.reference_search_all": "搜索全部任务",
+ "chat.reference_search_in": "搜索「{name}」中的任务",
+ "chat.reference_count_all": "共 {count} 个 · 最近活跃",
+ "chat.reference_count_found": "找到 {count} 个 · 最近活跃",
+ "chat.reference_load_more": "加载更早的任务(还有 {count} 个)",
+ "chat.reference_no_match": "未找到匹配的任务",
+ "chat.reference_no_match_hint": "换个关键词,或选择左侧其他范围。",
+ "chat.reference_scope_empty": "这里还没有任务",
+ "chat.reference_scope_empty_hint": "可使用上方入口在这里新建任务。",
+ "chat.reference_create_back": "返回任务列表",
+ "chat.reference_create_title": "新任务建在哪里?",
+ "chat.reference_create_desc": "选定归属后带入引用,不会自动发送。",
+ "chat.reference_create_global_desc": "不归属任何项目",
+ "chat.reference_create_project_desc": "在此项目中新建任务",
+ "chat.reference_target_footer": "选择后带入目标任务的输入区,不会自动发送。",
+ "project.todo.run_busy": "这个待办所在的对话还在处理中,结束后再执行。",
+ "settings.cleanup.title": "清理历史任务",
+ "settings.cleanup.age": "最后活动时间",
+ "settings.cleanup.scope": "清理项目内外的已完成任务。保留置顶、未读、有草稿的任务和自动化运行记录。",
+ "settings.cleanup.days": "{n} 天以前",
+ "settings.cleanup.result": "已移入回收站 {deleted} 项,跳过 {skipped} 项,失败 {failed} 项。",
+ "settings.cleanup.progress": "正在清理 {done} / {total}",
+ "settings.cleanup.error": "未能完成任务加载或清理,请刷新后重试。",
+ "settings.cleanup.count": "已选 {n} 项任务",
+ "settings.cleanup.empty": "暂无可清理的历史任务。",
+ "settings.cleanup.clean": "清理",
+ "settings.cleanup.confirm": "将 {n} 项任务及其附件、内嵌产物移入回收站,可在下方恢复。开启同步后,删除也会同步到其他设备。清空回收站后才会释放相应磁盘空间。",
+ "settings.cleanup.move": "移入回收站({n})",
+ "settings.cleanup.previous": "上一页",
+ "settings.cleanup.next": "下一页",
+ "apps.commercial_required": "网页应用需要 Orkas 商业版。下载商业版即可继续。",
+ "apps.commercial_download": "下载商业版",
+ "apps.commercial_open_failed": "无法打开下载页面,请重试。"
}
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 9d998526..6f3b663b 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -1591,6 +1591,14 @@ function _renderAgentDetailMemory(agent, editing = false) {
if (canEditMemory) _wireAgentMemoryControls(section, agent);
}
+// A full store is refused with model-facing guidance; users get the
+// localized full message, which does not ask them to clean up entries.
+function _agentMemoryFailureText(res, fallback) {
+ const error = String((res && res.error) || '');
+ if (/^memory full/i.test(error)) return t('memory.error_full');
+ return error || fallback;
+}
+
async function _agentMemoryAdd(agent, text) {
if (_isCommanderAgent(agent)) {
return window.orkas.invoke('memory.add', { target: 'agent', agentId: _COMMANDER_AGENT_ID, content: text });
@@ -1625,7 +1633,7 @@ function _wireAgentMemoryControls(host, agent) {
try {
const res = await _agentMemoryAdd(agent, text);
if (!res || res.ok === false) {
- uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
+ uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));
return;
}
await loadAgents(true);
@@ -1649,7 +1657,7 @@ function _wireAgentMemoryControls(host, agent) {
try {
const res = await _agentMemoryUpdate(agent, oldText, text);
if (!res || res.ok === false) {
- uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
+ uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));
return;
}
await loadAgents(true);
@@ -1676,7 +1684,7 @@ function _wireAgentMemoryControls(host, agent) {
try {
const res = await _agentMemoryRemove(agent, text);
if (!res || res.ok === false) {
- uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
+ uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));
return;
}
await loadAgents(true);
@@ -1732,6 +1740,7 @@ function _renderAgentDetail(agent, editing, { refreshCliOptions = false } = {})
// it duplicated information the dropdown already exposes.
_renderAgentDetailRuntime(agent);
_renderAgentDetailCliSettings(agent, { refresh: refreshCliOptions });
+ void renderCliAccountUsage(agent);
_renderAgentDetailProjectDir(agent);
const localizedDesc = _agentSummary(agent, lang);
descEl.textContent = localizedDesc;
@@ -1936,6 +1945,8 @@ async function _renderAgentDetailRuntime(agent) {
const section = document.getElementById('agents-detail-runtime-section');
const slot = document.getElementById('agents-detail-runtime');
if (!slot || !section) return;
+ const previousRuntimeKey = slot.dataset.runtimeKey;
+ const previousUpgradeControl = slot.querySelector('.local-cli-upgrade-control');
slot.innerHTML = '';
// In-process agents: section stays hidden. No selector, no
@@ -2023,6 +2034,10 @@ async function _renderAgentDetailRuntime(agent) {
const mount = document.createElement('div');
mount.className = 'ai-select agents-detail-runtime-select';
slot.appendChild(mount);
+ if (typeof window.createLocalCliUpgradeControl === 'function') {
+ slot.appendChild(previousRuntimeKey === runtimeKey && previousUpgradeControl
+ ? previousUpgradeControl : window.createLocalCliUpgradeControl({ type: currentType }));
+ }
_aiSelectMount(mount, {
options, value: `cli:${currentType}`,
onChange: async (next) => {
@@ -2318,10 +2333,11 @@ async function _renderAgentDetailCliSettings(agent, { refresh = false, cacheOnly
? t('agents.cli_settings_partial')
: t('agents.cli_settings_unavailable'),
)}</div>`;
- // A listed row already names its resolution in the picker, so the note is
- // left for a saved override the catalog does not list at all.
+ // Claude Code shows model information in the picker only. Other CLIs keep
+ // the note for a saved override the catalog does not list at all.
const selectedModelIsListed = models.some(model => String(model?.id || '') === currentModel);
- const observedModelNote = observedModelForCurrentSelection
+ const observedModelNote = runtime.cli !== 'claude'
+ && observedModelForCurrentSelection
&& !selectedModelIsListed
&& observedModelForCurrentSelection !== currentModel
? `<div class="agents-detail-cli-note agents-detail-cli-model-observed">${escapeHtml(
@@ -4797,3 +4813,20 @@ function bindAgentPickers() {
}
}
+
+window.addEventListener('local-cli-upgraded', async (event) => {
+ _agentCliRuntimeOptionsCache.clear();
+ _agentCliRuntimeSnapshots.clear();
+ const id = _selectedAgent?.id;
+ if (!id) return;
+ try {
+ const response = await window.orkas.invoke('agents.get', { agent_id: id });
+ const agent = response?.agent;
+ if (_selectedAgent?.id !== id || agent?.runtime?.cli !== event.detail?.type) return;
+ await loadLocalCliEntries({ force: true });
+ if (_selectedAgent?.id !== id) return;
+ void _renderAgentDetailRuntime(agent);
+ void _renderAgentDetailCliSettings(agent, { refresh: true });
+ void renderCliAccountUsage(agent, { force: true });
+ } catch (_) { /* next detail entry revalidates independently */ }
+});
diff --git a/src/renderer/modules/artifact-security.js b/src/renderer/modules/artifact-security.js
index da2fd08b..8b538885 100644
--- a/src/renderer/modules/artifact-security.js
+++ b/src/renderer/modules/artifact-security.js
@@ -31,6 +31,13 @@
let source;
try { source = frame.contentWindow; } catch (_) { return false; }
if (!source || event.source !== source) return false;
+ try {
+ const expected = new URL(frame.src);
+ // Node's URL treats custom schemes as opaque; Electron registers chat-app
+ // as standard and serializes its origin as scheme + host.
+ if (expected.protocol !== 'chat-app:' || !expected.host || expected.username || expected.password
+ || event.origin !== `chat-app://${expected.host}`) return false;
+ } catch (_) { return false; }
const data = event.data;
return !!data && typeof data === 'object' && data.__orkasArtifact === true;
}
diff --git a/src/renderer/modules/auto-title.js b/src/renderer/modules/auto-title.js
index aa1beda7..ed057bc8 100644
--- a/src/renderer/modules/auto-title.js
+++ b/src/renderer/modules/auto-title.js
@@ -20,7 +20,10 @@ const _AUTO_TITLE_ZH_FILLER = /^(帮我看一下|可不可以|帮我看下|帮
const _AUTO_TITLE_EN_FILLER = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;
// Half-width display units, not characters: counting characters cut a CJK
// title at twice the rendered width of a Latin one. Mirrors TITLE_MAX_UNITS.
-const _AUTO_TITLE_MAX_UNITS = 50;
+const _AUTO_TITLE_MAX_UNITS = 100;
+// Mirrors CONVERSATION_TITLE_MAX_UNITS: the stored-title cap for conversations,
+// wide enough for a full auto title plus its ellipsis.
+const _CONVERSATION_TITLE_MAX_UNITS = _AUTO_TITLE_MAX_UNITS + 1;
function _autoTitleGraphemes(text) {
try {
@@ -91,6 +94,7 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {
_AUTO_TITLE_ZH_FILLER,
_AUTO_TITLE_EN_FILLER,
_AUTO_TITLE_MAX_UNITS,
+ _CONVERSATION_TITLE_MAX_UNITS,
_truncateTitleToWidth,
};
}
diff --git a/src/renderer/modules/auto.js b/src/renderer/modules/auto.js
index ca98af3d..33cf752c 100644
--- a/src/renderer/modules/auto.js
+++ b/src/renderer/modules/auto.js
@@ -88,23 +88,6 @@ function _autoResultFailure(error, fallback, fallbackType = 'operation') {
};
}
-function _autoAttachmentPayload(files, source) {
- const list = Array.from(files || []);
- let totalBytes = 0;
- for (const file of list) {
- const bytes = Number((file && (file.size || file.bytes)) || 0);
- if (Number.isFinite(bytes) && bytes > 0) totalBytes += bytes;
- }
- const sourceType = ['drop', 'internal_drop', 'paste', 'picker'].includes(source)
- ? source
- : 'unknown';
- return {
- source: sourceType,
- file_count: list.length,
- total_bytes: totalBytes,
- mode: _autoEditingTaskId ? 'edit' : 'create',
- };
-}
const AUTO_ATTACH_ACCEPT = (typeof CHAT_ATTACH_ACCEPT !== 'undefined' && Array.isArray(CHAT_ATTACH_ACCEPT))
? CHAT_ATTACH_ACCEPT
@@ -818,28 +801,9 @@ function _closeAutoRowMenu(restoreFocus = false) {
if (restoreFocus && anchor && anchor.isConnected) anchor.focus();
}
-function _autoCreateActionLogger(action) {
- let done = false;
- return (result, errorCode = '') => {
- if (done) return;
- done = true;
- const payload = {
- result,
- action,
- };
- if (result !== 'success') {
- const failure = _autoResultFailure(errorCode, 'action_failed', 'ipc');
- payload.error_code = failure.error_code;
- payload.error_type = failure.error_type;
- }
- if (result === 'failure') {
- _autoLogFailure('auto_task_action', {
- action,
- error_type: payload.error_type,
- error_code: payload.error_code,
- });
- }
- };
+function _autoLogActionFailure(action, errorCode) {
+ const failure = _autoResultFailure(errorCode, 'action_failed', 'ipc');
+ _autoLogFailure('auto_task_action', { action, ...failure });
}
function _openAutoRowMenu(anchorBtn, task, opts) {
@@ -881,37 +845,33 @@ function _openAutoRowMenu(anchorBtn, task, opts) {
}
} else if (action === 'toggle-enabled') {
const next = !task.enabled;
- const logResult = _autoCreateActionLogger('toggle');
try {
const res = await window.orkas.invoke('autoTasks.setEnabled', { taskId: task.id, enabled: next });
if (res && res.ok && res.task) {
- logResult('success');
Object.assign(task, res.task);
const row = document.querySelector(`.auto-row[data-task-id="${task.id}"]`);
if (row) row.classList.toggle('is-disabled', !next);
if (opts && typeof opts.afterChange === 'function') opts.afterChange();
} else {
- logResult('failure', 'update_failed');
+ _autoLogActionFailure('toggle', 'update_failed');
}
} catch (err) {
- logResult('failure', 'invoke_failed');
+ _autoLogActionFailure('toggle', 'invoke_failed');
_autoLog.warn('toggle failed', err);
}
} else if (action === 'edit') {
if (opts && typeof opts.onEdit === 'function') opts.onEdit(task);
} else if (action === 'delete') {
if (!(await uiConfirm(t('auto.delete_confirm')))) return;
- const logResult = _autoCreateActionLogger('delete');
try {
const res = await window.orkas.invoke('autoTasks.delete', { taskId: task.id });
if (res && res.deleted) {
- logResult('success');
if (opts && typeof opts.afterChange === 'function') opts.afterChange();
} else {
- logResult('failure', 'delete_failed');
+ _autoLogActionFailure('delete', 'delete_failed');
}
} catch (err) {
- logResult('failure', 'invoke_failed');
+ _autoLogActionFailure('delete', 'invoke_failed');
await uiAlert(t('auto.delete_failed', { reason: (err && err.message) || err }));
}
}
@@ -986,6 +946,7 @@ function _autoRenderList() {
const onEdit = (task) => openAutoTaskDialog({ task });
const afterChange = () => loadAutoList(true);
const projects = typeof _projectsCache !== 'undefined' && Array.isArray(_projectsCache) ? _projectsCache : [];
+ const projectsById = new Map(projects.map((project) => [project.project_id, project]));
const groups = _autoGroupTasks(_autoTasks, projects);
if (!groups.some((group) => group.projectId === _autoActiveScope)) _autoActiveScope = groups[0].projectId;
const switcher = document.createElement('nav');
@@ -998,7 +959,9 @@ function _autoRenderList() {
chip.className = 'todo-scope-chip';
chip.dataset.projectId = group.projectId;
chip.setAttribute('aria-pressed', String(group.projectId === _autoActiveScope));
- chip.innerHTML = _autoUiIcon('folder', 'todo-scope-chip-icon')
+ const iconName = typeof window.projectIconName === 'function'
+ ? window.projectIconName(projectsById.get(group.projectId)) : 'folder';
+ chip.innerHTML = _autoUiIcon(iconName, 'todo-scope-chip-icon')
+ `<span class="todo-scope-chip-name">${escapeHtml(name)}</span>`
+ `<span class="todo-scope-chip-count">${group.tasks.length}</span>`;
chip.addEventListener('click', () => {
@@ -1376,6 +1339,7 @@ function _autoDatePickerMount(el, config = {}) {
const edge = 8;
const width = Math.min(296, Math.max(240, window.innerWidth - edge * 2));
const left = Math.max(edge, Math.min(rect.left, window.innerWidth - width - edge));
+ popover.dataset.uiOverlay = '';
popover.style.position = 'fixed';
popover.style.left = `${left}px`;
popover.style.width = `${width}px`;
@@ -1842,17 +1806,15 @@ async function _autoPrepareUploadFiles(fileList) {
return { prepared, rejected };
}
-async function _autoUploadFiles(files, source = 'drop') {
+async function _autoUploadFiles(files) {
const list = Array.from(files || []);
if (!list.length) return;
- const payload = _autoAttachmentPayload(list, source);
const taskId = await _ensureAutoDraftId();
if (!taskId) {
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
return;
}
const { prepared, rejected } = await _autoPrepareUploadFiles(list);
- const rejectedCount = rejected.length;
if (!prepared.length) {
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
return;
@@ -1877,7 +1839,6 @@ async function _autoUploadFiles(files, source = 'drop') {
}
_autoSetAttachmentItems(current);
- let uploadFailed = 0;
await Promise.all(placeholders.map(async (ph) => {
try {
const dataBase64 = _arrayBufferToBase64(ph.buf);
@@ -1896,7 +1857,7 @@ async function _autoUploadFiles(files, source = 'drop') {
});
} else {
_autoReplaceAttachmentByTempId(ph.tempId, null);
- uploadFailed += 1;
+
rejected.push(t('chat.attach_upload_fail', {
name: ph.file.name,
reason: t('chat.attach_upload_generic_fail'),
@@ -1904,7 +1865,7 @@ async function _autoUploadFiles(files, source = 'drop') {
}
} catch (err) {
_autoReplaceAttachmentByTempId(ph.tempId, null);
- uploadFailed += 1;
+
_autoLog.warn('upload failed', err);
rejected.push(t('chat.attach_upload_fail', {
name: ph.file.name,
@@ -1912,9 +1873,6 @@ async function _autoUploadFiles(files, source = 'drop') {
}));
}
}));
- const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
- const failedCount = rejected.length;
- const result = failedCount ? (uploadedCount ? 'partial_failure' : 'failure') : 'success';
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
}
@@ -1948,19 +1906,17 @@ function _bindAutoDropAttach() {
? _chatAttachInternalDragItems(e.dataTransfer)
: [];
if (internalFiles.length) {
- _autoImportPaths(internalFiles, 'internal_drop');
+ _autoImportPaths(internalFiles);
return;
}
- _autoUploadFiles(e.dataTransfer.files, 'drop');
+ _autoUploadFiles(e.dataTransfer.files);
});
area.dataset.autoDropBound = '1';
}
-async function _autoImportPaths(entries, source = 'internal_drop') {
+async function _autoImportPaths(entries) {
const files = Array.isArray(entries) ? entries.filter((it) => it && it.path) : [];
if (!files.length) return;
- const startedAt = performance.now();
- const payload = _autoAttachmentPayload(files, source);
const taskId = await _ensureAutoDraftId();
if (!taskId) {
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
@@ -1988,10 +1944,8 @@ async function _autoImportPaths(entries, source = 'internal_drop') {
});
placeholders.push({ tempId, path: item.path, name: displayName });
}
- const rejectedCount = rejected.length;
_autoSetAttachmentItems(current);
- let uploadFailed = 0;
await Promise.all(placeholders.map(async (ph) => {
try {
const data = await window.orkas.invoke('autoTasks.attachments.import', {
@@ -2011,20 +1965,17 @@ async function _autoImportPaths(entries, source = 'internal_drop') {
});
} catch (err) {
_autoReplaceAttachmentByTempId(ph.tempId, null);
- uploadFailed += 1;
+
rejected.push(t('chat.attach_upload_fail', {
name: ph.name,
reason: (err && err.message) || t('chat.attach_upload_generic_fail'),
}));
}
}));
- const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
- const result = rejected.length ? (uploadedCount ? 'partial_failure' : 'failure') : 'success';
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
}
async function _autoAttachLibraryFile(ref) {
- const startedAt = performance.now();
const scope = ref && ref.scope === 'project' ? 'project' : 'global';
const rel = String(ref && ref.rel || '');
const projectId = _autoValidProjectId(ref && ref.projectId || '');
@@ -2085,8 +2036,6 @@ async function _autoAttachLibraryFile(ref) {
}
async function _autoPickAndUploadFiles() {
- const startedAt = performance.now();
- const payload = _autoAttachmentPayload([], 'picker');
const taskId = await _ensureAutoDraftId();
if (!taskId) {
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
@@ -2108,13 +2057,6 @@ async function _autoPickAndUploadFiles() {
}
const names = Array.isArray(data && data.items) ? data.items : [];
const failed = Array.isArray(data && data.failed) ? data.failed : [];
- const fileCount = names.length + failed.length;
- const result = fileCount === 0
- ? 'failure'
- : (failed.length ? (names.length ? 'partial_failure' : 'failure') : 'success');
- const failure = result === 'success'
- ? null
- : _autoResultFailure(failed[0] && failed[0].error, 'upload_failed', 'operation');
for (const name of names) {
_autoPushReadyAttachment(name, { displayName: name });
}
@@ -2660,6 +2602,8 @@ if (typeof window !== 'undefined') {
await loadAutoList(true);
const task = _autoTasks.find((candidate) => candidate && candidate.id === id);
if (!task) return false;
+ _autoActiveScope = task.project_id || '';
+ _autoRenderList();
openAutoTaskDialog({ task });
return true;
};
@@ -2670,7 +2614,7 @@ if (typeof window !== 'undefined') {
const addBtn = document.getElementById('auto-add-btn');
if (addBtn && addBtn.dataset.bound !== '1') {
addBtn.dataset.bound = '1';
- addBtn.addEventListener('click', () => openAutoTaskDialog({}));
+ addBtn.addEventListener('click', () => openAutoTaskDialog({ initialProjectId: _autoActiveScope || '' }));
}
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bindAutoAddButton, { once: true });
diff --git a/src/renderer/modules/bash_permission.js b/src/renderer/modules/bash_permission.js
index 07815f6f..9fda323d 100644
--- a/src/renderer/modules/bash_permission.js
+++ b/src/renderer/modules/bash_permission.js
@@ -162,6 +162,7 @@ function _showBashPermissionModeDialog({
requestId,
allowRun = true,
allowRunLabel = t('bash.permission.allow_run'),
+ primaryChoice = 'allow_once',
showModeControl = true,
modes = _bashPermissionModeOptions(),
modeValidator = _bashIsMode,
@@ -201,8 +202,9 @@ function _showBashPermissionModeDialog({
${caretHtml}
</button>
</div>` : '';
+ const runIsPrimary = allowRun && primaryChoice === 'allow_run';
const allowRunHtml = allowRun
- ? `<button class="btn" data-act="choice" data-id="allow_run">${_bashEscapeHtml(allowRunLabel)}</button>`
+ ? `<button class="btn${runIsPrimary ? ' btn-primary' : ''}" data-act="choice" data-id="allow_run">${_bashEscapeHtml(allowRunLabel)}</button>`
: '';
overlay.innerHTML = `
@@ -215,7 +217,7 @@ function _showBashPermissionModeDialog({
${modeControlHtml}
<span class="bash-permission-actions-spacer" aria-hidden="true"></span>
<button class="btn" data-act="cancel">${_bashEscapeHtml(t('bash.permission.deny'))}</button>
- <button class="btn btn-primary" data-act="choice" data-id="allow_once">${_bashEscapeHtml(t('bash.permission.allow_once'))}</button>
+ <button class="btn${runIsPrimary ? '' : ' btn-primary'}" data-act="choice" data-id="allow_once">${_bashEscapeHtml(t('bash.permission.allow_once'))}</button>
${allowRunHtml}
</div>
${showModeControl ? `<div class="bash-permission-mode-hint">${_bashEscapeHtml(modeHint)}</div>` : ''}
@@ -334,38 +336,14 @@ function _showBashPermissionModeDialog({
btn.addEventListener('click', () => finish(btn.dataset.id || 'deny'));
});
const cancelBtn = overlay.querySelector('[data-act="cancel"]');
- const allowOnceBtn = overlay.querySelector('[data-id="allow_once"]');
+ const primaryBtn = overlay.querySelector(`[data-id="${runIsPrimary ? 'allow_run' : 'allow_once'}"]`);
cancelBtn.addEventListener('click', () => finish('deny'));
document.addEventListener('keydown', onKey, true);
document.addEventListener('click', onDocClick, true);
- setTimeout(() => allowOnceBtn?.focus(), 0);
+ setTimeout(() => primaryBtn?.focus(), 0);
});
}
-function _webAssistDecision(decision) {
- if (decision === 'allow_run') return 'run';
- return decision === 'allow_once' ? 'once' : 'deny';
-}
-
-function _webAssistActionMessage(info) {
- const site = String(info.page_origin || '').trim();
- const title = String(info.page_title || '').trim();
- const control = String(info.control_label || '').trim();
- return [
- _bashT(info.reason === 'high_impact_action'
- ? 'web_assist.action_confirm.high_impact_message'
- : 'web_assist.action_confirm.submission_message',
- 'The Agent wants to activate a control on the page you can see.'),
- '',
- ...(title ? [`${_bashT('web_assist.action_confirm.page', 'Page')}: ${title}`] : []),
- `${_bashT('web_assist.action_confirm.site', 'Site')}: ${site || _bashT('web_assist.action_confirm.site_unknown', 'Unknown site')}`,
- `${_bashT('web_assist.action_confirm.control', 'Control')}: ${control}`,
- '',
- _bashT('web_assist.action_confirm.note',
- 'Approving covers this control on this site in this browser tab. A different page, control or label asks again.'),
- ].join('\n');
-}
-
function _bashKeyFactsText(info) {
const facts = Array.isArray(info.key_facts) ? info.key_facts.slice(0, 6) : [];
const lines = [];
@@ -392,7 +370,6 @@ async function _showBashPermissionDialog(info) {
return;
}
const isConnector = info._permission_kind === 'connector';
- const isWebAssist = info._permission_kind === 'web-assist';
const agent = _bashAgentLabel(info);
const reasonsText = [
_bashReasonText(info.reasons),
@@ -401,9 +378,9 @@ async function _showBashPermissionDialog(info) {
const command = String(info.command || '');
const operation = String(info.operation || '').trim();
const subject = String(info.subject || '').trim();
- const isAction = isConnector || isWebAssist || !!(operation || subject);
+ const isAction = isConnector || !!(operation || subject);
const keyFactsText = !isAction ? _bashKeyFactsText(info) : '';
- const baseMessage = isWebAssist ? _webAssistActionMessage(info) : isConnector ? _connectorActionMessage(info) : isAction
+ const baseMessage = isConnector ? _connectorActionMessage(info) : isAction
? t('bash.permission.action_message', {
agent,
operation: operation || t('bash.permission.action_fallback'),
@@ -417,21 +394,25 @@ async function _showBashPermissionDialog(info) {
_bashPermTaskApproved.delete(info.request_id);
return;
}
+ // A read sensitive only for its personal location (Desktop, Documents,
+ // Downloads) is granted per folder: 2026-09-21 a user approved 58 images in
+ // two Desktop folders one by one.
+ const readFolder = !isConnector && info.can_allow_run === true
+ && typeof info.read_folder === 'string' ? info.read_folder.trim() : '';
// Needs the resolved mode: the same step is worth flagging in every mode,
// but only an all_files_auto user is owed an explanation for being asked.
const message = [
baseMessage,
_bashIrreversibleText(info, currentMode),
externalMutationText,
- ...(!isConnector && !isWebAssist && info.can_allow_run === true ? [t('bash.permission.grant_scope')] : []),
+ ...(!isConnector && info.can_allow_run === true
+ ? [readFolder ? t('bash.permission.folder_read_scope', { agent, folder: readFolder }) : t('bash.permission.grant_scope')]
+ : []),
].filter(Boolean).join('\n\n');
- const isSensitiveApproval = isConnector || isWebAssist || (Array.isArray(info.reasons)
+ const isSensitiveApproval = isConnector || (Array.isArray(info.reasons)
&& info.reasons.some((reason) => _BASH_PERMISSION_RISK_CATEGORIES.includes(reason)));
- // A page grant is safe to offer: the host binds it to this tab, origin and
- // control, so repeating the same approved step is the case it exists for.
- // A connector grant stays on the host's own terms.
- const canAllowRun = isWebAssist ? true
- : isConnector ? info.can_allow_run === true
+ // Connector grants stay on the host's own terms.
+ const canAllowRun = isConnector ? info.can_allow_run === true
: info.unresolved_paths !== true && (!isSensitiveApproval || info.can_allow_run === true);
// An earlier queued permission can switch the account to Trusted while this
// connector waits. Its host gate already checked availability/prohibitions.
@@ -440,8 +421,7 @@ async function _showBashPermissionDialog(info) {
result = isConnector && currentMode === 'all_files_auto'
? { choice: 'allow_once', mode: currentMode }
: await _showBashPermissionModeDialog({
- title: t(isWebAssist ? 'web_assist.action_confirm.title'
- : isAction ? 'bash.permission.action_title' : 'bash.permission.title'),
+ title: t(isAction ? 'bash.permission.action_title' : 'bash.permission.title'),
message,
context: info,
...(isConnector ? {
@@ -453,6 +433,7 @@ async function _showBashPermissionDialog(info) {
requestId,
allowRun: canAllowRun,
...(isConnector && info.usage_scope === true ? { allowRunLabel: t('bash.permission.allow_usage') } : {}),
+ ...(readFolder ? { allowRunLabel: t('bash.permission.allow_folder_read'), primaryChoice: 'allow_run' } : {}),
showModeControl: true,
});
} catch (err) {
@@ -495,11 +476,8 @@ async function _showBashPermissionDialog(info) {
try {
await window.orkas.invoke(
- isWebAssist ? 'webAssist.actionConfirmResponse'
- : isConnector ? 'connectors.action_confirm_response' : 'bash.permission_response',
- isWebAssist
- ? { request_id: info.request_id, decision: _webAssistDecision(decision) }
- : isConnector
+ isConnector ? 'connectors.action_confirm_response' : 'bash.permission_response',
+ isConnector
? { request_id: info.request_id, approved: decision !== 'deny', ...(decision === 'allow_run' ? { scope: info.usage_scope === true ? 'usage' : 'task' } : {}) }
: { request_id: info.request_id, decision },
);
@@ -649,19 +627,5 @@ if (window.orkas && typeof window.orkas.onPushEvent === 'function') {
if (appWindow && payload?.usage_scope !== true) return;
_cancelBashPermissionRequests(payload, 'connector');
});
- if (!appWindow) {
- window.orkas.onPushEvent('web-assist:action-confirm', (info) => {
- if (!info || typeof info.request_id !== 'string') return;
- _bashPermQueue.push({
- ...info,
- _permission_kind: 'web-assist',
- _renderer_received_at_ms: Date.now(),
- });
- _drainBashPermissionQueue();
- });
- window.orkas.onPushEvent('web-assist:action-confirm-cancelled', (payload) => {
- _cancelBashPermissionRequests(payload, 'web-assist');
- });
- }
} catch (_err) { /* push channel unavailable; bash calls deny on timeout */ }
}
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 374f3899..25c7b4dd 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -393,6 +393,7 @@ function setView(view, cid, opts = {}) {
// A resource detail opened from another page is only a transient overlay.
// Any explicit sidebar/programmatic navigation dismisses it first, so a
// later visit to AI Team or Skills always starts from its list.
+ if (typeof _closeProjectDriverHint === 'function') _closeProjectDriverHint();
if (typeof _resetAgentsDetailForNavigation === 'function') {
_resetAgentsDetailForNavigation();
}
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
index aff1c5f8..322f13bd 100644
--- a/src/renderer/modules/chat-file-viewer.js
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -723,7 +723,7 @@ async function _refreshSaveAppButton(path) {
try {
const inspected = await window.orkas.invoke('savedApps.inspectBundleFromPath', _viewerFileActionPayload(path));
if (!_isViewerOpen() || _viewerCurrentPath !== path) return;
- const canSave = !!(inspected && inspected.ok !== false && inspected.canSave);
+ const canSave = !!(inspected && inspected.ok !== false && (inspected.canSave || inspected.reason === 'app_bundle_root'));
_setSaveAppVisible(canSave);
} catch {
if (!_isViewerOpen() || _viewerCurrentPath !== path) return;
@@ -735,7 +735,6 @@ async function _refreshSaveAppButton(path) {
async function _onSaveAppClick() {
const p = _viewerCurrentPath;
if (!p || !_viewerSaveAppBtn || _viewerSaveAppBtn.disabled) return;
- const startedAt = Date.now();
if (_viewerDirty) {
const message = _viewerLabel('apps.save_from_file_dirty', 'Save the file changes before saving it as an app.');
await _viewerShowAlert(message, 'file_preview_save_app_presentation');
@@ -755,19 +754,25 @@ async function _onSaveAppClick() {
res = await window.orkas.invoke('savedApps.saveFromPath', _viewerFileActionPayload(p));
} catch (err) {
const failure = _viewerStableFailure(err, 'saved_app_save_failed', 'ipc');
- const reason = String(err && err.message || err);
_viewerLogFailure('file_preview_save_app', failure);
- const prefix = _viewerLabel('apps.save_failed', 'Could not save the app');
- await _viewerShowAlert(`${prefix}: ${reason}`, 'file_preview_save_app_presentation');
+ // Raw errors may hold local paths; the failure is logged by code only.
+ await _viewerShowAlert(_viewerLabel('apps.save_failed', 'Could not save the app'), 'file_preview_save_app_presentation');
_scheduleSaveAppButtonRestore(p, original);
return;
}
+ if (window.OrkasCommercialEntry?.isFailure(res)) {
+ _scheduleSaveAppButtonRestore(p, original);
+ await window.OrkasCommercialEntry.show();
+ return;
+ }
if (!res || res.ok === false) {
const failure = _viewerStableFailure(res, 'saved_app_save_failed', 'operation');
- const reason = String((res && res.error) || 'failed');
_viewerLogFailure('file_preview_save_app', failure);
- const prefix = _viewerLabel('apps.save_failed', 'Could not save the app');
- await _viewerShowAlert(`${prefix}: ${reason}`, 'file_preview_save_app_presentation');
+ // Raw errors may hold local paths; the failure is logged by code only.
+ const message = res?.error === 'app_bundle_root'
+ ? _viewerLabel('apps.save_root_folder_required', 'Move the HTML and its resources into a separate folder, then save as an app again.')
+ : _viewerLabel('apps.save_failed', 'Could not save the app');
+ await _viewerShowAlert(message, 'file_preview_save_app_presentation');
_scheduleSaveAppButtonRestore(p, original);
return;
}
@@ -1421,7 +1426,9 @@ async function openChatFileViewer(absPath, displayName, opts) {
if (window.OrkasPreviewWindows) {
if (!(await _ensureViewerFileExists(absPath, opts?.cid, opts?.projectId))) return;
if (_kindOf(absPath) === 'image') return window.OrkasPreviewWindows.image(_chatMediaLocalUrl(absPath), displayName || absPath.split(/[\\/]/).pop(), { ...opts, absPath });
- return window.OrkasPreviewWindows.open({ kind: 'file', path: absPath, title: displayName || absPath.split(/[\\/]/).pop(), options: window.OrkasPreviewWindows.options(opts) });
+ const result = await window.OrkasPreviewWindows.open({ kind: 'file', path: absPath, title: displayName || absPath.split(/[\\/]/).pop(), options: window.OrkasPreviewWindows.options(opts) });
+ if (window.OrkasCommercialEntry?.isFailure(result)) await window.OrkasCommercialEntry.show();
+ return result;
}
const cid = (opts && opts.cid) || null;
const projectId = (opts && opts.projectId) || null;
diff --git a/src/renderer/modules/cli-account-usage.js b/src/renderer/modules/cli-account-usage.js
new file mode 100644
index 00000000..5adafbef
--- /dev/null
+++ b/src/renderer/modules/cli-account-usage.js
@@ -0,0 +1,40 @@
+// Account allowance belongs to the CLI login, shared by its agents and sessions.
+// Query when rendering details or after a CLI upgrade; no background poll.
+let _cliAccountUsageGeneration = 0;
+const _cliAccountUsageLog = createLogger('cli-account-usage');
+
+async function renderCliAccountUsage(agent, { force = false } = {}) {
+ const generation = ++_cliAccountUsageGeneration;
+ const section = document.getElementById('agents-detail-cli-usage-section');
+ const slot = document.getElementById('agents-detail-cli-usage');
+ if (!section || !slot) return;
+ const supported = agent.runtime?.kind === 'cli' && ['codex', 'claude'].includes(agent.runtime.cli);
+ section.hidden = !supported;
+ slot.innerHTML = '';
+ if (!supported) return;
+ slot.innerHTML = `<div class="agents-detail-cli-loading">${escapeHtml(t('common.loading'))}</div>`;
+ let usage;
+ try {
+ const response = await window.orkas.invoke('localAgents.accountUsage', { agent_id: agent.agent_id, force });
+ usage = response?.usage;
+ } catch (_) {
+ _cliAccountUsageLog.warn('CLI account allowance request unavailable');
+ }
+ if (generation !== _cliAccountUsageGeneration) return;
+ const date = (value) => new Date(value).toLocaleString(getLang(), { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
+ const rows = usage?.status === 'ready' && Array.isArray(usage.windows) ? usage.windows : [];
+ const body = rows.length ? rows.map(row => {
+ const duration = row.minutes >= 1440 && row.minutes % 1440 === 0
+ ? t('agents.cli_usage_days', { count: row.minutes / 1440 })
+ : row.minutes > 0 ? t('agents.cli_usage_hours', { count: row.minutes / 60 }) : t('agents.cli_usage_window');
+ const name = [row.label, duration].filter(Boolean).join(' · ');
+ const percent = Math.max(0, Math.min(100, row.remaining_percent));
+ const formatted = new Intl.NumberFormat(getLang(), { maximumFractionDigits: 1 }).format(percent);
+ return `<div class="agents-detail-cli-field">
+ <div class="agents-detail-cli-field-label">${escapeHtml(name)} · ${escapeHtml(formatted)}%</div>
+ <progress max="100" value="${percent}" aria-label="${escapeHtml(name)}"></progress>
+ ${row.resets_at ? `<div class="agents-detail-cli-note">${escapeHtml(t('agents.cli_usage_resets', { time: date(row.resets_at) }))}</div>` : ''}
+ </div>`;
+ }).join('') : `<div class="agents-detail-cli-note">${escapeHtml(t(usage?.status === 'unsupported' ? 'agents.cli_usage_unsupported' : 'agents.cli_usage_unavailable'))}</div>`;
+ slot.innerHTML = `<div class="agents-detail-cli-settings agents-detail-cli-grid">${body}</div>`;
+}
diff --git a/src/renderer/modules/composer-input.js b/src/renderer/modules/composer-input.js
index 59d45b7b..61b854de 100644
--- a/src/renderer/modules/composer-input.js
+++ b/src/renderer/modules/composer-input.js
@@ -187,7 +187,24 @@ function composerSnapshot(input) {
}
function composerBindOwner(input, owner) {
const api = _composerApi(input);
- if (!api || api.owner === owner) return;
+ if (!api) return;
+ let doc = api.view.state.doc;
+ if (api.editor.id === 'project-chat-input') {
+ // The shared project panel must swap documents at the synchronous routing
+ // boundary, before its deferred project data load. Keep immutable drafts
+ // in this renderer session, scoped to the account as well as the project.
+ const account = typeof currentUserId === 'string' ? currentUserId : '';
+ const accountChanged = api.draftAccount !== account;
+ if (!accountChanged && api.owner === owner) return;
+ if (accountChanged) {
+ api.projectDrafts = new Map();
+ api.draftAccount = account;
+ } else if (api.owner) {
+ if (doc.content.size > 2) api.projectDrafts.set(api.owner, { doc, stamp: api.stamp });
+ else api.projectDrafts.delete(api.owner);
+ }
+ doc = api.projectDrafts.get(owner)?.doc || _composerDocument('', api.editor.id);
+ } else if (api.owner === owner) return;
api.owner = owner;
api.resetHistoryOnSet = true;
api.epoch++;
@@ -201,7 +218,14 @@ function composerBindOwner(input, owner) {
}
// Undo must never restore a different task's draft.
api.view.updateState(OrkasEditor.EditorState.create({ schema: _composerSchema,
- doc: api.view.state.doc, plugins: api.plugins }));
+ doc, plugins: api.plugins }));
+ if (api.editor.id === 'project-chat-input') api.autoGrow();
+}
+function composerDiscardStoredDraft(input, owner, snapshot) {
+ const api = _composerApi(input);
+ // A background send may finish after the panel switched projects. Consume
+ // only the submitted revision; edits made during the send remain unsent.
+ if (api?.projectDrafts?.get(owner)?.stamp === snapshot.stamp) api.projectDrafts.delete(owner);
}
function composerSetDisabled(input, disabled) {
const el = _composerElement(input), api = _composerApi(el);
diff --git a/src/renderer/modules/composer-model-picker.js b/src/renderer/modules/composer-model-picker.js
index 082be91f..215edbe1 100644
--- a/src/renderer/modules/composer-model-picker.js
+++ b/src/renderer/modules/composer-model-picker.js
@@ -61,6 +61,13 @@ function _composerRecipientForTarget(target) {
function _composerRecipientUsesExternalAgent(target) {
if (typeof _agentsCache === 'undefined' || !Array.isArray(_agentsCache)) return false;
+ // A planned send (D29) is split by a model call even when every mentioned
+ // actor is a CLI agent, so the model choice still applies.
+ if (target !== 'auto' && typeof _composerSendIsPlanned === 'function'
+ && typeof _composerRecipientInput === 'function' && typeof composerText === 'function') {
+ const input = _composerRecipientInput(target);
+ if (input && _composerSendIsPlanned(composerText(input) || '', target)) return false;
+ }
const preview = target !== 'auto' && _COMPOSER_RECIPIENT_TARGETS.includes(target)
&& typeof _mentionPreviewRecipients === 'function'
? _mentionPreviewRecipients(target)
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index b81df34a..f7979b16 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -56,8 +56,9 @@ function _renderCtxScopeSelector(projects) {
if (!host || typeof _aiSelectMount !== 'function') return;
const options = [
{ value: '', label: t('contexts.global'), iconName: 'folder' },
- ...(projects || []).slice().sort((a, b) => a.name.localeCompare(b.name)).map((project) => ({
- value: project.project_id, label: project.name, iconName: 'folder',
+ ...(projects || []).slice().sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''), undefined, { numeric: true, sensitivity: 'base' })).map((project) => ({
+ value: project.project_id, label: project.name,
+ iconName: typeof projectIconName === 'function' ? projectIconName(project) : 'folder',
})),
];
if (_ctxScopeSelector) {
diff --git a/src/renderer/modules/conv-bucket.js b/src/renderer/modules/conv-bucket.js
index d79de07e..5dbe0751 100644
--- a/src/renderer/modules/conv-bucket.js
+++ b/src/renderer/modules/conv-bucket.js
@@ -27,20 +27,36 @@ function timeBucket(iso, now) {
return 'older';
}
-// Rows whose sidebar activity falls in today's local bucket, in input order.
-// Feeds the "Today's Tasks" section with the same `last_active_at` reading as
-// the bucketed lists, so a row is never under "Today" in one list and missing
-// from the aggregate.
-function selectTodayConversations(rows, now) {
+// Rows whose sidebar activity falls in today's or yesterday's local bucket, in
+// input order. Feeds the sidebar "Recent Tasks" section with the same
+// `last_active_at` reading as the bucketed lists, so a row is never under
+// "Today"/"Yesterday" in one list and missing from the aggregate. Using the
+// calendar buckets (not a rolling 48h) keeps the section stable within a day:
+// it only changes when a conversation gets a new message or when the local date
+// rolls over, which is when the list already re-renders.
+const _RECENT_BUCKETS = new Set(['today', 'yesterday']);
+
+function selectRecentConversations(rows, now) {
const out = [];
for (const c of Array.isArray(rows) ? rows : []) {
if (!c || !c.conversation_id) continue;
const iso = c.last_active_at || c.updated_at || c.created_at || '';
- if (timeBucket(iso, now) === 'today') out.push(c);
+ if (_RECENT_BUCKETS.has(timeBucket(iso, now))) out.push(c);
}
return out;
}
+// Local start of yesterday: the lower bound the startup slice must load so
+// rows under collapsed projects reach the Recent Tasks section.
+function recentConversationsSince(now) {
+ const d = new Date(now || new Date());
+ d.setHours(0, 0, 0, 0);
+ d.setDate(d.getDate() - 1);
+ return d;
+}
+
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
- module.exports = { timeBucket, selectTodayConversations, _BUCKET_ORDER };
+ module.exports = {
+ timeBucket, selectRecentConversations, recentConversationsSince, _BUCKET_ORDER,
+ };
}
diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.js
index e148adca..90257873 100644
--- a/src/renderer/modules/conversation-info.js
+++ b/src/renderer/modules/conversation-info.js
@@ -85,14 +85,6 @@ const ConversationInfo = (() => {
return idx >= 0 ? base.slice(idx + 1).toLowerCase() : '';
}
- function _savedAppSourceKind(path, resourceKind) {
- if (resourceKind === 'dir') return 'directory';
- const ext = _extForName(path);
- if (ext === 'html' || ext === 'htm') return 'html';
- if (ext === 'css') return 'css';
- if (ext === 'js' || ext === 'mjs') return 'javascript';
- return 'file';
- }
function _savedAppSaveFailure(value, fallbackType = 'operation') {
const rawCode = String((value && (value.error_code || value.code)) || '').toLowerCase();
@@ -123,20 +115,8 @@ const ConversationInfo = (() => {
return { error_type: errorType, error_code: errorCode };
}
- function _logSavedAppSaveResult(startedAt, result, path, resourceKind, failure = {}) {
- const payload = {
- result,
- surface: 'conversation_info',
- kind: _savedAppSourceKind(path, resourceKind),
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') Object.assign(payload, failure);
- if (result === 'failure') {
- _infoLog.warn('conversation info app save failed', {
- error_type: payload.error_type,
- error_code: payload.error_code,
- });
- }
+ function _logSavedAppSaveFailure(failure) {
+ _infoLog.warn('conversation info app save failed', { error_type: failure.error_type, error_code: failure.error_code });
}
function _dirName(p) {
@@ -233,36 +213,9 @@ const ConversationInfo = (() => {
return 'unsupported';
}
- function _fileKindForLog(name) {
- const ext = _extForName(name);
- if (ext === 'html' || ext === 'htm') return 'html';
- if (ext === 'md' || ext === 'markdown') return 'markdown';
- const kind = _kindForName(name);
- if (kind === 'docx' || kind === 'spreadsheet' || kind === 'presentation') return 'office';
- if (kind === 'legacy_office') return 'unsupported';
- return kind;
- }
-
- function _logLibraryImportResult(startedAt, result, absPath, response, failure = {}) {
- const payload = {
- result,
- surface: 'conversation_info',
- kind: _fileKindForLog(absPath),
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result === 'success') {
- payload.scope = response && response.scope === 'project'
- ? 'project'
- : (response && response.scope === 'global' ? 'global' : 'unknown');
- } else {
- Object.assign(payload, failure);
- }
- if (result === 'failure') {
- _infoLog.warn('conversation info library import failed', {
- error_type: payload.error_type,
- error_code: payload.error_code,
- });
- }
+
+ function _logLibraryImportFailure(failure) {
+ _infoLog.warn('conversation info library import failed', { error_type: failure.error_type, error_code: failure.error_code });
}
function _fileOperationPolicy() {
@@ -1037,7 +990,7 @@ const ConversationInfo = (() => {
let canSaveApp = false;
try {
const inspected = await window.orkas.invoke('savedApps.inspectBundleFromPath', _fileActionPayload(absPath, targetCid));
- canSaveApp = !!(inspected && inspected.ok !== false && inspected.canSave);
+ canSaveApp = !!(inspected && inspected.ok !== false && (inspected.canSave || inspected.reason === 'app_bundle_root'));
} catch (_) { canSaveApp = false; }
const addItem = entryKind === 'file' && _canAddEntryToChat(name || absPath)
? `<div class="ctx-row-menu-item" data-action="add-to-chat">${escapeHtml(addLabel)}</div>`
@@ -1089,15 +1042,10 @@ const ConversationInfo = (() => {
async function _revealEntry(absPath, cidOverride) {
try {
const res = await window.orkas.invoke('workspace.revealPath', _fileActionPayload(absPath, cidOverride));
- if (!res || !res.ok) {
- await uiAlert(_label('conversation_info.file_reveal_failed', 'Could not show in folder: {reason}', {
- reason: (res && res.error) || 'failed',
- }));
- }
- } catch (err) {
- await uiAlert(_label('conversation_info.file_reveal_failed', 'Could not show in folder: {reason}', {
- reason: String(err && err.message || err),
- }));
+ // Host reasons can carry local paths or internal errors; show only localized recovery copy.
+ if (!res || !res.ok) await uiAlert(_label('conversation_info.file_reveal_failed', 'Could not open the folder. The file may have been moved or deleted.'));
+ } catch (_) {
+ await uiAlert(_label('conversation_info.file_reveal_failed', 'Could not open the folder. The file may have been moved or deleted.'));
}
}
@@ -1119,38 +1067,26 @@ const ConversationInfo = (() => {
async function _addEntryToLibrary(absPath, cidOverride) {
const targetCid = cidOverride || _cid;
if (!_canAddEntryToLibrary(absPath, _isProjectConversation(targetCid))) return;
- const startedAt = Date.now();
+
let res;
try {
res = await window.orkas.invoke('library.importProduced', _fileActionPayload(absPath, cidOverride));
} catch (err) {
- _logLibraryImportResult(
- startedAt,
- 'failure',
- absPath,
- null,
- _libraryImportFailure(err, 'ipc'),
- );
+ _logLibraryImportFailure(_libraryImportFailure(err, 'ipc'));
await uiAlert(_label('conversation_info.file_add_to_library_failed', 'Add to Library failed: {reason}', {
reason: String(err && err.message || err),
}));
return;
}
if (!res || !res.ok) {
- _logLibraryImportResult(
- startedAt,
- 'failure',
- absPath,
- res,
- _libraryImportFailure(res, 'operation'),
- );
+ _logLibraryImportFailure(_libraryImportFailure(res, 'operation'));
await uiAlert(_label('conversation_info.file_add_to_library_failed', 'Add to Library failed: {reason}', {
reason: String((res && res.error) || 'failed'),
}));
return;
}
- _logLibraryImportResult(startedAt, 'success', absPath, res);
+
try {
const libraryLabel = res.scope === 'project'
? _label('contexts.transfer.project_library', 'Project Library')
@@ -1174,15 +1110,15 @@ const ConversationInfo = (() => {
}
}
- async function _saveEntryAsApp(absPath, cidOverride, resourceKind = 'file') {
- const startedAt = Date.now();
+ async function _saveEntryAsApp(absPath, cidOverride) {
+
let res;
try {
res = await window.orkas.invoke('savedApps.saveFromPath', _fileActionPayload(absPath, cidOverride));
} catch (err) {
- _logSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(err, 'ipc'));
+ _logSavedAppSaveFailure(_savedAppSaveFailure(err, 'ipc'));
try {
- await uiAlert(_label('apps.save_failed', 'Could not save the app') + ': ' + String(err && err.message || err));
+ await uiAlert(_label('apps.save_failed', 'Could not save the app'));
} catch (_) {
_infoLog.warn('conversation info app save presentation failed', {
error_type: 'presentation',
@@ -1191,10 +1127,17 @@ const ConversationInfo = (() => {
}
return;
}
+ if (window.OrkasCommercialEntry?.isFailure(res)) {
+ await window.OrkasCommercialEntry.show();
+ return;
+ }
if (!res || res.ok === false) {
- _logSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(res, 'operation'));
+ _logSavedAppSaveFailure(_savedAppSaveFailure(res, 'operation'));
try {
- await uiAlert(_label('apps.save_failed', 'Could not save the app') + ': ' + String((res && res.error) || 'failed'));
+ const message = res?.error === 'app_bundle_root'
+ ? _label('apps.save_root_folder_required', 'Move the HTML and its resources into a separate folder, then save as an app again.')
+ : _label('apps.save_failed', 'Could not save the app');
+ await uiAlert(message);
} catch (_) {
_infoLog.warn('conversation info app save presentation failed', {
error_type: 'presentation',
@@ -1204,7 +1147,7 @@ const ConversationInfo = (() => {
return;
}
- _logSavedAppSaveResult(startedAt, 'success', absPath, resourceKind);
+
try {
const message = _label('apps.saved_toast', 'Saved to Apps');
if (typeof uiToast === 'function') uiToast(message, { variant: 'success' });
@@ -1259,7 +1202,7 @@ const ConversationInfo = (() => {
async function _runFileMenuAction(action, absPath, displayName, kind, options = {}) {
if (action === 'reveal') return _revealEntry(absPath, options.cid);
- if (action === 'save-as-app') return _saveEntryAsApp(absPath, options.cid, kind);
+ if (action === 'save-as-app') return _saveEntryAsApp(absPath, options.cid);
if (action === 'add-to-library') return _addEntryToLibrary(absPath, options.cid);
if (action === 'add-to-chat') return _addEntryToChat(absPath, kind, options.cid);
if (action === 'delete') return _deleteEntry(absPath, displayName, kind, options);
@@ -1411,6 +1354,19 @@ const ConversationInfo = (() => {
_renderBody();
return true;
}
+ function closeBrowserForTask(ownerCid) {
+ if (!ownerCid) return false;
+ if (ownerCid !== _cid) {
+ const saved = _panelStateByCid.get(ownerCid);
+ if (!saved?.open || saved.tab !== 'browser') return false;
+ _panelStateByCid.set(ownerCid, { ...saved, open: false });
+ return true;
+ }
+ // Model page closure must preserve the user's Files/Attachments selection.
+ if (!_open || _activeTab !== 'browser') return false;
+ _setOpen(false);
+ return true;
+ }
function openFileMenu(anchorBtn, absPath, displayName, options = {}) {
return _openFileMenu(anchorBtn, absPath, displayName, 'file', options);
}
@@ -1425,6 +1381,7 @@ const ConversationInfo = (() => {
close,
toggle,
openAndSetTab,
+ closeBrowserForTask,
openFileMenu,
};
})();
diff --git a/src/renderer/modules/conversation-to-project.js b/src/renderer/modules/conversation-to-project.js
index 220e4887..2c686408 100644
--- a/src/renderer/modules/conversation-to-project.js
+++ b/src/renderer/modules/conversation-to-project.js
@@ -171,9 +171,10 @@ async function _finishConversationProjectMove(projectId, name, agentIds) {
: t('chat.conv_moved', { name }));
}
-function _convProjectIcon() {
+function _convProjectIcon(project) {
if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
- return window.uiIconHtml('folder', 'conv-project-pick-icon');
+ const name = typeof window.projectIconName === 'function' ? window.projectIconName(project) : 'folder';
+ return window.uiIconHtml(name, 'conv-project-pick-icon');
}
return '';
}
@@ -198,7 +199,7 @@ function _openConversationProjectPicker(projects, agents = []) {
const rows = projects.map((project) => `
<button type="button" class="conv-project-pick-row" role="option" aria-selected="false"
data-project-id="${escapeHtml(project.project_id)}">
- ${_convProjectIcon()}
+ ${_convProjectIcon(project)}
<span class="conv-project-pick-name">${escapeHtml(project.name || project.project_id)}</span>
</button>
`).join('');
diff --git a/src/renderer/modules/conversation-turn-nav.js b/src/renderer/modules/conversation-turn-nav.js
index d47e1745..09130a5b 100644
--- a/src/renderer/modules/conversation-turn-nav.js
+++ b/src/renderer/modules/conversation-turn-nav.js
@@ -16,8 +16,8 @@
const MIN_TURNS = 5;
const PAGE_SIZE = 15;
const VISIBLE_MARKERS = 12;
- const PREVIEW_TITLE_CHARS = 40;
- const PREVIEW_BODY_CHARS = 80;
+ const PREVIEW_TITLE_CHARS = 100;
+ const PREVIEW_BODY_CHARS = 240;
const LOAD_THRESHOLD = 18;
const SCROLL_EDGE_EPSILON = 1;
const OVERFLOW_EDGE_MARKERS = 3;
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index adee9c10..b26217ca 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -1893,7 +1893,6 @@ async function validateRecipientAgainstProject(target, pid, boundAgentIds) {
_renderRecipientChip(target);
const input = _composerRecipientInput(target);
if (input && typeof refreshChatComposer === 'function') refreshChatComposer(input);
- if (typeof _updateComposerSeqToggle === 'function') _updateComposerSeqToggle(target);
const cur = _activeRecipient(target);
const recipients = _recipientList(cur);
const eligible = recipients.filter((r) => r.kind === 'commander' || bound.has(r.id));
@@ -1996,90 +1995,6 @@ function _quotedLineRanges(body) {
// by default) and the composer shows the order toggle. Blockquote-line
// mentions are quoted context, not dispatch — skipped, same rule as the
// router. Pure function — renderer tests extract it.
-function _composerMentionGroups(text, spans) {
- const groups = [];
- for (let i = 0; i < spans.length; i += 1) {
- const span = spans[i];
- const previous = groups[groups.length - 1];
- if (previous && /^\s*$/.test(text.slice(spans[i - 1].end, span.start))) {
- previous.recipients.push(span.recipient);
- previous.end = span.end;
- } else {
- groups.push({ start: span.start, end: span.end, recipients: [span.recipient] });
- }
- }
- return groups.filter((group, index) => text.slice(group.end, groups[index + 1]?.start ?? text.length).trim());
-}
-
-function _composerDispatchShape(text, knownAgents, target) {
- const body = String(text || '');
- const spans = _resolvedMentionSpans(body, knownAgents, target);
- if (!spans.length) return { segments: 0, groups: 0 };
- const groups = _composerMentionGroups(body, spans);
- const preamble = body.slice(0, spans[0].start).split('\n')
- .some((line) => line.trim() && !/^\s*>/.test(line)) ? 1 : 0;
- return {
- segments: preamble + groups.reduce((count, group) => count + _recipientList(_recipientSet(group.recipients)).length, 0),
- groups: preamble + groups.length,
- };
-}
-
-// Per-send cross-segment order choice (D23): the toggle surfaces for EVERY
-// multi-agent composer send — multi-group texts default to the adjudicated
-// serial chain, an adjacent single group defaults to its all-parallel
-// semantics, and either default can be flipped for this one send. The
-// override is per composer and resets when the send fires or the text stops
-// qualifying, so a flip never leaks into the next message.
-const _composerDispatchOverride = new Map(); // target → 'serial' | 'parallel'
-
-const _COMPOSER_SEQ_TOGGLES = [
- ['conversation', 'chat-seq-toggle', 'chat-input'],
- ['new-chat', 'new-chat-seq-toggle', 'new-chat-input'],
- ['project', 'project-chat-seq-toggle', 'project-chat-input'],
-];
-
-/** Shape default = today's behavior: written order chains multi-group sends;
- * one adjacent group is a parallel unit. Pure — renderer tests extract it. */
-function _composerDispatchDefaultMode(shape) {
- return shape && shape.groups >= 2 ? 'serial' : 'parallel';
-}
-
-function _composerDispatchShapeFor(target) {
- const row = _COMPOSER_SEQ_TOGGLES.find(([tg]) => tg === target);
- const ta = row ? document.getElementById(row[2]) : null;
- return _composerDispatchShape(
- ta ? composerText(ta) : '',
- undefined, target,
- );
-}
-
-/** The order this composer would send with right now, or null when the text
- * does not dispatch to two or more segments. */
-function _composerEffectiveDispatchMode(target) {
- const shape = _composerDispatchShapeFor(target);
- if (shape.segments < 2) return null;
- return _composerDispatchOverride.get(target) || _composerDispatchDefaultMode(shape);
-}
-
-function _updateComposerSeqToggle(target) {
- for (const [tg, btnId] of _COMPOSER_SEQ_TOGGLES) {
- if (target && tg !== target) continue;
- const btn = document.getElementById(btnId);
- if (!btn) continue;
- const mode = _composerEffectiveDispatchMode(tg);
- if (!mode) {
- btn.hidden = true;
- _composerDispatchOverride.delete(tg);
- continue;
- }
- btn.hidden = false;
- btn.textContent = mode === 'parallel'
- ? t('chat.multi_dispatch_parallel')
- : t('chat.multi_dispatch_serial');
- btn.title = t('chat.multi_dispatch_toggle_title');
- }
-}
-
// Share resolved recipient identities between the routing preview and model
// control. Unknown tokens and quoted lines do not replace the default target.
function _resolvedMentionSpans(text, agents, target = 'conversation') {
@@ -2158,26 +2073,50 @@ function _resolvedMentionRecipients(text, target = 'conversation') {
return _explicitMentionRecipients(text, target);
}
-// Prose before the first mention inherits the default; quotes stay context.
-function _composerHasUnaddressedInstruction(text, target = 'conversation') {
- const spans = _resolvedMentionSpans(text, undefined, target);
- return spans.length > 0 && String(text).slice(0, spans[0].start).split('\n')
- .some((line) => line.trim() && !/^\s*>/.test(line));
-}
-
-function _composerMessageRecipients(target, text, forSend = false) {
- const spans = _resolvedMentionSpans(text, undefined, target);
- const explicit = forSend
- ? _composerMentionGroups(String(text || ''), spans).flatMap((group) => group.recipients)
- : _explicitMentionRecipients(text, target);
+// D29: inline mentions name the actors a send involves. A message that starts
+// with its only mentioned actor goes to it; any other mention shape is split
+// by the main-process dispatch planner among the mentioned actors (and
+// Commander), so no default owner is added for prose around the mentions.
+function _composerMessageRecipients(target, text) {
+ const explicit = _explicitMentionRecipients(text, target);
const active = _activeRecipient(target);
const fallback = active.kind === 'group' ? _COMMANDER : active;
- const recipients = !spans.length || _composerHasUnaddressedInstruction(text, target)
- ? [fallback, ...explicit] : explicit;
+ const recipients = explicit.length ? explicit : [fallback];
return _recipientList(_recipientSet(recipients)).map((r) => r.kind === 'commander'
? { ...r, name: t('chat.recipient_commander') } : r);
}
+// Use the same resolved mention spans as routing. Keep literal examples and
+// unknown names as content, while a recipient alone cannot start a task.
+function _composerSendIsEmpty(text, target = 'conversation', quotes = [], attachments = []) {
+ if (quotes.length) return false;
+ const body = String(text || '');
+ if (!body.trim()) return true;
+ if (attachments.some((attachment) => attachment.status !== 'error')) return false;
+ const spans = _resolvedMentionSpans(body, undefined, target);
+ if (!spans.length) return !body.trim();
+ let rest = body;
+ for (const span of [...spans].reverse()) rest = rest.slice(0, span.start) + rest.slice(span.end);
+ return !rest.split('\n').some((line) => line.trim() && !/^\s*>/.test(line));
+}
+
+// D29 mirror of the main-process route classifier. Planning itself runs on
+// the selected model; structured resources can carry content without prose.
+function _composerSendIsPlanned(text, target = 'conversation') {
+ const body = String(text || '');
+ const spans = _resolvedMentionSpans(body, undefined, target);
+ if (!spans.length) return false;
+ const hasProse = (chunk) => chunk.split('\n').some((line) => line.trim() && !/^\s*>/.test(line));
+ let rest = body;
+ for (const span of [...spans].reverse()) rest = rest.slice(0, span.start) + rest.slice(span.end);
+ const cid = target === 'new-chat' ? DRAFT_CID
+ : target === 'project' ? _referenceNewTaskDraftCid(typeof _projectDetailPid === 'undefined' ? '' : _projectDetailPid) : currentCid;
+ if (!hasProse(rest) && _composerSendIsEmpty(body, target, _getQuotes(cid), _chatAttachList(cid))) return false;
+ const actors = new Set(spans.map(({ recipient }) => `${recipient.kind}:${recipient.id}`));
+ if (actors.size > 1) return true;
+ return spans[0].recipient.kind !== 'commander' && hasProse(body.slice(0, spans[0].start));
+}
+
function _composerSelectedRecipients(target) {
const text = composerText(_composerRecipientInput(target)) || '';
const recipients = _composerMessageRecipients(target, text);
@@ -2335,6 +2274,8 @@ function onEnterNewChatView() {
_initEmptyStateScenarios();
// The open-source marketplace entry is rendered as one Quick task card.
if (typeof initOssQuickTask === 'function') initOssQuickTask();
+ // Work to pick up (open to-dos, finished runs not yet opened); home.js.
+ if (typeof homeOnEnter === 'function') homeOnEnter();
}
// ── Empty-state landing helpers ──────────────────────────────────────────
@@ -2464,7 +2405,6 @@ const _DEFAULT_QUICK_START_ITEMS = [
];
let _quickStartItems = _DEFAULT_QUICK_START_ITEMS.map((item) => ({ ...item }));
let _quickStartConfigPromise = null;
-let _quickStartSource = 'pc_default';
let _SCENARIO_CONFIGS = {};
// English fallback templates — used when the i18n table doesn't yet carry
// the scenario template key. These are complete, ready-to-run tasks so a
@@ -2500,7 +2440,6 @@ function _setQuickStartItems(raw, source) {
const normalized = _normalizeQuickStartItems(raw);
const items = normalized || _DEFAULT_QUICK_START_ITEMS.map((item) => ({ ...item }));
_quickStartItems = items;
- _quickStartSource = normalized && source === 'server_config' ? 'server_config' : 'pc_default';
_SCENARIO_CONFIGS = Object.fromEntries(items.map((item) => [item.id, {
..._SCENARIO_CATALOG[item.id],
agentId: item.agent_id,
@@ -2508,84 +2447,21 @@ function _setQuickStartItems(raw, source) {
return !!normalized;
}
-function _normalizeCommanderTemplateAttribution(raw, defaultManual = false) {
- const src = raw && typeof raw === 'object' ? raw : {};
- const entryPoint = String(src.entry_point || src.entryPoint || '').trim();
- const validEntryPoint = /^(?:manual|quick_start|oss_tool)$/.test(entryPoint)
- ? entryPoint
- : (defaultManual ? 'manual' : '');
- if (!validEntryPoint) return {};
- const out = { entry_point: validEntryPoint };
- const resourceId = _commanderAttributionId(src.resource_id || src.resourceId);
- const agentId = _commanderAttributionId(src.agent_id || src.agentId);
- const source = String(src.source || '').trim();
- const recipientType = String(src.recipient_type || src.recipientType).trim();
- const position = Math.round(Number(src.position) || 0);
- if (resourceId) out.resource_id = resourceId;
- if (agentId) out.agent_id = agentId;
- if (/^(?:pc_default|server_config|commander_home)$/.test(source)) out.source = source;
- if (/^(?:agent|commander)$/.test(recipientType)) out.recipient_type = recipientType;
- if (position > 0 && position <= 100) out.position = position;
- return out;
+function _clearQuickStartDraft(input) {
+ if (input?.dataset) delete input.dataset.commanderQuickStartPlaceholder;
}
-function _setCommanderTemplateAttribution(input, raw) {
- if (!input || !input.dataset) return {};
- const value = _normalizeCommanderTemplateAttribution(raw);
- _clearCommanderTemplateAttribution(input);
- if (!value.entry_point) return value;
- input.dataset.commanderEntryPoint = value.entry_point;
- if (value.resource_id) input.dataset.commanderResourceId = value.resource_id;
- if (value.agent_id) input.dataset.commanderAgentId = value.agent_id;
- if (value.source) input.dataset.commanderSource = value.source;
- if (value.recipient_type) input.dataset.commanderRecipientType = value.recipient_type;
- if (value.position) input.dataset.commanderPosition = String(value.position);
- return value;
-}
-
-function _clearCommanderTemplateAttribution(input) {
- if (!input || !input.dataset) return;
- delete input.dataset.commanderEntryPoint;
- delete input.dataset.commanderResourceId;
- delete input.dataset.commanderAgentId;
- delete input.dataset.commanderSource;
- delete input.dataset.commanderRecipientType;
- delete input.dataset.commanderPosition;
- delete input.dataset.commanderQuickStartPlaceholder;
-}
-
-function _readCommanderTemplateAttribution(input) {
- if (!input || !String(composerText(input) || '').trim()) return { entry_point: 'manual' };
- const dataset = input.dataset || {};
- return _normalizeCommanderTemplateAttribution({
- entry_point: dataset.commanderEntryPoint,
- resource_id: dataset.commanderResourceId,
- agent_id: dataset.commanderAgentId,
- source: dataset.commanderSource,
- recipient_type: dataset.commanderRecipientType,
- position: dataset.commanderPosition,
- }, true);
-}
-
-function _bindCommanderTemplateAttributionReset(input) {
- if (!input || !input.dataset || input.dataset.commanderAttributionBound === '1'
+function _bindQuickStartPlaceholderReset(input) {
+ if (!input?.dataset || input.dataset.quickStartPlaceholderBound === '1'
|| typeof input.addEventListener !== 'function') return;
- input.dataset.commanderAttributionBound = '1';
+ input.dataset.quickStartPlaceholderBound = '1';
input.addEventListener(composerChangeEvent(input), () => {
- if (!input.dataset.commanderEntryPoint) return;
- if (!composerHasText(input)) {
- _clearCommanderTemplateAttribution(input);
- return;
- }
const marker = String(input.dataset.commanderQuickStartPlaceholder || '');
- if (marker && !composerIncludes(input, marker)) {
- delete input.dataset.commanderQuickStartPlaceholder;
- }
+ if (!composerHasText(input) || (marker && !composerIncludes(input, marker))) _clearQuickStartDraft(input);
+ if (!composerHasText(input)) delete input.dataset.ossTemplateDraft;
});
}
-window.setCommanderTemplateAttribution = _setCommanderTemplateAttribution;
-
function _findQuickStartPlaceholder(text) {
const match = String(text || '').match(/【[^】]+】|\[[^\]]+\]/);
if (!match || typeof match.index !== 'number') return null;
@@ -2712,7 +2588,7 @@ function _refreshEmptyStateAll() {
// Title + project swatch + project name + stacked agent avatars
// + message count + 详情 toggle. Driven by the same data sources the sidebar
// already consumes (conversations[] cache, _groupMembersCache, pendingConvs)
-// so the header stays consistent across refreshes without new IPC.
+// so header repaints use cached identity.
function _refreshChatHeader() {
const cid = currentCid;
@@ -2868,70 +2744,73 @@ function _bindEmptyStateScenarioButtons(row) {
buttons.forEach((btn, index) => {
if (btn.dataset.quickStartBound === '1') return;
btn.dataset.quickStartBound = '1';
- btn.addEventListener('click', async () => {
- const id = btn.dataset.scenario || '';
- const config = _SCENARIO_CONFIGS[id];
- const position = index + 1;
- const attribution = {
- resource_id: id,
- agent_id: String((config && config.agentId) || ''),
- position,
- source: _quickStartSource,
- };
- if (!config) {
- _convLog.warn('Commander quick-start scenario config missing', { resource_id: id, position });
- return;
- }
- const key = config && config.templateKey;
- const raw = key ? t(key) : '';
- const tmpl = (raw && raw !== key) ? raw : (_SCENARIO_TEMPLATES_FALLBACK_EN[id] || '');
- if (!tmpl) {
- _convLog.warn('Commander quick-start template missing', { resource_id: id, position });
- return;
- }
- const applied = await _scenarioApplyAgent(config, id);
- if (!applied || applied.kind === 'unavailable') {
- _convLog.warn('Commander quick-start recipient API unavailable', { resource_id: id, position });
- return;
- }
- const input = document.getElementById('new-chat-input');
- if (!input) {
- _convLog.warn('Commander quick-start composer missing', { resource_id: id, position });
- return;
- }
- composerSetText(input, tmpl);
- _setCommanderTemplateAttribution(input, {
- entry_point: 'quick_start',
- ...attribution,
- recipient_type: applied.kind === 'agent' ? 'agent' : 'commander',
- });
- input.focus();
- // Select the concrete subject (coffee machine, login page, etc.) so the
- // user's next keystroke customizes the example immediately. Server-fed
- // templates may still carry a real placeholder; retain the existing
- // blocking behavior for those templates only.
- const subject = _quickStartText(config.subjectKey, config.subjectFallback || '');
- const editableSubject = _findQuickStartSubject(tmpl, subject);
- const placeholder = _findQuickStartPlaceholder(tmpl);
- if (editableSubject) {
- delete input.dataset.commanderQuickStartPlaceholder;
- composerSetSelection(input, editableSubject.start, editableSubject.end);
- } else if (placeholder) {
- input.dataset.commanderQuickStartPlaceholder = placeholder.text;
- composerSetSelection(input, placeholder.start, placeholder.end);
- } else {
- delete input.dataset.commanderQuickStartPlaceholder;
- composerSetSelection(input, tmpl.length, tmpl.length);
- }
- try { composerNotify(input); } catch (_) {}
- });
+ btn.addEventListener('click', () => (
+ _applyQuickStartScenario(btn.dataset.scenario || '', index + 1, { surface: 'home_grid' })
+ ));
});
}
+/** Apply one Quick start task to the home composer. `surface` says where it
+ * was picked (the empty home's grid). */
+async function _applyQuickStartScenario(id, position, { surface = '' } = {}) {
+ const target = 'new-chat';
+ const inputId = 'new-chat-input';
+ try {
+ const config = _SCENARIO_CONFIGS[id];
+ if (!config) {
+ _convLog.warn('Commander quick-start scenario config missing', { resource_id: id, position });
+ return;
+ }
+ const key = config && config.templateKey;
+ const raw = key ? t(key) : '';
+ const tmpl = (raw && raw !== key) ? raw : (_SCENARIO_TEMPLATES_FALLBACK_EN[id] || '');
+ if (!tmpl) {
+ _convLog.warn('Commander quick-start template missing', { resource_id: id, position });
+ return;
+ }
+ const applied = await _scenarioApplyAgent(config, id, target);
+ if (!applied || applied.kind === 'unavailable') {
+ _convLog.warn('Commander quick-start recipient API unavailable', { resource_id: id, position });
+ return;
+ }
+ const input = document.getElementById(inputId);
+ if (!input) {
+ _convLog.warn('Commander quick-start composer missing', { resource_id: id, position });
+ return;
+ }
+ composerSetText(input, tmpl);
+ delete input.dataset.ossTemplateDraft;
+ input.focus();
+ // Select the concrete subject (coffee machine, login page, etc.) so the
+ // user's next keystroke customizes the example immediately. Server-fed
+ // templates may still carry a real placeholder; retain the existing
+ // blocking behavior for those templates only.
+ const subject = _quickStartText(config.subjectKey, config.subjectFallback || '');
+ const editableSubject = _findQuickStartSubject(tmpl, subject);
+ const placeholder = _findQuickStartPlaceholder(tmpl);
+ if (editableSubject) {
+ delete input.dataset.commanderQuickStartPlaceholder;
+ composerSetSelection(input, editableSubject.start, editableSubject.end);
+ } else if (placeholder) {
+ input.dataset.commanderQuickStartPlaceholder = placeholder.text;
+ composerSetSelection(input, placeholder.start, placeholder.end);
+ } else {
+ delete input.dataset.commanderQuickStartPlaceholder;
+ composerSetSelection(input, tmpl.length, tmpl.length);
+ }
+ try { composerNotify(input); } catch (_) {}
+ } catch (err) {
+ _convLog.warn('Commander quick-start action failed', {
+ resource_id: String(id || ''),
+ error_type: err && typeof err === 'object' ? 'Error' : typeof err,
+ });
+ }
+}
+
function _initEmptyStateScenarios() {
const row = document.getElementById('new-chat-scenarios');
if (!row) return;
- _bindCommanderTemplateAttributionReset(document.getElementById('new-chat-input'));
+ _bindQuickStartPlaceholderReset(document.getElementById('new-chat-input'));
const grid = document.getElementById('new-chat-scenario-grid');
if (grid && !grid.children.length) _renderQuickStartScenarios();
_bindEmptyStateScenarioButtons(row);
@@ -2981,11 +2860,14 @@ function onEnterConversationView() {
const mountedPendingState = currentCid ? pendingConvs.get(currentCid) : null;
if (mountedPendingState?.loadingEl?.isConnected) {
if (_offViewLiveDisplayDirty.has(currentCid)) {
- void loadConversationHistory(currentCid, { preserveScroll: true });
+ _refreshVisibleConversationDisplay(currentCid);
} else {
_replayOffViewGroupProcessEvents(currentCid, mountedPendingState.loadingEl, { archive: true });
}
}
+ if (currentCid && document.getElementById('chat-history')?._conversationDisplayCid === currentCid) {
+ _refreshVisibleConversationDisplay(currentCid);
+ }
// Returning to a conversation while its original send-stream is still
// alive can miss state/process events that fired while another view was
// active (the cross-cid guard intentionally drops them). Ask main for the
@@ -3067,6 +2949,42 @@ const _conversationInfoFileRefreshTimers = new Map(); // cid → timeout id
const _offViewLiveDisplayDirty = new Set();
const _offViewGroupProcessEvents = new Map(); // cid → bounded non-delta process events
const _MAX_OFF_VIEW_GROUP_PROCESS_EVENTS = 300;
+let _conversationWindowActive = true;
+// A full (cold or anchored) history load whose response arrived while the
+// transcript was not visible. Recovery replays it as itself: the refresh-mode
+// reload keeps mounted rows, so it would leave this load without its paging
+// rows and its search or quote target. Only the current task's load defers.
+let _deferredHistoryLoad = null; // { cid, opts }
+
+function _isConversationDisplayVisible(cid) {
+ return cid === currentCid
+ && (typeof currentView === 'undefined' || currentView === 'conversation')
+ && _conversationWindowActive
+ && document.visibilityState !== 'hidden';
+}
+
+function _suspendConversationDisplay() {
+ if (!currentCid || (typeof currentView !== 'undefined' && currentView !== 'conversation')) return;
+ _offViewLiveDisplayDirty.add(currentCid);
+ const history = document.getElementById('chat-history');
+ for (const row of history?.querySelectorAll('.chat-message.assistant') || []) _cancelPendingStreamRaf(row);
+}
+
+function _onConversationWindowVisibility(payload) {
+ if (typeof payload?.active !== 'boolean') return;
+ _conversationWindowActive = payload.active;
+ if (!payload.active) _suspendConversationDisplay();
+ else _refreshVisibleConversationDisplay(currentCid);
+}
+
+// Execution and persistence belong to main. Hidden transcripts retain only a
+// dirty marker; the existing history/live snapshot supplies their full state.
+function _refreshVisibleConversationDisplay(cid) {
+ const deferred = _deferredHistoryLoad?.cid === cid ? _deferredHistoryLoad.opts : null;
+ if (!_isConversationDisplayVisible(cid) || (!deferred && !_offViewLiveDisplayDirty.has(cid))) return;
+ if (_conversationHistoryLoad?.cid === cid) return;
+ void loadConversationHistory(cid, deferred || { preserveScroll: true, refreshDisplay: true });
+}
function _isReplayableOffViewGroupProcessEvent(ev) {
if (!ev || ev.type !== 'event' || ev.event?.stream !== 'group') return false;
@@ -3079,6 +2997,7 @@ function _isReplayableOffViewGroupProcessEvent(ev) {
}
return processData?.type === 'event'
|| processData?.type === 'progress'
+ || processData?.type === 'native-message-finalized'
|| processData?.type === 'commentary-finalized';
}
@@ -3440,7 +3359,9 @@ function _bindChatHeaderActions() {
}
if (titleInput && titleInput.dataset.bound !== '1') {
titleInput.dataset.bound = '1';
- if (typeof window.bindNameLimitControl === 'function') window.bindNameLimitControl(titleInput);
+ if (typeof window.bindNameLimitControl === 'function') {
+ window.bindNameLimitControl(titleInput, _CONVERSATION_TITLE_MAX_UNITS);
+ }
let committing = false;
const commit = async (accept) => {
if (committing) return;
@@ -3586,14 +3507,10 @@ function _applyRecipientPrefixWithSnapshot(raw, snapshot, target = 'conversation
const text = String(raw || '');
const snap = _normaliseRecipientSnapshot(snapshot);
if (!snap) return raw;
- // Freeze the unaddressed first instruction's owner at send time. A leading
- // mention already names its owner and must replace the default.
- if (_textCarriesRoutingMention(text, target)) {
- if (!_composerHasUnaddressedInstruction(text, target)) return text;
- const owner = snap.defaultRecipient || _COMMANDER;
- const name = owner.kind === 'agent' ? _recipientPrefixName(owner) : 'commander';
- return '@' + name + (/^\s*>/.test(text) ? '\n' : ' ') + text;
- }
+ // A message carrying routing mentions already names who it involves; the
+ // main process routes it (D29). Prose before a mention no longer gets a
+ // default owner injected.
+ if (_textCarriesRoutingMention(text, target)) return text;
if (snap.preserveFloorSource && !snap.resetFloor) {
const current = _activeRecipient('conversation');
if (snap.kind === current.kind && snap.id === current.id) return text;
@@ -3635,28 +3552,16 @@ if (typeof window !== 'undefined') {
clearTimeout(previewTimer);
previewTimer = setTimeout(() => {
_syncComposerRecipientInput(tg);
- _updateComposerSeqToggle(tg);
}, 180);
});
}
- for (const [tg, btnId] of _COMPOSER_SEQ_TOGGLES) {
- const seqBtn = document.getElementById(btnId);
- if (!seqBtn || seqBtn.dataset.seqWired) continue;
- seqBtn.dataset.seqWired = '1';
- seqBtn.addEventListener('click', () => {
- const mode = _composerEffectiveDispatchMode(tg);
- if (!mode) return;
- _composerDispatchOverride.set(tg, mode === 'parallel' ? 'serial' : 'parallel');
- _updateComposerSeqToggle(tg);
- });
- }
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initChip, { once: true });
} else {
initChip();
}
- window.addEventListener('i18n-change', () => { _renderRecipientChip(); _renderQuotePreview(); _updateComposerSeqToggle(); });
+ window.addEventListener('i18n-change', () => { _renderRecipientChip(); _renderQuotePreview(); _refreshChatHeader(); });
}
// ─── Group-chat translation layer ─────────────────────────────────────────
@@ -3714,7 +3619,7 @@ function _actorLinkAttrs(fromId) {
: '';
}
-async function _openActorAgentDetail(actorId, opts = {}) {
+async function _openActorAgentDetail(actorId) {
const aid = String(actorId || '').trim();
if (!_isActorDetailTarget(aid)) return;
const returnTarget = (typeof _captureAgentDetailReturnTarget === 'function')
@@ -4036,6 +3941,18 @@ function _messageDisplayProjection(message) {
return { contentHtml, isHtmlSnippet, displayContent };
}
+// The bus publishes turn_end on the live envelope, while older durable records
+// retain the host's runtime end receipt instead. Neither streamed answer text
+// nor a segment_end receipt proves that the actor's whole turn has settled.
+function _isTerminalGroupHistoryRecord(gm) {
+ if (!gm || !(gm.id || gm._msg_id) || gm.from === 'user' || gm._from === 'user' || gm.dispatch) return false;
+ if (gm.turn_end === true || gm._turn_end === true) return true;
+ return Array.isArray(gm.process) && gm.process.some((item) => {
+ const evt = item?.type === 'event' || item?.type === 'progress' ? item.event : null;
+ return evt?.stream === 'runtime' && evt.data?.phase === 'end';
+ });
+}
+
function _groupMsgToLegacy(gm) {
if (!gm || typeof gm !== 'object') return gm;
if (gm.role !== undefined) return gm; // already legacy shape
@@ -4044,7 +3961,7 @@ function _groupMsgToLegacy(gm) {
// Prepend a "from-name" header so user can tell who sent each message.
// Skip for `user` (their own messages) and `commander` (default reply
// source — labeling every commander msg is noise; UI accent color tells).
- let body = String(gm.text || '');
+ let body = gm.display_phase === 'commentary' ? '' : String(gm.text || '');
let label = '';
if (fromId !== 'user' && fromId !== 'commander') {
label = _groupActorLabel(fromId) || fromId;
@@ -4052,6 +3969,7 @@ function _groupMsgToLegacy(gm) {
const out = {
role,
content: body,
+ ...(gm.display_phase ? { display_phase: gm.display_phase } : {}),
...(fromId === 'user' && typeof gm.display_text === 'string' ? { display_text: gm.display_text } : {}),
time: gm.ts || new Date().toISOString(),
_from: fromId,
@@ -4068,13 +3986,16 @@ function _groupMsgToLegacy(gm) {
...(gm.cli_answer ? { cli_answer: gm.cli_answer } : {}),
...(_normalizeCreatedAgents(gm) ? { created_agents: _normalizeCreatedAgents(gm) } : {}),
...(_normalizeCreatedSkills(gm) ? { created_skills: _normalizeCreatedSkills(gm) } : {}),
+ ...(Array.isArray(gm.saved_tasks) && gm.saved_tasks.length ? { saved_tasks: gm.saved_tasks } : {}),
...(Array.isArray(gm.artifacts) && gm.artifacts.length ? { artifacts: gm.artifacts } : {}),
...(Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length ? { marketplace_requests: gm.marketplace_requests } : {}),
...(Array.isArray(gm.app_nav_requests) && gm.app_nav_requests.length ? { app_nav_requests: gm.app_nav_requests } : {}),
...(gm.plan_announcement ? { _plan_announcement: true } : {}),
...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),
+ ...(Array.isArray(gm.process_parts) && gm.process_parts.length ? { process_parts: gm.process_parts } : {}),
...(Array.isArray(gm._narration) && gm._narration.length ? { _narration: gm._narration } : {}),
...(gm.turn_id ? { _turn_id: gm.turn_id } : {}),
+ ...(_isTerminalGroupHistoryRecord(gm) ? { _turn_end: true } : {}),
...(gm.failure_kind ? { failure_kind: gm.failure_kind } : {}),
...(gm.failure_code ? { failure_code: gm.failure_code } : {}),
...(_groupMessageSystemKind(gm) ? { _system_kind: _groupMessageSystemKind(gm) } : {}),
@@ -4091,6 +4012,7 @@ function _syncRenderedGroupMessageIdentity(el, message) {
if (from && !el.dataset.fromActor) el.dataset.fromActor = String(from);
const turnId = message.turn_id || message.turnId || message._turn_id;
if (turnId && !el.dataset.turnId) el.dataset.turnId = String(turnId);
+ _stampTurnEndRow(el, { turn_id: turnId }, _isTerminalGroupHistoryRecord(message));
const systemKind = message.system_kind || message._system_kind;
if (systemKind && !el.dataset.systemKind) el.dataset.systemKind = String(systemKind);
const failureKind = message.failure_kind || message._failure_kind;
@@ -5351,11 +5273,71 @@ function _hydrateMessageCreatedAgentChip(msgDiv) {
if (!aid) return;
// Reuse the actor-detail boundary so a stale created-agent chip gets the
// same explicit not-found/network feedback as a stale sender link.
- await _openActorAgentDetail(aid, { trackClick: false });
+ await _openActorAgentDetail(aid);
});
}
}
+// Task links come from successful host mutations, never from reply-text parsing.
+// Reuse the resource footer and the existing lazy-loaded navigation owners.
+function _refreshSavedTaskChipLabel(button) {
+ const name = button.dataset.savedTaskTitle || '';
+ const page = t(button.dataset.savedTaskKind === 'automation' ? 'sidebar.auto' : 'project.todo.title');
+ button.title = name || page;
+ const label = button.querySelector('.chat-msg-created-agent-label');
+ if (label) label.textContent = t('chat.app_nav_open', { name: page }) + (name ? ` · ${name}` : '');
+}
+
+window.addEventListener('i18n-change', () => {
+ document.querySelectorAll('[data-saved-task-key]').forEach(_refreshSavedTaskChipLabel);
+});
+
+function _mountSavedTaskChips(msg, tasks) {
+ const bubble = msg?.querySelector('.chat-bubble');
+ if (!bubble || !Array.isArray(tasks)) return;
+ for (const task of tasks.slice(0, 100)) {
+ if (!task || !['automation', 'todo'].includes(task.kind)
+ || typeof task.task_id !== 'string' || !task.task_id) continue;
+ const pid = typeof task.project_id === 'string' ? task.project_id : '';
+ const key = JSON.stringify([task.kind, pid, task.task_id]);
+ if (bubble.querySelector(`[data-saved-task-key="${CSS.escape(key)}"]`)) continue;
+ let row = bubble.querySelector('.chat-msg-created-agent[data-saved-tasks]');
+ if (!row) {
+ row = document.createElement('div');
+ row.className = 'chat-msg-created-agent';
+ row.dataset.savedTasks = '1';
+ bubble.appendChild(row);
+ }
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'btn btn-sm chat-msg-created-agent-chip';
+ button.dataset.savedTaskKey = key;
+ const name = typeof task.title === 'string' ? task.title.slice(0, 160) : '';
+ button.dataset.savedTaskKind = task.kind;
+ button.dataset.savedTaskTitle = name;
+ button.innerHTML = `<span class="chat-app-nav-btn-page-icon" aria-hidden="true">${_uiIconHtml(task.kind === 'automation' ? 'clock' : 'clipboard-list', 'ui-icon chat-app-nav-btn-page-icon-svg')}</span><span class="chat-msg-created-agent-label"></span>`;
+ _refreshSavedTaskChipLabel(button);
+ button.addEventListener('click', async () => {
+ if (button.disabled) return;
+ button.disabled = true;
+ try {
+ if (task.kind === 'automation') {
+ await _APP_NAV_SURFACES.auto.open({ action: 'configure', target_id: task.task_id });
+ } else {
+ await _appNavLoadFeature('project', () => {
+ if (typeof focusTodo !== 'function') return false;
+ focusTodo(pid, task.task_id);
+ return true;
+ });
+ }
+ } catch (error) {
+ _appNavReportFailure(task.kind === 'automation' ? 'auto' : 'todos', 'open', error);
+ } finally { button.disabled = false; }
+ });
+ row.appendChild(button);
+ }
+}
+
// Skill mirror of the agent chip. Commander writes only custom skills,
// so the chip always opens the custom-source detail view.
function _renderMessageCreatedSkillHtml(list) {
@@ -5604,30 +5586,53 @@ function _startupConversationParams() {
const params = new URLSearchParams({ mode: 'startup' });
if (activeCid) params.set('active_cid', activeCid);
if (expanded.length) params.set('expanded_projects', expanded.join(','));
- // Local day start: the Today section aggregates every task active today,
- // including rows under collapsed projects that the page slices would omit.
- const dayStart = new Date();
- dayStart.setHours(0, 0, 0, 0);
- params.set('active_since', dayStart.toISOString());
+ // Local start of yesterday: the Recent Tasks section aggregates every task
+ // active today or yesterday, including rows under collapsed projects that the
+ // page slices would omit.
+ const shared = typeof recentConversationsSince === 'function' ? recentConversationsSince(new Date()) : null;
+ const since = shared && typeof shared.toISOString === 'function'
+ ? shared
+ : (() => { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - 1); return d; })();
+ params.set('active_since', since.toISOString());
return params.toString();
}
function _replaceConversationSlice(rows, shouldReplace) {
- const incoming = Array.isArray(rows) ? rows : [];
- const keep = (Array.isArray(conversations) ? conversations : []).filter((c) => !shouldReplace(c));
- conversations = keep.concat(incoming);
+ conversations = (Array.isArray(conversations) ? conversations : []).filter((c) => !shouldReplace(c));
+ _appendConversationSlice(rows);
}
-function _appendConversationSlice(rows) {
+function _appendConversationSlice(rows, { creationReceipt = false, optimisticTitle } = {}) {
const byCid = new Map((Array.isArray(conversations) ? conversations : [])
.filter((c) => c && c.conversation_id)
.map((c) => [c.conversation_id, c]));
for (const row of Array.isArray(rows) ? rows : []) {
- if (row && row.conversation_id) byCid.set(row.conversation_id, row);
+ if (!row || !row.conversation_id) continue;
+ if (!creationReceipt) {
+ byCid.set(row.conversation_id, row);
+ continue;
+ }
+ const existing = byCid.get(row.conversation_id);
+ // Creation is the earliest snapshot even when later mutations share its
+ // second-resolution timestamp. It must not reset cached participants/state.
+ const merged = { ...row, ...existing };
+ const cachedTime = Date.parse(existing?.updated_at || existing?.created_at || '');
+ const receiptTime = Date.parse(row.updated_at || row.created_at || '');
+ if (optimisticTitle && !existing?.title_manually_set
+ && (!existing || cachedTime <= receiptTime)) merged.title = optimisticTitle;
+ byCid.set(row.conversation_id, merged);
}
conversations = Array.from(byCid.values());
}
+// A creation receipt acknowledges persistence, not absence from this cache:
+// a concurrent list read may already have observed the conversation and its
+// later activity. Merge at the cache boundary before any sidebar is painted.
+function _cacheCreatedConversation(conversation, optimisticTitle) {
+ if (!conversation || !conversation.conversation_id) return;
+ _appendConversationSlice([conversation], { creationReceipt: true, optimisticTitle });
+}
+
function _projectConversationPageInfo(projectId) {
return _conversationProjectPages.get(String(projectId || '')) || null;
}
@@ -5660,7 +5665,7 @@ async function loadConversations(options = {}) {
const res = await apiFetch(url);
const data = await res.json();
if (data.ok) {
- conversations = data.conversations || [];
+ _replaceConversationSlice(data.conversations, () => true);
_loadedConversationProjectIds.clear();
_conversationProjectPages.clear();
if (startup) {
@@ -5913,17 +5918,20 @@ function _convRowStatus(c) {
const raw = c && typeof c.status === 'string' ? c.status : '';
return _CONV_ROW_STATUSES.includes(raw) ? raw : 'idle';
}
-function _convRowStatusLabel(status) {
+function _convRowStatusKey(status) {
// `failed` is a conversation-level state with its own copy; the task-vocab
// states reuse the To-do status strings.
- const key = status === 'failed' ? 'chat.status.failed_short' : `project.todo.status_${status}`;
+ return status === 'failed' ? 'chat.status.failed_short' : `project.todo.status_${status}`;
+}
+function _convRowStatusLabel(status) {
+ const key = _convRowStatusKey(status);
const label = t(key);
return (label && label !== key) ? label : status;
}
function _convRowStatusHtml(c) {
const status = _convRowStatus(c);
const label = _CONV_ROW_LABEL_STATUSES.has(status)
- ? `<span class="conv-item-status-label is-${status}">${escapeHtml(_convRowStatusLabel(status))}</span>`
+ ? `<span class="conv-item-status-label is-${status}" data-i18n="${escapeHtml(_convRowStatusKey(status))}">${escapeHtml(_convRowStatusLabel(status))}</span>`
: '';
return { dot: '', label };
}
@@ -5956,6 +5964,7 @@ function _repaintConvRowStatus(cid, snapshot) {
else row.appendChild(label);
}
label.className = `conv-item-status-label is-${status}`;
+ label.dataset.i18n = _convRowStatusKey(status);
label.textContent = _convRowStatusLabel(status);
} else if (label) {
label.remove();
@@ -6056,7 +6065,9 @@ function _renderConversationSidebarItem(c, opts = {}) {
function _normaliseConversationTitle(raw) {
let title = String(raw || '').trim();
- if (typeof window.limitNameDisplayText === 'function') title = window.limitNameDisplayText(title);
+ if (typeof window.limitNameDisplayText === 'function') {
+ title = window.limitNameDisplayText(title, _CONVERSATION_TITLE_MAX_UNITS);
+ }
return title;
}
@@ -6175,6 +6186,8 @@ async function _saveConversationTitle(cid, raw, opts = {}) {
_refreshChatHeader();
if (typeof renderProjectsSection === 'function') renderProjectsSection();
if (typeof _renderProjectAllTasks === 'function') _renderProjectAllTasks();
+ // The home lists unopened finished tasks by title.
+ if (typeof homeRefresh === 'function') homeRefresh();
if (window.ConversationInfo && typeof window.ConversationInfo.refresh === 'function') {
window.ConversationInfo.refresh(cid, { silent: true });
}
@@ -6441,7 +6454,9 @@ function _bindConversationSidebarItems(container, opts = {}) {
container.querySelectorAll('input.conv-item-title-input').forEach((input) => {
if (input.dataset.renameBound === '1') return;
input.dataset.renameBound = '1';
- if (typeof window.bindNameLimitControl === 'function') window.bindNameLimitControl(input);
+ if (typeof window.bindNameLimitControl === 'function') {
+ window.bindNameLimitControl(input, _CONVERSATION_TITLE_MAX_UNITS);
+ }
const cid = input.dataset.convRenameCid;
const original = _conversationInlineRenameCid === cid
? _conversationInlineRenameOriginal
@@ -6805,14 +6820,23 @@ function _setEarlierHistoryLoaderState(row, state, error = '') {
row.textContent = '';
}
+// Loader rows are created and removed only by _setLoadEarlierHistory and
+// _setLoadNewerHistory, which keep a reference on the container, so per-event
+// scroll and wheel handling never searches the transcript for them. A rebuilt
+// transcript detaches the rows, and contains() rejects the stale reference.
+function _historyLoaderRow(container, key) {
+ const row = container?.[key];
+ return row && container.contains(row) ? row : null;
+}
+
function _maybeAutoLoadEarlierHistory(container, userGesture = false) {
if (!container || Number(container.scrollTop || 0) > HISTORY_AUTO_LOAD_THRESHOLD) {
- const row = container?.querySelector?.('.chat-history-load-earlier');
+ const row = _historyLoaderRow(container, '_historyEarlierRow');
if (row?.dataset.state === 'error') _setEarlierHistoryLoaderState(row, 'idle');
return;
}
if (!userGesture && _isProgrammaticStickyScroll(container)) return;
- const row = container.querySelector('.chat-history-load-earlier');
+ const row = _historyLoaderRow(container, '_historyEarlierRow');
if (!row || row.dataset.state === 'loading' || row.dataset.state === 'error') return;
const cursor = _historyNextCursor(row.dataset.cursor);
const cid = String(row.dataset.cid || '');
@@ -6842,6 +6866,7 @@ function _setLoadNewerHistory(container, cid, nextCursor, boundaryTime = Infinit
let row = container.querySelector('.chat-history-load-newer');
if (cursor === null) {
row?.remove();
+ container._historyNewerRow = null;
return;
}
if (!row) {
@@ -6852,6 +6877,7 @@ function _setLoadNewerHistory(container, cid, nextCursor, boundaryTime = Infinit
container.insertBefore(row, later || null);
row.addEventListener('click', () => void _loadNewerConversationHistory(cid));
}
+ container._historyNewerRow = row;
row.dataset.cursor = String(cursor);
row.dataset.cid = cid;
row.dataset.state = 'idle';
@@ -6862,7 +6888,7 @@ function _setLoadNewerHistory(container, cid, nextCursor, boundaryTime = Infinit
function _maybeAutoLoadNewerHistory(container, userGesture = false) {
if (!userGesture && _isProgrammaticStickyScroll(container)) return;
- const row = container.querySelector('.chat-history-load-newer');
+ const row = _historyLoaderRow(container, '_historyNewerRow');
if (!row || row.dataset.state !== 'idle') return;
const rect = row.getBoundingClientRect();
const bounds = container.getBoundingClientRect();
@@ -6943,8 +6969,8 @@ async function _loadNewerConversationHistory(cid) {
}
// A forward page can continue a native turn whose earlier segments are already
-// painted. Move those rendered blocks, including their formula nodes, into the
-// final row rather than rendering the earlier content again.
+// painted. Join its earlier text and tool history into the final row's shared
+// process disclosure; the newest message remains the only answer body.
function _joinNewerHistoryTurn(container, added) {
const actor = added.dataset.fromActor;
const turn = added.dataset.turnId;
@@ -6953,35 +6979,21 @@ function _joinNewerHistoryTurn(container, added) {
row !== added && row.dataset.turnId === turn && row.dataset.fromActor === actor
&& row.dataset.msgId && _rowSegmentIndex(row) < _rowSegmentIndex(added));
if (!prior) return;
- const previousBounds = prior.getBoundingClientRect();
- const viewportBounds = container.getBoundingClientRect();
- const wasVisible = previousBounds.bottom > viewportBounds.top && previousBounds.top < viewportBounds.bottom;
const bubble = added.querySelector('.chat-bubble');
const oldBubble = prior.querySelector('.chat-bubble');
if (!bubble || !oldBubble) return;
- const anchor = bubble.querySelector('.chat-turn-narration, .markdown-body');
- for (const block of oldBubble.querySelectorAll(':scope > .chat-turn-narration')) bubble.insertBefore(block, anchor);
- const body = oldBubble.querySelector(':scope > .markdown-body');
- const narration = [...(prior._narration || [])];
- if (body) {
- const block = document.createElement('div');
- block.className = 'chat-turn-narration';
- block.dataset.narrationSeg = String(_rowSegmentIndex(prior));
- block.appendChild(body);
- bubble.insertBefore(block, anchor);
- narration.push({ seg: _rowSegmentIndex(prior), text: prior._historyLegacyMessage?.content || body.textContent });
- }
- added._narration = narration.concat(added._narration || []);
- const process = [...(prior._persistedProcessItems || []), ...(added._persistedProcessItems || [])];
- if (process.length) {
- const expanded = prior.querySelector('.stream-process')?.open === true;
- added.querySelector('.stream-process')?.remove();
- _renderPersistedProcess(added, process, { expanded });
- }
- // Loading the continuation must not suddenly fold the answer being read.
- // An explicit fold choice still takes precedence inside _applyNarrationFold.
- added.dataset.narrationExpanded = wasVisible ? '1' : prior.dataset.narrationExpanded || '0';
- _applyNarrationFold(added);
+ const previousText = prior._historyLegacyMessage?.content
+ || oldBubble.querySelector(':scope > .markdown-body')?.textContent || '';
+ const commentary = _nativeSegmentCommentary({ text: previousText,
+ display_phase: prior._historyLegacyMessage?.display_phase });
+ added._narration = [...(prior._narration || []),
+ { seg: _rowSegmentIndex(prior), text: previousText }, ...(added._narration || [])];
+ const process = [...(prior._persistedProcessItems || []), ...commentary, ...(added._persistedProcessItems || [])];
+ const processParts = [...(prior._persistedProcessParts || [{ items: prior._persistedProcessItems || [] }]),
+ { items: commentary }, ...(added._persistedProcessParts || [{ items: added._persistedProcessItems || [] }])];
+ const expanded = prior.querySelector('.stream-process')?.open === true;
+ added.querySelector('.stream-process')?.remove();
+ _renderPersistedProcess(added, process, { expanded, parts: processParts });
prior.replaceWith(added);
}
@@ -7005,6 +7017,7 @@ function _setLoadEarlierHistory(container, cid, nextCursor) {
const cursor = _historyNextCursor(nextCursor);
if (cursor === null) {
if (existing) existing.remove();
+ container._historyEarlierRow = null;
return;
}
const row = existing || document.createElement('div');
@@ -7015,6 +7028,7 @@ function _setLoadEarlierHistory(container, cid, nextCursor) {
row.dataset.cursor = String(cursor);
_setEarlierHistoryLoaderState(row, 'idle');
if (!existing) container.insertBefore(row, container.firstChild);
+ container._historyEarlierRow = row;
_bindAutoLoadEarlierHistory(container);
}
@@ -7175,7 +7189,12 @@ function _revealConversationHistorySearchTarget(cid, target = {}) {
const container = document.getElementById('chat-history');
if (!container) return false;
const message = _findConversationHistorySearchTarget(container, target);
- if (!message) return false;
+ if (!message) {
+ // The mounted transcript was searched and the target is not in it. A
+ // quoted reference reports its missing original; search hits stay silent.
+ if (typeof target.onMiss === 'function') target.onMiss();
+ return false;
+ }
_flashConversationHistorySearchTarget(message);
return true;
}
@@ -7287,18 +7306,27 @@ function _restoreLiveDisplaySnapshot(cid, snapshot) {
}
_absorbedTurnSegments.delete(`${cid}|${turn.turn_id}`);
if (row) {
+ // Repainting a recovered body is frame-deferred (and math is prepared
+ // offscreen). Keep the same segment readable until that paint commits,
+ // including its parser cache and mounted math/media nodes. Empty bodies
+ // and segment changes must still retire the previous segment's text.
+ const keepBody = _rowSegmentIndex(row) === Number(current.seg) && !!current.text;
_stampRenderKey(row, cid, _segmentRenderKey(turn.turn_id, current.seg));
row.querySelector('[data-role="process"]')?.replaceChildren();
const final = row.querySelector('[data-role="final"]');
- if (final) { final.textContent = ''; if (final.style) final.style.display = 'none'; }
- for (const block of row.querySelectorAll('.chat-turn-narration')) block.remove();
+ if (final && !keepBody) {
+ final.textContent = '';
+ if (final.style) final.style.display = 'none';
+ delete row.dataset.streamPaintedDisplay;
+ }
+ row._nativeProcessBoundary = null;
row._narration = [];
row._commentaryLine = null;
row._commentaryBuf = '';
delete row._processDisplayContext;
delete row._reasoningSummaryById;
- for (const key of ['narrationSegs', 'streamBuf', 'finalText', 'streamDisplay',
- 'streamPaintedDisplay', 'streamPhase', 'commentaryFinalized', 'commentaryStreamed']) delete row.dataset[key];
+ for (const key of ['narrationSegs', 'nativeClassifiedSeg', 'streamBuf', 'finalText', 'streamDisplay',
+ 'streamPhase', 'commentaryFinalized', 'commentaryStreamed']) delete row.dataset[key];
} else {
row = _ensureActorPlaceholder(
cid, turn.actor, null, turn.turn_id, turn.msg_id, turn.started_at_ms, current.seg,
@@ -7317,14 +7345,16 @@ function _restoreLiveDisplaySnapshot(cid, snapshot) {
pending.loadingEl = row;
}
}
- if (turns.size) _liveDisplayWatermarks.set(cid, { sequence: Number(snapshot.sequence) || 0, turns });
+ if (Number.isSafeInteger(snapshot.sequence)) _liveDisplayWatermarks.set(cid, { sequence: snapshot.sequence, turns });
else _liveDisplayWatermarks.delete(cid);
_offViewLiveDisplayDirty.delete(cid);
}
function _isSnapshottedProcess(cid, event) {
const snapshot = _liveDisplayWatermarks.get(cid);
- return !!snapshot && snapshot.turns.has(event.turn_id)
+ // The sequence is conversation-wide, including turns already completed by
+ // the snapshot. Their delayed IPC events must not reopen a retired row.
+ return !!snapshot
&& Number.isSafeInteger(event.display_seq) && event.display_seq <= snapshot.sequence;
}
@@ -7342,16 +7372,17 @@ function _isCurrentHistoryLoad(load) {
function _rememberHistoryLoadMessage(cid, message, turnEnd = false) {
const load = _conversationHistoryLoad;
- if (!load || !load.collecting || load.cid !== cid || !_isCurrentHistoryLoad(load)
+ if (!load || load.cid !== cid || !_isCurrentHistoryLoad(load)
|| !message?.id || message.deleted_at || !_isVisibleGroupHistoryRecord(message)) return;
- load.messages.set(String(message.id), message);
if (turnEnd && message.turn_id) load.endedTurnIds.add(String(message.turn_id));
+ if (load.collecting) load.messages.set(String(message.id), message);
}
async function loadConversationHistory(cid, opts = {}) {
const perfStartedAt = performance.now();
const container = document.getElementById('chat-history');
if (!container || cid !== currentCid) return;
+ container._conversationDisplayCid = cid;
const previousLoad = _conversationHistoryLoad;
const load = {
cid, container, collecting: true, collectingProcess: true, painted: false,
@@ -7364,6 +7395,9 @@ async function loadConversationHistory(cid, opts = {}) {
};
_conversationHistoryLoad = load;
const preserveScroll = opts && opts.preserveScroll === true;
+ const refreshDisplay = preserveScroll && opts.refreshDisplay === true;
+ // A newer full load supersedes one deferred while the transcript was hidden.
+ if (!refreshDisplay) _deferredHistoryLoad = null;
let scrollSnapshot = preserveScroll ? _captureHistoryReloadScroll(container) : null;
// A task switch rebuilds this container. Cancel any delayed send-time pin
// before replacing its children; otherwise a queued double-rAF callback can
@@ -7442,6 +7476,13 @@ async function loadConversationHistory(cid, opts = {}) {
}
if (!data.ok) throw new Error(data.error || 'load failed');
if (cid !== currentCid) return;
+ // A foreground request can finish after the native window hides. Main
+ // retains the latest display, so defer DOM recovery until it is visible.
+ if (!_isConversationDisplayVisible(cid)) {
+ _offViewLiveDisplayDirty.add(cid);
+ if (!refreshDisplay) _deferredHistoryLoad = { cid, opts };
+ return;
+ }
// The history request is asynchronous. The user may scroll upward after
// this background reconcile starts but before its response arrives, so
// the start-of-request snapshot can already be stale. Re-capture at the
@@ -7476,7 +7517,7 @@ async function loadConversationHistory(cid, opts = {}) {
// re-adopts `state.loadingEl` (re-attached below via the
// `isConvPending` branch) for the first actor and mints fresh
// placeholders for any additional actors — no orphan window.
- _groupPlaceholders.clear();
+ if (!refreshDisplay) _groupPlaceholders.clear();
// Drop internal plan-step dispatch messages (commander → agent
// hand-off) AND redundant routing-only commander tails (the "second
// commander bubble" — read agent.json + hand_off_to, no prose). The user
@@ -7509,12 +7550,16 @@ async function loadConversationHistory(cid, opts = {}) {
indexedHistory.push(message);
window.CliAsyncInput?.observe(cid, message);
}
+ for (const message of indexedHistory) {
+ if (message?.turn_id && _isTerminalGroupHistoryRecord(message)) load.endedTurnIds.add(message.turn_id);
+ }
// The transcript is rebuilt below, so the rows now in the DOM are not the
// live rows to consult. A foldable turn the runtime still lists as active
// gets its persisted segments restored into a live row after the rebuild
// (`_restoreLiveTurnRows`) instead of settling as a history bubble the
// next segment could not join.
- const rebuildActiveTurns = _normaliseActiveTurns(convMeta.active_turns);
+ const rebuildActiveTurns = _normaliseActiveTurns(convMeta.active_turns)
+ .filter(turn => !load.endedTurnIds.has(turn.turn_id));
const rebuildProcessingFresh = convMeta.processing === true
&& convMeta.processing_since
&& (Date.now() - new Date(convMeta.processing_since).getTime()) < 15 * 60 * 1000;
@@ -7532,7 +7577,16 @@ async function loadConversationHistory(cid, opts = {}) {
// but stable-sort guards against any future writer that lands a message
// out of order so loadConversationHistory matches `_insertByTimestamp`.
.sort((a, b) => _msTs(a && a.time) - _msTs(b && b.time));
- if (!history.length) {
+ if (refreshDisplay) {
+ // Foreground recovery preserves loaded older pages, mounted cards and
+ // reading position. Only canonical arrivals and unfinished rows change.
+ _latestActiveTurns.set(cid, rebuildActiveTurns);
+ for (const message of indexedHistory) {
+ if (message?.from === 'user') _renderOrClaimPersistedUserMessage(cid, message, { autoScroll: false });
+ }
+ await _recoverPolledVisibleMessages(cid, indexedHistory);
+ if (!_isCurrentHistoryLoad(load)) return;
+ } else if (!history.length) {
container.innerHTML = `<div class="empty">${escapeHtml(t('chat.empty'))}</div>`;
} else {
container.innerHTML = '';
@@ -7554,7 +7608,7 @@ async function loadConversationHistory(cid, opts = {}) {
});
// Retain terminal identity across the DOM rebuild so a stale live
// display snapshot or deferred process event cannot reopen this turn.
- _stampTurnEndRow(row, { turn_id: msg._turn_id }, load.endedTurnIds.has(msg._turn_id));
+ _stampTurnEndRow(row, { turn_id: msg._turn_id }, msg._turn_end === true || load.endedTurnIds.has(msg._turn_id));
});
container.appendChild(historyFragment);
}
@@ -7565,10 +7619,12 @@ async function loadConversationHistory(cid, opts = {}) {
// conversation is (re)opened — the failure lives in the history message,
// not the conversation index. See `_syncFailedFromHistory`.
if (!_historyNextCursor(data.following_cursor)) _syncFailedFromHistory(cid, history);
- _setLoadEarlierHistory(container, cid, data.next_cursor);
- _setLoadNewerHistory(container, cid, data.following_cursor,
- Math.max(0, ...(data.history || []).map(message => _msTs(message.ts || message.time))));
- _setHistoryLatestAction(container, cid);
+ if (!refreshDisplay) {
+ _setLoadEarlierHistory(container, cid, data.next_cursor);
+ _setLoadNewerHistory(container, cid, data.following_cursor,
+ Math.max(0, ...(data.history || []).map(message => _msTs(message.ts || message.time))));
+ _setHistoryLatestAction(container, cid);
+ }
_bindAutoLoadEarlierHistory(container);
const searchTargetRevealed = opts.searchTarget
? _revealConversationHistorySearchTarget(cid, opts.searchTarget)
@@ -7596,6 +7652,17 @@ async function loadConversationHistory(cid, opts = {}) {
// `processing: true` from a crashed prior run is swept on boot, but we
// also belt-and-braces check the flag here so no flash occurs.
const lastMsg = history[history.length - 1];
+ // Canonical terminal messages can arrive during post-paint async work.
+ // Retire their stale runtime slots before seeding recovery placeholders.
+ if (Array.isArray(convMeta.active_turns) && load.endedTurnIds.size) {
+ const reported = _normaliseActiveTurns(convMeta.active_turns);
+ const active = reported.filter(turn => !load.endedTurnIds.has(turn.turn_id));
+ convMeta.active_turns = active;
+ if (Array.isArray(convMeta.in_flight)) convMeta.in_flight = convMeta.in_flight.filter(actor =>
+ !reported.some(turn => turn.actor === actor && load.endedTurnIds.has(turn.turn_id))
+ || active.some(turn => turn.actor === actor));
+ if (reported.length && !active.length && !convMeta.in_flight?.length) convMeta.processing = false;
+ }
// Cache the conv-bound agent's enabled state so _updateConvSendUI can
// grey out the input without a second IPC round trip. Backend stamps
// `agent_enabled` on the conversation payload (true when no agent_id).
@@ -7730,6 +7797,9 @@ function _messageRecordHasMountedSidecars(gm, el, opts = {}) {
if (gm.plan_announcement && !el.querySelector('.chat-plan-announce')) return false;
if (Array.isArray(gm.produced) && gm.produced.length && !el.querySelector('.chat-msg-produced')) return false;
if ((_normalizeCreatedAgents(gm) || _normalizeCreatedSkills(gm)) && !el.querySelector('.chat-msg-created-agent-chip')) return false;
+ if (Array.isArray(gm.saved_tasks) && gm.saved_tasks.some((task) => !el.querySelector(
+ `[data-saved-task-key="${CSS.escape(JSON.stringify([task.kind, task.project_id || '', task.task_id]))}"]`,
+ ))) return false;
if (Array.isArray(gm.artifacts) && gm.artifacts.length && !el.querySelector('.chat-artifact-host')) return false;
if (Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length && !el.querySelector('.chat-marketplace-request')) return false;
if (_processItemsHaveRenderableLine(gm.process) && !el.querySelector('.stream-process')) return false;
@@ -7747,6 +7817,12 @@ function _processItemsHaveRenderableLine(items) {
});
}
+function _processItemsHavePublicCommentary(items) {
+ return Array.isArray(items) && items.some((item) => item?.type === 'progress'
+ && String(item.text || '').trim() && item.event?.stream === 'assistant'
+ && item.event.data?.phase === 'commentary');
+}
+
async function _recoverPolledVisibleMessages(cid, rawMessages) {
if (!cid || cid !== currentCid || !Array.isArray(rawMessages)) return false;
for (const message of rawMessages) _rememberHistoryLoadMessage(cid, message);
@@ -7763,6 +7839,17 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
);
for (const gm of visible) {
if (!gm.id) continue;
+ // Terminal recovery must claim the turn's live row even if a previous
+ // segment recovery already advanced its render key past this record.
+ if (_isTerminalGroupHistoryRecord(gm)) {
+ const live = _claimRenderNodeForMessage(cid, gm);
+ if (live) {
+ _finalizeActorPlaceholder(live, _mergedTurnRecord(cid, gm), cid, true);
+ _stampTurnEndRow(live, gm, true);
+ changed = true;
+ continue;
+ }
+ }
const existing = _findRenderedGroupMessage(container, gm);
if (existing) {
if (existing.dataset.placeholder === '1' && existing.dataset.finalized !== '1') {
@@ -7791,6 +7878,7 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
const legacy = _groupMsgToLegacy(gm);
const bubble = appendChatMessage(legacy, true, { cid, archive: true });
if (bubble) bubble.dataset.fromActor = String(gm.from || '');
+ _stampTurnEndRow(bubble, gm, _isTerminalGroupHistoryRecord(gm));
changed = true;
}
if (_removeSupersededInterruptionBubbles(container) > 0) changed = true;
@@ -8648,6 +8736,7 @@ function _paintStreamingFinalMarkdown(msg, finalEl, display, { stickBottom = fal
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'visible') return;
+ _refreshVisibleConversationDisplay(currentCid);
// Cover every chat history surface (main conv + skill/agent edit chats).
const ids = ['chat-history', 'skills-chat-messages', 'agents-chat-messages'];
for (const id of ids) {
@@ -8655,6 +8744,10 @@ if (typeof document !== 'undefined') {
if (el && el._stickyEnabled !== false) _stickBottomIfPinned(el);
}
});
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') _suspendConversationDisplay();
+ });
+ window.orkas?.onPushEvent?.('conversations:window-visibility', _onConversationWindowVisibility);
}
function appendChatMessage(message, autoScroll = true, opts = {}) {
@@ -8723,6 +8816,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
const { contentHtml, isHtmlSnippet, displayContent } = _messageDisplayProjection(message);
const messageCid = opts.cid || currentCid;
+ msgDiv.dataset.billingCid = messageCid || '';
const attachmentCid = message.attachment_cid || message.attachments_cid || messageCid;
const attachmentsHtml = (role === 'user' && Array.isArray(message.attachments) && message.attachments.length)
? _renderMessageAttachmentsHtml(message.attachments, attachmentCid)
@@ -8778,6 +8872,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
if (message._client_msg_id) msgDiv.dataset.clientMsgId = String(message._client_msg_id);
if (message._from) msgDiv.dataset.fromActor = String(message._from);
if (message._turn_id) msgDiv.dataset.turnId = String(message._turn_id);
+ _stampTurnEndRow(msgDiv, { turn_id: message._turn_id }, message._turn_end === true);
if (message._system_kind) msgDiv.dataset.systemKind = String(message._system_kind);
if (message.failure_kind) msgDiv.dataset.failureKind = String(message.failure_kind);
if (message.failure_code) msgDiv.dataset.failureCode = String(message.failure_code);
@@ -8827,7 +8922,10 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
if (md) typesetMath(md);
}
if (attachmentsHtml) _hydrateMessageAttachments(msgDiv, attachmentCid);
- if (referencesHtml) _hydrateMessageReferenceFiles(msgDiv);
+ if (referencesHtml) {
+ _hydrateMessageReferenceFiles(msgDiv);
+ _hydrateMessageReferenceLocators(msgDiv);
+ }
_hydrateActorHeaderLinks(msgDiv);
if (createdAgentHtml) _hydrateMessageCreatedAgentChip(msgDiv);
if (createdSkillHtml) _hydrateMessageCreatedSkillChip(msgDiv);
@@ -8855,6 +8953,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
const bubble = msgDiv.querySelector('.chat-bubble');
if (bubble) _mountAppNavRequests(bubble, message);
}
+ if (role === 'assistant') _mountSavedTaskChips(msgDiv, message.saved_tasks);
// Interactive web-app artifacts (assistant messages only) — sandboxed
// `<iframe>` over the `chat-app://` protocol, appended after the form so it
// reads as "reply text → embedded app". See chat-artifact.js.
@@ -8894,17 +8993,20 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// for HTML-stub bodies too (e.g. CLI warning spans), otherwise after a
// refresh the only visible signal of a failed run is the red error line
// and "what happened" is gone. Persisted turns are already settled, so
- // their process trail is always a user-controlled collapsed disclosure.
- if (role === 'assistant' && Array.isArray(message.process) && message.process.length) {
- _renderPersistedProcess(msgDiv, message.process);
+ // their process trail normally starts collapsed. A commentary-only segment
+ // has no answer body, so keep its public working text visible.
+ if (role === 'assistant' && (message.process?.length || message.process_parts?.length)) {
+ _renderPersistedProcess(msgDiv, message.process || [], {
+ expanded: !message.display_phase && !String(rawContent || '').trim() && _processItemsHavePublicCommentary(message.process),
+ parts: message.process_parts,
+ });
}
// Earlier native segments of the same turn (merged by
- // `_mergeNativeSegmentRecords`) read as narration above the body.
+ // `_mergeNativeSegmentRecords`) appear inside the shared process disclosure.
if (role === 'assistant' && Array.isArray(message._narration) && message._narration.length) {
for (const item of message._narration) {
- _appendNarrationBlock(msgDiv, item.seg, item.text, { deferFold: true });
+ _appendNarrationBlock(msgDiv, item.seg, item.text, { paint: false });
}
- _applyNarrationFold(msgDiv);
}
if (autoScroll) {
@@ -9039,7 +9141,7 @@ function _mountChatInputForm(host, msgDiv, message, opts) {
: undefined;
try {
const replayResult = await sendInConversation(cid, submissionText, extra, {
- source_view: 'conversation',
+
});
if (replayResult?.started === false && replayResult?.queued !== true) {
throw new Error(t('chat.form.submit_failed'));
@@ -9408,8 +9510,9 @@ function _mountAppNavRequests(host, message) {
const pageLabel = label && label !== labelKey ? label : `Open ${name}`;
const paintTarget = (target) => {
const targetName = target && typeof target.name === 'string' ? target.name : '';
- const targetLabel = targetName ? t('chat.app_nav_configure_target', { target: targetName }) : '';
- if (!targetLabel || targetLabel === 'chat.app_nav_configure_target') return false;
+ const targetKey = surface.configureTargetKey || 'chat.app_nav_configure_target';
+ const targetLabel = targetName ? t(targetKey, { target: targetName }) : '';
+ if (!targetLabel || targetLabel === targetKey) return false;
_paintAppNavButton(btn, targetLabel, target.iconSvg || '');
return true;
};
@@ -9526,13 +9629,15 @@ async function _resolveMarketplaceInstallRequest(card, req, cid, msgId, decision
// large process rail is materialized only on first open: a collapsed details
// element does not make hundreds of hidden DOM rows useful during history
// loading.
-function _renderPersistedProcess(msgDiv, items, { expanded = false } = {}) {
+function _renderPersistedProcess(msgDiv, items, { expanded = false, parts = null } = {}) {
msgDiv._persistedProcessItems = Array.isArray(items) ? items : [];
+ msgDiv._persistedProcessParts = Array.isArray(parts) ? parts : null;
const bubble = msgDiv.querySelector('.chat-bubble');
if (!bubble) return;
const runtimeText = _processSummaryRuntimeFromItems(items);
const displayItems = _processItemsForDisplay(items);
- const hasRenderableLine = _processItemsHaveRenderableLine(displayItems);
+ const deferred = Array.isArray(parts) && parts.some(part => part.ref);
+ const hasRenderableLine = deferred || _processItemsHaveRenderableLine(displayItems);
if (!hasRenderableLine && !runtimeText) return;
const details = document.createElement('details');
details.className = 'stream-process';
@@ -9551,9 +9656,14 @@ function _renderPersistedProcess(msgDiv, items, { expanded = false } = {}) {
if (!hasRenderableLine) details.classList.add('runtime-only');
let materialized = false;
+ let loadMore = null;
+ if (deferred) {
+ loadMore = _bindPersistedProcessPages(msgDiv, details, body, parts);
+ }
const materialize = () => {
if (materialized || !hasRenderableLine) return;
materialized = true;
+ if (loadMore) { void loadMore(); return; }
const displayContext = _createProcessDisplayContext();
for (const item of displayItems) {
const itemEvent = item && item.type === 'event'
@@ -9584,6 +9694,92 @@ function _renderPersistedProcess(msgDiv, items, { expanded = false } = {}) {
bubble.insertBefore(details, bubble.firstChild);
}
+function _nativeSegmentCommentary(record) {
+ // Only unclassified records from older event producers need the legacy
+ // projection. Current storage and history-cache records already own it.
+ if (record?.display_phase) return [];
+ const text = String(record?.text || '');
+ return text.trim() ? [{ type: 'progress', text,
+ event: { stream: 'assistant', data: { phase: 'commentary' } } }] : [];
+}
+
+function _nativeSegmentProcessItems(record) {
+ return [..._nativeSegmentCommentary(record), ...(record?.process || [])];
+}
+
+function _processPartsForRecord(record, includeNativeText = false) {
+ const parts = Array.isArray(record?.process_parts) && record.process_parts.length
+ ? record.process_parts : [{ items: record?.process || [] }];
+ const leading = includeNativeText ? _nativeSegmentCommentary(record) : [];
+ if (!leading.length) return parts;
+ return [{ ...parts[0], leading_items: [...leading, ...(parts[0].leading_items || [])] }, ...parts.slice(1)];
+}
+
+/** At most one bounded page per explicit disclosure action. Keep one display
+ * context across pages so a use/result pair split at a boundary stays one row. */
+function _bindPersistedProcessPages(msgDiv, details, body, parts) {
+ const cid = currentCid;
+ const context = _createProcessDisplayContext();
+ const more = document.createElement('button');
+ more.type = 'button';
+ more.className = 'chat-process-load-more';
+ more.textContent = t('sidebar.load_more_conversations');
+ more.setAttribute('aria-busy', 'false');
+ details.appendChild(more);
+ let partIndex = 0;
+ let cursor = 0;
+ let loading = false;
+ const next = async () => {
+ if (loading || partIndex >= parts.length) return;
+ loading = true;
+ more.disabled = true;
+ more.setAttribute('aria-busy', 'true');
+ more.textContent = t('common.loading');
+ more.classList.remove('is-error');
+ try {
+ const part = parts[partIndex];
+ let pageItems;
+ let nextCursor;
+ if (part.ref) {
+ const url = `/api/conversations/${encodeURIComponent(cid)}/process?ref=${encodeURIComponent(part.ref)}`
+ + `&message_id=${encodeURIComponent(part.message_id || '')}&cursor=${cursor}`
+ + `&project_id=${encodeURIComponent(_projectIdForConversation(cid))}`;
+ const result = await (await apiFetch(url)).json();
+ if (!result?.ok || !Array.isArray(result.items)
+ || (result.next_cursor !== null && (!Number.isSafeInteger(result.next_cursor) || result.next_cursor <= cursor))) {
+ throw new Error('Process page unavailable');
+ }
+ pageItems = result.items;
+ nextCursor = result.next_cursor;
+ } else {
+ const inline = Array.isArray(part.items) ? part.items : [];
+ pageItems = inline.slice(cursor, cursor + 200);
+ nextCursor = cursor + 200 < inline.length ? cursor + 200 : null;
+ }
+ if (cid !== currentCid || details.isConnected === false) return;
+ for (const item of _processItemsForDisplay(cursor === 0 ? [...(part.leading_items || []), ...pageItems] : pageItems)) {
+ const event = item?.type === 'event' || item?.type === 'progress' ? item.event : null;
+ const projection = _projectProcessRow(event, context, item?.type === 'progress' ? item.text : '');
+ if (projection) _appendProjectedProcessRowToBody(body, projection);
+ }
+ if (nextCursor === null) { partIndex++; cursor = 0; }
+ else cursor = nextCursor;
+ more.hidden = partIndex >= parts.length;
+ more.textContent = t('sidebar.load_more_conversations');
+ } catch (_) {
+ more.classList.add('is-error');
+ more.textContent = t('chat.history_retry_newer');
+ _convLog.warn('conversation process page unavailable', { failure_stage: 'process_page' });
+ } finally {
+ loading = false;
+ more.disabled = false;
+ more.setAttribute('aria-busy', 'false');
+ }
+ };
+ more.addEventListener('click', () => { void next(); });
+ return next;
+}
+
// ─── Quote-reply (per-cid) ───────────────────────────────────────────────
// Clicking quote on assistant bubbles appends their text + chip-tracked
// produced files to a per-cid collection. The collection renders above the
@@ -9639,13 +9835,18 @@ function _quotePreviewAttribution(quote, targetCid) {
function _renderMessageReferencesHtml(references, targetCid) {
const refs = Array.isArray(references) ? references.slice(0, 20) : [];
if (!refs.length) return '';
+ const locateTitle = t('chat.reference_locate_title');
const rows = refs.map((ref) => {
const attribution = _quotePreviewAttribution(ref, targetCid);
const text = String(ref.text || '').replace(/\s+/g, ' ').trim();
- return `<div class="chat-reference-message">
- <span class="chat-reference-author">${escapeHtml(attribution)}</span>
- <span class="chat-reference-text">${escapeHtml(text)}</span>
- </div>`;
+ const inner = `<span class="chat-reference-author">${escapeHtml(attribution)}</span>
+ <span class="chat-reference-text">${escapeHtml(text)}</span>`;
+ const sourceCid = String(ref.source_cid || '');
+ const sourceMsgId = String(ref.source_msg_id || '');
+ // Only a reference that still carries its source identity can be located;
+ // legacy rows without one stay static text.
+ if (!sourceCid || !sourceMsgId) return `<div class="chat-reference-message">${inner}</div>`;
+ return `<button type="button" class="chat-reference-message is-locatable" data-source-cid="${escapeHtml(sourceCid)}" data-source-msg-id="${escapeHtml(sourceMsgId)}" title="${escapeHtml(locateTitle)}">${inner}</button>`;
}).join('');
const attachmentFiles = refs.flatMap((ref) => (Array.isArray(ref.attachments) ? ref.attachments : [])
.map((attachment) => ({
@@ -9690,6 +9891,49 @@ function _hydrateMessageReferenceFiles(msgDiv) {
});
}
+function _hydrateMessageReferenceLocators(msgDiv) {
+ msgDiv.querySelectorAll('.chat-reference-message.is-locatable[data-source-cid][data-source-msg-id]').forEach((row) => {
+ if (row.dataset.bound === '1') return;
+ row.dataset.bound = '1';
+ row.addEventListener('click', (event) => {
+ event.stopPropagation();
+ void _locateReferencedMessage({
+ source_cid: row.dataset.sourceCid || '',
+ source_msg_id: row.dataset.sourceMsgId || '',
+ });
+ });
+ });
+}
+
+function _showReferenceMissingToast() {
+ const message = t('chat.reference_locate_missing');
+ if (typeof uiToast === 'function') uiToast(message, { variant: 'warning' });
+ else if (typeof uiAlert === 'function') uiAlert(message);
+}
+
+// Clicking a quoted reference locates its original message. A same-task
+// original that is still mounted is revealed in place; otherwise the search-hit
+// path loads the page around the message id and flashes it, in this task or
+// after switching to the source task. Main reads the latest page when the id
+// is gone, and the reveal then reports the missing original.
+async function _locateReferencedMessage(ref) {
+ const sourceCid = String(ref?.source_cid || '');
+ const msgId = String(ref?.source_msg_id || '');
+ if (!sourceCid || !msgId) {
+ _showReferenceMissingToast();
+ return false;
+ }
+ const target = { msgId, onMiss: _showReferenceMissingToast };
+ if (sourceCid !== currentCid) {
+ setView('conversation', sourceCid, { historyTarget: target });
+ return true;
+ }
+ if (_revealConversationHistorySearchTarget(sourceCid, { msgId })) return true;
+ await loadConversationHistory(sourceCid, { searchTarget: target });
+ const container = sourceCid === currentCid ? document.getElementById('chat-history') : null;
+ return !!(container && _findConversationHistorySearchTarget(container, { msgId }));
+}
+
function _addQuote(cid, payload) {
if (!cid || !payload) return false;
const quotes = _quotesByCid.get(cid) || [];
@@ -9886,6 +10130,8 @@ function _attachBubbleRetryBtn(actions, msgDiv) {
if (!actions || actions.querySelector('.bubble-retry-btn')) return;
const retryBtn = document.createElement('button');
retryBtn.className = 'bubble-action-btn bubble-retry-btn';
+ retryBtn.dataset.i18nTitle = 'chat.retry_btn_title';
+ retryBtn.dataset.i18n = 'chat.retry_btn';
retryBtn.title = t('chat.retry_btn_title');
retryBtn.textContent = t('chat.retry_btn');
retryBtn.addEventListener('click', async (e) => {
@@ -9909,6 +10155,21 @@ function _attachFailedAssistantActions(msgDiv, getContent) {
archive: false,
retry: true,
});
+ const code = msgDiv.dataset.failureCode;
+ if (code === 'version_too_old'
+ && typeof window.createLocalCliUpgradeControl === 'function'
+ && !msgDiv.querySelector('.local-cli-upgrade-control') && !msgDiv._cliUpgradeLoading) {
+ const actor = msgDiv.dataset.fromActor;
+ const bubble = msgDiv.querySelector('.chat-bubble');
+ if (bubble && actor && actor !== 'user' && actor !== 'commander') {
+ msgDiv._cliUpgradeLoading = true;
+ void window.orkas.invoke('agents.get', { agent_id: actor }).then(result => {
+ const runtime = result?.agent?.runtime;
+ if (!bubble.isConnected || runtime?.kind !== 'cli' || !runtime.cli) return;
+ bubble.appendChild(window.createLocalCliUpgradeControl({ type: runtime.cli }, { chip: true }));
+ }).catch(() => {}).finally(() => { msgDiv._cliUpgradeLoading = false; });
+ }
+ }
}
function _attachInterruptedAssistantActions(msgDiv, getContent, opts) {
@@ -9949,8 +10210,6 @@ async function _selectedMessagePayloads() {
fromActor: message._from || '', attachments: JSON.stringify(message.attachments || []),
references: JSON.stringify(message.references || []), produced: JSON.stringify(message.produced || []) });
let html = _messageDisplayProjection(message).contentHtml;
- if (message._narration?.length) html = message._narration.map(item =>
- `<div class="chat-turn-narration"><div class="markdown-body">${_renderMessageMarkdown(item.text)}</div></div>`).join('') + html;
if (typeof typesetMathHtml === 'function') html = await typesetMathHtml(html);
if (message.artifacts?.length) html += message.artifacts.map(artifact =>
`<div class="chat-artifact-host">${escapeHtml(artifact.title || t('artifact.title'))}</div>`).join('');
@@ -10033,8 +10292,7 @@ async function _transferSelectedReferences(targetCid, payloads, opts = {}) {
_closeReferenceTargetPicker();
_exitMessageSelection();
if (opts.conversation) {
- conversations = (Array.isArray(conversations) ? conversations : []).filter((c) => c.conversation_id !== targetCid);
- conversations.unshift(opts.conversation);
+ _cacheCreatedConversation(opts.conversation);
renderConversationList();
}
setView('conversation', targetCid, opts.fresh ? { skipLoad: true } : undefined);
@@ -10047,16 +10305,29 @@ function _referenceTargetProject(projectId) {
return _projectsCache.find((project) => project && project.project_id === projectId) || null;
}
+function _referenceTargetProjectName(projectId) {
+ return _referenceTargetProject(projectId)?.name || t('chat.reference_area_project');
+}
+
function _referenceTargetAreaLabel(conversation) {
const projectId = conversation?.project_id || '';
- if (!projectId) return t('chat.reference_area_commander');
- return _referenceTargetProject(projectId)?.name || t('chat.reference_area_project');
+ if (!projectId) return t('chat.reference_scope_global');
+ return _referenceTargetProjectName(projectId);
}
function _referenceTargetActivity(conversation) {
return String(conversation?.last_active_at || conversation?.updated_at || conversation?.created_at || '');
}
+function _referenceTargetSubtitle(conversation) {
+ const area = _referenceTargetAreaLabel(conversation);
+ const activeMs = Date.parse(_referenceTargetActivity(conversation));
+ const when = typeof _homeRelativeTime === 'function' ? _homeRelativeTime(activeMs) : '';
+ return when ? `${area} · ${when}` : area;
+}
+
+const _REFERENCE_TARGET_PAGE_SIZE = 12;
+
function _referenceNewTaskDraftCid(projectId = '') {
return projectId ? `projchat-${projectId}` : DRAFT_CID;
}
@@ -10098,70 +10369,161 @@ async function _openReferenceTargetPicker(payloads) {
if (typeof loadProjects === 'function') loads.push(loadProjects());
const [targetConversations] = await Promise.all(loads);
_closeReferenceTargetPicker();
- const sourceProjectId = _projectIdForConversation(currentCid);
+ const projects = (Array.isArray(_projectsCache) ? _projectsCache : [])
+ .filter((project) => project && project.project_id);
+ const candidates = (Array.isArray(targetConversations) ? targetConversations : [])
+ .filter((conv) => conv && conv.conversation_id)
+ .sort((a, b) => _referenceTargetActivity(b).localeCompare(_referenceTargetActivity(a)));
+ // Scope: 'all' conversations, 'global' (no project), or one project.
+ const picker = { scope: 'all', projectId: '', limit: _REFERENCE_TARGET_PAGE_SIZE };
+ const rowHtml = (attrs, title, subtitle, badge = '') => `<button type="button" class="chat-reference-target-item" ${attrs} title="${escapeHtml(title)}">
+ <span class="chat-reference-target-main">
+ <strong>${escapeHtml(title)}</strong>
+ <small>${escapeHtml(subtitle)}</small>
+ </span>
+ ${badge}
+ <span class="chat-reference-row-arrow" aria-hidden="true">›</span>
+ </button>`;
+ const scopeButton = (scope, label, projectId = '') => `<button type="button" class="chat-reference-scope" data-reference-scope="${scope}" data-project-id="${escapeHtml(projectId)}" title="${escapeHtml(label)}" aria-pressed="false"><span>${escapeHtml(label)}</span></button>`;
const overlay = document.createElement('div');
overlay.id = 'chat-reference-target-overlay';
overlay.className = 'modal-overlay open chat-reference-target-overlay';
- overlay.innerHTML = `<div class="modal-standard chat-reference-target-modal" role="dialog" aria-modal="true" aria-labelledby="chat-reference-target-title">
+ overlay.innerHTML = `<div class="modal-standard chat-reference-target-modal" role="dialog" aria-modal="true" aria-labelledby="chat-reference-target-title" aria-describedby="chat-reference-target-footer">
<div class="modal-header chat-reference-target-header">
<h2 class="modal-title" id="chat-reference-target-title">${escapeHtml(t('chat.reference_target_title', { count: payloads.length }))}</h2>
<button type="button" class="modal-close-btn chat-reference-target-close" title="${escapeHtml(t('common.close'))}" aria-label="${escapeHtml(t('common.close'))}">${_uiIconHtml('x', 'modal-close-icon') || '×'}</button>
</div>
<div class="modal-body chat-reference-target-body">
- <button type="button" class="chat-reference-new-task" data-new-task="1">
- <span class="chat-reference-leading-plus" aria-hidden="true">${_uiIconHtml('plus')}</span>
- <span class="chat-reference-new-task-label">${escapeHtml(t('chat.reference_new_task'))}</span>
- <span class="chat-reference-row-arrow" aria-hidden="true">›</span>
- </button>
- <section class="chat-reference-existing" aria-labelledby="chat-reference-existing-title">
- <div class="chat-reference-existing-head">
- <h3 id="chat-reference-existing-title">${escapeHtml(t('chat.reference_existing_tasks'))}</h3>
- <span data-reference-list-hint>${escapeHtml(t('chat.reference_recent_tasks_hint'))}</span>
- </div>
+ <nav class="chat-reference-scopes" aria-label="${escapeHtml(t('chat.reference_scope_label'))}">
+ ${scopeButton('all', t('chat.reference_scope_all'))}
+ ${scopeButton('global', t('chat.reference_scope_global'))}
+ ${projects.length ? `<p class="chat-reference-scope-label">${escapeHtml(t('sidebar.projects'))}</p>
+ <div class="chat-reference-project-scopes">${projects.map((project) => scopeButton('project', project.name || t('chat.reference_area_project'), project.project_id)).join('')}</div>` : ''}
+ </nav>
+ <section class="chat-reference-browse" data-reference-browse aria-labelledby="chat-reference-existing-title">
+ <button type="button" class="chat-reference-new-task" data-new-task="1">
+ <span class="chat-reference-leading-plus" aria-hidden="true">${_uiIconHtml('plus')}</span>
+ <span class="chat-reference-new-task-label"></span>
+ <span class="chat-reference-row-arrow" aria-hidden="true">›</span>
+ </button>
<label class="chat-reference-target-search-wrap">
- <input type="search" class="chat-reference-target-search" placeholder="${escapeHtml(t('chat.reference_target_search'))}" />
+ <span class="chat-reference-target-search-icon" aria-hidden="true">${_uiIconHtml('search')}</span>
+ <input type="search" class="chat-reference-target-search" />
</label>
- <div class="chat-reference-target-list"></div>
+ <div class="chat-reference-existing-head">
+ <h3 id="chat-reference-existing-title"></h3>
+ <span data-reference-list-hint aria-live="polite"></span>
+ </div>
+ <div class="chat-reference-target-list" data-reference-list></div>
+ </section>
+ <section class="chat-reference-create" data-reference-create aria-labelledby="chat-reference-create-title" hidden>
+ <button type="button" class="chat-reference-create-back" data-reference-create-back>‹ ${escapeHtml(t('chat.reference_create_back'))}</button>
+ <h3 id="chat-reference-create-title">${escapeHtml(t('chat.reference_create_title'))}</h3>
+ <p>${escapeHtml(t('chat.reference_create_desc'))}</p>
+ <div class="chat-reference-target-list">
+ ${rowHtml('data-create-project-id=""', t('chat.reference_scope_global'), t('chat.reference_create_global_desc'))}
+ ${projects.map((project) => rowHtml(`data-create-project-id="${escapeHtml(project.project_id)}"`, project.name || t('chat.reference_area_project'), t('chat.reference_create_project_desc'))).join('')}
+ </div>
</section>
</div>
+ <div class="chat-reference-target-footer" id="chat-reference-target-footer">${escapeHtml(t('chat.reference_target_footer'))}</div>
</div>`;
document.body.appendChild(overlay);
- const list = overlay.querySelector('.chat-reference-target-list');
+ const browse = overlay.querySelector('[data-reference-browse]');
+ const create = overlay.querySelector('[data-reference-create]');
+ const list = overlay.querySelector('[data-reference-list]');
const search = overlay.querySelector('.chat-reference-target-search');
const hint = overlay.querySelector('[data-reference-list-hint]');
+ const newTask = overlay.querySelector('[data-new-task]');
+ const inScope = (conv) => {
+ if (picker.scope === 'global') return !conv.project_id;
+ if (picker.scope === 'project') return conv.project_id === picker.projectId;
+ return true;
+ };
const render = () => {
const needle = String(search.value || '').trim().toLowerCase();
- const matches = (Array.isArray(targetConversations) ? targetConversations : [])
- .filter((conv) => conv && conv.conversation_id)
- .filter((conv) => {
- if (!needle) return true;
- return String(conv.title || '').toLowerCase().includes(needle);
- })
- .sort((a, b) => _referenceTargetActivity(b).localeCompare(_referenceTargetActivity(a)));
- const tasks = needle ? matches.slice(0, 80) : matches.slice(0, 5);
- if (hint) hint.textContent = needle
- ? t('chat.reference_search_results_count', { count: matches.length })
- : t('chat.reference_recent_tasks_hint');
- list.innerHTML = `${tasks.map((conv) => `<button type="button" class="chat-reference-target-item" data-target-cid="${escapeHtml(conv.conversation_id)}">
- <span class="chat-reference-target-main">
- <strong>${escapeHtml(conv.title || t('chat.untitled'))}</strong>
- <small>${escapeHtml(_referenceTargetAreaLabel(conv))}</small>
- </span>
- ${conv.conversation_id === currentCid ? `<span class="chat-reference-current-task">${escapeHtml(t('chat.reference_current_task'))}</span>` : ''}
- <span class="chat-reference-row-arrow" aria-hidden="true">›</span>
- </button>`).join('')}
- ${tasks.length ? '' : `<div class="chat-reference-target-empty">${escapeHtml(t('chat.reference_no_tasks'))}</div>`}`;
- list.querySelectorAll('[data-target-cid]').forEach((item) => {
- item.addEventListener('click', () => _transferSelectedReferences(item.dataset.targetCid, payloads));
+ const matches = candidates.filter((conv) => inScope(conv)
+ && (!needle || String(conv.title || '').toLowerCase().includes(needle)));
+ const scopeName = picker.scope === 'global' ? t('chat.reference_scope_global')
+ : picker.scope === 'project' ? _referenceTargetProjectName(picker.projectId)
+ : t('chat.reference_scope_all');
+ const placeholder = picker.scope === 'all'
+ ? t('chat.reference_search_all') : t('chat.reference_search_in', { name: scopeName });
+ search.placeholder = placeholder;
+ search.setAttribute('aria-label', placeholder);
+ overlay.querySelector('#chat-reference-existing-title').textContent = scopeName;
+ overlay.querySelector('.chat-reference-new-task-label').textContent = picker.scope === 'all'
+ ? t('chat.reference_new_task')
+ : picker.scope === 'global' ? t('chat.reference_new_in_global')
+ : t('chat.reference_new_in_project', { name: scopeName });
+ hint.textContent = t(needle ? 'chat.reference_count_found' : 'chat.reference_count_all', { count: matches.length });
+ const shown = matches.slice(0, picker.limit);
+ const remaining = matches.length - shown.length;
+ list.innerHTML = `${shown.map((conv) => rowHtml(
+ `data-target-cid="${escapeHtml(conv.conversation_id)}"`,
+ conv.title || t('chat.untitled'),
+ _referenceTargetSubtitle(conv),
+ conv.conversation_id === currentCid ? `<span class="chat-reference-current-task">${escapeHtml(t('chat.reference_current_task'))}</span>` : '',
+ )).join('')}
+ ${shown.length ? '' : `<div class="chat-reference-target-empty"><strong>${escapeHtml(t(needle ? 'chat.reference_no_match' : 'chat.reference_scope_empty'))}</strong>${escapeHtml(t(needle ? 'chat.reference_no_match_hint' : 'chat.reference_scope_empty_hint'))}</div>`}
+ ${remaining > 0 ? `<button type="button" class="chat-reference-load-more" data-reference-load-more>${escapeHtml(t('chat.reference_load_more', { count: remaining }))}</button>` : ''}`;
+ overlay.querySelectorAll('[data-reference-scope]').forEach((button) => {
+ const active = button.dataset.referenceScope === picker.scope
+ && (picker.scope !== 'project' || button.dataset.projectId === picker.projectId);
+ button.setAttribute('aria-pressed', String(active));
});
};
- overlay.querySelector('[data-new-task]')?.addEventListener('click', () => {
- _stageReferencesForNewTask(payloads, sourceProjectId);
+ const showBrowse = () => {
+ create.hidden = true;
+ browse.hidden = false;
+ };
+ overlay.querySelector('.chat-reference-scopes').addEventListener('click', (event) => {
+ const button = event.target.closest('[data-reference-scope]');
+ if (!button) return;
+ picker.scope = button.dataset.referenceScope;
+ picker.projectId = button.dataset.projectId || '';
+ picker.limit = _REFERENCE_TARGET_PAGE_SIZE;
+ search.value = '';
+ showBrowse();
+ render();
+ list.scrollTop = 0;
+ });
+ list.addEventListener('click', (event) => {
+ const target = event.target.closest('[data-target-cid]');
+ if (target) {
+ _transferSelectedReferences(target.dataset.targetCid, payloads);
+ return;
+ }
+ if (!event.target.closest('[data-reference-load-more]')) return;
+ const firstNew = picker.limit;
+ picker.limit += _REFERENCE_TARGET_PAGE_SIZE;
+ render();
+ list.querySelectorAll('[data-target-cid]')[firstNew]?.focus();
+ });
+ newTask.addEventListener('click', () => {
+ if (picker.scope === 'project') return _stageReferencesForNewTask(payloads, picker.projectId);
+ if (picker.scope === 'global') return _stageReferencesForNewTask(payloads, '');
+ browse.hidden = true;
+ create.hidden = false;
+ overlay.querySelector('[data-reference-create-back]').focus();
+ });
+ overlay.querySelector('[data-reference-create-back]').addEventListener('click', () => {
+ showBrowse();
+ newTask.focus();
+ });
+ create.addEventListener('click', (event) => {
+ const target = event.target.closest('[data-create-project-id]');
+ if (target) _stageReferencesForNewTask(payloads, target.dataset.createProjectId);
});
overlay.querySelector('.chat-reference-target-close')?.addEventListener('click', _closeReferenceTargetPicker);
overlay.addEventListener('keydown', (event) => { if (event.key === 'Escape') _closeReferenceTargetPicker(); });
- search.addEventListener('input', render);
+ search.addEventListener('input', () => {
+ picker.limit = _REFERENCE_TARGET_PAGE_SIZE;
+ render();
+ list.scrollTop = 0;
+ });
render();
+ search.focus();
}
function _updateMessageSelectionToolbar() {
@@ -10364,10 +10726,10 @@ function _attachBubbleActions(msgDiv, getContent, opts = {}) {
actionsRow.appendChild(actions);
return;
}
- const quoteButton = `<button type="button" class="bubble-action-btn bubble-quote-btn" title="${escapeHtml(t('chat.quote_btn_title'))}">${escapeHtml(t('chat.quote_btn'))}</button>`;
- const secondaryActions = `<button type="button" class="bubble-action-btn bubble-copy-btn" title="${escapeHtml(t('chat.copy_btn_title'))}">${escapeHtml(t('chat.copy_btn'))}</button>
- <button type="button" class="bubble-action-btn bubble-select-btn" title="${escapeHtml(t('chat.message_select_title'))}">${escapeHtml(t('chat.message_select'))}</button>
- ${includeArchive ? `<button type="button" class="bubble-action-btn bubble-archive-btn" title="${escapeHtml(t('chat.archive_btn_title'))}">${escapeHtml(t('chat.archive_btn'))}</button>` : ''}`;
+ const quoteButton = `<button type="button" class="bubble-action-btn bubble-quote-btn" data-i18n="chat.quote_btn" data-i18n-title="chat.quote_btn_title" title="${escapeHtml(t('chat.quote_btn_title'))}">${escapeHtml(t('chat.quote_btn'))}</button>`;
+ const secondaryActions = `<button type="button" class="bubble-action-btn bubble-copy-btn" data-i18n="chat.copy_btn" data-i18n-title="chat.copy_btn_title" title="${escapeHtml(t('chat.copy_btn_title'))}">${escapeHtml(t('chat.copy_btn'))}</button>
+ <button type="button" class="bubble-action-btn bubble-select-btn" data-i18n="chat.message_select" data-i18n-title="chat.message_select_title" title="${escapeHtml(t('chat.message_select_title'))}">${escapeHtml(t('chat.message_select'))}</button>
+ ${includeArchive ? `<button type="button" class="bubble-action-btn bubble-archive-btn" data-i18n="chat.archive_btn" data-i18n-title="chat.archive_btn_title" title="${escapeHtml(t('chat.archive_btn_title'))}">${escapeHtml(t('chat.archive_btn'))}</button>` : ''}`;
actions.innerHTML = `
<span class="chat-bubble-direct-actions">${quoteButton}</span>
${secondaryActions}
@@ -10431,14 +10793,19 @@ function _attachBubbleActions(msgDiv, getContent, opts = {}) {
const text = typeof getContent === 'function' ? (getContent() || '') : '';
if (!text.trim() || copyBtn.disabled) return;
copyBtn.disabled = true;
- const orig = copyBtn.innerHTML;
try {
await navigator.clipboard.writeText(text);
+ copyBtn.dataset.i18n = 'chat.copy_done';
copyBtn.textContent = t('chat.copy_done');
} catch (err) {
+ copyBtn.dataset.i18n = 'chat.copy_failed';
copyBtn.textContent = t('chat.copy_failed');
}
- setTimeout(() => { copyBtn.innerHTML = orig; copyBtn.disabled = false; }, 1500);
+ setTimeout(() => {
+ copyBtn.dataset.i18n = 'chat.copy_btn';
+ copyBtn.textContent = t('chat.copy_btn');
+ copyBtn.disabled = false;
+ }, 1500);
});
if (!btn) {
actionsRow.appendChild(actions);
@@ -10472,7 +10839,6 @@ function _attachBubbleActions(msgDiv, getContent, opts = {}) {
});
if (!pick) return;
btn.disabled = true;
- const orig = btn.innerHTML;
try {
const data = await window.orkas.invoke('library.writeText', {
cid: currentCid,
@@ -10481,6 +10847,7 @@ function _attachBubbleActions(msgDiv, getContent, opts = {}) {
content: text,
});
if (data.ok) {
+ btn.dataset.i18n = 'chat.archive_done';
btn.textContent = t('chat.archive_done');
if (typeof uiToast === 'function') uiToast(t('chat.archive_done'), { variant: 'success' });
if (data.scope === 'global' && currentView === 'contexts' && typeof loadContexts === 'function') {
@@ -10490,18 +10857,24 @@ function _attachBubbleActions(msgDiv, getContent, opts = {}) {
loadProjectDetail(data.projectId).catch(() => {});
}
} else {
+ btn.dataset.i18n = 'chat.archive_failed';
btn.textContent = t('chat.archive_failed');
const message = t('chat.archive_failed_with_reason', { reason: data.error || t('chat.unknown_error') });
if (typeof uiToast === 'function') uiToast(message, { variant: 'error' });
else await uiAlert(message);
}
} catch (err) {
+ btn.dataset.i18n = 'chat.archive_failed';
btn.textContent = t('chat.archive_failed');
const message = t('chat.archive_failed_with_reason', { reason: err.message || err });
if (typeof uiToast === 'function') uiToast(message, { variant: 'error' });
else await uiAlert(message);
}
- setTimeout(() => { btn.innerHTML = orig; btn.disabled = false; }, 2000);
+ setTimeout(() => {
+ btn.dataset.i18n = 'chat.archive_btn';
+ btn.textContent = t('chat.archive_btn');
+ btn.disabled = false;
+ }, 2000);
});
actionsRow.appendChild(actions);
_syncBubbleReferenceActionState(msgDiv);
@@ -10569,7 +10942,7 @@ async function _retryFailedAssistantMessage(msgDiv) {
// turn finishes made a queued retry look like already-running work and
// prevented the user from deliberately queuing another attempt.
await sendInConversation(currentCid, payload.content, payload.extra, {
- source_view: 'conversation',
+
});
}
@@ -10591,14 +10964,12 @@ async function handleNewChatSubmit() {
const recipientSnapshot = _recipientSnapshotForSend('new-chat');
const raw = submittedDraft.text().trim();
const quotes = _getQuotes(DRAFT_CID).slice();
- if (!raw && !quotes.length) return;
+ if (_composerSendIsEmpty(raw, 'new-chat', quotes, _chatAttachList(DRAFT_CID))) return;
const requestText = raw || t('chat.reference_default_prompt');
let draftItems = _chatAttachList(DRAFT_CID);
const pendingUseSelections = (typeof getChatUseSelections === 'function')
? getChatUseSelections('new-chat')
: [];
- const entryAttribution = _readCommanderTemplateAttribution(input);
- const multiDispatch = _composerEffectiveDispatchMode('new-chat');
const unresolvedQuickStart = _unresolvedQuickStartPlaceholder(input);
const unresolvedOss = typeof unresolvedOssTemplatePlaceholder === 'function'
? unresolvedOssTemplatePlaceholder(input)
@@ -10646,8 +11017,7 @@ async function handleNewChatSubmit() {
content_length: content.length,
use: useSelections.map((sel) => sel.kind),
attachments: draftNames.length,
- entry_point: entryAttribution.entry_point,
- resource_id: entryAttribution.resource_id || '',
+
});
const newBtn = document.getElementById('new-chat-send-btn');
if (newBtn) newBtn.disabled = true;
@@ -10680,8 +11050,7 @@ async function handleNewChatSubmit() {
createdConversation = conv;
} catch (e) {
_convLog.warn('new chat conversation creation failed', {
- entry_point: entryAttribution.entry_point,
- resource_id: entryAttribution.resource_id || '',
+
error: e && e.message ? e.message : String(e || ''),
});
await uiAlert(t('chat.create_conv_failed_with_reason', { reason: e.message || e }));
@@ -10735,14 +11104,14 @@ async function handleNewChatSubmit() {
error_code: 'discard_empty_failed',
});
}
- await uiAlert(t('chat.attach_adopt_failed', { reason: adoptionError }));
+ await uiAlert(t('chat.attach_sync_failed'));
if (newBtn) newBtn.disabled = false;
_newChatSubmitting = false;
releaseAttachmentSend();
return;
}
if (createdConversation) {
- conversations.unshift(createdConversation);
+ _cacheCreatedConversation(createdConversation, createdConversation.title);
renderConversationList();
}
if (typeof consumeChatUseSelections === 'function') consumeChatUseSelections('new-chat');
@@ -10755,10 +11124,9 @@ async function handleNewChatSubmit() {
const ownsDraft = submittedDraft.matches();
const openCreated = ownsDraft && navigationEpoch === _composerNavigationEpoch;
if (ownsDraft) {
- _clearCommanderTemplateAttribution(input);
+ _clearQuickStartDraft(input);
composerSetText(input, '');
_draftHadRecipient.delete('new-chat');
- _updateComposerSeqToggle('new-chat');
}
_newChatSubmitting = false;
_transferNewChatRecipientTo(convId);
@@ -10777,7 +11145,6 @@ async function handleNewChatSubmit() {
...(attachments.length ? { attachments } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
...(references.length ? { references } : {}),
- ...(multiDispatch ? { multi_dispatch: multiDispatch } : {}),
};
// The initial turn uses the same abort-recovery contract as a follow-up:
// stopping must restore the user's authored text and adopted attachments.
@@ -10791,9 +11158,7 @@ async function handleNewChatSubmit() {
}
await sendInConversation(convId, content, Object.keys(extra).length ? extra : undefined, {
restoreComposerOnFailure: true,
- source_view: 'new_chat',
- content_length: requestText.length,
- ...entryAttribution,
+
});
}
@@ -10807,9 +11172,8 @@ async function handleChatSubmit() {
const authoredText = submittedDraft.text();
const raw = authoredText.trim();
if (!currentCid) return;
- // A bare quote with no extra text is a legitimate "look at this" forward;
- // only reject when both the textarea AND the quote are empty.
- if (!raw && !_getQuotes(currentCid).length) return;
+ // References and attachments carry content; routing mentions alone do not.
+ if (_composerSendIsEmpty(raw, 'conversation', _getQuotes(currentCid), _chatAttachList(currentCid))) return;
const cid = currentCid;
const quotes = _getQuotes(cid).slice();
const requestText = raw || t('chat.reference_default_prompt');
@@ -10819,6 +11183,11 @@ async function handleChatSubmit() {
let attachList = _chatAttachList(cid);
let attachments = attachList.filter((a) => a.status !== 'error').map((a) => a.name);
_convLog.info('chat submit', { cid, length: raw.length, use: useSelections.map((sel) => sel.kind), attachments: attachments.length });
+ const unresolvedQuickStart = _unresolvedQuickStartPlaceholder(input);
+ if (unresolvedQuickStart) {
+ await uiAlert(t('new_chat.quick.task_required'));
+ return;
+ }
if (!ensureModelConfigured()) {
return;
}
@@ -10831,17 +11200,14 @@ async function handleChatSubmit() {
const recipientSnapshot = _recipientSnapshotForSend('conversation');
const commanderDisplay = _commanderMentionDisplayForSend(requestText, recipientSnapshot);
const content = transformWithChatUse(_applyRecipientPrefixWithSnapshot(requestText, recipientSnapshot));
- // Single-target sends carry no cross-group ordering override.
- const multiDispatch = _composerEffectiveDispatchMode('conversation');
const pendingFloorSync = _floorSyncByCid.get(cid);
const clearSubmittedComposer = () => {
const ownsVisibleDraft = currentCid === cid && submittedDraft.matches();
if (ownsVisibleDraft) {
- _clearCommanderTemplateAttribution(input);
+ _clearQuickStartDraft(input);
composerSetText(input, '');
_draftHadRecipient.delete('conversation');
autoGrow(input, 200);
- _updateComposerSeqToggle();
}
// Navigation saves the old draft under cid; never clear a newer draft
// authored in this same composer while the send was waiting.
@@ -10885,7 +11251,6 @@ async function handleChatSubmit() {
...(attachments.length ? { attachments } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
...(references.length ? { references } : {}),
- ...(multiDispatch ? { multi_dispatch: multiDispatch } : {}),
}),
});
const data = await res.json();
@@ -10961,7 +11326,6 @@ async function handleChatSubmit() {
...(attachments.length ? { attachments } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
...(references.length ? { references } : {}),
- ...(multiDispatch ? { multi_dispatch: multiDispatch } : {}),
...commanderDisplay,
};
await sendInConversation(cid, content, Object.keys(extra).length ? extra : undefined, {
@@ -11001,12 +11365,12 @@ function _conversationMediaHandleMaterialized(payload) {
_applyMaterializedMarkdownMedia(payload, document);
}
-function _notifyAgentRunFinished(agentId, payload = {}) {
+function _notifyAgentRunFinished(agentId) {
const id = String(agentId || '');
if (!id || typeof window === 'undefined') return;
try {
window.dispatchEvent(new CustomEvent('orkas-agent-run-finished', {
- detail: { agent_id: id, ...payload },
+ detail: { agent_id: id },
}));
} catch (_) {}
}
@@ -11150,10 +11514,8 @@ function _makeConvChatController(cid, options = {}) {
async function sendInConversation(cid, content, extra, options = {}) {
if (!cid) return { started: false, aborted: false, errored: false, result: 'failure' };
- const startedAt = performance.now();
const sendOptions = options && typeof options === 'object' ? options : {};
- const entryAttribution = _normalizeCommanderTemplateAttribution(sendOptions);
- const statAgentId = String(sendOptions.agent_id || '');
+ const agentId = String(sendOptions.agent_id || '');
let doneResult = null;
let taskStarted = false;
let accepted = false;
@@ -11162,10 +11524,6 @@ async function sendInConversation(cid, content, extra, options = {}) {
accepted = true;
try { sendOptions.onAccepted?.(); } catch (_) {}
};
- const attachmentCount = Array.isArray(extra && extra.attachments) ? extra.attachments.length : 0;
- const measuredContentLength = Number.isFinite(Number(sendOptions.content_length))
- ? Math.max(0, Math.round(Number(sendOptions.content_length)))
- : String(content || '').length;
if (isConvPending(cid)) {
// Busy conversation: hand the message straight to the bus — the scheduler
// queues it as a visible, cancellable board task and the already-open
@@ -11248,24 +11606,12 @@ async function sendInConversation(cid, content, extra, options = {}) {
errored: true,
reason: 'unknown',
};
- const durationMs = Math.round(performance.now() - startedAt);
const started = terminal.started !== false && taskStarted;
const aborted = !!terminal.aborted;
const errored = !!terminal.errored || !started;
const result = aborted ? 'cancelled' : (errored ? 'failure' : 'success');
- const terminalReason = String(terminal.reason || '');
- const failureReason = started
- ? 'stream_error'
- : terminalReason === 'model_not_configured'
- ? 'model_not_configured'
- : 'stream_not_started';
- if (statAgentId) {
- _notifyAgentRunFinished(statAgentId, {
- duration_ms: durationMs,
- aborted,
- errored,
- success: !aborted && !errored,
- });
+ if (agentId) {
+ _notifyAgentRunFinished(agentId);
}
if (sendOptions.restoreComposerOnFailure && (!started || controllerResult?.accepted === false) && errored && !aborted
&& typeof _restoreSentComposerSnapshot === 'function') {
@@ -11281,13 +11627,8 @@ async function sendInConversation(cid, content, extra, options = {}) {
}
return { ...terminal, started, aborted, errored, result };
} catch (err) {
- const durationMs = Math.round(performance.now() - startedAt);
- if (statAgentId) {
- _notifyAgentRunFinished(statAgentId, {
- duration_ms: durationMs,
- errored: true,
- success: false,
- });
+ if (agentId) {
+ _notifyAgentRunFinished(agentId);
}
_convLog.warn('chat send request failed', {
cid,
@@ -11409,10 +11750,17 @@ function _nowForStreamYield() {
: Date.now();
}
-function _makeStreamPaintYield() {
+function _makeStreamPaintYield(shouldPaint = () => _conversationWindowActive && document.visibilityState !== 'hidden') {
let eventsSinceYield = 0;
let lastYieldAt = _nowForStreamYield();
return function maybeYieldToPaint() {
+ // Background timers can be throttled for seconds. Waiting on them in the
+ // reader creates an ever-growing SSE backlog even though main keeps running.
+ if (!shouldPaint()) {
+ eventsSinceYield = 0;
+ lastYieldAt = _nowForStreamYield();
+ return null;
+ }
eventsSinceYield += 1;
const now = _nowForStreamYield();
if (eventsSinceYield < 32 && now - lastYieldAt < 24) return null;
@@ -11549,7 +11897,8 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {
}
const decoder = new TextDecoder('utf-8');
let buffer = '';
- const maybeYieldToPaint = _makeStreamPaintYield();
+ const maybeYieldToPaint = _makeStreamPaintYield(() =>
+ _isConversationDisplayVisible(cid) && !_offViewLiveDisplayDirty.has(cid));
while (true) {
const { value, done } = await reader.read();
if (done) break;
@@ -12532,6 +12881,8 @@ function _setProcessSummaryState(root, state) {
function _completeProcessDisclosure(msg, { collapse = true } = {}) {
if (!msg) return null;
+ msg._nativeProcessBoundary?.remove();
+ msg._nativeProcessBoundary = null;
_sealStreamingCommentary(msg);
_streamingStopActivity(msg);
_setProcessSummaryState(msg, 'complete');
@@ -12730,6 +13081,7 @@ function _processItemsContainSuccessfulTerminalHandoff(processItems) {
// process) may still carry these whole-turn process arrays.
function _isRedundantRoutingOnlyCommanderRecord(gm) {
if (!gm || gm.from !== 'commander') return false;
+ if (_processItemsHavePublicCommentary(gm.process)) return false;
const routingOnly = _isRoutingOnlyProcessItems(gm.process);
const terminalHandoff = _processItemsContainSuccessfulTerminalHandoff(gm.process);
if (!routingOnly && !terminalHandoff) return false;
@@ -12737,6 +13089,7 @@ function _isRedundantRoutingOnlyCommanderRecord(gm) {
if (gm.form
|| (Array.isArray(gm.produced) && gm.produced.length)
|| _normalizeCreatedAgents(gm) || _normalizeCreatedSkills(gm)
+ || (Array.isArray(gm.saved_tasks) && gm.saved_tasks.length)
|| (Array.isArray(gm.artifacts) && gm.artifacts.length)
|| (Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length)) {
return false;
@@ -13047,9 +13400,34 @@ function _streamingMarkAborted(msg) {
);
}
+async function _settleFinishedConversationDisplay(cid, wasAborted) {
+ const container = document.getElementById('chat-history');
+ const unresolved = Array.from(container?.querySelectorAll?.(
+ '.chat-message[data-from-actor]:not([data-msg-id]):not([data-frozen-silent="1"])',
+ ) || []).some((row) => {
+ const body = row.querySelector('[data-role="final"]');
+ const process = row.querySelector('[data-role="process"]');
+ return (body?.textContent || '').trim() || process?.children.length;
+ });
+ if (wasAborted || !unresolved) {
+ _settleDanglingActorPlaceholders(cid, { preserveProcess: wasAborted });
+ return;
+ }
+ // Transport completion does not prove that its terminal message reached the
+ // DOM. Reconcile through durable history before retiring any readable row.
+ const recovered = await _recoverObservedConversationHistory(cid);
+ if (cid !== currentCid || document.getElementById('chat-history') !== container
+ || pendingConvs.has(cid) || isGroupConversationBusy(cid)) return;
+ // A failed read or a page without the terminal record is not permission to
+ // erase the user's streamed reply. Preserve unconfirmed content in both cases.
+ _settleDanglingActorPlaceholders(cid, { preserveProcess: true });
+ if (!recovered) _convLog.warn('stream completion has unconfirmed display content', { failure_stage: 'terminal_reconcile' });
+}
+
function _finishStreamingMsg(cid) {
_liveDisplayWatermarks.delete(cid);
- _offViewLiveDisplayDirty.delete(cid);
+ // A completed background task still needs its canonical reply displayed on
+ // return. Transport cleanup is not a transcript-reconciliation boundary.
const wasAborted = pendingConvs.get(cid)?.aborted === true;
// The turn is over: a user-initiated stop already consumed its snapshot, and
// any other ending means the message was answered. Keeping it would let a
@@ -13079,8 +13457,9 @@ function _finishStreamingMsg(cid) {
// boundary so observer/recovery completion cannot leave the artificial
// spacer behind.
_setChatScrollOffset(false, document.getElementById('chat-history'));
- _settleDanglingActorPlaceholders(cid, { preserveProcess: wasAborted });
+ const settling = _settleFinishedConversationDisplay(cid, wasAborted);
_updateConvSendUI(cid);
+ return settling;
}
}
@@ -13650,7 +14029,10 @@ function createChatController(config) {
const reader = res.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
- const maybeYieldToPaint = _makeStreamPaintYield();
+ const maybeYieldToPaint = _makeStreamPaintYield(() => {
+ const active = typeof config.isRenderTargetActive !== 'function' || config.isRenderTargetActive(id);
+ return active && _conversationWindowActive && document.visibilityState !== 'hidden' && !_offViewLiveDisplayDirty.has(id);
+ });
while (true) {
const { value, done } = await reader.read();
if (done) break;
@@ -13679,8 +14061,9 @@ function createChatController(config) {
const renderTargetActive = typeof config.isRenderTargetActive === 'function'
? config.isRenderTargetActive(id)
: id === config.getCurrentId();
- if (renderTargetActive) {
- _replayOffViewGroupProcessEvents(id, msgEl, { archive: features.archive });
+ const groupEvent = ev.type === 'event' && ev.event?.stream === 'group';
+ if (renderTargetActive || groupEvent) {
+ if (renderTargetActive) _replayOffViewGroupProcessEvents(id, msgEl, { archive: features.archive });
_handleStreamEvent(id, msgEl, ev, { archive: features.archive });
// Main-conversation sends deliberately do not paint a user
// bubble while the task is only queued. Once this controller's
@@ -13689,7 +14072,7 @@ function createChatController(config) {
// register it with turn navigation, and activate the one-shot
// scroll pin. Matching the echoed client id prevents concurrent
// controllers from claiming or pinning each other's messages.
- if (!userMsgEl) {
+ if (renderTargetActive && !userMsgEl) {
// The redundant observer can win the delivery race, so the
// current primary-stream event is not necessarily the user
// `message` event that created the bubble. Query the DOM by
@@ -14011,6 +14394,7 @@ function _phKey(cid, renderKey) { return `${cid}|${renderKey}`; }
function _stampRenderKey(el, cid, renderKey) {
if (!el || !renderKey) return;
el.dataset.renderKey = renderKey;
+ el.dataset.billingCid = cid || '';
_groupPlaceholders.set(_phKey(cid, renderKey), el);
}
@@ -14045,8 +14429,7 @@ function _findRenderNode(cid, renderKey) {
* Persistence keeps every native Claude message as its own ordered record
* (the 2026-09-14 contract: nothing guessed, nothing dropped). The transcript
* renders the turn as ONE bubble: the tool trail of every segment in one
- * process rail, the text of the earlier segments as muted narration blocks
- * above the body, and the final segment's text as the body.
+ * process rail, the text of the earlier segments inside that process rail, and the final segment's text as the body.
*
* Live, the turn's row simply advances from segment to segment: when the next
* segment opens, the body streamed so far becomes a narration block and the
@@ -14086,7 +14469,7 @@ function _liveTurnRow(cid, actorId, turnId) {
/** An older history page can end inside a turn already shown by a later page.
* Add its earlier segments to that settled row without replacing the final
* reply, its actions, timestamp or identity. State lives only with that row. */
-function _absorbEarlierTurnPage(cid, actorId, turnId, records, { expandNarration = true } = {}) {
+function _absorbEarlierTurnPage(cid, actorId, turnId, records) {
if (cid !== currentCid) return false;
const container = document.getElementById('chat-history');
if (!container) return false;
@@ -14100,13 +14483,14 @@ function _absorbEarlierTurnPage(cid, actorId, turnId, records, { expandNarration
if (!row._earlierPageSegments) {
row._earlierPageSegments = new Map();
row._laterPageProcessItems = row._persistedProcessItems || [];
+ row._laterPageProcessParts = row._persistedProcessParts || [{ items: row._laterPageProcessItems }];
}
let processChanged = false;
for (const record of records) {
const seg = Number(record.seg);
if (seg >= _rowSegmentIndex(row)) continue;
const known = row._narration?.some(item => item.seg === seg);
- _appendNarrationBlock(row, seg, String(record.text || ''), { canonical: true, deferFold: true });
+ _appendNarrationBlock(row, seg, String(record.text || ''), { canonical: true, paint: false });
if (!known) {
row._earlierPageSegments.set(seg, record);
processChanged = true;
@@ -14115,29 +14499,25 @@ function _absorbEarlierTurnPage(cid, actorId, turnId, records, { expandNarration
if (processChanged) {
const process = [...row._earlierPageSegments.values()]
.sort((a, b) => Number(a.seg) - Number(b.seg))
- .flatMap(record => Array.isArray(record.process) ? record.process : [])
+ .flatMap(_nativeSegmentProcessItems)
.concat(row._laterPageProcessItems);
const details = row.querySelector('.stream-process');
+ // History reconciliation updates content, never the reader's open/closed choice.
const expanded = details?.open === true;
details?.remove();
- _renderPersistedProcess(row, process, { expanded });
- }
- // Folding was added after this path: a folded block adds no height, so the
- // row would never leave the auto-load threshold and pages would fire back to
- // back. Reading upward is explicit intent — show what this page delivered,
- // unless the reader already chose a fold for this turn.
- // Passive late-record delivery reuses this merge without implying navigation.
- if (expandNarration && !_narrationFoldChoice.has(turnId)) row.dataset.narrationExpanded = '1';
- _applyNarrationFold(row);
+ const parts = [...row._earlierPageSegments.values()].sort((a, b) => Number(a.seg) - Number(b.seg))
+ .flatMap(record => _processPartsForRecord(record, true)).concat(row._laterPageProcessParts || []);
+ _renderPersistedProcess(row, process, { expanded, parts });
+ }
return true;
}
-/** Append one earlier segment's text as a narration block above the body.
+/** Retain one earlier segment's text as process commentary.
* One entry per segment index. The streamed copy is provisional: a renderer
* that attached or rebuilt mid-turn streamed nothing for the segment, so the
* persisted record (`canonical`) fills an empty slot or replaces a partial
* copy; a non-canonical repeat is ignored. */
-function _appendNarrationBlock(row, seg, text, { canonical = false, deferFold = false } = {}) {
+function _appendNarrationBlock(row, seg, text, { canonical = false, paint = true, before = null } = {}) {
if (!row || !row.dataset) return;
const index = Number(seg);
const body = String(text || '').trim();
@@ -14146,7 +14526,7 @@ function _appendNarrationBlock(row, seg, text, { canonical = false, deferFold =
if (entry) {
if (!canonical || entry.text === body) return;
entry.text = body;
- _paintNarrationBlock(row, index, body, { deferFold });
+ if (paint) _paintNarrationBlock(row, index, body, { before });
return;
}
const segs = String(row.dataset.narrationSegs || '').split(',').filter(Boolean);
@@ -14155,142 +14535,54 @@ function _appendNarrationBlock(row, seg, text, { canonical = false, deferFold =
row.dataset.narrationSegs = segs.join(',');
}
row._narration.push({ seg: index, text: body });
- if (body) _paintNarrationBlock(row, index, body, { deferFold });
+ if (body && paint) _paintNarrationBlock(row, index, body, { before });
}
-function _paintNarrationBlock(row, index, body, { deferFold = false } = {}) {
- const bubble = typeof row.querySelector === 'function' ? row.querySelector('.chat-bubble') : null;
- if (!bubble || typeof document.createElement !== 'function') return;
- let block = typeof bubble.querySelector === 'function'
- ? bubble.querySelector(`.chat-turn-narration[data-narration-seg="${index}"]`)
- : null;
+function _paintNarrationBlock(row, index, text, { before = null } = {}) {
+ const process = row.querySelector?.('[data-role="process"]');
+ if (!process || typeof process.appendChild !== 'function') return;
+ let block = process.querySelector?.(`.stream-process-commentary[data-native-seg="${index}"]`);
+ if (!text) { block?.remove(); return; }
if (!block) {
- if (typeof bubble.insertBefore !== 'function') return;
block = document.createElement('div');
- block.className = 'chat-turn-narration';
- if (block.dataset) block.dataset.narrationSeg = String(index);
- // Segments read in order above the body, below the process rail.
- const children = Array.from(bubble.children || []);
- const laterNarration = children.find((child) => child && child.classList
- && child.classList.contains('chat-turn-narration')
- && Number(child.dataset && child.dataset.narrationSeg) > index);
- const anchor = laterNarration
- || bubble.querySelector('[data-role="final"]')
- || children.find((child) => child && child.classList
- && !child.classList.contains('stream-process')
- && !child.classList.contains('chat-plan-announce')
- && !child.classList.contains('chat-turn-narration'));
- if (anchor) bubble.insertBefore(block, anchor);
- else bubble.appendChild(block);
- }
- if (!body) {
- if (typeof block.remove === 'function') block.remove();
- if (!deferFold) _applyNarrationFold(row);
- return;
- }
- block.innerHTML = `<div class="markdown-body">${_renderMessageMarkdown(body)}</div>`;
- if (!deferFold) _applyNarrationFold(row);
-}
-
-/* A long external-CLI turn narrates every tool loop, so one turn can carry
- * dozens of segments (2026-09-18: 62 in a 16-minute task, 61 narration blocks
- * filling 95% of the bubble). Keep the tail readable and fold the rest behind
- * one line the reader can open. Folding is presentation only: every block
- * stays in the DOM and in `row._narration`. */
-const NARRATION_VISIBLE_TAIL = 2;
-const NARRATION_FOLD_THRESHOLD = 4;
-/** Turns the reader has explicitly folded or opened, by turn id. The row's
- * dataset cannot hold this: switching conversations rebuilds the transcript,
- * so a fold the reader chose would come back open. Absorbing an older page
- * must not override that choice either (2026-09-18). */
-const _narrationFoldChoice = new Map();
-const NARRATION_FOLD_CHOICE_LIMIT = 500;
-
-function _narrationTurnKey(row) {
- return _normaliseTurnId(row && row.dataset ? row.dataset.turnId : '');
-}
-
-function _rememberNarrationFoldChoice(key, expanded) {
- if (!key) return;
- if (_narrationFoldChoice.size >= NARRATION_FOLD_CHOICE_LIMIT) {
- for (const oldest of _narrationFoldChoice.keys()) {
- _narrationFoldChoice.delete(oldest);
- if (_narrationFoldChoice.size < NARRATION_FOLD_CHOICE_LIMIT / 2) break;
- }
- }
- _narrationFoldChoice.set(key, !!expanded);
-}
-
-function _narrationFoldLabel(count) {
- const t = (typeof window !== 'undefined' && window.t) ? window.t : null;
- if (typeof t === 'function') {
- const translated = t('chat.narration_fold', { count });
- if (translated && translated !== 'chat.narration_fold') return translated;
- }
- return `${count} 条过程说明`;
-}
-
-function _narrationCollapseLabel() {
- const t = (typeof window !== 'undefined' && window.t) ? window.t : null;
- if (typeof t === 'function') {
- const translated = t('chat.narration_collapse');
- if (translated && translated !== 'chat.narration_collapse') return translated;
- }
- return '收起过程说明';
-}
-
-function _applyNarrationFold(row) {
- const bubble = row && typeof row.querySelector === 'function' ? row.querySelector('.chat-bubble') : null;
- if (!bubble || typeof bubble.querySelectorAll !== 'function') return;
- const blocks = Array.from(bubble.querySelectorAll('.chat-turn-narration'))
- .sort((a, b) => Number(a.dataset?.narrationSeg || 0) - Number(b.dataset?.narrationSeg || 0));
- let toggle = bubble.querySelector('.chat-turn-narration-toggle');
- if (blocks.length < NARRATION_FOLD_THRESHOLD) {
- for (const block of blocks) block.classList.remove('chat-turn-narration--folded');
- if (toggle && typeof toggle.remove === 'function') toggle.remove();
- return;
+ block.dataset.nativeSeg = String(index);
+ if (before && before.parentElement === process) process.insertBefore(block, before);
+ else process.appendChild(block);
}
- const turnKey = _narrationTurnKey(row);
- const chosen = turnKey ? _narrationFoldChoice.get(turnKey) : undefined;
- const expanded = chosen === undefined ? row.dataset.narrationExpanded === '1' : chosen;
- if (chosen !== undefined) row.dataset.narrationExpanded = chosen ? '1' : '0';
- const hiddenCount = blocks.length - NARRATION_VISIBLE_TAIL;
- blocks.forEach((block, i) => {
- const fold = !expanded && i < hiddenCount;
- block.classList[fold ? 'add' : 'remove']('chat-turn-narration--folded');
- });
- if (!toggle) {
- if (typeof document.createElement !== 'function' || typeof bubble.insertBefore !== 'function') return;
- toggle = document.createElement('button');
- toggle.type = 'button';
- toggle.className = 'chat-turn-narration-toggle';
- toggle.addEventListener('click', (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- const next = row.dataset.narrationExpanded !== '1';
- row.dataset.narrationExpanded = next ? '1' : '0';
- _rememberNarrationFoldChoice(_narrationTurnKey(row), next);
- _applyNarrationFold(row);
- });
- bubble.insertBefore(toggle, blocks[0]);
- } else if (toggle.parentElement === bubble && bubble.firstChild !== toggle) {
- // Later pages can prepend older blocks above the toggle (cross-page absorb).
- try { bubble.insertBefore(toggle, blocks[0]); } catch (_) { /* shim */ }
- }
- toggle.dataset.hiddenCount = String(hiddenCount);
- toggle.dataset.expanded = expanded ? '1' : '0';
- toggle.textContent = expanded ? _narrationCollapseLabel() : _narrationFoldLabel(hiddenCount);
- toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
+ block.hidden = false;
+ _setProcessCommentaryLineContent(block, text);
+ const container = row.querySelector?.('[data-role="process-container"]');
+ if (container) container.style.display = '';
}
/** The body streamed so far belongs to the segment that just ended: move it
- * above the body as narration and clear the live body for the next segment. */
-function _demoteBodyToNarration(row, seg) {
+ * into process information and clear the live body for the next segment. */
+function _demoteBodyToNarration(row, seg, classifiedText = null) {
if (!row || !row.dataset) return;
const finalEl = typeof row.querySelector === 'function' ? row.querySelector('[data-role="final"]') : null;
- const text = String(row.dataset.streamBuf || row.dataset.finalText || (finalEl && finalEl.textContent) || '');
+ const text = typeof classifiedText === 'string' ? classifiedText
+ : String(row.dataset.streamBuf || row.dataset.finalText || (finalEl && finalEl.textContent) || '');
+ if (typeof classifiedText === 'string') row.dataset.nativeClassifiedSeg = String(seg);
try { _cancelPendingStreamRaf(row); } catch (_) { /* minimal DOM shims */ }
- _appendNarrationBlock(row, seg, text);
+ const process = row.querySelector?.('[data-role="process"]');
+ let boundary = row._nativeProcessBoundary;
+ if (process && typeof process.insertBefore === 'function') {
+ if (!boundary || boundary.parentElement !== process) {
+ boundary = document.createElement('span');
+ process.insertBefore(boundary, process.firstChild);
+ }
+ boundary.hidden = true;
+ boundary.className = 'stream-process-commentary';
+ boundary.dataset.nativeSeg = String(seg);
+ }
+ _appendNarrationBlock(row, seg, text, { before: boundary });
+ // A hidden element separates operation groups until the next native
+ // message boundary tells us where that message's prose belongs.
+ if (process && typeof process.appendChild === 'function') {
+ row._nativeProcessBoundary = document.createElement('span');
+ row._nativeProcessBoundary.hidden = true;
+ process.appendChild(row._nativeProcessBoundary);
+ }
row.dataset.streamBuf = '';
row.dataset.finalText = '';
delete row.dataset.streamDisplay;
@@ -14303,10 +14595,14 @@ function _demoteBodyToNarration(row, seg) {
}
}
-function _advanceTurnRowToSegment(cid, row, renderKey, seg) {
+function _advanceTurnRowToSegment(cid, row, renderKey, seg, record = null) {
const previousSeg = _rowSegmentIndex(row);
const previousKey = String(row.dataset.renderKey || '');
- _demoteBodyToNarration(row, previousSeg);
+ if (record?.display_phase === 'commentary') {
+ if (row.dataset.nativeClassifiedSeg !== String(record.seg)) {
+ _demoteBodyToNarration(row, Number(record.seg), String(record.text || ''));
+ }
+ } else if (row.dataset.nativeClassifiedSeg !== String(previousSeg)) _demoteBodyToNarration(row, previousSeg);
if (previousKey) _groupPlaceholders.delete(_phKey(cid, previousKey));
_stampRenderKey(row, cid, renderKey);
void seg;
@@ -14324,7 +14620,9 @@ function _absorbSegmentRecord(cid, gm, row, { replayProcess = false } = {}) {
_absorbedTurnSegments.set(key, list);
// The record is canonical: a renderer that attached mid-turn never streamed
// this text, and a demoted stream copy may be partial.
- _appendNarrationBlock(row, Number(gm.seg), String(gm.text || ''), { canonical: true });
+ if (!gm.display_phase || (gm.display_phase === 'commentary' && !replayProcess)) {
+ _appendNarrationBlock(row, Number(gm.seg), String(gm.text || ''), { canonical: true });
+ }
if (!known && replayProcess) _replayPersistedProcessItems(row, gm.process);
}
@@ -14336,7 +14634,7 @@ function _absorbRecordIntoLiveTurnRow(cid, gm, row, opts = {}) {
const recSeg = Number(gm && gm.seg);
if (!row || !Number.isInteger(recSeg)) return false;
if (recSeg >= _rowSegmentIndex(row)) {
- _advanceTurnRowToSegment(cid, row, _segmentRenderKey(gm.turn_id, recSeg + 1), recSeg + 1);
+ _advanceTurnRowToSegment(cid, row, _segmentRenderKey(gm.turn_id, recSeg + 1), recSeg + 1, gm);
}
_absorbSegmentRecord(cid, gm, row, opts);
return true;
@@ -14355,7 +14653,9 @@ function _replayPersistedProcessItems(row, items) {
const itemEvent = item.type === 'event' || item.type === 'progress' ? item.event : null;
if (item.type === 'progress' && itemEvent?.stream === 'assistant'
&& itemEvent.data?.phase === 'commentary') {
- _streamingAppendCommentaryDelta(row, item.text);
+ if (Number.isInteger(itemEvent.data.native_segment)) {
+ _appendNarrationBlock(row, itemEvent.data.native_segment, item.text, { canonical: true });
+ } else _streamingAppendCommentaryDelta(row, item.text);
continue;
}
const projection = _projectProcessRow(
@@ -14375,11 +14675,13 @@ function _mergeSegmentGroup(records) {
const earlier = ordered.slice(0, -1);
if (!earlier.length) return { merged: final, base: final };
const process = [];
- for (const gm of earlier) if (Array.isArray(gm.process)) process.push(...gm.process);
+ for (const gm of earlier) process.push(..._nativeSegmentProcessItems(gm));
if (Array.isArray(final.process)) process.push(...final.process);
const merged = {
...final,
...(process.length ? { process } : {}),
+ ...(ordered.some(record => record.process_parts?.length)
+ ? { process_parts: ordered.flatMap(record => _processPartsForRecord(record, record !== final)) } : {}),
_narration: earlier.map((gm) => ({
id: gm.id, seg: Number(gm.seg), ts: gm.ts, text: String(gm.text || ''),
})),
@@ -14421,15 +14723,16 @@ function _mergeNativeSegmentRecords(records, cid, {
const replacement = new Map();
for (const [key, group] of groups) {
const [actor, tid] = key.split('|');
+ const hasTerminal = group.some(_isTerminalGroupHistoryRecord);
if (rebuild) {
- if (activeTurnIds && activeTurnIds.has(tid)) {
+ if (!hasTerminal && activeTurnIds && activeTurnIds.has(tid)) {
if (Array.isArray(liveTurnGroups)) liveTurnGroups.push({ actor, turnId: tid, records: group });
for (const gm of group) replacement.set(gm, null);
continue;
}
} else {
const liveRow = _liveTurnRow(cid, actor, tid);
- if (liveRow) {
+ if (liveRow && !hasTerminal) {
const ordered = [...group].sort((a, b) => Number(a.seg) - Number(b.seg));
for (const gm of ordered) _absorbRecordIntoLiveTurnRow(cid, gm, liveRow);
for (const gm of group) replacement.set(gm, null);
@@ -14751,11 +15054,16 @@ function _ensureActorPlaceholder(cid, actorId, fallbackPh, turnId, triggerMsgId,
function _claimRenderNodeForMessage(cid, gm) {
const renderKey = _messageRenderKey(gm);
if (!renderKey) return null;
- const ph = _findRenderNode(cid, renderKey);
+ let ph = _findRenderNode(cid, renderKey);
+ if (!ph && _isTerminalGroupHistoryRecord(gm)) ph = _liveTurnRow(cid, String(gm.from || ''), gm.turn_id);
if (!ph || !ph.parentElement) return null;
// An actor-level pending row belongs to whichever turn is streaming; only a
// segment row can be claimed by a persisted record.
if (ph.dataset.finalized === '1') return null;
+ if (ph.dataset.renderKey !== renderKey) {
+ _groupPlaceholders.delete(_phKey(cid, ph.dataset.renderKey || ''));
+ _stampRenderKey(ph, cid, renderKey);
+ }
ph.dataset.finalized = '1';
return ph;
}
@@ -14885,7 +15193,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
// Final markdown body: reuses the legacy helper which preserves the
// .stream-process rail (collapsed if non-empty, hidden if empty) so
// tool calls stay scannable after the reply lands.
- const text = String(gm.text || '');
+ const text = gm.display_phase === 'commentary' ? '' : String(gm.text || '');
const failedAssistant = _isFailedAssistantContent(text, gm);
const interruptedAssistant = _isInterruptedAssistantMessage(gm);
_streamingSetFinal(ph, text, { archive: archive && !failedAssistant && !interruptedAssistant });
@@ -14894,18 +15202,20 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
// while the replacement row saw only the post-handback synthesis. Rebuild
// from `gm.process` so live settlement and a cold history load expose the
// same complete, de-duplicated rail.
- if (Array.isArray(gm.process) && gm.process.length) {
+ if (gm.process?.length || gm.process_parts?.length) {
ph.querySelector('.stream-process')?.remove();
- _renderPersistedProcess(ph, gm.process);
+ _renderPersistedProcess(ph, gm.process || [], {
+ expanded: !gm.display_phase && !text.trim() && _processItemsHavePublicCommentary(gm.process),
+ parts: gm.process_parts,
+ });
}
- // Earlier segments of a foldable turn read as narration above the body. The
+ // Earlier segments of a foldable turn appear inside the shared process disclosure. The
// records are canonical: a slot the stream left empty (renderer attached or
// rebuilt mid-turn) is filled here, matching a cold history load.
if (Array.isArray(gm._narration) && gm._narration.length) {
for (const item of gm._narration) {
- _appendNarrationBlock(ph, item.seg, item.text, { canonical: true, deferFold: true });
+ _appendNarrationBlock(ph, item.seg, item.text, { canonical: true, paint: false });
}
- _applyNarrationFold(ph);
}
if (failedAssistant) {
_mountEmptyResponseNotice(ph, gm);
@@ -14940,6 +15250,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
if (gmSkills) {
for (const payload of gmSkills) _mountCreatedSkillChip(ph, payload);
}
+ _mountSavedTaskChips(ph, gm.saved_tasks);
// Form widget (agent → user input form).
if (gm.form && typeof window.renderChatInputForm === 'function') {
@@ -14994,7 +15305,10 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
// { type: 'aborted', cid }
function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {}) {
if (!evData || typeof evData !== 'object') return;
- if (evData.type === 'message') window.CliAsyncInput?.observe(cid, evData.msg);
+ if (evData.type === 'message') {
+ window.CliAsyncInput?.observe(cid, evData.msg);
+ _rememberHistoryLoadMessage(cid, evData.msg, !!evData.turn_end);
+ }
if (
evData.type === 'process'
|| evData.type === 'artifact_created'
@@ -15086,10 +15400,33 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// Observer-delivered events are dropped here to avoid a second delivery
// path. A view rebuild reads the main process's active display snapshot;
// only legacy unsequenced producers need the bounded milestone buffer.
- if (cid !== currentCid) return;
if (evData.type === 'process') {
if (_isSnapshottedProcess(cid, evData) || _deferHistoryLoadProcess(cid, evData)) return;
}
+ const recoveringVisible = _conversationHistoryLoad?.cid === cid && _conversationHistoryLoad.painted;
+ if (!_isConversationDisplayVisible(cid) || (_offViewLiveDisplayDirty.has(cid) && !recoveringVisible)) {
+ // Level state and task completion remain current even while transcript
+ // rendering is suspended. No execution, storage or cancellation is changed.
+ if (evData.type === 'state_changed') {
+ const st = evData.state || {};
+ const inFlight = Array.isArray(st.in_flight) ? st.in_flight.slice() : [];
+ const activeTurns = _normaliseActiveTurns(evData.active_turns);
+ _rememberServerFloor(cid, st);
+ _latestInFlight.set(cid, inFlight);
+ _latestActiveTurns.set(cid, activeTurns);
+ setGroupConversationBusy(cid, st.status === 'running' || inFlight.length > 0 || activeTurns.length > 0);
+ } else if (evData.type === 'aborted') {
+ setGroupConversationBusy(cid, false);
+ _latestInFlight.set(cid, []);
+ _latestActiveTurns.set(cid, []);
+ }
+ _offViewLiveDisplayDirty.add(cid);
+ if (evData.type === 'process' && !Number.isSafeInteger(evData.display_seq)) {
+ _bufferOffViewGroupProcessEvent(cid, { type: 'event', event: { stream: 'group', data: evData } });
+ }
+ _refreshVisibleConversationDisplay(cid);
+ return;
+ }
if (evData.type === 'message') {
const gm = evData.msg;
if (!gm) return;
@@ -15146,7 +15483,6 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// goes through the batch merge — folds them back into one.
if (_absorbEarlierTurnPage(
cid, String(gm.from || ''), _normaliseTurnId(gm.turn_id), [gm],
- { expandNarration: false },
)) return;
}
_dropSupersededTurnRows(cid, String(gm.from || ''), gm.turn_id, gm.seg);
@@ -15268,7 +15604,13 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
}
}
try {
- if (data.type === 'commentary-finalized') {
+ if (data.type === 'native-message-finalized' && data.phase === 'commentary' && typeof data.text === 'string') {
+ if (Number(evData.seg) === _rowSegmentIndex(target)) {
+ _demoteBodyToNarration(target, Number(evData.seg), data.text);
+ } else {
+ _appendNarrationBlock(target, Number(evData.seg), data.text, { canonical: true });
+ }
+ } else if (data.type === 'commentary-finalized') {
_advanceStreamingMessageActivityPosition(target);
_streamingFinalizeCommentary(target, data.text);
_streamingUpdateActivity(target, t('chat.activity_writing'));
@@ -16317,6 +16659,7 @@ function _appendProjectedProcessRowToBody(body, projection) {
function _appendProjectedProcessRow(msg, projection) {
if (!projection) return;
+ if (projection.byokFallback && msg?.dataset) msg.dataset.billingByok = '1';
_sealStreamingCommentary(msg);
if (projection.expandable) {
_streamingAppendToolResultRow(
@@ -16379,6 +16722,7 @@ function _materializeReasoningSummary(msg, evt) {
// text deltas update the single "live" line; everything else becomes a new
// process-pane line (via _formatEventLine).
function _renderAgentEvent(msg, evt) {
+ window.OrkasCommercialEntry?.observeToolResult(msg, evt);
if (!evt || typeof evt !== 'object') return;
evt = _materializeReasoningSummary(msg, evt);
const { stream, data } = evt;
@@ -16472,9 +16816,9 @@ function _streamingAppendToolResultRow(
async function _toggleToolResultRow(row) {
if (!row) return;
- // Toggle existing expansion.
const next = row.nextElementSibling;
if (next && next.classList.contains('stream-process-line-full')) {
+ row._toolResultDisclosure = null;
next.remove();
_setExpandableProcessRowSemantics(row, true, false);
_compactAdjacentProcessRows(row.parentElement);
@@ -16483,32 +16827,75 @@ async function _toggleToolResultRow(row) {
const ref = row.dataset.toolResultRef;
const path = row.dataset.toolResultPath;
const inline = row._fullOutput;
+ const inv = window.orkas && window.orkas.invoke;
+ if ((ref || path) && typeof inv !== 'function') return;
const pre = document.createElement('pre');
pre.className = 'stream-process-line-full';
+ const ownerCid = currentCid;
+ row._toolResultDisclosure = pre;
+ row.insertAdjacentElement('afterend', pre);
+ _setExpandableProcessRowSemantics(row, true, true);
- if (ref || path) {
- // window.orkas.invoke is the canonical IPC entry (matches every
- // other feature's pattern — saved-apps / chat-artifact / workspace).
- const inv = window.orkas && window.orkas.invoke;
- if (typeof inv !== 'function') return;
- let res;
+ if (!ref && !path) {
+ pre.textContent = typeof inline === 'string' && inline ? inline : '[no content recorded for this row]';
+ return;
+ }
+ let cursor = 0;
+ let loading = false;
+ let more = null;
+ const active = () => row._toolResultDisclosure === pre && pre.isConnected !== false
+ && row.isConnected !== false && currentCid === ownerCid;
+ const ensureMore = () => {
+ if (more) return;
+ more = document.createElement('button');
+ more.type = 'button';
+ more.className = 'chat-process-load-more';
+ more.addEventListener('click', load);
+ pre.appendChild(more);
+ };
+ const load = async () => {
+ if (loading || !active()) return;
+ loading = true;
+ if (more) { more.disabled = true; more.setAttribute('aria-busy', 'true'); more.textContent = t('common.loading'); }
try {
- res = await inv('localAgents.readToolResult', ref ? { ref } : { path });
- } catch (err) {
- res = { ok: false, error: String(err?.message || err) };
- }
- if (res && res.ok) {
- pre.textContent = res.content + (res.truncated ? '\n\n[…truncated for display, open file for full content]' : '');
- } else {
- pre.textContent = '[failed to read: ' + (res?.error || 'unknown') + ']';
+ const request = ref ? { ref } : { path };
+ if (cursor) request.cursor = cursor;
+ const res = await inv('localAgents.readToolResult', request);
+ if (!active()) return;
+ if (!res?.ok || typeof res.content !== 'string') throw new Error('Result page unavailable');
+ const nextCursor = res.next_cursor ?? null;
+ if (nextCursor !== null && (!Number.isSafeInteger(nextCursor) || nextCursor <= cursor)) {
+ throw new Error('Invalid result continuation');
+ }
+ if (!more) pre.textContent = res.content;
+ else {
+ const chunk = document.createElement('span');
+ chunk.textContent = res.content;
+ pre.insertBefore(chunk, more);
+ }
+ // Older hosts return a head-only receipt without a continuation.
+ if (res.truncated && res.next_cursor === undefined) {
+ pre.textContent += '\n\n[…truncated for display, open file for full content]';
+ }
+ if (nextCursor !== null) {
+ cursor = nextCursor;
+ ensureMore();
+ more.hidden = false;
+ more.classList.remove('is-error');
+ more.textContent = t('sidebar.load_more_conversations');
+ } else if (more) more.hidden = true;
+ } catch (_) {
+ if (!active()) return;
+ ensureMore();
+ more.hidden = false;
+ more.classList.add('is-error');
+ more.textContent = t('chat.history_retry_newer');
+ } finally {
+ loading = false;
+ if (more) { more.disabled = false; more.setAttribute('aria-busy', 'false'); }
}
- } else if (typeof inline === 'string' && inline) {
- pre.textContent = inline;
- } else {
- pre.textContent = '[no content recorded for this row]';
- }
- row.insertAdjacentElement('afterend', pre);
- _setExpandableProcessRowSemantics(row, true, true);
+ };
+ await load();
}
async function _onToolResultRowClick(ev) {
@@ -16558,7 +16945,6 @@ function _streamingUpdateLive(msg, prefix, text, appendDelta) {
// messages typed in during the stream go to the queue via plain Enter.
function _updateConvSendUI(cid) {
if (cid !== currentCid) return;
- _updateComposerSeqToggle();
const sendBtn = document.getElementById('chat-send-btn');
const input = document.getElementById('chat-input');
if (!sendBtn) return;
@@ -17519,11 +17905,6 @@ function _initAllMentionMirrors() {
if (autoTaskInput) _initMentionMirror(autoTaskInput);
}
-function _commanderAttributionId(value) {
- const text = String(value || '').trim();
- return /^[A-Za-z0-9._-]{1,64}$/.test(text) ? text : '';
-}
-
function _quickStartThumbHtml(thumb) {
switch (thumb) {
case 'web':
@@ -17631,34 +18012,6 @@ function _selectedMessageElements() {
.filter((msg) => _messageSelectionState.selected.has(msg.dataset.msgId || ''));
}
-// Consume only the draft submitted by this request. Attachment preparation and
-// acceptance can both finish after another draft was typed or a tab switched.
-function _consumeSubmittedComposer(cid, submittedText, submittedQuotes) {
- const input = cid === currentCid ? document.getElementById('chat-input') : null;
- const stored = input ? null : _readDraftData(cid);
- let text = input ? composerText(input) : String((stored && stored.text) || '');
- if (text === submittedText) {
- text = '';
- if (input) {
- composerSetText(input, '');
- _draftHadRecipient.delete('conversation');
- autoGrow(input, 200);
- _updateComposerSeqToggle();
- }
- }
- const submittedQuoteIds = new Set(submittedQuotes.map(_quoteIdentity));
- const remainingQuotes = _getQuotes(cid).filter((quote) => !submittedQuoteIds.has(_quoteIdentity(quote)));
- if (remainingQuotes.length) _quotesByCid.set(cid, remainingQuotes);
- else _quotesByCid.delete(cid);
- _renderQuotePreview(cid);
- if (text || remainingQuotes.length) {
- _cancelDraftSave(cid);
- _writeDraftData(cid, text, remainingQuotes);
- } else {
- _clearDraft(cid);
- }
-}
-
window.attachKbFileToDraft = async function attachKbFileToDraft(channel, payload, draftCid, afterNavigate) {
const finishOperation = _chatAttachBeginOperation(draftCid);
diff --git a/src/renderer/modules/dialogs.js b/src/renderer/modules/dialogs.js
index 502a9aeb..05842423 100644
--- a/src/renderer/modules/dialogs.js
+++ b/src/renderer/modules/dialogs.js
@@ -103,13 +103,22 @@ function _uiTrapDialogTab(overlay, e) {
return false;
}
-function _uiRestoreDialogFocus(previousFocus) {
+function _uiRestoreDialogFocus(previousFocus, options) {
if (
previousFocus
&& typeof previousFocus.focus === 'function'
&& document.body.contains(previousFocus)
) {
- previousFocus.focus();
+ previousFocus.focus(options);
+ // Resource-card actions are revealed by :focus-within. Re-enter the
+ // focusable card before restoring an action that is hidden at rest.
+ if (document.activeElement !== previousFocus && !previousFocus.disabled && !previousFocus.hidden) {
+ const parent = previousFocus.parentElement?.closest('[tabindex]');
+ if (parent && parent.tabIndex >= 0) {
+ parent.focus(options);
+ previousFocus.focus(options);
+ }
+ }
}
}
diff --git a/src/renderer/modules/home.js b/src/renderer/modules/home.js
new file mode 100644
index 00000000..f61cc556
--- /dev/null
+++ b/src/renderer/modules/home.js
@@ -0,0 +1,551 @@
+/* Orkas Frontend — Commander home (the New task view)
+ *
+ * The greeting and the composer stay at the top in every state; the state
+ * picks what sits below them (PC/docs/design/PATTERNS.md P15):
+ * - empty: two guidance blocks and Quick start;
+ * - populated: work to pick up — unfinished to-dos, and finished automation
+ * runs and tasks the user has not opened yet.
+ * "Not opened yet" is the sidebar's unread record (task-unread.js), so the
+ * home and the sidebar dots always agree and opening a row clears both.
+ * Each visit looks both lists up once and paints when they settle. A failed
+ * lookup hides its group and is only logged: there are no loading, error or
+ * stale-data states.
+ */
+
+const _homeLog = createLogger('home');
+
+const _HOME_VISIBLE_ROWS = 3;
+// Unread runs folded under the first three; older ones stay in the sidebar.
+const _HOME_MAX_FOLDED_ROWS = 20;
+// Unread runs missing from the sidebar cache are looked up by id, in batches
+// of what `conversations.getMany` accepts, enough to fill both run groups.
+const _HOME_LOOKUP_BATCH = 25;
+const _HOME_LOOKUP_LIMIT = 50;
+const _HOME_REFRESH_DEBOUNCE_MS = 500;
+// A slow first lookup must not keep the greeting and Quick start invisible.
+const _HOME_FIRST_PAINT_FALLBACK_MS = 1500;
+// "Connect Feishu / DingTalk / email": the connectors that hold the user's
+// work context. A legacy Lark connection counts as Feishu.
+const _HOME_CONNECT_TARGETS = [
+ { id: 'feishu', instanceIds: ['feishu', 'lark'] },
+ { id: 'dingtalk', instanceIds: ['dingtalk'] },
+ { id: 'gmail', instanceIds: ['gmail'] },
+ { id: 'm365-mail', instanceIds: ['m365-mail'] },
+];
+
+// 'pending' only until the first visit's lookups settle; later visits keep
+// the last painted state until the new lookup replaces it.
+let _homeState = 'pending';
+let _homeData = { todos: [], todoTotal: 0, automations: [], tasks: [] };
+let _homeLoadSeq = 0; // { startedAt, reported }
+let _homeRefreshTimer = null;
+let _homeBound = false;
+const _homeExpanded = new Set();
+
+function _homeErrorType(err) {
+ return err && typeof err.name === 'string' && /^[A-Za-z]{1,40}$/.test(err.name) ? err.name : 'unknown';
+}
+
+function _homeVisible() {
+ try {
+ return currentView === 'new-chat';
+ } catch (_) {
+ return false;
+ }
+}
+
+function _homeIcon(name, className) {
+ return typeof window.uiIconHtml === 'function' ? window.uiIconHtml(name, className) : '';
+}
+
+// ── Lookups ─────────────────────────────────────────────────────────────
+
+async function _homeLoadTodos() {
+ try {
+ const res = await window.orkas.invoke('projects.tasks.listOpen', { limit: _HOME_VISIBLE_ROWS });
+ if (!res || res.ok === false || !Array.isArray(res.tasks)) throw new Error('invalid_response');
+ const tasks = res.tasks.slice(0, _HOME_VISIBLE_ROWS);
+ return { tasks, total: Math.max(tasks.length, Math.round(Number(res.total) || 0)) };
+ } catch (err) {
+ _homeLog.warn('open to-dos unavailable for the home', { error_type: _homeErrorType(err) });
+ return { tasks: [], total: 0 };
+ }
+}
+
+function _homeConversationInfo(row) {
+ return {
+ title: String(row.title || ''),
+ projectId: String(row.project_id || ''),
+ automation: !!row.origin_auto_task_id,
+ };
+}
+
+/** Unread finished runs split into automation runs and other tasks, newest
+ * first. A conversation an automation created stays an automation run even
+ * when its latest turn was a reply the user wrote there. */
+async function _homeLoadRuns() {
+ let records = [];
+ try {
+ records = window.TaskUnread && typeof window.TaskUnread.list === 'function'
+ ? window.TaskUnread.list()
+ : [];
+ } catch (err) {
+ _homeLog.warn('unread tasks unavailable for the home', { error_type: _homeErrorType(err) });
+ }
+ const cached = new Map();
+ const rows = typeof conversations !== 'undefined' && Array.isArray(conversations) ? conversations : [];
+ for (const row of rows) {
+ if (row && row.conversation_id) cached.set(row.conversation_id, row);
+ }
+ const info = new Map();
+ const lookups = [];
+ for (const record of records) {
+ const row = cached.get(record.cid);
+ if (row) info.set(record.cid, _homeConversationInfo(row));
+ else if (lookups.length < _HOME_LOOKUP_LIMIT) lookups.push(record.cid);
+ }
+ const missing = [];
+ for (let offset = 0; offset < lookups.length; offset += _HOME_LOOKUP_BATCH) {
+ try {
+ const res = await window.orkas.invoke('conversations.getMany', {
+ cids: lookups.slice(offset, offset + _HOME_LOOKUP_BATCH),
+ });
+ for (const row of (res && res.conversations) || []) {
+ if (row && row.conversation_id) info.set(row.conversation_id, _homeConversationInfo(row));
+ }
+ for (const cid of (res && res.missing) || []) missing.push(cid);
+ } catch (err) {
+ // The rows still show, untitled, and can be opened.
+ _homeLog.warn('unread task titles unavailable for the home', { error_type: _homeErrorType(err) });
+ break;
+ }
+ }
+ // A conversation deleted elsewhere (another device) leaves its unread record
+ // behind; drop it here so neither the home nor the sidebar keeps it.
+ if (missing.length && typeof _forgetUnreadConversation === 'function') {
+ for (const cid of missing) _forgetUnreadConversation(cid);
+ }
+ const gone = new Set(missing);
+ const automations = [];
+ const tasks = [];
+ for (const record of records) {
+ if (gone.has(record.cid)) continue;
+ const known = info.get(record.cid);
+ const run = {
+ cid: record.cid,
+ status: record.status || '',
+ finishedAt: Number(record.finishedAt) || 0,
+ title: known ? known.title : '',
+ projectId: known ? known.projectId : String(record.projectId || ''),
+ };
+ const automation = record.entryPoint === 'automation' || !!(known && known.automation);
+ (automation ? automations : tasks).push(run);
+ }
+ return { automations, tasks };
+}
+
+function _homeLoad() {
+ const seq = ++_homeLoadSeq;
+ Promise.all([_homeLoadTodos(), _homeLoadRuns()])
+ .then(([todos, runs]) => {
+ if (seq !== _homeLoadSeq) return;
+ _homeData = {
+ todos: todos.tasks,
+ todoTotal: todos.total,
+ automations: runs.automations,
+ tasks: runs.tasks,
+ };
+ _homeRender();
+ })
+ .catch((err) => {
+ _homeLog.warn('home lookup failed', { error_type: _homeErrorType(err) });
+ if (seq === _homeLoadSeq && _homeState === 'pending') _homeApplyState('empty');
+ });
+ return seq;
+}
+
+// ── Rendering ───────────────────────────────────────────────────────────
+
+function _homeApplyState(state) {
+ _homeState = state;
+ const panel = document.getElementById('panel-new-chat');
+ if (panel) panel.dataset.homeState = state;
+}
+
+function _homeLocale() {
+ try {
+ return getLocaleMeta(getLang()).intlLocale || undefined;
+ } catch (_) {
+ return undefined;
+ }
+}
+
+/** "just now", "5 minutes ago", "yesterday", then a short date. */
+function _homeRelativeTime(ms) {
+ if (!Number.isFinite(ms) || ms <= 0) return '';
+ const diff = Date.now() - ms;
+ if (diff < 60000) return t('common.just_now');
+ const locale = _homeLocale();
+ try {
+ const relative = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
+ const minutes = Math.round(diff / 60000);
+ if (minutes < 60) return relative.format(-minutes, 'minute');
+ const hours = Math.round(diff / 3600000);
+ if (hours < 24) return relative.format(-hours, 'hour');
+ const days = Math.round(diff / 86400000);
+ if (days < 7) return relative.format(-days, 'day');
+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(new Date(ms));
+ } catch (_) {
+ return new Date(ms).toLocaleDateString();
+ }
+}
+
+function _homeProjectName(pid) {
+ const projects = typeof _projectsCache !== 'undefined' && Array.isArray(_projectsCache) ? _projectsCache : [];
+ const project = projects.find((item) => item && item.project_id === pid);
+ return (project && project.name) || t('sidebar.projects');
+}
+
+function _homeTodoStatusLabel(status) {
+ if (status === 'progress') return t('project.todo.status_progress');
+ if (status === 'review') return t('project.todo.status_review');
+ return t('project.todo.status_todo');
+}
+
+function _homeResultLabel(status) {
+ if (status === 'completed') return t('new_chat.home.result.completed');
+ if (status === 'failed') return t('new_chat.home.result.failed');
+ if (status === 'waiting_input') return t('new_chat.home.result.waiting_input');
+ if (status === 'stopped') return t('new_chat.home.result.stopped');
+ return t('new_chat.home.result.unknown');
+}
+
+function _homeRunActionLabel(status) {
+ if (status === 'waiting_input') return t('new_chat.home.action.reply');
+ if (status === 'failed') return t('new_chat.home.action.view_reason');
+ return t('new_chat.home.action.view_result');
+}
+
+// Run status glyphs. To-dos use the sidebar's To-do icon; the meta line
+// repeats each row's status in words.
+const _HOME_STATUS_ICONS = {
+ todo: 'circle',
+ progress: 'live',
+ review: 'hourglass',
+ completed: 'check-circle',
+ failed: 'x-circle',
+ waiting_input: 'message-circle-more',
+ stopped: 'stop',
+};
+
+function _homeRowHtml({ attrs, status, icon, title, source, details, action }) {
+ const attributes = Object.entries(attrs)
+ .map(([name, value]) => ` ${name}="${escapeHtml(String(value))}"`)
+ .join('');
+ const meta = details.filter(Boolean).map((part) => escapeHtml(part)).join(' · ');
+ const kind = Object.prototype.hasOwnProperty.call(_HOME_STATUS_ICONS, status) ? status : 'unknown';
+ return `<button type="button" class="home-row"${attributes}>`
+ + `<span class="home-row-status is-${kind}" aria-hidden="true">${_homeIcon(icon || _HOME_STATUS_ICONS[kind] || 'dot', 'home-row-status-icon')}</span>`
+ + '<span class="home-row-main">'
+ + `<span class="home-row-title">${escapeHtml(title)}</span>`
+ + `<span class="home-row-meta"><span class="home-row-source">${escapeHtml(source)}</span>${meta}</span>`
+ + '</span>'
+ + `<span class="home-row-action">${escapeHtml(action)}${_homeIcon('chevron-right', 'home-row-action-icon')}</span>`
+ + '</button>';
+}
+
+function _homeTodoRowHtml(task, index) {
+ const pid = String(task.project_id || '');
+ const status = String(task.status || 'todo');
+ const content = String(task.content || '').split('\n').map((line) => line.trim()).find(Boolean);
+ const updated = _homeRelativeTime(Date.parse(task.updated_at || task.created_at || ''));
+ return _homeRowHtml({
+ attrs: {
+ 'data-home-todo': task.id,
+ 'data-home-pid': pid,
+ 'data-home-status': status,
+ 'data-home-position': index + 1,
+ // The conversation this to-do belongs to (saved from it, or last run in
+ // it). Opening the row returns there when that conversation still exists.
+ ...(task.origin_cid ? { 'data-home-origin-cid': String(task.origin_cid) } : {}),
+ },
+ status,
+ icon: 'clipboard-list',
+ title: content || t('new_chat.home.untitled'),
+ source: pid
+ ? t('new_chat.home.source.project_todo', { project: task.project_name || _homeProjectName(pid) })
+ : t('new_chat.home.source.global_todo'),
+ details: [_homeTodoStatusLabel(status), updated ? t('new_chat.home.time.updated', { time: updated }) : ''],
+ action: t('new_chat.home.action.view'),
+ });
+}
+
+function _homeRunRowHtml(run, section, index) {
+ let source = t('new_chat.home.source.global_task');
+ if (section === 'automations') source = t('new_chat.home.source.automation');
+ else if (run.projectId) source = t('new_chat.home.source.project_task', { project: _homeProjectName(run.projectId) });
+ return _homeRowHtml({
+ attrs: {
+ 'data-home-cid': run.cid,
+ 'data-home-section': section,
+ 'data-home-status': run.status || 'unknown',
+ 'data-home-position': index + 1,
+ },
+ status: run.status,
+ title: run.title || t('new_chat.home.untitled'),
+ source,
+ details: [_homeResultLabel(run.status), _homeRelativeTime(run.finishedAt)],
+ action: _homeRunActionLabel(run.status),
+ });
+}
+
+function _homeGroupTitle(section) {
+ if (section === 'todos') return t('new_chat.home.group.todos');
+ if (section === 'automations') return t('new_chat.home.group.automations');
+ return t('new_chat.home.group.tasks');
+}
+
+function _homeSectionHtml(section) {
+ const titleId = `home-group-${section}-title`;
+ const isTodos = section === 'todos';
+ const items = isTodos ? _homeData.todos : _homeData[section];
+ const total = isTodos ? _homeData.todoTotal : items.length;
+ const rowHtml = (item, index) => (isTodos ? _homeTodoRowHtml(item, index) : _homeRunRowHtml(item, section, index));
+ // Group-level links sit in the group header: all automations, and the full
+ // To-dos page when there are more to-dos than the rows shown here.
+ let link = '';
+ if (section === 'automations') {
+ link = `<button type="button" class="home-text-btn" data-home-action="all_automations">${escapeHtml(t('new_chat.home.all_automations'))}</button>`;
+ } else if (isTodos && total > _HOME_VISIBLE_ROWS) {
+ link = `<button type="button" class="home-text-btn" data-home-action="more_todos" aria-describedby="${titleId}">${escapeHtml(t('new_chat.home.view_all_todos'))}</button>`;
+ }
+ let fold = '';
+ let footer = '';
+ if (!isTodos && items.length > _HOME_VISIBLE_ROWS) {
+ const folded = items.slice(_HOME_VISIBLE_ROWS, _HOME_VISIBLE_ROWS + _HOME_MAX_FOLDED_ROWS);
+ const expanded = _homeExpanded.has(section);
+ const foldId = `home-fold-${section}`;
+ fold = `<div class="home-list-fold" id="${foldId}"${expanded ? '' : ' hidden'}>`
+ + folded.map((item, index) => rowHtml(item, index + _HOME_VISIBLE_ROWS)).join('')
+ + '</div>';
+ footer = `<button type="button" class="home-text-btn home-group-more" data-home-toggle="${section}"`
+ + ` data-home-folded="${folded.length}" aria-controls="${foldId}" aria-expanded="${expanded}">`
+ + escapeHtml(expanded ? t('new_chat.home.collapse') : t('new_chat.home.expand', { count: folded.length }))
+ + '</button>';
+ }
+ return `<section class="home-group" data-section="${section}" aria-labelledby="${titleId}">`
+ + '<div class="home-group-head">'
+ + `<h2 class="home-group-title" id="${titleId}">${escapeHtml(_homeGroupTitle(section))}<span class="home-group-count">${total}</span></h2>`
+ + link
+ + '</div>'
+ + `<div class="home-list">${items.slice(0, _HOME_VISIBLE_ROWS).map(rowHtml).join('')}${fold}</div>`
+ + footer
+ + '</section>';
+}
+
+function _homeSectionCounts() {
+ return {
+ todos: _homeData.todoTotal,
+ automations: _homeData.automations.length,
+ tasks: _homeData.tasks.length,
+ };
+}
+
+function _homeRender() {
+ const counts = _homeSectionCounts();
+ // Groups keep this order; one without items is left out entirely.
+ const sections = ['todos', 'automations', 'tasks'].filter((section) => counts[section] > 0);
+ const host = document.getElementById('home-groups');
+ if (host) host.innerHTML = sections.map(_homeSectionHtml).join('');
+ _homeApplyState(sections.length ? 'populated' : 'empty');
+}
+
+/** The empty state's "share files, or connect Feishu / DingTalk / email" line;
+ * the connect phrase is a button inside the translated sentence. */
+function _homeRenderExploreContext() {
+ const el = document.getElementById('home-explore-context');
+ if (!el) return;
+ const marker = '\u0001';
+ const text = t('new_chat.home.explore_context', { connect: marker });
+ const at = text.indexOf(marker);
+ const link = `<button type="button" class="home-connect-link" data-home-connect="1">${escapeHtml(t('new_chat.home.explore_connect_link'))}</button>`;
+ el.innerHTML = at < 0
+ ? `${escapeHtml(text)} ${link}`
+ : `${escapeHtml(text.slice(0, at))}${link}${escapeHtml(text.slice(at + marker.length))}`;
+}
+
+// ── Actions ─────────────────────────────────────────────────────────────
+
+function _homeOpenRun(row) {
+ const cid = row.dataset.homeCid || '';
+ const section = row.dataset.homeSection === 'automations' ? 'automations' : 'tasks';
+ // Opening it marks it read; drop it now so coming back never shows it.
+ _homeData[section] = _homeData[section].filter((run) => run.cid !== cid);
+ setView('conversation', cid, { entryPoint: 'home' });
+}
+
+// Whether a conversation can still be opened: the sidebar cache first, then one
+// read-only lookup. A failed lookup counts as missing so the row falls back to
+// the To-dos page.
+async function _homeConversationExists(cid) {
+ if (!cid) return false;
+ const rows = typeof conversations !== 'undefined' && Array.isArray(conversations) ? conversations : [];
+ if (rows.some((c) => c && c.conversation_id === cid)) return true;
+ try {
+ const res = await window.orkas.invoke('conversations.getMany', { cids: [cid] });
+ return ((res && res.conversations) || []).some((row) => row && row.conversation_id === cid);
+ } catch (err) {
+ _homeLog.warn('to-do conversation lookup failed', { error_type: _homeErrorType(err) });
+ return false;
+ }
+}
+
+async function _homeOpenTodo(row) {
+ const pid = row.dataset.homePid || '';
+ const id = row.dataset.homeTodo || '';
+ const originCid = row.dataset.homeOriginCid || '';
+ const openConversation = !!originCid && await _homeConversationExists(originCid);
+ // A to-do that belongs to a conversation returns the user there, so the
+ // work continues with that conversation's plan and history. Nothing is
+ // prefilled; the user decides what to send.
+ if (openConversation) {
+ setView('conversation', originCid, { entryPoint: 'home' });
+ return;
+ }
+ // The To-dos page code loads with the page; load it first so the page can
+ // open on this to-do.
+ try {
+ if (typeof loadRendererFeature === 'function') await loadRendererFeature('project');
+ } catch (err) {
+ _homeLog.warn('to-dos page unavailable from the home', { error_type: _homeErrorType(err) });
+ }
+ if (typeof focusTodo === 'function') focusTodo(pid, id, { entryPoint: 'home' });
+ else setView('todos', null, { entryPoint: 'home' });
+}
+
+function _homeToggleFold(button) {
+ const section = button.dataset.homeToggle;
+ const fold = document.getElementById(`home-fold-${section}`);
+ if (!fold) return;
+ const expanded = fold.hidden;
+ fold.hidden = !expanded;
+ if (expanded) _homeExpanded.add(section);
+ else _homeExpanded.delete(section);
+ button.setAttribute('aria-expanded', String(expanded));
+ button.textContent = expanded
+ ? t('new_chat.home.collapse')
+ : t('new_chat.home.expand', { count: Number(button.dataset.homeFolded) || 0 });
+}
+
+function _homeOnGroupsClick(event) {
+ const target = event.target && typeof event.target.closest === 'function' ? event.target : null;
+ if (!target) return;
+ const toggle = target.closest('[data-home-toggle]');
+ if (toggle) {
+ _homeToggleFold(toggle);
+ return;
+ }
+ const action = target.closest('[data-home-action]');
+ if (action) {
+ if (action.dataset.homeAction === 'more_todos') setView('todos', null, { entryPoint: 'home' });
+ else if (action.dataset.homeAction === 'all_automations') setView('auto', null, { entryPoint: 'home' });
+ return;
+ }
+ const row = target.closest('.home-row');
+ if (!row) return;
+ if (row.dataset.homeTodo) void _homeOpenTodo(row);
+ else if (row.dataset.homeCid) _homeOpenRun(row);
+}
+
+/** Context menus open below their trigger, or above it near the window bottom. */
+function _homeMenuAnchor(el) {
+ const rect = el.getBoundingClientRect();
+ const below = window.innerHeight - rect.bottom > 320;
+ return { clientX: rect.left, clientY: below ? rect.bottom + 4 : rect.top - 4 };
+}
+
+function _homeConnect(id) {
+ setView('connectors', null, { entryPoint: 'home' });
+ if (typeof window.openConnectorSetupById !== 'function') return;
+ Promise.resolve(window.openConnectorSetupById(id, 'form')).catch((err) => {
+ _homeLog.warn('connector setup from the home failed', { error_type: _homeErrorType(err) });
+ });
+}
+
+async function _homeOpenConnectChooser(button) {
+ if (typeof showContextMenu !== 'function') return;
+ const anchor = _homeMenuAnchor(button);
+ const connected = new Set();
+ try {
+ const res = await window.orkas.invoke('connectors.list', {});
+ for (const inst of (res && Array.isArray(res.instances) ? res.instances : [])) {
+ if (inst && inst.status && inst.status.kind === 'connected') connected.add(inst.id);
+ }
+ } catch (err) {
+ _homeLog.warn('connector states unavailable for the home', { error_type: _homeErrorType(err) });
+ }
+ const items = [];
+ for (const target of _HOME_CONNECT_TARGETS) {
+ let name = target.id;
+ try {
+ const nav = typeof window.loadConnectorNavTarget === 'function'
+ ? await window.loadConnectorNavTarget(target.id)
+ : null;
+ if (nav && nav.name) name = nav.name;
+ } catch (_) {}
+ const isConnected = target.instanceIds.some((id) => connected.has(id));
+ items.push({
+ label: isConnected ? `${name} · ${t('connectors.group.connected')}` : name,
+ onClick: () => _homeConnect(target.id),
+ });
+ }
+ showContextMenu(anchor, items);
+}
+
+// ── Lifecycle ───────────────────────────────────────────────────────────
+
+function _homeBind() {
+ if (_homeBound) return;
+ _homeBound = true;
+ document.getElementById('home-groups')?.addEventListener('click', _homeOnGroupsClick);
+ document.getElementById('home-explore-context')?.addEventListener('click', (event) => {
+ const link = event.target && typeof event.target.closest === 'function'
+ ? event.target.closest('[data-home-connect]')
+ : null;
+ if (link) void _homeOpenConnectChooser(link);
+ });
+ window.addEventListener('task-unread-change', homeRefresh);
+ window.addEventListener('i18n-change', () => {
+ _homeRenderExploreContext();
+ if (_homeState === 'populated') _homeRender();
+ });
+ if (window.orkas && typeof window.orkas.onPushEvent === 'function') {
+ try { window.orkas.onPushEvent('projects:tasks-changed', homeRefresh); } catch (_) {}
+ }
+}
+
+/** Called by `onEnterNewChatView` on every visit to the home. */
+function homeOnEnter() {
+ _homeBind();
+ _homeExpanded.clear();
+ clearTimeout(_homeRefreshTimer);
+ _homeRefreshTimer = null;
+ _homeRenderExploreContext();
+ const seq = _homeLoad();
+ if (_homeState === 'pending') {
+ setTimeout(() => {
+ if (seq === _homeLoadSeq && _homeState === 'pending') _homeApplyState('empty');
+ }, _HOME_FIRST_PAINT_FALLBACK_MS);
+ }
+}
+
+/** Re-read both lists while the home is showing; the next visit re-reads
+ * them anyway. */
+function homeRefresh() {
+ if (!_homeVisible()) return;
+ clearTimeout(_homeRefreshTimer);
+ _homeRefreshTimer = setTimeout(() => {
+ _homeRefreshTimer = null;
+ if (_homeVisible()) _homeLoad();
+ }, _HOME_REFRESH_DEBOUNCE_MS);
+}
diff --git a/src/renderer/modules/icons.js b/src/renderer/modules/icons.js
index 2cd58f82..ba6ea4d5 100644
--- a/src/renderer/modules/icons.js
+++ b/src/renderer/modules/icons.js
@@ -37,6 +37,8 @@
const UI_ICONS = {
search: '<circle cx="11" cy="11" r="7"></circle><path d="m21 21-4.3-4.3"></path>',
+ camera: '<path d="M14.5 4h-5L7 7H3v13h18V7h-4z"></path><circle cx="12" cy="13" r="4"></circle>',
+ smartphone: '<rect x="6" y="2" width="12" height="20" rx="3"></rect><path d="M10 5h4M11 19h2"></path>',
// Video-studio fine-tune drawer icons (lucide-style).
film: '<rect x="3" y="3" width="18" height="18" rx="2"></rect><path d="M7 3v18M17 3v18M3 7.5h4M3 12h18M3 16.5h4M17 7.5h4M17 16.5h4"></path>',
music: '<path d="M9 18V5l12-2v13"></path><circle cx="6" cy="18" r="3"></circle><circle cx="18" cy="16" r="3"></circle>',
@@ -60,9 +62,12 @@
'book-open': '<path d="M12 7v14"></path><path d="M3 5.5A3.5 3.5 0 0 1 6.5 2H12v19H6.5A3.5 3.5 0 0 1 3 17.5z"></path><path d="M21 5.5A3.5 3.5 0 0 0 17.5 2H12v19h5.5a3.5 3.5 0 0 0 3.5-3.5z"></path>',
palette: '<path d="M12 22a10 10 0 1 1 10-10 5 5 0 0 1-5 5h-2.4a1.6 1.6 0 0 0-1.3 2.5l.3.4A1.4 1.4 0 0 1 12 22z"></path><circle cx="7.5" cy="10" r="1" fill="currentColor" stroke="none"></circle><circle cx="10" cy="6.8" r="1" fill="currentColor" stroke="none"></circle><circle cx="14" cy="6.8" r="1" fill="currentColor" stroke="none"></circle><circle cx="16.5" cy="10" r="1" fill="currentColor" stroke="none"></circle>',
download: '<path d="M12 3v12m-5-5 5 5 5-5"></path><path d="M4 15v5h16v-5"></path>',
+ cloud: '<path d="M18 18H6a4 4 0 0 1-.7-7.94A7 7 0 0 1 18.4 8.1 5 5 0 0 1 18 18z"></path>',
globe: '<circle cx="12" cy="12" r="9"></circle><path d="M3 12h18"></path><path d="M12 3a14 14 0 0 1 0 18"></path><path d="M12 3a14 14 0 0 0 0 18"></path>',
database: '<ellipse cx="12" cy="5" rx="8" ry="3"></ellipse><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"></path><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"></path>',
'layout-grid': '<rect x="3" y="3" width="7" height="7" rx="1.5"></rect><rect x="14" y="3" width="7" height="7" rx="1.5"></rect><rect x="3" y="14" width="7" height="7" rx="1.5"></rect><rect x="14" y="14" width="7" height="7" rx="1.5"></rect>',
+ 'chart-spline': '<path d="M3 3v16a2 2 0 0 0 2 2h16"></path><path d="M7 15c6 0 5-8 14-8"></path>',
+ layers: '<path d="m12 3 9 5-9 5-9-5 9-5z"></path><path d="m3 12 9 5 9-5M3 16l9 5 9-5"></path>',
settings: '<circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3 1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8 1.7 1.7 0 0 0 1.5 1h.1a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"></path>',
terminal: '<path d="m8 8 4 4-4 4"></path><path d="M14 16h4"></path><rect x="3" y="4" width="18" height="16" rx="3"></rect>',
x: '<path d="M18 6 6 18M6 6l12 12"></path>',
@@ -181,6 +186,10 @@
return wrapUiIcon(key, UI_ICONS[key], className);
}
+ function projectIconName(project) {
+ return 'folder';
+ }
+
function fileKindForName(name, kind) {
return normalizeFileKind(kind, extOf(name));
}
@@ -208,6 +217,7 @@
}
root.uiIconHtml = uiIconHtml;
+ root.projectIconName = projectIconName;
root.hydrateUiIcons = hydrateUiIcons;
root.fileKindForName = fileKindForName;
root.fileKindIconHtml = fileKindIconHtml;
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index 86d04d61..9d76611c 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -22,6 +22,14 @@ let _ipcErrorSentCount = 0;
// - opts.stream: boolean (this call yields an SSE-style stream)
// - opts.wrapAsUpdates: wrap the whole body under `updates` key
const _IPC_ROUTES = [
+ ['POST', '/api/conversations/cleanup/preview', 'conversations.cleanup.preview'],
+ ['POST', '/api/conversations/cleanup/page', 'conversations.cleanup.page'],
+ ['POST', '/api/conversations/cleanup/remove', 'conversations.cleanup.remove'],
+ ['POST', '/api/local-agents/account-usage', 'localAgents.accountUsage'],
+ ['POST', '/api/conversations/artifacts/edit-target', 'conversations.artifacts.editTarget'],
+ ['POST', '/api/conversations/artifacts/data-impact', 'conversations.artifacts.dataImpact'],
+ ['POST', '/api/conversations/artifacts/export-data', 'conversations.artifacts.exportData'],
+ ['POST', '/api/conversations/artifacts/save', 'conversations.artifacts.save'],
['GET', '/api/projects/tasks/attachments/abs-path', 'projects.tasks.attachments.absPath'],
['POST', '/api/connectors/account-choice-response', 'connectors.account_choice_response'],
// Exact routes
@@ -75,6 +83,7 @@ const _IPC_ROUTES = [
['POST', /^\/api\/conversations\/([^/]+)\/rename$/, 'conversations.rename', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/move$/, 'conversations.move', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/history$/, 'conversations.history', ['cid']],
+ ['GET', /^\/api\/conversations\/([^/]+)\/process$/, 'conversations.processPage', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/turns$/, 'conversations.turns', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/files$/, 'conversations.files.list', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/send$/, 'groupChat.send', ['cid']],
diff --git a/src/renderer/modules/lazy-features.js b/src/renderer/modules/lazy-features.js
index 3f78afab..546f65d0 100644
--- a/src/renderer/modules/lazy-features.js
+++ b/src/renderer/modules/lazy-features.js
@@ -9,6 +9,7 @@ const _rendererFeatureManifest = Object.freeze({
settings: [
{ src: './modules/settings.js' },
{ src: './modules/memory.js' },
+ { src: './modules/task-cleanup.js' },
],
marketplace: [
{ src: './modules/semver.js' },
@@ -63,22 +64,19 @@ function _rendererFeatureLogName(feature) {
: 'unknown';
}
-function _trackRendererFeatureLoad(result, feature, startedAt, retryCount, errorCode = '') {
- const normalizedResult = result === 'success' ? 'success' : 'failure';
+function _logRendererFeatureLoadFailure(feature, startedAt, retryCount, errorCode = '') {
const normalizedFeature = _rendererFeatureLogName(feature);
const normalizedCode = errorCode === 'unknown_feature'
? 'unknown_feature'
: 'script_load_failed';
const payload = {
- result: normalizedResult,
+ result: 'failure',
feature: normalizedFeature,
duration_ms: Math.max(0, Math.round(_rendererFeatureNow() - startedAt)),
retry_count: Math.max(0, Number(retryCount) || 0),
};
- if (normalizedResult === 'failure') payload.error_code = normalizedCode;
- if (normalizedResult === 'failure') {
- try { console.warn('[renderer-feature]', payload); } catch (_) {}
- }
+ payload.error_code = normalizedCode;
+ try { console.warn('[renderer-feature]', payload); } catch (_) {}
}
function _appendRendererFeatureScript(entry) {
@@ -113,7 +111,7 @@ function loadRendererFeature(name) {
const entries = _rendererFeatureManifest[feature];
if (!entries) {
const startedAt = _rendererFeatureNow();
- _trackRendererFeatureLoad('failure', feature, startedAt, 0, 'unknown_feature');
+ _logRendererFeatureLoadFailure(feature, startedAt, 0, 'unknown_feature');
return Promise.reject(new Error(`unknown renderer feature: ${feature}`));
}
const existing = _rendererFeatureLoads.get(feature);
@@ -125,11 +123,8 @@ function loadRendererFeature(name) {
for (const entry of entries) await _appendRendererFeatureScript(entry);
})();
_rendererFeatureLoads.set(feature, run);
- run.then(
- () => _trackRendererFeatureLoad('success', feature, startedAt, attempt - 1),
- () => _trackRendererFeatureLoad('failure', feature, startedAt, attempt - 1, 'script_load_failed'),
- );
run.catch(() => {
+ _logRendererFeatureLoadFailure(feature, startedAt, attempt - 1, 'script_load_failed');
if (_rendererFeatureLoads.get(feature) === run) _rendererFeatureLoads.delete(feature);
});
return run;
diff --git a/src/renderer/modules/library-transfer.js b/src/renderer/modules/library-transfer.js
index d157e26a..f9ba232e 100644
--- a/src/renderer/modules/library-transfer.js
+++ b/src/renderer/modules/library-transfer.js
@@ -175,7 +175,7 @@
value: `project:${project.project_id}`,
label: project.name || project.project_id,
hint: t('contexts.transfer.project_library'),
- iconName: 'folder',
+ iconName: typeof root.projectIconName === 'function' ? root.projectIconName(project) : 'folder',
})),
];
const initialLibrary = _libraryValue(source);
diff --git a/src/renderer/modules/local_agent_user_input.js b/src/renderer/modules/local_agent_user_input.js
index 1f2dda47..d0341884 100644
--- a/src/renderer/modules/local_agent_user_input.js
+++ b/src/renderer/modules/local_agent_user_input.js
@@ -2,7 +2,7 @@
//
// Codex and Claude Code can pause a running turn for structured questions.
// Main pushes a bounded request here; dialogs are serialized, cancellable,
-// and answers return only through IPC (never through the chat transcript).
+// and answers return through IPC. Main saves non-secret conversation replies.
(function () {
const queue = [];
@@ -52,8 +52,8 @@
: [text];
});
try {
- await respond(requestId, answers, false);
- return true;
+ const result = await respond(requestId, answers, false);
+ return result?.handled === true;
} catch (_) {
return false;
}
@@ -149,7 +149,24 @@
}
answers[String(question.id || '')] = value;
}
- await respond(requestId, answers, false);
+ while (!controller.signal.aborted) {
+ const result = await respond(requestId, answers, false);
+ if (result?.handled === true || result?.save_failed !== true) return;
+ // The fallback dialog has already closed, but main has not resumed the
+ // CLI. Retain the collected answers while offering the same save retry.
+ const retry = await uiChoice({
+ title: t('agents.cli_user_input_title'),
+ context: info,
+ message: t('chat.cli_question.send_failed'),
+ choices: [{ id: 'retry', label: t('chat.cli_question.send') }],
+ signal: controller.signal,
+ });
+ if (controller.signal.aborted) return;
+ if (retry !== 'retry') {
+ await respond(requestId, {}, true);
+ return;
+ }
+ }
} catch (error) {
try {
createLogger('local-agent-user-input').warn('structured CLI input response failed', {
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index 75b1cc19..fc1b6cb3 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -1984,7 +1984,7 @@ function _mpActionResult(result) {
return result === 'success' || result === 'cancelled' ? result : 'failure';
}
-function _mpLogActionResult(startedAt, action, kind, result, errorCode = '') {
+function _mpLogActionResult(action, kind, result, errorCode = '') {
const safeAction = _mpActionName(action);
const safeKind = _mpResourceKind(kind);
const safeResult = _mpActionResult(result);
@@ -2040,14 +2040,13 @@ async function _mpInstall(kind, id, itemOverride = null) {
if (!item) return;
const key = `${kind}:${id}`;
if (_mpState.installing.has(key)) return;
- const startedAt = Date.now();
const initialStatus = _mpInstallStatus(kind, item);
const actionName = initialStatus.installed && initialStatus.updateAvailable ? 'update' : 'install';
let resultLogged = false;
const logResult = (result, errorCode = '') => {
if (resultLogged) return;
resultLogged = true;
- _mpLogActionResult(startedAt, actionName, kind, result, errorCode);
+ _mpLogActionResult(actionName, kind, result, errorCode);
};
_mpState.installing.add(key);
_mpRender();
@@ -2131,12 +2130,11 @@ async function _mpUninstall(kind, id) {
if (!_mpState.uninstalling) _mpState.uninstalling = new Set();
const key = `${kind}:${id}`;
if (_mpState.installing.has(key)) return;
- const startedAt = Date.now();
let resultLogged = false;
const logResult = (result, errorCode = '') => {
if (resultLogged) return;
resultLogged = true;
- _mpLogActionResult(startedAt, 'uninstall', kind, result, errorCode);
+ _mpLogActionResult('uninstall', kind, result, errorCode);
};
_mpState.installing.add(key);
_mpState.uninstalling.add(key);
diff --git a/src/renderer/modules/math.js b/src/renderer/modules/math.js
index c73c74ab..f4d646fc 100644
--- a/src/renderer/modules/math.js
+++ b/src/renderer/modules/math.js
@@ -103,6 +103,7 @@ async function typesetMathHtml(html, { cache = true } = {}) {
if (typeof document === 'undefined' || !document.createElement) return key;
const host = document.createElement('div');
host.className = 'math-typeset-buffer';
+ host.dataset.uiLayoutChrome = '';
host.style.position = 'fixed';
host.style.left = '-10000px';
host.style.top = '0';
diff --git a/src/renderer/modules/oss.js b/src/renderer/modules/oss.js
index 7540029d..ab088a6f 100644
--- a/src/renderer/modules/oss.js
+++ b/src/renderer/modules/oss.js
@@ -331,35 +331,18 @@ function ossOpenRepo(p) {
// ③ behavior — prefill the Commander composer, focus, NO send. The caret lands
// on the first `[...]` placeholder (the blank task slot) when present, so the
// user types their specific task over it; otherwise it goes to the end.
-function _setOssCommanderAttribution(input, raw) {
- if (!input || !input.dataset || !raw || typeof raw !== 'object') return;
- if (typeof window.setCommanderTemplateAttribution === 'function') {
- window.setCommanderTemplateAttribution(input, raw);
- return;
- }
- const resourceId = String(raw.resource_id || '').trim();
- const position = Math.round(Number(raw.position) || 0);
- input.dataset.commanderEntryPoint = 'oss_tool';
- if (/^[A-Za-z0-9._-]{1,64}$/.test(resourceId)) input.dataset.commanderResourceId = resourceId;
- input.dataset.commanderSource = 'commander_home';
- input.dataset.commanderRecipientType = 'commander';
- if (position > 0 && position <= 100) input.dataset.commanderPosition = String(position);
-}
-
-function prefillCommander(text, attribution, opts = {}) {
+function prefillCommander(text, opts = {}) {
const value = String(text || '');
if (!value) return false;
if (typeof setView === 'function') setView('new-chat');
if (typeof setChatRecipient === 'function') setChatRecipient('new-chat', { kind: 'commander' });
const input = document.getElementById('new-chat-input');
if (!input) {
- _ossLog.warn('Commander OSS prefill failed: composer missing', {
- resource_id: String((attribution && attribution.resource_id) || ''),
- });
+ _ossLog.warn('Commander OSS prefill failed: composer missing');
return false;
}
composerSetText(input, value);
- if (attribution) _setOssCommanderAttribution(input, attribution);
+ input.dataset.ossTemplateDraft = '1';
const m = opts.trackPlaceholder === false ? null : value.match(/\[[^\]]*\]/);
if (m) input.dataset.ossTemplatePlaceholder = m[0];
else delete input.dataset.ossTemplatePlaceholder;
@@ -399,8 +382,8 @@ function unresolvedOssTemplatePlaceholder(input) {
function _ossPromptForComposer(p, input) {
const prompt = ossPromptFor(p);
const existing = String((input && composerText(input)) || '').trim();
- const existingEntryPoint = String((input && input.dataset && input.dataset.commanderEntryPoint) || '');
- if (!existing || existingEntryPoint === 'oss_tool') return prompt;
+ const existingOssDraft = input?.dataset?.ossTemplateDraft === '1';
+ if (!existing || existingOssDraft) return prompt;
if (/\[[^\]]*\]/.test(prompt)) return prompt.replace(/\[[^\]]*\]/, () => existing);
return `${prompt}\n\n${existing}`;
}
diff --git a/src/renderer/modules/overlay-manager.js b/src/renderer/modules/overlay-manager.js
new file mode 100644
index 00000000..fa6b4580
--- /dev/null
+++ b/src/renderer/modules/overlay-manager.js
@@ -0,0 +1,208 @@
+// Application layer ownership is declared by CSS, not browser-specific names.
+// A new instance of a shared floating style automatically participates. Custom
+// inline surfaces use .ui-overlay or data-ui-overlay. Only trusted app DOM is
+// inspected; remote pages/frames cannot acquire application layer ownership.
+(function () {
+ const log = createLogger('overlay-manager');
+ const candidates = new Set();
+ const listeners = new Set();
+ const semanticRoots = '[role="dialog"], [role="alertdialog"], [role="menu"], [aria-modal="true"], [popover], dialog[open]';
+ let selector = semanticRoots + ', .ui-overlay, [data-ui-overlay], [style*="--orkas-ui-layer"]';
+ let active = new Set();
+ let browserOpen = false;
+ let revision = 0;
+ let epoch = 0;
+ let sentBlocked = null;
+ let acknowledgedBlocked = false;
+ let pending = Promise.resolve(true);
+ let scheduled = false;
+
+ function readStyles() {
+ const selectors = new Set([semanticRoots, '.ui-overlay', '[data-ui-overlay]', '[style*="--orkas-ui-layer"]']);
+ const visited = new Set();
+ const readSheet = (sheet) => {
+ if (visited.has(sheet)) return;
+ visited.add(sheet);
+ try { visit(sheet.cssRules); } catch (_) {}
+ };
+ const visit = (rules) => {
+ for (const rule of rules) {
+ if (rule.selectorText && rule.style?.getPropertyValue('--orkas-ui-layer').trim() === 'overlay') {
+ selectors.add(rule.selectorText);
+ }
+ if (rule.cssRules) visit(rule.cssRules);
+ if (rule.styleSheet) readSheet(rule.styleSheet);
+ }
+ };
+ for (const sheet of document.styleSheets) {
+ // Third-party sheet contents are not an app layer declaration.
+ readSheet(sheet);
+ }
+ selector = [...selectors].join(', ');
+ }
+
+ function discover(root) {
+ if (root.nodeType !== 1) return;
+ if (root.matches(selector)) candidates.add(root);
+ for (const element of root.querySelectorAll(selector)) candidates.add(element);
+ }
+
+ function displayed(element) {
+ if (!element.isConnected || element.hidden) return false;
+ const style = window.getComputedStyle(element);
+ const kind = style.getPropertyValue('--orkas-ui-layer').trim();
+ // Standards-based third-party menus/dialogs also participate, without a
+ // vendor-name inventory. Inline ARIA regions are not floating surfaces.
+ const semantic = kind !== 'chrome' && element.matches(semanticRoots)
+ && (['absolute', 'fixed'].includes(style.position) || element.matches('[popover], dialog[open]'));
+ const declared = element.matches('.ui-overlay, [data-ui-overlay]')
+ || kind === 'overlay' || semantic;
+ return declared && style.display !== 'none' && style.visibility !== 'hidden'
+ && style.visibility !== 'collapse'
+ && [...element.getClientRects()].some(rect => rect.width > 0 && rect.height > 0);
+ }
+
+ function gatePendingLayers() {
+ // Keep a newly opened surface unpainted until main has removed the native
+ // pixels. Opacity does not change its geometry or the detection above.
+ for (const element of candidates) {
+ const waiting = browserOpen && active.has(element) && !acknowledgedBlocked;
+ if (element.classList.contains('ui-overlay-waiting') !== waiting) {
+ element.classList.toggle('ui-overlay-waiting', waiting);
+ }
+ }
+ }
+
+ function synchronize(force = false) {
+ const blocked = active.size > 0;
+ if (!browserOpen) {
+ sentBlocked = null;
+ acknowledgedBlocked = false;
+ gatePendingLayers();
+ return pending = Promise.resolve(true);
+ }
+ if (!force && sentBlocked === blocked) {
+ gatePendingLayers();
+ return pending;
+ }
+ sentBlocked = blocked;
+ const request = ++revision;
+ const documentEpoch = epoch;
+ if (!blocked) acknowledgedBlocked = false;
+ gatePendingLayers();
+ pending = window.orkas.invoke('webAssist.overlayState', { blocked, revision: request, epoch: documentEpoch }).then(result => {
+ if (documentEpoch !== epoch || request !== revision || !browserOpen) return true;
+ if (!result?.ok) throw new Error('overlay presentation unavailable');
+ acknowledgedBlocked = result.blocked === true;
+ gatePendingLayers();
+ return true;
+ }).catch(() => {
+ if (documentEpoch === epoch && request === revision && browserOpen) {
+ // Permit a later state change/explicit refresh to retry; never display
+ // a floating control underneath a native page after an IPC failure.
+ sentBlocked = null;
+ log.warn('overlay presentation update failed');
+ }
+ return false;
+ });
+ return pending;
+ }
+
+ function refresh() {
+ const next = new Set();
+ for (const element of candidates) {
+ if (!element.isConnected || !element.matches(selector)) candidates.delete(element);
+ else if (displayed(element)) next.add(element);
+ }
+ const changed = next.size !== active.size || [...next].some(element => !active.has(element));
+ active = next;
+ synchronize();
+ if (changed) for (const listener of listeners) listener();
+ return active.size;
+ }
+
+ function scheduleRefresh() {
+ if (scheduled) return;
+ scheduled = true;
+ queueMicrotask(() => { scheduled = false; refresh(); });
+ }
+
+ function setBrowserOpen(open, documentEpoch = epoch) {
+ const next = !!open;
+ if (browserOpen === next && epoch === documentEpoch) return;
+ browserOpen = next;
+ epoch = documentEpoch;
+ // Invalidate old acknowledgements across close/reopen of the browser.
+ revision += 1;
+ sentBlocked = null;
+ acknowledgedBlocked = false;
+ refresh();
+ }
+
+ readStyles();
+ discover(document.body);
+ refresh();
+ new MutationObserver(records => {
+ let relevant = false;
+ let stylesChanged = false;
+ for (const record of records) {
+ const target = record.target;
+ if (target.nodeType === 1 && target.matches('style')) stylesChanged = true;
+ if (record.type === 'childList') {
+ for (const node of record.addedNodes) {
+ if (node.nodeType !== 1) continue;
+ if (node.matches('style, link[rel="stylesheet"]') || node.querySelector('style, link[rel="stylesheet"]')) stylesChanged = true;
+ const size = candidates.size;
+ discover(node);
+ if (size !== candidates.size) relevant = true;
+ }
+ if (record.removedNodes.length && [...candidates].some(element => !element.isConnected)) relevant = true;
+ } else if (target.nodeType === 1 && target.matches(selector)) {
+ candidates.add(target);
+ relevant = true;
+ }
+ // Changes in a floating root or its ancestors can alter layout/visibility.
+ // Ordinary transcript mutations do not scan the body or every message.
+ if (!relevant && target.nodeType === 1) {
+ relevant = [...candidates].some(element => element.contains(target) || target.contains(element));
+ }
+ }
+ if (stylesChanged) { readStyles(); discover(document.body); relevant = true; }
+ if (relevant) scheduleRefresh();
+ }).observe(document.documentElement, {
+ subtree: true, childList: true, attributes: true,
+ attributeFilter: ['hidden', 'class', 'style', 'data-ui-overlay', 'role', 'aria-modal', 'open', 'popover'],
+ });
+ window.addEventListener('resize', scheduleRefresh);
+ document.addEventListener('toggle', scheduleRefresh, true);
+ // CSS-driven popovers can change without a DOM mutation. Refresh only the
+ // recorded roots on hover/focus transitions, never on every pointer move.
+ for (const event of ['pointerover', 'pointerout', 'focusin', 'focusout']) {
+ document.addEventListener(event, scheduleRefresh, true);
+ }
+ document.addEventListener('load', event => {
+ if (event.target?.matches?.('link[rel="stylesheet"]')) {
+ readStyles(); discover(document.body); scheduleRefresh();
+ }
+ }, true);
+
+ window.OverlayManager = {
+ hasOpenLayers: () => active.size > 0,
+ count: () => active.size,
+ refresh,
+ setBrowserOpen,
+ settled: () => pending,
+ version: () => revision,
+ epoch: () => epoch,
+ hasModalLayers: () => [...active].some(element => element.matches('[aria-modal="true"]')
+ || !!element.querySelector('[aria-modal="true"]')),
+ layerForEvent(event) {
+ // composedPath survives removal by an earlier Escape handler.
+ return (event.composedPath?.() || [event.target]).find(element => (
+ element?.nodeType === 1 && element.matches(selector)
+ && window.getComputedStyle(element).getPropertyValue('--orkas-ui-layer').trim() !== 'chrome'
+ )) || null;
+ },
+ subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
+ };
+})();
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index c7de9d9c..b9d565b8 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -2,8 +2,8 @@
// Drives `#panel-project`: shows the project composer, task panes, and a
// right-side rail for project agents + files.
//
-// Header carries Rename / Delete. The "Back" button
-// was intentionally removed — the sidebar IS the back navigation.
+// Header carries the title and a menu with Rename and Delete.
+// The sidebar provides back navigation.
//
// Add picker and project-file viewer are centered modals (`.modal-overlay`)
// so they don't get clipped by the project panel's scrolling regions.
@@ -89,6 +89,7 @@ const _projectLibraryExpanded = new Set();
const _projectLibrarySelected = new Set();
let _projectLibrarySelectionAnchor = null;
const _projectLibraryDrafts = new Map();
+let _projectLibraryRevision = 0;
let _projectKbStatusRefreshTimer = null;
let _projectKbReconcileInFlight = false;
let _projectKbReconciledLoadSeq = -1;
@@ -113,7 +114,9 @@ function _setProjectDetailBusy(busy) {
/** Called by boot.js setView('project', pid) on entry. */
async function loadProjectDetail(pid) {
+ _closeProjectDriverHint();
const loadSeq = ++_projectDetailLoadSeq;
+ const libraryRevision = _projectLibraryRevision;
const account = typeof currentUserId === 'string' ? currentUserId : '';
const isCurrent = () => loadSeq === _projectDetailLoadSeq && pid === _projectDetailPid
&& account === (typeof currentUserId === 'string' ? currentUserId : '');
@@ -135,9 +138,12 @@ async function loadProjectDetail(pid) {
}
if (prevPid !== _projectDetailPid || !_projectDetailMeta) {
_projectTodos = [];
+ _projectTodoMembers = [];
+ _projectTodoMemberScope = '';
_setTodoLoadError(false);
_renderProjectTodosList();
_projectMemory = [];
+ _projectMemoryFull = false;
_projectMemoryEditor = null;
_projectMemoryLoadSeq += 1;
_projectKbStatusByName = {};
@@ -217,7 +223,7 @@ async function loadProjectDetail(pid) {
_renderProjectInstructions();
}).catch(() => { /* the batch below owns the load failure */ });
filesCall.then((res) => {
- if (!isCurrent() || !res?.ok || !_projectDetailMeta) return;
+ if (!isCurrent() || !res?.ok || !_projectDetailMeta || libraryRevision !== _projectLibraryRevision) return;
_projectDetailMeta.files = Array.isArray(res.tree) ? res.tree : [];
_renderProjectFiles(_projectDetailMeta.files);
_bindProjectFileRows();
@@ -235,7 +241,8 @@ async function loadProjectDetail(pid) {
if (!getRes?.ok || !listRes?.ok || !filesRes?.ok) {
throw new Error((getRes && getRes.error) || (listRes && listRes.error) || (filesRes && filesRes.error) || 'load_failed');
}
- const fileTree = Array.isArray(filesRes.tree) ? filesRes.tree : [];
+ const fileTree = libraryRevision === _projectLibraryRevision
+ ? (Array.isArray(filesRes.tree) ? filesRes.tree : []) : (_projectDetailMeta?.files || []);
const flatFiles = _flattenProjectLibraryFiles(fileTree);
_projectKbStatusByName = _buildProjectKbStatusMap(flatFiles, kbRes?.ok ? (kbRes.files || []) : []);
_projectDetailMeta = {
@@ -301,14 +308,7 @@ function _renderProjectAgents() {
function _renderProjectDetail({ hydrateSecondary = true, refreshMemory = hydrateSecondary } = {}) {
if (!_projectDetailMeta) { _renderProjectDetailEmpty(); return; }
const { project, files } = _projectDetailMeta;
- const renameBtn = document.getElementById('project-action-rename');
- const deleteBtn = document.getElementById('project-action-delete');
const addAgentBtn = document.getElementById('project-add-agent-btn');
- if (renameBtn) renameBtn.hidden = false;
- if (deleteBtn) {
- deleteBtn.hidden = false;
- deleteBtn.setAttribute('data-i18n', 'project.action.delete');
- }
if (addAgentBtn) addAgentBtn.hidden = false;
const titleEl = document.getElementById('project-detail-title');
@@ -421,6 +421,7 @@ async function _ensureProjectAutoTabLoaded(pid) {
}
function _syncProjectDetailTabState() {
+ if (_projectDetailActiveTab !== 'todo') _closeProjectDriverHint();
const tabs = document.querySelectorAll('.project-detail-tab');
const panels = document.querySelectorAll('.project-detail-tab-panel');
for (const tab of tabs) {
@@ -434,6 +435,10 @@ function _syncProjectDetailTabState() {
panel.hidden = (panel.dataset.projectPanel !== _projectDetailActiveTab);
panel.setAttribute('role', 'tabpanel');
}
+ // The tab row carries only the active tab's tools.
+ for (const tools of document.querySelectorAll('[data-project-tools]')) {
+ tools.hidden = tools.dataset.projectTools !== _projectDetailActiveTab;
+ }
}
/** The right rail has two compact tab groups. Their cards stay fixed in the
@@ -706,9 +711,7 @@ function _onProjectAdvance(payload) {
const pid = payload && payload.projectId;
if (!conv || !conv.conversation_id) return;
if (typeof conversations === 'undefined' || !Array.isArray(conversations)) return;
- const idx = conversations.findIndex((c) => c && c.conversation_id === conv.conversation_id);
- if (idx >= 0) conversations[idx] = { ...conversations[idx], ...conv };
- else conversations.unshift(conv);
+ _cacheCreatedConversation(conv);
if (typeof renderConversationList === 'function') renderConversationList();
if (currentView === 'project' && _projectDetailMeta && pid === _projectDetailPid) {
_renderProjectAllTasks();
@@ -832,18 +835,21 @@ let _projectMemoryLoadSeq = 0;
let _projectMemoryLoadedPid = '';
let _projectMemoryEditor = null; // { mode:'add'|'edit', oldText:string } | null
let _projectMemoryMutating = false;
+let _projectMemoryFull = false; // the store refuses new entries until the AI consolidates it
async function _loadProjectMemory(pid) {
const loadSeq = ++_projectMemoryLoadSeq;
_projectMemoryLoadedPid = '';
const account = typeof currentUserId === 'string' ? currentUserId : '';
- if (!pid) { _projectMemory = []; _renderProjectMemoryList(); return; }
+ if (!pid) { _projectMemory = []; _projectMemoryFull = false; _renderProjectMemoryList(); return; }
let nextMemory = [];
+ let nextFull = false;
let loaded = false;
try {
const res = await window.orkas.invoke('memory.list', { target: 'project', projectId: pid });
loaded = !!res?.ok && Array.isArray(res.entries);
nextMemory = loaded ? res.entries : [];
+ nextFull = loaded && !!res.usage?.full;
} catch (err) {
_projectDetailLog.warn('load project memory failed', err);
nextMemory = [];
@@ -851,6 +857,7 @@ async function _loadProjectMemory(pid) {
if (loadSeq !== _projectMemoryLoadSeq || pid !== _projectDetailPid
|| account !== (typeof currentUserId === 'string' ? currentUserId : '')) return;
_projectMemory = nextMemory;
+ _projectMemoryFull = nextFull;
_projectMemoryLoadedPid = loaded ? pid : '';
_renderProjectMemoryList();
}
@@ -907,6 +914,8 @@ function _renderProjectMemoryList() {
// the goals-and-rules panel makes.
const headEl = document.getElementById('project-memory-section-head');
if (headEl) headEl.hidden = !shown;
+ const fullEl = document.getElementById('project-memory-full');
+ if (fullEl) fullEl.hidden = !(shown && _projectMemoryFull);
}
function _updateProjectMemoryEditor() {
@@ -955,6 +964,9 @@ function _projectMemoryFailure(value, invoked = false) {
if (message.includes('empty content')) {
return { error_type: 'validation', error_code: 'memory_content_empty' };
}
+ if (message.startsWith('memory full')) {
+ return { error_type: 'validation', error_code: 'memory_full' };
+ }
if (message.includes('old_text is required')) {
return { error_type: 'validation', error_code: 'memory_entry_selector_missing' };
}
@@ -996,13 +1008,20 @@ async function _mutateProjectMemory(channel, payload) {
if (!res || res.ok === false) {
const failure = _projectMemoryFailure(res);
_projectDetailLog.warn('project memory mutate rejected', failure);
- if (typeof uiAlert === 'function') uiAlert(t('project.memory.failed'));
+ if (failure.error_code === 'memory_full') {
+ _projectMemoryFull = true;
+ _renderProjectMemoryList();
+ }
+ if (typeof uiAlert === 'function') {
+ uiAlert(t(failure.error_code === 'memory_full' ? 'memory.error_full' : 'project.memory.failed'));
+ }
return { ok: false, failure };
}
if (pid !== _projectDetailPid) return { ok: true, failure: null };
try {
if (Array.isArray(res.entries)) {
_projectMemory = res.entries;
+ _projectMemoryFull = !!res.usage?.full;
_renderProjectMemoryList();
} else {
await _loadProjectMemory(pid);
@@ -1160,7 +1179,16 @@ function _todoAttachAccept() {
async function _loadProjectTodos(pid) {
const loadSeq = ++_projectTodoLoadSeq;
- if (!pid) { _projectTodos = []; _renderProjectTodosList(); return; }
+ const account = typeof currentUserId === 'string' ? currentUserId : '';
+ const isCurrent = () => loadSeq === _projectTodoLoadSeq && pid === _projectDetailPid
+ && account === (typeof currentUserId === 'string' ? currentUserId : '');
+ if (!pid) {
+ _projectTodos = [];
+ _projectTodoMembers = [];
+ _projectTodoMemberScope = '';
+ _renderProjectTodosList();
+ return;
+ }
let nextTodos = [];
try {
const res = await window.orkas.invoke('projects.tasks.list', { projectId: pid });
@@ -1169,18 +1197,23 @@ async function _loadProjectTodos(pid) {
if (pid === _projectDetailPid && loadSeq === _projectTodoLoadSeq) _setTodoLoadError(false);
} catch (err) {
_projectDetailLog.warn('load project todos failed');
- if (pid === _projectDetailPid && loadSeq === _projectTodoLoadSeq) _setTodoLoadError(true);
+ if (isCurrent()) _setTodoLoadError(true);
return;
}
// Ignore responses superseded by a mutation/newer refresh as well as
// responses that belong to a project the user has already left.
- if (loadSeq !== _projectTodoLoadSeq || pid !== _projectDetailPid) return;
+ if (!isCurrent()) return;
_projectTodos = nextTodos;
_renderProjectTodosList();
}
// Disclosure preferences are presentation-only and never rewrite task records.
const _todoCollapsed = new Map();
+const _todoExpanded = new Set();
+function _todoContentKey(tid, context) {
+ return JSON.stringify([typeof currentUserId === 'string' ? currentUserId : '',
+ context.global ? 'global' : 'project', context.pid || '', tid]);
+}
function _todoBoardStatus(status) {
return _PROJECT_TODO_STATUSES.includes(status) ? status : 'todo';
}
@@ -1193,15 +1226,54 @@ function _todoContextHasScope(context) {
return !!context && (context.global === true || !!context.pid);
}
+// Capture immediately before a paint, so scrolling during an async reload is
+// retained. Keep only the mounted board's positions; never carry them across
+// accounts, projects or grouping modes. Browsers clamp after content shrinks.
+function _captureTodoScroll(host) {
+ const boards = new Map();
+ for (const board of host.querySelectorAll?.('.todo-board') || []) {
+ const columns = new Map();
+ for (const body of board.querySelectorAll('.todo-column-body')) {
+ columns.set(body.parentElement.dataset.status, [body.scrollTop, body.scrollLeft]);
+ }
+ boards.set(board.dataset.todoScrollKey, { top: board.scrollTop, left: board.scrollLeft, columns });
+ }
+ return { top: host.scrollTop, left: host.scrollLeft, boards };
+}
+
+function _restoreTodoScroll(host, snapshot) {
+ let matched = false;
+ for (const board of host.querySelectorAll?.('.todo-board') || []) {
+ const previous = snapshot.boards.get(board.dataset.todoScrollKey);
+ if (!previous) continue;
+ matched = true;
+ board.scrollTop = previous.top;
+ board.scrollLeft = previous.left;
+ for (const body of board.querySelectorAll('.todo-column-body')) {
+ const position = previous.columns.get(body.parentElement.dataset.status);
+ if (!position) continue;
+ [body.scrollTop, body.scrollLeft] = position;
+ }
+ }
+ if (matched) {
+ host.scrollTop = snapshot.top;
+ host.scrollLeft = snapshot.left;
+ }
+}
+
function _renderTodoBoard(tasks, context, scope) {
const board = document.createElement('div');
board.className = 'todo-board';
+ board.dataset.todoScrollKey = JSON.stringify([
+ typeof currentUserId === 'string' ? currentUserId : '', scope,
+ ]);
for (const status of _PROJECT_TODO_STATUSES) {
const items = tasks.filter((task) => task?.id && _todoBoardStatus(task.status) === status);
const key = scope + ':' + status;
const collapsed = _todoCollapsed.has(key) ? _todoCollapsed.get(key) : status === 'done';
const column = document.createElement('section');
- column.className = 'todo-column is-' + status;
+ // `is-collapsed` lets the project board narrow a collapsed lane to a strip.
+ column.className = 'todo-column is-' + status + (collapsed ? ' is-collapsed' : '');
column.dataset.status = status;
const header = document.createElement('div');
header.className = 'todo-column-head';
@@ -1209,7 +1281,7 @@ function _renderTodoBoard(tasks, context, scope) {
toggle.type = 'button';
toggle.className = 'todo-collapse';
toggle.setAttribute('aria-expanded', String(!collapsed));
- toggle.innerHTML = '<span class="project-todo-status-dot"></span><span>'
+ toggle.innerHTML = '<span class="project-todo-status-dot"></span><span class="todo-collapse-label">'
+ escapeHtml(t('project.todo.status_' + status)) + '</span><span class="project-detail-tab-count">'
+ items.length + '</span>'
+ (typeof uiIconHtml === 'function' ? uiIconHtml('chevron-down', 'todo-disclosure-chevron') : '');
@@ -1220,6 +1292,7 @@ function _renderTodoBoard(tasks, context, scope) {
body.hidden = !body.hidden;
_todoCollapsed.set(key, body.hidden);
toggle.setAttribute('aria-expanded', String(!body.hidden));
+ column.classList.toggle('is-collapsed', body.hidden);
});
header.appendChild(toggle);
for (const task of items) {
@@ -1250,22 +1323,26 @@ function _renderProjectTodosList() {
if (countEl) countEl.textContent = String(tasks.length);
const listEl = document.getElementById('project-todo-list');
if (!listEl) return;
+ const scroll = _captureTodoScroll(listEl);
listEl.innerHTML = '';
listEl.style.display = '';
const context = _projectTodoContext();
// The board always renders its four columns; each column carries its own
// empty hint, so there is no list-level empty element.
listEl.appendChild(_renderTodoBoard(tasks, context, 'project:' + _projectDetailPid));
+ _restoreTodoScroll(listEl, scroll);
}
function _renderTodoCard(task, context) {
const status = task.status || 'todo';
const row = document.createElement('div');
- row.className = 'project-todo-item' + (status === 'done' ? ' is-done' : '');
+ const expanded = _todoExpanded.has(_todoContentKey(task.id, context));
+ row.className = 'project-todo-item' + (status === 'done' ? ' is-done' : '')
+ + (expanded ? ' is-expanded' : '');
row.dataset.tid = task.id;
row.dataset.status = status;
- // The status chip and menu use the same four workflow states.
+ // Keep the same status chip on project and account boards.
const statusSel = document.createElement('button');
statusSel.type = 'button';
statusSel.className = 'btn btn-sm project-todo-status-select is-' + status;
@@ -1278,7 +1355,8 @@ function _renderTodoCard(task, context) {
+ (typeof uiIconHtml === 'function' ? uiIconHtml('chevron-down', 'project-todo-status-caret') : '');
const content = document.createElement('button');
content.type = 'button';
- content.dataset.action = 'todo-edit';
+ content.dataset.action = 'todo-toggle-content';
+ content.setAttribute('aria-expanded', String(expanded));
content.className = 'project-todo-title';
content.textContent = task.content || '';
row.appendChild(content);
@@ -1295,9 +1373,9 @@ function _renderTodoCard(task, context) {
row.appendChild(menuBtn);
row.dataset.pid = context.pid || '';
row.dataset.todoScope = context.global ? 'global' : 'project';
- const metaRow = context.showProject ? document.createElement('div') : null;
- if (metaRow) metaRow.className = 'todo-card-meta';
- const appendMeta = (element) => (metaRow || row).appendChild(element);
+ const metaRow = document.createElement('div');
+ metaRow.className = 'todo-card-meta';
+ const appendMeta = (element) => metaRow.appendChild(element);
if (context.showProject && context.project) {
const project = document.createElement(context.pid ? 'button' : 'span');
if (context.pid) {
@@ -1306,7 +1384,7 @@ function _renderTodoCard(task, context) {
}
project.className = 'todo-card-project';
const projectIcon = typeof uiIconHtml === 'function'
- ? uiIconHtml('folder', 'todo-card-project-icon')
+ ? uiIconHtml(typeof projectIconName === 'function' ? projectIconName(context.project) : 'folder', 'todo-card-project-icon')
: '';
project.innerHTML = projectIcon
+ `<span class="todo-card-project-name">${escapeHtml(context.project.name)}</span>`;
@@ -1344,8 +1422,8 @@ function _renderTodoCard(task, context) {
}
// Assignment chip: (re)assign the task to one of the project's bound agents
- // or clear it. Global tasks use the account registry. Assigned → the owner's avatar + name (always visible);
- // unassigned → a faint icon revealed on row hover. Click opens the menu
+ // or clear it. Global tasks use the account registry. Both assigned and
+ // unassigned Agents show an icon and label. Click opens the menu
// built in _openTodoAssignMenu; the write goes through projects.tasks.update
// (owner_agent + owner_agent_id), the same fields the agent/LLM path uses.
{
@@ -1376,9 +1454,11 @@ function _renderTodoCard(task, context) {
: '×';
} else {
assign.classList.add('is-empty');
- assign.innerHTML = typeof uiIconHtml === 'function'
- ? uiIconHtml('users', 'project-todo-assign-icon')
+ const emptyIcon = typeof uiIconHtml === 'function'
+ ? `<span class="project-todo-agent-icon">${uiIconHtml('users', 'project-todo-assign-icon')}</span>`
: '+';
+ assign.innerHTML = emptyIcon
+ + `<span class="project-todo-assign-name">${escapeHtml(t('todo.unassigned'))}</span>`;
assign.title = t('project.todo.assign');
}
assign.setAttribute('aria-label', assign.title);
@@ -1465,8 +1545,7 @@ async function _loadTodoEditorAgents(task) {
if (seq !== _todoEditorAgentLoadSeq || generation !== _todoEditorGeneration || pid !== _todoEditorPid) return;
const agents = pid ? res?.agentDetails : res?.agents;
if (res?.ok === false || !Array.isArray(agents)) throw new Error('load_failed');
- _todoEditorAgents = agents.filter((a) => a?.agent_id && (pid || a.enabled !== false))
- .sort((a, b) => String(a.name || a.agent_id).localeCompare(String(b.name || b.agent_id)));
+ _todoEditorAgents = _todoAssignableAgents(agents.filter((a) => a?.agent_id && (pid || a.enabled !== false)));
const owner = _findProjectAgent(task?.owner_agent_id, task?.owner_agent, _todoEditorAgents);
const value = owner?.agent_id || ownerValue;
const next = [{ value: '', label: t('todo.unassigned') },
@@ -1533,6 +1612,10 @@ async function _previewTodoAttachment(pid, taskId, name, sourceElement) {
if (pid === null || !taskId || !name || typeof openChatFileViewer !== 'function') return;
try {
const result = await window.orkas.invoke('projects.tasks.attachments.absPath', { projectId: pid, taskId, name });
+ if (result?.error === 'loading') {
+ if (typeof uiToast === 'function') uiToast(t('common.loading'));
+ return;
+ }
if (!result?.ok || !result.path) throw new Error('attachment_unavailable');
await openChatFileViewer(result.path, name, { projectId: pid || null, cid: null, readOnly: true, sourceElement });
} catch (_) {
@@ -1854,23 +1937,36 @@ async function _setTodoStatus(tid, status, context = _projectTodoContext()) {
}
}
-// Look up an owner's avatar/name from the project's bound-agent details so the
-// chip can render a real avatar. Falls back to null (chip shows the stored
-// owner_agent name) if the owner is no longer a bound member.
+function _todoCommanderAgent() {
+ const avatar = typeof _commanderAvatarFallback === 'function' ? _commanderAvatarFallback()
+ : { icon: 'crown', color: 'gold' };
+ return { agent_id: 'commander', name: t('chat.recipient_commander'), enabled: true, ...avatar };
+}
+
+function _todoAssignableAgents(list = []) {
+ return [_todoCommanderAgent(), ...list.filter((a) => a?.agent_id && a.agent_id !== 'commander')
+ .slice().sort((a, b) => String(a.name || a.agent_id).localeCompare(String(b.name || b.agent_id)))];
+}
+
+// Commander is always available. Other owners resolve from the scope's agent
+// details; missing owners keep their stored display name on the chip.
function _findProjectAgent(agentId, name, list = _projectDetailMeta?.agentDetails || []) {
+ if (agentId === 'commander' || (!agentId && (name === 'commander' || name === 'Commander'))) {
+ return _todoCommanderAgent();
+ }
if (agentId) {
const byId = list.find((a) => a && a.agent_id === agentId);
if (byId) return byId;
}
if (name) {
- const byName = list.find((a) => a && a.name === name);
+ const byName = list.find((a) => a && a.agent_id !== 'commander' && a.name === name);
if (byName) return byName;
}
return null;
}
// Assign / reassign / clear the owner of a task. Owners must be project-bound
-// agents, or available account agents for global tasks; an empty
+// agents, available account agents for global tasks, or Commander; an empty
// owner clears both fields. Passing agent=null unassigns.
async function _assignTodoAgent(tid, agent, context = _projectTodoContext()) {
if (!_todoContextHasScope(context)) return;
@@ -1897,13 +1993,16 @@ let _projectTodoRunning = false;
// global assistant, then open it so the user can follow the work. Completion
// and review decisions belong to the executor, not this navigation action.
async function _runTodoTask(tid, context = _projectTodoContext()) {
- if (_projectTodoRunning || !context) return;
+ const task = (context?.tasks || []).find((item) => item.id === tid);
+ if (_projectTodoRunning || !task || task.status === 'done') return;
if (typeof ensureModelConfigured === 'function' && !ensureModelConfigured()) return;
_projectTodoRunning = true;
const startedAt = Date.now();
let ok = false;
let cid = '';
let conversation = null;
+ let reused = false;
+ let busy = false;
try {
const res = await window.orkas.invoke('projects.tasks.run', {
projectId: context.pid,
@@ -1912,19 +2011,29 @@ async function _runTodoTask(tid, context = _projectTodoContext()) {
ok = !!(res && res.ok);
cid = (res && res.cid) || '';
conversation = (res && res.conversation) || null;
+ reused = !!(res && res.reused);
+ busy = !ok && !!(res && res.error === 'conversation_busy' && cid);
} catch (err) {
_projectDetailLog.warn('project todo run failed', err);
} finally {
_projectTodoRunning = false;
}
+ if (busy) {
+ // Its conversation is still working: take the user there instead of
+ // starting a second run in parallel.
+ if (typeof setView === 'function') setView('conversation', cid);
+ if (typeof uiAlert === 'function') uiAlert(t('project.todo.run_busy'));
+ return;
+ }
if (!ok) {
_projectLogFailure('project_todo_run', { error_type: 'run_failed' });
if (typeof uiAlert === 'function') uiAlert(t('project.todo.run_failed'));
return;
}
- // Surface the new conversation in the list, then open it.
- if (conversation && typeof conversations !== 'undefined' && Array.isArray(conversations)) {
- conversations.unshift(conversation);
+ // Surface a newly created conversation in the list, then open it. A run in
+ // the to-do's own conversation is already listed.
+ if (!reused && conversation && typeof conversations !== 'undefined' && Array.isArray(conversations)) {
+ _cacheCreatedConversation(conversation);
if (typeof renderConversationList === 'function') renderConversationList();
}
if (typeof loadProjects === 'function') loadProjects(true);
@@ -1958,14 +2067,11 @@ function _openTodoRowMenu(evt, tid, context = _projectTodoContext()) {
function _openTodoAssignMenu(evt, tid, context = _projectTodoContext()) {
if (!_todoContextHasScope(context) || typeof showContextMenu !== 'function') return;
const task = (context.tasks || []).find((x) => x && x.id === tid);
- const agents = (context.agents || []).filter((a) => a && a.agent_id)
- .slice().sort((a, b) => String(a.name || a.agent_id).localeCompare(String(b.name || b.agent_id)));
+ const agents = _todoAssignableAgents(context.agents);
+ const currentId = task?.owner_agent_id || _findProjectAgent('', task?.owner_agent, agents)?.agent_id;
const items = [];
for (const a of agents) {
- const isCurrent = !!task && (
- (task.owner_agent_id && task.owner_agent_id === a.agent_id)
- || (!task.owner_agent_id && task.owner_agent && task.owner_agent === a.name)
- );
+ const isCurrent = currentId === a.agent_id;
items.push({
label: a.name || a.agent_id,
avatar: { icon: a.icon, color: a.color, seed: a.agent_id },
@@ -1973,9 +2079,6 @@ function _openTodoAssignMenu(evt, tid, context = _projectTodoContext()) {
onClick: () => (isCurrent ? undefined : _assignTodoAgent(tid, a, context)),
});
}
- if (!agents.length) {
- items.push({ label: t(context.global ? 'ai_select.empty' : 'project.todo.assign_no_agents'), disabled: true });
- }
showContextMenu(evt, items);
}
@@ -2104,48 +2207,167 @@ function _bindTodoListActions(listEl, resolveContext) {
else if (e.target.closest('[data-action="todo-menu"]')) _openTodoRowMenu(e, tid, context);
else if (e.target.closest('[data-action="todo-assign"]')) _openTodoAssignMenu(e, tid, context);
else if (e.target.closest('[data-action="todo-status"]')) _openTodoStatusMenu(e, tid, context);
- else if (e.target.closest('[data-action="todo-edit"]')) {
- _openProjectTodoEditor(context.tasks.find((task) => task.id === tid), context);
+ else if (e.target.closest('[data-action="todo-toggle-content"]')
+ || !e.target.closest('button, a, input, select, textarea, [role="button"]')) {
+ const key = _todoContentKey(tid, context);
+ const expanded = !_todoExpanded.has(key);
+ if (expanded) _todoExpanded.add(key);
+ else _todoExpanded.delete(key);
+ row.classList.toggle('is-expanded', expanded);
+ row.querySelector('.project-todo-title')?.setAttribute('aria-expanded', String(expanded));
}
});
}
let _projectDriverMutating = false;
+let _projectDriverLoadSeq = 0;
+let _projectDriverShownPid = '';
+
+let _closeProjectDriverHint = () => {};
+let _todoDriverHintBound = false;
+
+function _bindProjectDriverHint() {
+ if (_todoDriverHintBound) return;
+ _todoDriverHintBound = true;
+ // One body-level tooltip and one delegated binding serve static project
+ // controls and account controls replaced during backlog refreshes.
+ const tooltip = document.createElement('div');
+ tooltip.id = 'project-driver-tooltip';
+ tooltip.className = 'project-driver-tooltip';
+ tooltip.setAttribute('role', 'tooltip');
+ tooltip.dataset.i18n = 'project.driver.toggle_hint';
+ tooltip.hidden = true;
+ document.body.appendChild(tooltip);
+ let button = null;
+ let pinned = false;
+ let leaveTimer;
+ const close = () => {
+ clearTimeout(leaveTimer);
+ pinned = false;
+ tooltip.hidden = true;
+ button = null;
+ };
+ _closeProjectDriverHint = close;
+ const position = () => {
+ if (tooltip.hidden) return;
+ if (!button.checkVisibility()) { close(); return; }
+ const rect = button.getBoundingClientRect();
+ tooltip.style.maxHeight = '';
+ const placement = _dropdownVerticalPlacement(rect, tooltip.offsetHeight, window.innerHeight, { gap: 4 });
+ const left = document.documentElement.dir === 'rtl' ? rect.left : rect.right - tooltip.offsetWidth;
+ tooltip.style.left = Math.max(8, Math.min(left, window.innerWidth - tooltip.offsetWidth - 8)) + 'px';
+ tooltip.style.top = placement.top + 'px';
+ tooltip.style.maxHeight = placement.availableHeight + 'px';
+ };
+ const show = (anchor) => {
+ if (anchor !== button) { close(); button = anchor; }
+ clearTimeout(leaveTimer);
+ tooltip.textContent = t('project.driver.toggle_hint');
+ tooltip.hidden = false;
+ position();
+ };
+ const leave = () => {
+ clearTimeout(leaveTimer);
+ // Allow crossing the small gap to read the tooltip itself.
+ leaveTimer = setTimeout(() => {
+ if (!tooltip.hidden && !pinned && document.activeElement !== button
+ && !button.matches(':hover') && !tooltip.matches(':hover')) close();
+ }, 100);
+ };
+ document.addEventListener('mouseover', event => {
+ const anchor = event.target.closest?.('.project-driver-hint');
+ if (anchor && !anchor.contains(event.relatedTarget)) show(anchor);
+ if (tooltip.contains(event.target)) clearTimeout(leaveTimer);
+ });
+ document.addEventListener('mouseout', event => {
+ if (button?.contains(event.target) || tooltip.contains(event.target)) leave();
+ });
+ document.addEventListener('focusin', event => {
+ const anchor = event.target.closest?.('.project-driver-hint');
+ if (anchor) show(anchor);
+ });
+ document.addEventListener('focusout', event => {
+ if (button?.contains(event.target)) leave();
+ });
+ document.addEventListener('click', event => {
+ const anchor = event.target.closest?.('.project-driver-hint');
+ if (anchor) {
+ if (pinned && button === anchor) close();
+ else { show(anchor); pinned = true; }
+ } else if (!tooltip.hidden && !tooltip.contains(event.target)) close();
+ });
+ document.addEventListener('keydown', event => {
+ if (event.isComposing || event.keyCode === 229 || event.key !== 'Escape' || tooltip.hidden) return;
+ close();
+ });
+ window.addEventListener('resize', position);
+ document.addEventListener('scroll', position, true);
+ window.addEventListener('i18n-change', () => {
+ if (!tooltip.hidden) { tooltip.textContent = t('project.driver.toggle_hint'); position(); }
+ });
+}
+
+function _todoDriverDeviceName(config, device) {
+ if (!config?.enabled) return '';
+ const local = config.device_id && config.device_id === device?.id;
+ if (local) return t('auto.device_current');
+ return String(config.device_name || config.device_id || '').trim();
+}
-function _setProjectDriverToggleState(enabled) {
+function _setProjectDriverToggleState(config, device) {
const btn = document.getElementById('project-driver-toggle');
if (!btn) return;
+ const enabled = !!config?.enabled;
btn.hidden = false;
btn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
+ const suffix = document.getElementById('project-driver-device');
+ if (suffix) {
+ const name = _todoDriverDeviceName(config, device);
+ suffix.textContent = name ? ' · ' + name : '';
+ }
}
async function _loadProjectDriver(pid) {
- if (!pid || !document.getElementById('project-driver-toggle')) return;
+ const btn = document.getElementById('project-driver-toggle');
+ if (!pid || !btn) return;
+ if (_projectDriverMutating) {
+ if (pid !== _projectDriverShownPid) _setProjectDriverToggleState(null);
+ return;
+ }
+ const seq = ++_projectDriverLoadSeq;
+ btn.disabled = true;
+ if (pid !== _projectDriverShownPid) _setProjectDriverToggleState(null);
try {
const res = await window.orkas.invoke('projects.driver.get', { projectId: pid });
- if (pid !== _projectDetailPid) return;
- _setProjectDriverToggleState(!!(res && res.config && res.config.enabled));
+ if (pid !== _projectDetailPid || seq !== _projectDriverLoadSeq) return;
+ _setProjectDriverToggleState(res?.config, res?.device);
+ _projectDriverShownPid = pid;
+ btn.disabled = false;
} catch (err) {
_projectDetailLog.warn('load project driver failed', err);
}
}
function _bindProjectDriver() {
+ if (document.getElementById('project-driver-hint')) _bindProjectDriverHint();
const btn = document.getElementById('project-driver-toggle');
if (!btn || btn.dataset.bound === '1') return;
btn.dataset.bound = '1';
btn.addEventListener('click', async () => {
const pid = _projectDetailPid;
- if (!pid || _projectDriverMutating) return;
+ if (!pid || _projectDriverMutating || btn.disabled) return;
const next = btn.getAttribute('aria-pressed') !== 'true';
_projectDriverMutating = true;
+ btn.disabled = true;
+ ++_projectDriverLoadSeq;
const startedAt = Date.now();
let ok = false;
try {
const res = await window.orkas.invoke('projects.driver.set', { projectId: pid, enabled: next });
ok = !!(res && res.ok !== false);
if (ok && pid === _projectDetailPid) {
- _setProjectDriverToggleState(!!(res.config && res.config.enabled));
+ _setProjectDriverToggleState(res.config, res.device);
+ _projectDriverShownPid = pid;
// The driver runs silently in the background; confirm the toggle and
// say what "on" means so the user isn't left guessing.
if (typeof uiToast === 'function') {
@@ -2158,6 +2380,8 @@ function _bindProjectDriver() {
if (typeof uiAlert === 'function') uiAlert(t('project.todo.failed'));
} finally {
_projectDriverMutating = false;
+ if (pid === _projectDetailPid) btn.disabled = false;
+ else void _loadProjectDriver(_projectDetailPid);
}
if (!ok) _projectLogFailure('project_driver_toggle', { enabled: next, error_type: 'set_failed' });
});
@@ -2609,6 +2833,11 @@ function _renderProjectFileNodes(nodes, depth = 0) {
</div>
`;
}
+ if (f.pending) return `<div class="skill-tree-node skill-tree-file muted" style="padding-left:${indent}px">
+ <span class="skill-tree-caret skill-tree-caret-empty"></span>
+ <span class="skill-tree-icon icon-file">${_projectFileIconHtml(name, f.kind)}</span>
+ <span class="skill-tree-label">${label}</span>
+ </div>`;
const chip = _projectKbStatusChipHtml(rel);
const ext = _projectFileExt(name).replace(/^\./, '');
const active = _projectLibraryActiveName === rel ? ' active' : '';
@@ -3220,6 +3449,9 @@ async function _reprocessProjectFile(name) {
async function _deleteProjectFile(name) {
if (!_projectDetailPid || !name) return;
const projectId = _projectDetailPid;
+ const account = typeof currentUserId === 'string' ? currentUserId : '';
+ const isCurrent = () => projectId === _projectDetailPid
+ && account === (typeof currentUserId === 'string' ? currentUserId : '');
const row = _findProjectFileRow(name);
const isDir = !!_findProjectDirRow(name);
const kind = isDir ? 'dir' : (row?.dataset?.projectFileKind || '');
@@ -3228,6 +3460,7 @@ async function _deleteProjectFile(name) {
? t('contexts.dir.del_confirm', { name: _projectBasename(name) })
: t('contexts.file.del_confirm', { name: _projectBasename(name) });
if (!(await uiConfirm(prompt))) return;
+ if (!isCurrent()) return;
const startedAt = performance.now();
let res;
try {
@@ -3244,14 +3477,26 @@ async function _deleteProjectFile(name) {
return;
}
try {
+ if (!isCurrent()) return;
+ // The local delete is committed. Update this rail immediately and reject
+ // older tree responses, without reloading unrelated project cards.
+ _projectLibraryRevision += 1;
+ const removed = (rel) => rel === name || rel.startsWith(`${name}/`);
+ const prune = (nodes) => nodes.filter(node => !removed(_projectLibraryRel(node)))
+ .map(node => node.type === 'dir' ? { ...node, children: prune(node.children || []) } : node);
+ if (_projectDetailMeta) _projectDetailMeta.files = prune(_projectDetailMeta.files || []);
+ for (const key of Array.from(_projectLibraryDrafts.keys())) {
+ if (removed(key)) _projectLibraryDrafts.delete(key);
+ }
+ for (const key of Array.from(_projectLibraryExpanded)) {
+ if (removed(key)) _projectLibraryExpanded.delete(key);
+ }
if (_projectLibraryActiveName === name || _projectLibraryActiveName.startsWith(`${name}/`)) {
- for (const key of Array.from(_projectLibraryDrafts.keys())) {
- if (key === name || key.startsWith(`${name}/`)) _projectLibraryDrafts.delete(key);
- }
_clearProjectLibraryViewer();
}
- _projectLibraryExpanded.delete(name);
- if (projectId === _projectDetailPid) await loadProjectDetail(projectId);
+ _renderProjectFiles(_projectDetailMeta?.files || []);
+ _bindProjectFileRows();
+ if (typeof hydrateUiIcons === 'function') hydrateUiIcons(document.getElementById('project-files-list'));
} catch (err) {
_projectDetailLog.warn('refresh after project file delete failed', err);
}
@@ -4030,7 +4275,7 @@ async function _submitProjectChat() {
const raw = submittedDraft.text().trim();
const draftCid = _projectChatDraftCid(projectId);
const quotes = (typeof _getQuotes === 'function') ? _getQuotes(draftCid).slice() : [];
- if (!raw && !quotes.length) return;
+ if (_composerSendIsEmpty(raw, 'project', quotes, _chatAttachList(draftCid))) return;
const requestText = raw || t('chat.reference_default_prompt');
const pendingUseSelections = (typeof getChatUseSelections === 'function')
? getChatUseSelections('project')
@@ -4039,11 +4284,6 @@ async function _submitProjectChat() {
? _recipientSnapshotForSend('project')
: null;
const recipientType = recipient && recipient.kind ? recipient.kind : 'commander';
- // D23: capture the send's serial/parallel choice before the composer is
- // cleared — the shape is read from the live textarea.
- const multiDispatch = (typeof _composerEffectiveDispatchMode === 'function')
- ? _composerEffectiveDispatchMode('project')
- : null;
let draftItems = (typeof _chatAttachList === 'function')
? _chatAttachList(draftCid)
: [];
@@ -4169,7 +4409,7 @@ async function _submitProjectChat() {
});
}
if (typeof uiAlert === 'function') {
- await uiAlert(t('chat.attach_adopt_failed', { reason: adoptionError }));
+ await uiAlert(t('chat.attach_sync_failed'));
}
if (btn) btn.disabled = false;
releaseAttachmentSend();
@@ -4180,7 +4420,7 @@ async function _submitProjectChat() {
}
releaseAttachmentSend();
if (createdConversation) {
- conversations.unshift(createdConversation);
+ _cacheCreatedConversation(createdConversation, createdConversation.title);
renderConversationList();
if (typeof loadProjects === 'function') loadProjects(true);
}
@@ -4189,10 +4429,12 @@ async function _submitProjectChat() {
const ownsDraft = submittedDraft.matches();
const openCreated = ownsDraft && navigationEpoch === _composerNavigationEpoch;
+ if (typeof composerDiscardStoredDraft === 'function') {
+ composerDiscardStoredDraft(input, projectId, submittedDraft);
+ }
if (ownsDraft) {
composerSetText(input, '');
if (typeof _draftHadRecipient !== 'undefined') _draftHadRecipient.delete('project');
- if (typeof _updateComposerSeqToggle === 'function') _updateComposerSeqToggle('project');
}
if (recipient) {
_recipientByCid[convId] = recipient.defaultRecipient || recipient;
@@ -4213,7 +4455,6 @@ async function _submitProjectChat() {
...(_adopted.length ? { attachments: _adopted } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
...(references.length ? { references } : {}),
- ...(multiDispatch ? { multi_dispatch: multiDispatch } : {}),
};
if (typeof _rememberSentComposerSnapshot === 'function') {
_rememberSentComposerSnapshot(convId, {
@@ -4351,7 +4592,7 @@ async function _openAddPicker() {
${descHtml}
</div>
- <button type="button" class="btn btn-sm" data-action="pick" aria-label="Add">+</button>
+ <button type="button" class="btn btn-sm" data-action="pick" aria-label="Add">${_projectUiIconHtml('plus')}</button>
</div>
`;
}).join('');
@@ -4388,7 +4629,7 @@ async function _openAddPicker() {
}
} catch (err) {
btn.disabled = false;
- btn.textContent = '+';
+ btn.innerHTML = _projectUiIconHtml('plus');
const failure = _projectDetailFailure(err, 'binding_add_failed');
_projectLogFailure('project_binding_add', { binding_kind: k, ...failure });
_projectDetailLog.warn('add binding failed', err);
@@ -4421,7 +4662,22 @@ async function _openAddPicker() {
setTimeout(() => searchEl.focus(), 0);
}
-// ── Header actions: Rename / Delete ────────────────────────────────────
+// ── Header actions: "⋯" menu with Rename / Delete ──────────────────────
+
+function _projectHeaderMenuItems() {
+ if (!_projectDetailPid || !_projectDetailMeta?.project) return [];
+ return [
+ { label: t('project.action.rename'), onClick: () => _onRenameAction() },
+ { label: t('project.action.delete'), onClick: () => _onDeleteAction() },
+ ];
+}
+
+function _openProjectHeaderMenu(button) {
+ if (typeof showContextMenu !== 'function' || !button) return;
+ const rect = button.getBoundingClientRect();
+ // Anchored under the button; the menu flips left at the window edge.
+ showContextMenu({ clientX: rect.right, clientY: rect.bottom + 4 }, _projectHeaderMenuItems());
+}
function _onRenameAction() {
if (!_projectDetailMeta) return;
@@ -4495,18 +4751,16 @@ function _exitRenameMode() {
_setProjectDetailRenameMode(false);
}
+// While renaming, "Done" commits and the "⋯" menu steps aside.
function _setProjectDetailRenameMode(on) {
const titleEl = document.getElementById('project-detail-title');
const inputEl = document.getElementById('project-detail-title-input');
- const renameBtn = document.getElementById('project-action-rename');
- const deleteBtn = document.getElementById('project-action-delete');
+ const doneBtn = document.getElementById('project-action-rename');
+ const moreBtn = document.getElementById('project-action-more');
if (titleEl) titleEl.style.display = on ? 'none' : '';
if (inputEl) inputEl.style.display = on ? '' : 'none';
- if (renameBtn) {
- renameBtn.textContent = on ? t('project.action.done') : t('project.action.rename');
- renameBtn.setAttribute('data-rename-mode', on ? '1' : '0');
- }
- if (deleteBtn) deleteBtn.style.display = on ? 'none' : '';
+ if (doneBtn) doneBtn.hidden = !on;
+ if (moreBtn) moreBtn.hidden = on;
}
function _isProjectDetailRenameMode() {
@@ -4569,11 +4823,10 @@ function _initProjectDetailBindings() {
e.stopPropagation();
const inputEl = document.getElementById('project-detail-title-input');
if (_isProjectDetailRenameMode() && inputEl) _commitRename(inputEl.value);
- else _onRenameAction();
});
- document.getElementById('project-action-delete')?.addEventListener('click', (e) => {
+ document.getElementById('project-action-more')?.addEventListener('click', (e) => {
e.stopPropagation();
- _onDeleteAction();
+ _openProjectHeaderMenu(e.currentTarget);
});
document.getElementById('project-library-root-menu-btn')?.addEventListener('click', (e) => {
e.stopPropagation();
diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.js
index 6c36c153..cbe25ca7 100644
--- a/src/renderer/modules/search.js
+++ b/src/renderer/modules/search.js
@@ -17,7 +17,9 @@ let _searchTab = 'all'; // 'all' | 'chat' | 'agent' | 'skill' | 'con
let _searchResults = [];
let _searchActiveIdx = -1;
let _searchLastQuery = '';
-let _searchChatIndexComplete = true;
+// Only a first full build announces incomplete history. Catch-up after that
+// (an unverified index waiting for its idle repair) stays quiet.
+let _searchChatIndexBuilding = false;
let _searchLoading = false;
const _SEARCH_FAILURE_DEDUPE_MS = 60 * 1000;
const _SEARCH_FAILURE_MAX_KEYS = 16;
@@ -134,7 +136,7 @@ function openGlobalSearch(entryPoint = 'unknown') {
_searchResults = [];
_searchActiveIdx = -1;
_searchLastQuery = '';
- _searchChatIndexComplete = true;
+ _searchChatIndexBuilding = false;
_searchSeq++; // invalidate any in-flight query from a previous session
_setSearchTab('all'); // reset to default tab each open
_setSearchTabsVisible(false); // hide tabs while empty/history state is shown
@@ -199,8 +201,8 @@ async function _refreshSearchIndexStatus(seq, query, pending) {
const response = await apiFetch('/api/search/status');
const data = await response.json();
if (seq !== _searchSeq || !pending.active || !data.ok) return;
- _searchChatIndexComplete = data.chat_index_complete !== false;
- if (!_searchChatIndexComplete) {
+ _searchChatIndexBuilding = data.chat_index_building === true;
+ if (_searchChatIndexBuilding) {
if (query) {
if (query !== _searchLastQuery) {
_searchResults = [];
@@ -235,7 +237,7 @@ async function _runSearchNow(queryArg) {
_searchVisibleResults = [];
_searchActiveIdx = -1;
_searchLastQuery = '';
- _searchChatIndexComplete = true;
+ _searchChatIndexBuilding = false;
_setSearchTabsVisible(false);
_renderSearchEmptyState();
void _refreshSearchIndexStatus(_searchSeq, '', { active: true });
@@ -274,7 +276,7 @@ async function _runSearchNow(queryArg) {
code: _searchDegradationErrorCode(data.degradation_code),
}, 'search_degraded');
}
- _searchChatIndexComplete = data.chat_index_complete !== false;
+ _searchChatIndexBuilding = data.chat_index_building === true;
_searchResults = data.results || [];
_searchLastQuery = query;
_setSearchTabsVisible(true);
@@ -346,7 +348,7 @@ function _renderSearchEmptyState() {
${history.map((q) => `<button class="search-history-item" data-history-q="${escapeHtml(q)}">${escapeHtml(q)}</button>`).join('')}
</div>`
: '';
- const notice = !_searchChatIndexComplete
+ const notice = _searchChatIndexBuilding
? `<div class="search-section-label is-status" role="status">${escapeHtml(t('search.history_indexing'))}</div>` : '';
body.innerHTML = notice + (historyHtml || (notice ? '' : `<div class="search-empty">${escapeHtml(t('search.empty_hint'))}</div>`));
body.querySelectorAll('[data-history-q]').forEach((btn) => {
@@ -462,7 +464,7 @@ function _renderSearchResults(query) {
const body = document.getElementById('search-body');
if (!body) return;
body.classList.remove('is-start-state');
- const indexing = !_searchChatIndexComplete && (_searchTab === 'all' || _searchTab === 'chat');
+ const indexing = _searchChatIndexBuilding && (_searchTab === 'all' || _searchTab === 'chat');
const notice = indexing
? `<div class="search-section-label is-status" role="status">${escapeHtml(t('search.history_indexing'))}</div>`
: '';
@@ -603,6 +605,8 @@ async function _gotoSearchResult(r) {
// Open the agent detail view in read mode. Edit mode is intentionally
// NOT auto-toggled — the user is looking up "this agent", not editing.
setTimeout(async () => {
+ const loader = typeof loadRendererFeature === 'function' ? loadRendererFeature : window.loadRendererFeature;
+ if (typeof loader === 'function') await loader('agents');
if (typeof openAgentDetail === 'function') {
await openAgentDetail(r.id, { returnTarget: agentReturnTarget });
}
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index f30b0aa4..284b8366 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -371,6 +371,49 @@ function _settingsRecycleAvailable() {
}
const _settingsRecycleExpandedIds = new Set();
+let _settingsRecycleBatches = [];
+let _settingsRecycleBusy = false;
+
+function _settingsRecycleAutomationKey(item) {
+ const path = String(item?.path || '').replace(/\\/g, '/');
+ const root = /^cloud\/(?:projects\/[^/]+\/)?auto_tasks\/[^/]+(?=\/|$)/.exec(path);
+ return root ? root[0] : String(item?.id || item?.title || '');
+ }
+
+function _settingsRecycleDetailRows(batch) {
+ const displayItems = _settingsRecycleDisplayItems(batch);
+ const rows = [];
+ const seen = new Set();
+ for (const item of displayItems) {
+ const automation = _settingsRecycleCategoryKey(item?.category) === 'auto_task';
+ const title = automation
+ ? String(item?.title || '').trim() || t('settings.recycle.display_unknown')
+ : _settingsRecycleItemTitle(item);
+ const category = _settingsRecycleCategoryLabel(item?.category);
+ const pathValue = String(item?.path || '').replace(/^cloud\//, '');
+ const key = automation ? _settingsRecycleAutomationKey(item) : `${category}\n${title}\n${pathValue}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ rows.push({ category, title, path: pathValue, automation,
+ detail: automation ? String(item?.detail || '').trim() : '',
+ tooltip: [String(item?.title || '').trim(), automation ? item?.id : '', pathValue].filter(Boolean).join('\n'),
+ });
+ }
+ if (!rows.length) {
+ for (const item of Array.isArray(batch?.items) ? batch.items : []) {
+ const pathValue = String(item?.path || '').replace(/^cloud\//, '');
+ if (!pathValue || seen.has(pathValue)) continue;
+ seen.add(pathValue);
+ rows.push({
+ category: _settingsRecycleCategoryLabel('file'),
+ title: _settingsRecyclePathTitle(pathValue),
+ path: pathValue,
+ });
+ }
+ }
+ return rows;
+ }
+
function _settingsRecycleCategoryKey(category) {
const value = String(category || '').replace(/[^A-Za-z0-9_]/g, '');
@@ -447,32 +490,42 @@ function _settingsRecycleListJoin(items) {
}
function _settingsRecycleTitle(batch) {
- const groups = new Map();
- for (const item of _settingsRecycleDisplayItems(batch)) {
- const title = String(item?.title || '').trim();
- if (!title) continue;
- const category = _settingsRecycleCategoryKey(item?.category);
- const titles = groups.get(category) || [];
- if (!titles.includes(title)) titles.push(title);
- groups.set(category, titles);
- }
- if (groups.size > 0) {
- const joinerKey = t('settings.recycle.display_group_joiner');
- const joiner = joinerKey === 'settings.recycle.display_group_joiner' ? ';' : joinerKey;
- return Array.from(groups.entries()).map(([category, titles]) => {
- const visibleTitles = titles.slice(0, 3);
- if (titles.length > visibleTitles.length) visibleTitles.push(`+${titles.length - visibleTitles.length}`);
- return t('settings.recycle.display_group')
- .replace('{type}', t(`settings.recycle.display_${category}`))
- .replace('{items}', _settingsRecycleListJoin(visibleTitles));
- }).join(joiner);
- }
- const direct = String(batch?.label || batch?.display_title || '').trim();
- if (direct) return direct;
- const paths = Array.isArray(batch?.paths_preview) ? batch.paths_preview : [];
- return _settingsRecycleListJoin(paths.map(_settingsRecyclePathTitle))
- || t('settings.recycle.display_unknown');
-}
+ const displayItems = _settingsRecycleDisplayItems(batch);
+ const groups = new Map();
+ const taskIds = new Set();
+ for (const item of displayItems) {
+ const title = String(item?.title || '').trim();
+ if (!title) continue;
+ const category = _settingsRecycleCategoryKey(item?.category);
+ if (category === 'auto_task') {
+ const key = _settingsRecycleAutomationKey(item);
+ if (taskIds.has(key)) continue;
+ taskIds.add(key);
+ }
+ const text = title;
+ const list = groups.get(category) || [];
+ if (category === 'auto_task' || !list.includes(text)) list.push(text);
+ groups.set(category, list);
+ }
+ if (groups.size > 0) {
+ const groupJoiner = t('settings.recycle.display_group_joiner');
+ const separator = groupJoiner === 'settings.recycle.display_group_joiner' ? ';' : groupJoiner;
+ return Array.from(groups.entries()).map(([category, titles]) => {
+ const label = t(`settings.recycle.display_${category}`);
+ if (category === 'auto_task' && titles.length > 1) {
+ return t('settings.recycle.automation_count').replace('{count}', String(titles.length));
+ }
+ return t('settings.recycle.display_group')
+ .replace('{type}', label)
+ .replace('{items}', _settingsRecycleListJoin(titles.length > 3 ? [...titles.slice(0, 3), `+${titles.length - 3}`] : titles));
+ }).join(separator);
+ }
+ const label = String(batch?.label || batch?.display_title || '').trim();
+ if (label) return label;
+ const previews = Array.isArray(batch?.paths_preview) ? batch.paths_preview : [];
+ const names = previews.map(_settingsRecyclePathTitle).filter(Boolean);
+ return names.length ? _settingsRecycleListJoin(names) : t('settings.recycle.display_unknown');
+ }
function _settingsRecycleCategoryLabel(category) {
const key = _settingsRecycleCategoryKey(category);
@@ -491,42 +544,27 @@ function _settingsRecycleItemTitle(item) {
}
function _settingsRecycleDetailsHtml(batch) {
- const rows = [];
- const seen = new Set();
- for (const item of _settingsRecycleDisplayItems(batch)) {
- const title = _settingsRecycleItemTitle(item);
- const category = _settingsRecycleCategoryLabel(item?.category);
- const pathValue = String(item?.path || '').replace(/^cloud\//, '');
- const key = `${category}\n${title}\n${pathValue}`;
- if (seen.has(key)) continue;
- seen.add(key);
- rows.push({ category, title, path: pathValue });
- }
- if (!rows.length) {
- for (const item of Array.isArray(batch?.items) ? batch.items : []) {
- const pathValue = String(item?.path || '').replace(/^cloud\//, '');
- if (!pathValue || seen.has(pathValue)) continue;
- seen.add(pathValue);
- rows.push({
- category: _settingsRecycleCategoryLabel('file'),
- title: _settingsRecyclePathTitle(pathValue),
- path: pathValue,
- });
- }
+ const rows = _settingsRecycleDetailRows(batch);
+ if (!rows.length) return '';
+ return `
+ <div class="settings-recycle-details">
+ ${rows.map((row) => `
+ <div class="settings-recycle-detail-row${row.automation ? ' is-auto-task' : ''}" title="${escapeHtml(row.tooltip || row.title)}">
+ ${row.automation ? `
+ <div class="settings-recycle-main">
+ <div class="settings-recycle-detail-title">${escapeHtml(row.title)}</div>
+ ${row.detail ? `<div class="settings-recycle-meta">${escapeHtml(row.detail)}</div>` : ''}
+ </div>
+ ` : `
+ <span class="settings-recycle-detail-category">${escapeHtml(row.category)}</span>
+ <span class="settings-recycle-detail-title">${escapeHtml(row.title)}</span>
+ ${row.path ? `<span class="settings-recycle-detail-path" title="${escapeHtml(row.path)}">${escapeHtml(row.path)}</span>` : ''}
+ `}
+ </div>
+ `).join('')}
+ </div>
+ `;
}
- if (!rows.length) return '';
- return `
- <div class="settings-recycle-details">
- ${rows.map((row) => `
- <div class="settings-recycle-detail-row">
- <span class="settings-recycle-detail-category">${escapeHtml(row.category)}</span>
- <span class="settings-recycle-detail-title">${escapeHtml(row.title)}</span>
- ${row.path ? `<span class="settings-recycle-detail-path" title="${escapeHtml(row.path)}">${escapeHtml(row.path)}</span>` : ''}
- </div>
- `).join('')}
- </div>
- `;
-}
function _settingsRecycleRowHtml(batch) {
const id = escapeHtml(String(batch?.id || ''));
@@ -553,37 +591,63 @@ function _settingsRecycleRowHtml(batch) {
`;
}
-async function _settingsRefreshRecycleBin() {
+function _settingsRenderRecycleBin() {
const body = document.getElementById('settings-recycle-body');
- if (!body || !_settingsRecycleAvailable()) return;
+ if (!body) return;
+ const rows = _settingsRecycleBatches;
+ body.innerHTML = `<div class="settings-recycle-toolbar">
+ <button class="btn btn-sm btn-danger" type="button" data-recycle-clear ${!rows.length || _settingsRecycleBusy ? 'disabled' : ''}>${escapeHtml(t('settings.recycle.clear'))}</button>
+ </div><div class="settings-recycle-scroll" data-recycle-source="local">${rows.length ? rows.map(_settingsRecycleRowHtml).join('') : '<div class="settings-empty">' + escapeHtml(t('settings.recycle.empty')) + '</div>'}</div>`;
+}
+
+async function _settingsRefreshRecycleBin() {
+ if (!_settingsRecycleAvailable()) return;
try {
const res = await window.orkas.recycleBin.list();
- const batches = Array.isArray(res?.batches) ? res.batches : [];
- // This build does not create remote-deletion batches. Keep older batches
- // readable, but present every snapshot through one local recycle-bin
- // surface instead of exposing the hosted product's source split.
- const rowsHtml = batches.length
- ? batches.map(_settingsRecycleRowHtml).join('')
- : `<div class="settings-empty">${escapeHtml(t('settings.recycle.empty'))}</div>`;
- body.innerHTML = `
- <div class="settings-recycle-scroll" data-recycle-source="local">
- ${rowsHtml}
- </div>
- `;
- } catch (err) {
- _settingsLog.warn('recycle bin refresh failed', {
- error: (err && err.message) || String(err),
- });
- body.innerHTML = `<div class="settings-empty">${escapeHtml(t('settings.recycle.empty'))}</div>`;
- }
+ if (res?.ok === false || !Array.isArray(res?.batches)) throw new Error('recycle_list_failed');
+ _settingsRecycleBatches = res.batches;
+ } catch (_) { _settingsLog.warn('recycle bin refresh failed', { code: 'recycle_list_failed' }); }
+ _settingsRenderRecycleBin();
+}
+
+// Shared local-data actions use this refresh hook without the hosted sync module.
+window.initRecycleBin = async function () {
+ _settingsBindRecycleBinOnce();
+ await _settingsRefreshRecycleBin();
+};
+
+async function _settingsClearRecycleBin() {
+ if (_settingsRecycleBusy || !_settingsRecycleBatches.length || !_settingsRecycleAvailable()) return;
+ const ids = _settingsRecycleBatches.map(batch => String(batch.id));
+ _settingsRecycleBusy = true;
+ _settingsRenderRecycleBin();
+ try {
+ if (!await uiConfirmDanger({ title: t('settings.recycle.clear_title'),
+ message: t('settings.recycle.clear_confirm').replace('{source}', t('settings.recycle.title')).replace('{count}', String(ids.length)),
+ dangerLabel: t('settings.recycle.clear') })) return;
+ const body = document.getElementById('settings-recycle-body');
+ if (body) body.innerHTML = '<div role="status">' + escapeHtml(t('settings.recycle.clearing').replace('{done}', '0').replace('{total}', String(ids.length))) + '</div>';
+ for (const id of ids) {
+ const result = await window.orkas.recycleBin.delete(id);
+ if (result?.ok === false || result?.deleted !== true) throw new Error('recycle_delete_failed');
+ _settingsRecycleExpandedIds.delete(id);
+ }
+ if (typeof uiToast === 'function') uiToast(t('settings.recycle.cleared'), { variant: 'success' });
+ } catch (_) {
+ _settingsLog.warn('recycle bin clearing failed', { code: 'recycle_delete_failed' });
+ if (typeof uiToast === 'function') uiToast(t('settings.recycle.clear_failed'), { variant: 'error' });
+ } finally { _settingsRecycleBusy = false; await _settingsRefreshRecycleBin(); }
}
+
function _settingsBindRecycleBinOnce() {
if (_settingsState.recycleBound) return;
const body = document.getElementById('settings-recycle-body');
if (!body) return;
_settingsState.recycleBound = true;
body.addEventListener('click', async (event) => {
+ if (_settingsRecycleBusy) return;
+ if (event.target?.closest?.('[data-recycle-clear]')) { await _settingsClearRecycleBin(); return; }
const viewButton = event.target?.closest?.('[data-recycle-view]');
if (viewButton) {
const id = viewButton.getAttribute('data-recycle-view') || '';
@@ -598,6 +662,8 @@ function _settingsBindRecycleBinOnce() {
const deleting = button.hasAttribute('data-recycle-delete');
const id = button.getAttribute(deleting ? 'data-recycle-delete' : 'data-recycle-restore') || '';
if (!id) return;
+ _settingsRecycleBusy = true;
+ try {
const confirmed = deleting && typeof uiConfirmDanger === 'function'
? await uiConfirmDanger({
title: t('settings.recycle.delete_title'),
@@ -608,7 +674,7 @@ function _settingsBindRecycleBinOnce() {
message: t(deleting ? 'settings.recycle.delete_confirm' : 'settings.recycle.restore_confirm'),
okLabel: t(deleting ? 'settings.recycle.delete' : 'settings.recycle.restore'),
});
- if (!confirmed) return;
+ if (!confirmed) { _settingsRecycleBusy = false; _settingsRenderRecycleBin(); return; }
button.disabled = true;
try {
if (deleting) {
@@ -616,7 +682,28 @@ function _settingsBindRecycleBinOnce() {
if (!res?.deleted) throw new Error(t('settings.recycle.delete_not_found'));
_settingsRecycleExpandedIds.delete(id);
} else {
- await window.orkas.recycleBin.restore(id);
+ const result = await window.orkas.recycleBin.restore(id);
+ if (!result || result.ok === false
+ || !Object.prototype.hasOwnProperty.call(result, 'restored')
+ || !Number.isFinite(Number(result.restored))) {
+ throw new Error(t('settings.recycle.restore_failed'));
+ }
+ const failed = Math.max(0, Number(result.failed)
+ || (Array.isArray(result.failed_paths) ? result.failed_paths.length : 0));
+ const changedValue = Number(result.changed);
+ const changed = Number.isFinite(changedValue) ? Math.max(0, changedValue)
+ : Math.max(0, Number(result.restored) || 0)
+ + Math.max(0, Number(result.skipped)
+ || (Array.isArray(result.skipped_paths) ? result.skipped_paths.length : 0))
+ + Math.max(0, Number(result.reactivated)
+ || (Array.isArray(result.reactivated_paths) ? result.reactivated_paths.length : 0));
+ if (typeof uiToast === 'function') {
+ const key = failed > 0 ? 'settings.recycle.restore_partial'
+ : changed <= 0 ? 'settings.recycle.restore_no_changes' : 'settings.recycle.restored';
+ uiToast(t(key).replace('{count}', String(failed > 0 ? failed : changed)), {
+ variant: failed > 0 || changed <= 0 ? 'warning' : 'success',
+ });
+ }
// 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),
@@ -636,8 +723,10 @@ function _settingsBindRecycleBinOnce() {
}
} finally {
button.disabled = false;
+ _settingsRecycleBusy = false;
await _settingsRefreshRecycleBin();
}
+ } finally { _settingsRecycleBusy = false; _settingsRenderRecycleBin(); }
});
}
@@ -902,6 +991,7 @@ function _settingsSyncLanguageRadio() {
// re-render sections whose text is written by JS (so their content
// isn't refreshed by applyDomI18n's data-i18n sweep).
window.addEventListener('i18n-change', () => {
+ _settingsRenderRecycleBin();
void _settingsRefreshOperatorPolicy();
_settingsSyncLanguageRadio();
_settingsRenderLocalExec();
@@ -1070,7 +1160,6 @@ async function _settingsRefreshProviders() {
async function _settingsRefreshEntries() {
const res = await window.orkas.invoke('auth.listEntries', { includeUnavailable: true });
_settingsState.entries = (res && res.ok && Array.isArray(res.entries)) ? res.entries : [];
- if (typeof trackModelConfigSnapshot === 'function') trackModelConfigSnapshot(_settingsState.entries);
_settingsRenderOrkasApiCard();
_settingsEmitModelEntriesChanged();
}
diff --git a/src/renderer/modules/settings_tabs.js b/src/renderer/modules/settings_tabs.js
index 977f8d4f..c0ae7dd2 100644
--- a/src/renderer/modules/settings_tabs.js
+++ b/src/renderer/modules/settings_tabs.js
@@ -21,6 +21,7 @@ function activateSettingsTab(name) {
panes.forEach((pane) => {
pane.hidden = pane.dataset.settingsPane !== target;
});
+ if (target === 'data' && typeof window.initTaskCleanup === 'function') window.initTaskCleanup();
}
const _settingsTabsBound = new WeakSet();
diff --git a/src/renderer/modules/sidebar-sections.js b/src/renderer/modules/sidebar-sections.js
index ff8c4e51..35c01cc6 100644
--- a/src/renderer/modules/sidebar-sections.js
+++ b/src/renderer/modules/sidebar-sections.js
@@ -1,4 +1,6 @@
-// Top-level Today, Projects and Tasks section collapse state.
+// Sidebar task sections persist local collapse preferences. The navigation
+// entries above them are a flat, always-visible list; collapse values stored for
+// the retired navigation groups are ignored and dropped on the next write.
(function () {
const STORAGE_KEY = 'sidebar.sectionCollapsed';
const SECTION_CONFIG = [
@@ -26,15 +28,16 @@
];
function readCollapsedState(storage) {
+ let parsed = {};
try {
- const parsed = JSON.parse(storage.getItem(STORAGE_KEY) || '{}');
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
- return Object.fromEntries(
- SECTION_CONFIG.map(({ name }) => [name, parsed[name] === true]),
- );
- } catch (_) {
- return {};
- }
+ const saved = JSON.parse(storage.getItem(STORAGE_KEY) || '{}');
+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) parsed = saved;
+ } catch (_) {}
+ return Object.fromEntries(
+ SECTION_CONFIG.map(({ name, defaultCollapsed }) => [
+ name, typeof parsed[name] === 'boolean' ? parsed[name] : defaultCollapsed === true,
+ ]),
+ );
}
function writeCollapsedState(storage, state) {
diff --git a/src/renderer/modules/task-board.js b/src/renderer/modules/task-board.js
index affc4d32..5d467f2d 100644
--- a/src/renderer/modules/task-board.js
+++ b/src/renderer/modules/task-board.js
@@ -274,12 +274,33 @@ function _taskBoardStatusLabel(status) {
}
}
+const _TASK_BOARD_ENDED_WITHOUT_DONE = new Set(['failed', 'stopped', 'cancelled']);
+
+// Dependency ids as a list (D29). Snapshots written before D29 stored a
+// single id string.
+function _taskBoardDeps(task) {
+ if (!task || !task.after) return [];
+ return (Array.isArray(task.after) ? task.after : [task.after])
+ .filter((id) => typeof id === 'string' && id);
+}
+
+// Locale-aware "A, B and C" for the waiting chip.
+function _taskBoardJoinNames(names) {
+ try {
+ const lang = typeof getLang === 'function' ? getLang() : 'en';
+ return new Intl.ListFormat(lang, { style: 'long', type: 'conjunction' }).format(names);
+ } catch (_) {
+ return names.join(', ');
+ }
+}
+
// Send now is meaningful only for a user-authored queued task whose exact
-// assignee currently exposes a live-turn ingress. Commander-created child
-// contracts intentionally remain cancel-only.
+// assignee currently exposes a live-turn ingress. Commander-created queued
+// contracts remain cancel-only; the user's queued update
+// can also guide a Commander-dispatched Agent's steerable live turn.
function _taskBoardCanSendNow(cid, task) {
if (!cid || !task || task.status !== 'queued' || task.created_by !== 'user') return false;
- if (task.after) return false; // chained starts stay ordered (§4.8)
+ if (_taskBoardDeps(task).length) return false; // dependent starts stay ordered (§4.8)
if (typeof _latestActiveTurns === 'undefined') return false;
const turns = _latestActiveTurns.get(cid);
return Array.isArray(turns) && turns.some((turn) => (
@@ -386,16 +407,22 @@ function _taskBoardRender(cid) {
? `<span class="chat-queue-skill chat-queue-dep" title="${escapeHtml(origin)}">${escapeHtml(t('chat.task_dispatched'))}</span>`
: '';
const preview = escapeHtml(String(task.instruction || '').replace(/\s+/g, ' ')).slice(0, 160);
- // Chain dependency as read-only row information (D18/D24): a queued row
- // that waits on a predecessor names it inline. The predecessor may
- // already be terminal (snapshot still in the map) during the moments
- // before this row flips running.
+ // Dependencies as read-only row information (D18/D24/D29): a queued row
+ // names the predecessors it still waits on; finished ones drop off.
+ // A predecessor may already be terminal (snapshot still in the map)
+ // during the moments before this row flips running.
let depChip = '';
- if (task.status === 'queued' && task.after) {
- const prev = _taskBoardMapFor(cid).get(task.after);
- const prevName = prev ? _taskBoardAssigneeLabel(cid, prev) : String(task.after).slice(0, 6);
- const prevPreview = prev ? String(prev.instruction || '').replace(/\s+/g, ' ').slice(0, 80) : '';
- depChip = `<span class="chat-queue-skill chat-queue-dep" title="${escapeHtml(prevPreview)}">${escapeHtml(t('chat.task_waiting_on', { name: prevName }))}</span>`;
+ const waitingOn = task.status === 'queued'
+ ? _taskBoardDeps(task).filter((id) => {
+ const prev = _taskBoardMapFor(cid).get(id);
+ return !prev || prev.status !== 'done';
+ })
+ : [];
+ if (waitingOn.length) {
+ const prevs = waitingOn.map((id) => _taskBoardMapFor(cid).get(id));
+ const names = waitingOn.map((id, i) => (prevs[i] ? _taskBoardAssigneeLabel(cid, prevs[i]) : String(id).slice(0, 6)));
+ const previews = prevs.filter(Boolean).map((prev) => String(prev.instruction || '').replace(/\s+/g, ' ').slice(0, 80));
+ depChip = `<span class="chat-queue-skill chat-queue-dep" title="${escapeHtml(previews.join('\n'))}">${escapeHtml(t('chat.task_waiting_on', { name: _taskBoardJoinNames(names) }))}</span>`;
}
// queued → cancel before it runs; running → stop ONLY this execution
// (per-task abort; the header Stop remains the whole-conversation one);
@@ -588,7 +615,15 @@ async function _taskBoardResumeBlocked(cid, taskId) {
// State events may beat the command acknowledgement. Only advance a
// still-blocked snapshot; never overwrite an already running or
// completed task with this acknowledgement's earlier queued state.
- if (task && task.status === 'blocked') m.set(taskId, { ...task, status: 'queued', after: undefined });
+ // Run-anyway drops only predecessors that ended without done (D29);
+ // unfinished ones keep gating, mirroring the main-process rule.
+ if (task && task.status === 'blocked') {
+ const keep = _taskBoardDeps(task).filter((id) => {
+ const dep = m.get(id);
+ return !!dep && (dep.status === 'done' || !_TASK_BOARD_ENDED_WITHOUT_DONE.has(dep.status));
+ });
+ m.set(taskId, { ...task, status: 'queued', after: keep.length ? keep : undefined });
+ }
_taskBoardRender(cid);
// Run-anyway STARTS an execution from a bare invoke — no send stream is
// attached, so the released task's task_state/turn events would have no
diff --git a/src/renderer/modules/task-cleanup.js b/src/renderer/modules/task-cleanup.js
new file mode 100644
index 00000000..bc82b762
--- /dev/null
+++ b/src/renderer/modules/task-cleanup.js
@@ -0,0 +1,183 @@
+/* Inline Settings > Data cleanup. Preview receipts belong to one account;
+ * selection stays frozen while confirming and executing. */
+(() => {
+ let owner = '', days = 90, token = '', total = 0, rows = [], offset = 0, nextOffset = null;
+ let expanded = false, confirming = false, busy = false, loading = false, stopped = false;
+ let allSelected = true, excluded = new Set(), result = null, failed = [], error = false, picker = null, bound = false;
+ const log = createLogger('task-cleanup');
+ const user = () => typeof currentUserId === 'string' ? currentUserId : '';
+ const body = () => document.getElementById('settings-task-cleanup-body');
+ const selectedCount = () => allSelected ? total - excluded.size : excluded.size;
+ const isSelected = cid => allSelected !== excluded.has(cid);
+ const aliases = { retry: 'chat.retry_btn', stop: 'chat.task_stop', loading: 'common.loading', refresh: 'common.refresh', view: 'settings.recycle.view', collapse: 'settings.recycle.collapse', cancel: 'common.cancel', confirm_title: 'settings.cleanup.title' };
+ const tr = (key, values) => key === 'all' ? `${t('chat.message_select_all')} (${values.n})`
+ : key === 'page' ? `${values.from}–${values.to} / ${values.n}`
+ : t(aliases[key] || `settings.cleanup.${key}`, values);
+ const esc = value => escapeHtml(String(value));
+ const button = (action, label, disabled = false, danger = false) =>
+ `<button type="button" class="btn btn-sm${danger ? ' btn-danger' : ''}" data-cleanup-action="${action}"${disabled ? ' disabled' : ''}>${esc(label)}</button>`;
+ const options = () => [30, 90, 180].map(n => ({ value: String(n), label: tr('days', { n }) }));
+ function protectedIds() {
+ const ids = new Set((window.TaskUnread?.list?.() || []).map(row => row.cid));
+ // Drafts are owned by the composer and may belong to unloaded task pages.
+ // Storage failure blocks cleanup rather than treating unknown as empty.
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ const match = /^draft_([A-Za-z0-9_-]+)(:queue-edit)?$/.exec(key || '');
+ if (!match) continue;
+ const raw = localStorage.getItem(key);
+ if (!raw) continue;
+ let draft;
+ try { draft = JSON.parse(raw); } catch (_) { ids.add(match[1]); continue; }
+ if (match[2] || draft?.text?.trim() || draft?.references?.length) ids.add(match[1]);
+ }
+ if (typeof _chatAttachments !== 'undefined') {
+ for (const [cid, items] of _chatAttachments) if (items.length) ids.add(cid);
+ }
+ if (typeof currentCid === 'string' && currentCid && typeof _composerHoldsUnsentInput === 'function'
+ && _composerHoldsUnsentInput(currentCid)) ids.add(currentCid);
+ return [...ids].filter(cid => /^[A-Za-z0-9_-]+$/.test(cid));
+ }
+ function protectedNow(cid) {
+ return window.TaskUnread?.isUnread?.(cid)
+ || (typeof _composerHoldsUnsentInput === 'function' && _composerHoldsUnsentInput(cid))
+ || (typeof _chatAttachList === 'function' && _chatAttachList(cid).length);
+ }
+ async function invoke(action, payload) {
+ if (!owner || owner !== user()) throw new Error('cleanup_account_changed');
+ const expectedOwner = owner;
+ const response = await window.orkas.invoke(`conversations.cleanup.${action}`, { ...payload, expectedUserId: expectedOwner });
+ if (expectedOwner !== user() || owner !== expectedOwner) throw new Error('cleanup_account_changed');
+ if (!response || response.ok !== true) throw new Error('cleanup_failed');
+ return response;
+ }
+ function render() {
+ const host = body(); if (!host) return;
+ picker?.setOptions(options(), { value: String(days) });
+ picker?.setAriaLabel(tr('age'));
+ const trigger = document.getElementById('settings-task-cleanup-age')?.querySelector?.('.ai-select-trigger');
+ if (trigger) trigger.disabled = busy || loading || confirming;
+ const selected = Math.max(0, selectedCount());
+ let html = '';
+ if (result && !busy) html += `<div class="settings-row" role="status"><span class="settings-row-desc">${esc(tr('result', result))}</span>${failed.length && !busy ? button('retry', tr('retry')) : ''}</div>`;
+ if (busy) {
+ html += `<div class="settings-row" role="status"><span>${esc(tr('progress', { done: result.done, total: result.total }))}</span>${button('stop', tr('stop'), stopped)}</div>`;
+ } else if (loading) {
+ html += `<div class="settings-row" role="status">${esc(tr('loading'))}</div>`;
+ } else if (error) {
+ html += `<div class="settings-row" role="alert"><span class="settings-row-desc">${esc(tr('error'))}</span>${button('refresh', tr('refresh'))}</div>`;
+ } else {
+ html += `<div class="settings-row"><span class="settings-row-desc" role="status">${esc(total ? tr('count', { n: selected }) : tr('empty'))}</span><div class="settings-cleanup-actions">${total ? button('view', tr(expanded ? 'collapse' : 'view'), confirming) : ''}${button('prepare', tr('clean'), !selected || confirming, true)}</div></div>`;
+ if (expanded && total) {
+ html += `<div class="settings-cleanup-list"><label class="settings-cleanup-item"><input type="checkbox" data-cleanup-all${selectedCount() === total ? ' checked' : ''}${confirming ? ' disabled' : ''}><span>${esc(tr('all', { n: total }))}</span></label>`;
+ for (const row of rows) html += `<label class="settings-cleanup-item"><input type="checkbox" data-cleanup-cid="${esc(row.cid)}"${isSelected(row.cid) ? ' checked' : ''}${confirming ? ' disabled' : ''}><span class="settings-cleanup-title">${esc(row.title)}</span><time class="settings-row-desc">${esc(new Date(row.activeAt).toLocaleDateString())}</time></label>`;
+ html += `</div><div class="settings-sheet-foot"><span>${esc(tr('page', { from: offset + 1, to: offset + rows.length, n: total }))}</span><div class="settings-cleanup-actions">${button('previous', tr('previous'), offset === 0 || confirming)}${button('next', tr('next'), nextOffset === null || confirming)}</div></div>`;
+ }
+ if (confirming) html += `<div class="settings-row settings-row-stack" role="group" aria-label="${esc(tr('confirm_title'))}"><p class="settings-row-desc">${esc(tr('confirm', { n: selected }))}</p><div class="settings-cleanup-actions">${button('cancel', tr('cancel'))}${button('confirm', tr('move', { n: selected }), !selected, true)}</div></div>`;
+ }
+ host.innerHTML = html;
+ }
+ async function refresh(keepResult = false) {
+ if (busy || loading) return;
+ loading = true; error = false; confirming = false;
+ if (!keepResult) { result = null; failed = []; }
+ render();
+ try {
+ const p = await invoke('preview', { days, protectedIds: protectedIds() });
+ if (!Array.isArray(p.rows) || !Number.isSafeInteger(p.total) || typeof p.token !== 'string') throw new Error('invalid_preview');
+ token = p.token; total = p.total; rows = p.rows; offset = 0; nextOffset = p.nextOffset; excluded = new Set(); allSelected = true;
+ } catch (_) { error = true; token = ''; total = 0; rows = []; }
+ finally { loading = false; render(); }
+ }
+ async function changePage(next) {
+ if (loading || busy || confirming) return;
+ loading = true; render();
+ try {
+ const p = await invoke('page', { token, offset: next });
+ rows = p.rows; offset = next; nextOffset = p.nextOffset;
+ } catch (_) { error = true; }
+ finally { loading = false; render(); }
+ }
+ async function run(retry = false) {
+ if (busy || loading || owner !== user() || (!retry && !confirming)) return;
+ busy = true; confirming = false; stopped = false; error = false;
+ const operationOwner = owner;
+ const retryIds = failed.slice(); failed = [];
+ result = { deleted: 0, skipped: 0, failed: 0, done: 0, total: retry ? retryIds.length : selectedCount() };
+ render();
+ try {
+ // Page the frozen receipt, never a live query that could add new tasks.
+ let next = 0;
+ do {
+ const p = retry ? { rows: retryIds.map(cid => ({ cid })), nextOffset: null }
+ : await invoke('page', { token, offset: next });
+ for (const row of p.rows) {
+ if (stopped || operationOwner !== user()) break;
+ if (!retry && !isSelected(row.cid)) continue;
+ try {
+ if (protectedNow(row.cid)) { result.skipped++; }
+ else {
+ const response = await invoke('remove', { token, cid: row.cid });
+ if (!['deleted', 'skipped'].includes(response.status)) throw new Error('invalid_cleanup_result');
+ result[response.status]++;
+ if (response.status === 'deleted' && typeof _forgetConvLocal === 'function') _forgetConvLocal(row.cid);
+ }
+ } catch (_) { result.failed++; failed.push(row.cid); }
+ result.done++; render();
+ }
+ next = p.nextOffset;
+ } while (!retry && next !== null && !stopped && operationOwner === user());
+ } catch (_) { error = true; }
+ finally {
+ busy = false;
+ if (operationOwner === user()) {
+ window.initRecycleBin?.();
+ if (typeof loadConversations === 'function') {
+ try { await loadConversations(); } catch (_) { log.warn('cleanup navigation refresh failed'); }
+ }
+ // Preserve the receipt for failed-only retries. A fresh filter or
+ // explicit refresh creates a new receipt after the user sees results.
+ if (!failed.length && !error) await refresh(true);
+ else render();
+ } else { owner = ''; token = ''; total = 0; rows = []; result = null; failed = []; render(); }
+ }
+ }
+ async function click(event) {
+ const action = event.target.closest('[data-cleanup-action]')?.dataset.cleanupAction;
+ if (action === 'stop') { stopped = true; render(); return; }
+ if (busy || loading) return;
+ if (action === 'view') { expanded = !expanded; render(); }
+ if (action === 'prepare' && token && selectedCount() > 0) { confirming = true; render(); body().querySelector('[data-cleanup-action="cancel"]')?.focus(); }
+ if (action === 'cancel') { confirming = false; render(); body().querySelector('[data-cleanup-action="prepare"]')?.focus(); }
+ if (action === 'confirm') await run();
+ if (action === 'retry') await run(true);
+ if (action === 'refresh') await refresh();
+ if (action === 'previous') await changePage(Math.max(0, offset - 20));
+ if (action === 'next' && nextOffset !== null) await changePage(nextOffset);
+ }
+ async function change(event) {
+ if (busy || loading || confirming) return;
+ const cid = event.target.getAttribute('data-cleanup-cid');
+ if (cid) {
+ if (event.target.checked === allSelected) excluded.delete(cid); else excluded.add(cid);
+ } else if (event.target.hasAttribute('data-cleanup-all')) {
+ allSelected = event.target.checked; excluded.clear();
+ }
+ render();
+ }
+
+ window.initTaskCleanup = async function () {
+ if (!body() || !user()) return;
+ if (!bound) {
+ body().addEventListener('click', click); body().addEventListener('change', change); bound = true;
+ picker = _aiSelectMount(document.getElementById('settings-task-cleanup-age'), {
+ options: options(), value: String(days), ariaLabel: tr('age'),
+ });
+ picker.onChange(value => { if (!busy && !loading && !confirming) { days = Number(value); refresh(); } });
+ }
+ if (owner !== user()) { owner = user(); token = ''; excluded.clear(); result = null; failed = []; confirming = false; }
+ if (!busy && !loading && !confirming) await refresh();
+ };
+ window.addEventListener('i18n-change', render);
+ if (document.querySelector('[data-settings-tab="data"].is-active')) window.initTaskCleanup();
+})();
diff --git a/src/renderer/modules/task-unread.js b/src/renderer/modules/task-unread.js
index bbed7c75..73fa8405 100644
--- a/src/renderer/modules/task-unread.js
+++ b/src/renderer/modules/task-unread.js
@@ -12,9 +12,12 @@ const _TASK_UNREAD_MAX_RECORDS = 500;
let _taskUnreadOwnerUserId = '';
let _taskUnreadScopeRefreshPromise = null;
-const _taskUnreadByCid = new Map(); // cid -> { projectId: string|null, finishedAt: number }
+const _taskUnreadByCid = new Map(); // cid -> { projectId: string|null, finishedAt: number, status?: string, entryPoint?: string }
const _taskReadAtByCid = new Map(); // cid -> last acknowledged terminal timestamp
-const _taskUnreadPendingTerminals = new Map(); // terminal events received before initUser
+const _taskUnreadPendingTerminals = new Map(); // cid -> { finishedAt, status, entryPoint } received before initUser
+// Terminal states that make a run unread; the home page shows the same
+// statuses next to each unread task.
+const _TASK_UNREAD_STATUSES = new Set(['completed', 'stopped', 'failed', 'waiting_input']);
function _taskUnreadCurrentUserId() {
try {
return typeof currentUserId === 'string' ? currentUserId.trim() : '';
@@ -37,6 +40,26 @@ function _taskUnreadTimestamp(value, fallback = Date.now()) {
return Number.isFinite(n) && n > 0 ? Math.round(n) : fallback;
}
+function _taskUnreadStatus(value) {
+ const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
+ return _TASK_UNREAD_STATUSES.has(status) ? status : '';
+}
+
+function _taskUnreadEntryPoint(value) {
+ const entryPoint = typeof value === 'string' ? value.trim() : '';
+ return /^[a-z_]{1,32}$/.test(entryPoint) ? entryPoint : '';
+}
+
+/** Optional fields only when known, so old records keep their stored shape. */
+function _taskUnreadOutcome(status, entryPoint) {
+ const out = {};
+ const s = _taskUnreadStatus(status);
+ const e = _taskUnreadEntryPoint(entryPoint);
+ if (s) out.status = s;
+ if (e) out.entryPoint = e;
+ return out;
+}
+
function _taskUnreadLoadOwner(userId) {
_taskUnreadOwnerUserId = userId;
_taskUnreadByCid.clear();
@@ -61,6 +84,7 @@ function _taskUnreadLoadOwner(userId) {
_taskUnreadByCid.set(cid, {
projectId,
finishedAt: _taskUnreadTimestamp(row.finishedAt, 0),
+ ..._taskUnreadOutcome(row.status, row.entryPoint),
});
}
for (const row of readRows.slice(0, _TASK_UNREAD_MAX_RECORDS)) {
@@ -114,6 +138,10 @@ function _taskUnreadSave() {
// The indicator is helpful but must never affect task settlement or view
// navigation when storage is unavailable.
}
+ // The home page lists the same unread runs; it listens for this to refresh.
+ try {
+ window.dispatchEvent(new CustomEvent('task-unread-change'));
+ } catch (_) {}
}
function _taskUnreadConversationScope(cid) {
@@ -150,6 +178,15 @@ function _taskUnreadConversationIsActivelyViewed(cid) {
return true;
}
+/** Unread finished runs, newest first. `status` and `entryPoint` are absent on
+ * records written before they were tracked. */
+function _listUnreadTasks() {
+ _taskUnreadEnsureOwner();
+ return Array.from(_taskUnreadByCid.entries())
+ .map(([cid, record]) => ({ cid, ...record }))
+ .sort((a, b) => (b.finishedAt || 0) - (a.finishedAt || 0));
+}
+
function _isConversationUnread(cid) {
_taskUnreadEnsureOwner();
return _taskUnreadByCid.has(String(cid || ''));
@@ -186,23 +223,27 @@ function _markConversationUnread(cid, options = {}) {
const id = _taskUnreadSafeCid(cid);
if (!id) return false;
const finishedAt = _taskUnreadTimestamp(options.finishedAt);
+ const outcome = _taskUnreadOutcome(options.status, options.entryPoint);
if (_taskUnreadConversationIsActivelyViewed(id)) {
_markConversationRead(id, { readAt: finishedAt });
return false;
}
if (!_taskUnreadEnsureOwner()) {
- _taskUnreadPendingTerminals.set(id, Math.max(
- _taskUnreadPendingTerminals.get(id) || 0,
- finishedAt,
- ));
+ const pending = _taskUnreadPendingTerminals.get(id);
+ if (!pending || finishedAt >= pending.finishedAt) {
+ _taskUnreadPendingTerminals.set(id, { finishedAt, ...outcome });
+ }
return true;
}
if ((_taskReadAtByCid.get(id) || 0) >= finishedAt) return false;
const scope = _taskUnreadConversationScope(id);
const previous = _taskUnreadByCid.get(id);
+ // The newest terminal decides what the home page says about this task.
+ const newer = !previous || finishedAt >= (previous.finishedAt || 0);
_taskUnreadByCid.set(id, {
projectId: scope.known ? scope.projectId : (previous?.projectId ?? null),
finishedAt: Math.max(previous?.finishedAt || 0, finishedAt),
+ ...(newer ? outcome : _taskUnreadOutcome(previous.status, previous.entryPoint)),
});
_taskUnreadSave();
_refreshUnreadTaskIndicators();
@@ -267,9 +308,9 @@ function _forgetUnreadProject(projectId) {
function _restoreUnreadTaskState() {
_taskUnreadOwnerUserId = '';
if (!_taskUnreadEnsureOwner()) return;
- for (const [cid, finishedAt] of Array.from(_taskUnreadPendingTerminals.entries())) {
+ for (const [cid, pending] of Array.from(_taskUnreadPendingTerminals.entries())) {
_taskUnreadPendingTerminals.delete(cid);
- _markConversationUnread(cid, { finishedAt });
+ _markConversationUnread(cid, pending);
}
_taskUnreadHydrateScopes();
_refreshUnreadTaskIndicators();
@@ -330,7 +371,8 @@ function _refreshUnreadTaskIndicators(projectIdOverride) {
);
for (const dot of document.querySelectorAll?.('[data-project-unread-dot]') || []) {
- _taskUnreadSetDot(dot, _taskUnreadProjectCount(dot.dataset?.projectUnreadDot) > 0);
+ const projectId = dot.dataset?.projectUnreadDot;
+ _taskUnreadSetDot(dot, _taskUnreadProjectCount(projectId) > 0);
}
}
@@ -340,6 +382,8 @@ function _handleTaskTerminalUnread(payload) {
if (!['completed', 'stopped', 'failed', 'waiting_input'].includes(status)) return false;
return _markConversationUnread(payload.conversation_id, {
finishedAt: payload.finished_at_ms,
+ status,
+ entryPoint: payload.entry_point,
});
}
@@ -364,5 +408,6 @@ if (typeof window !== 'undefined') {
projectCount: _taskUnreadProjectCount,
markRead: _markConversationRead,
refresh: _refreshUnreadTaskIndicators,
+ list: _listUnreadTasks,
};
}
diff --git a/src/renderer/modules/today-tasks.js b/src/renderer/modules/today-tasks.js
index 247cec5e..806060c4 100644
--- a/src/renderer/modules/today-tasks.js
+++ b/src/renderer/modules/today-tasks.js
@@ -1,34 +1,45 @@
-/* Orkas Frontend — sidebar "Today's Tasks"
+/* Orkas Frontend — sidebar "Recent Tasks" (formerly "Today's Tasks")
*
- * Aggregates every conversation with activity today, whether it lives under a
+ * Aggregates every conversation with activity today or yesterday (local
+ * calendar), whether it lives under a
* Project or in the catch-all Tasks list, so running work and finished work
* that still needs a look sit in one place. The section is a mirror only:
* rows reuse the shared conversation row renderer, click/menu handlers,
* unread dots, and live-run badges, and the `conversations` cache remains the
- * single source of truth. Nothing here owns state or changes what the other
- * lists do; opening a task from either copy clears both copies' attention cue.
+ * single source of truth. Only the visible row limit belongs to this list;
+ * opening a task from either copy clears both copies' attention cue.
*
- * Day boundary: `selectTodayConversations` (conv-bucket.js) reads the same
- * activity timestamp and local-midnight rule as the "Today" bucket headers, so
- * a row is never "today" in one list and absent here. Rows for collapsed
- * projects reach the cache through the startup slice's `active_since` filter.
+ * Day boundary: `selectRecentConversations` (conv-bucket.js) reads the same
+ * activity timestamp and local-midnight rule as the "Today"/"Yesterday" bucket
+ * headers, so a row is never "today" or "yesterday" in one list and absent
+ * here. The date rollover re-render (conversation.js
+ * `_refreshConversationBucketsForDateChange`) is the once-a-day check that drops
+ * rows older than yesterday. Rows for collapsed projects reach the cache through
+ * the startup slice's `active_since` filter (start of yesterday).
*
- * Badges and unread dots are not painted here: every caller is a branch of
- * `renderConversationList`, whose single trailing `_refreshAllConvBadges` pass
- * runs after this list and the Projects section have both rendered.
+ * DOM ids, the i18n keys and the section's collapse key keep their historical
+ * `today` names; only the window and the label changed.
+ *
+ * Regular refreshes use `renderConversationList`'s trailing badge pass.
+ * Loading more or reopening refreshes only this list and its badges;
+ * reopening resets the visible row limit to the first page.
*/
+const _RECENT_TASK_PAGE_SIZE = 10;
+let _recentTaskVisibleCount = _RECENT_TASK_PAGE_SIZE;
+
function _todayTaskRows(now) {
const rows = typeof conversations !== 'undefined' && Array.isArray(conversations)
? conversations
: [];
- const today = typeof selectTodayConversations === 'function'
- ? selectTodayConversations(rows, now)
+ const selected = typeof selectRecentConversations === 'function'
+ ? selectRecentConversations(rows, now)
: [];
+ const recent = Array.isArray(selected) ? selected : [];
if (typeof _compareConversationsForSidebar === 'function') {
- today.sort(_compareConversationsForSidebar);
+ recent.sort(_compareConversationsForSidebar);
}
- return today;
+ return recent;
}
function renderTodayTasksSection() {
@@ -45,10 +56,21 @@ function renderTodayTasksSection() {
container.innerHTML = `<div class="conv-empty" data-i18n="sidebar.today_empty">${escapeHtml(t('sidebar.today_empty'))}</div>`;
return;
}
- const projectByCid = new Map(rows.map((c) => [c.conversation_id, c.project_id || '']));
- container.innerHTML = rows.map((c) => _renderConversationSidebarItem(c, { listId: 'today-list' })).join('');
+ const visibleRows = rows.slice(0, _recentTaskVisibleCount);
+ const projectByCid = new Map(visibleRows.map((c) => [c.conversation_id, c.project_id || '']));
+ container.innerHTML = visibleRows.map((c) => _renderConversationSidebarItem(c, { listId: 'today-list' })).join('');
+ if (rows.length > visibleRows.length) {
+ container.insertAdjacentHTML('beforeend', `<button type="button" class="conversation-list-load-more" data-recent-conv-more="1">
+ ${escapeHtml(t('sidebar.load_more_conversations'))}</button>`);
+ container.querySelector('[data-recent-conv-more]').addEventListener('click', () => {
+ _recentTaskVisibleCount += _RECENT_TASK_PAGE_SIZE;
+ renderTodayTasksSection();
+ _refreshAllConvBadges();
+ container.querySelector('[data-recent-conv-more]')?.focus({ preventScroll: true });
+ });
+ }
_bindConversationSidebarItems(container, {
- scope: 'today',
+ scope: 'recent',
async afterDelete(cid) {
// A projected task also changes its project's count; the nested project
// list does the same refresh after its own delete.
@@ -56,3 +78,10 @@ function renderTodayTasksSection() {
},
});
}
+
+window.addEventListener('sidebar-section-toggle', (event) => {
+ if (event?.detail?.name !== 'today' || event.detail.collapsed !== false) return;
+ _recentTaskVisibleCount = _RECENT_TASK_PAGE_SIZE;
+ renderTodayTasksSection();
+ _refreshAllConvBadges();
+});
diff --git a/src/renderer/modules/todos.js b/src/renderer/modules/todos.js
index 54fc6e77..93ffefbe 100644
--- a/src/renderer/modules/todos.js
+++ b/src/renderer/modules/todos.js
@@ -16,6 +16,8 @@ let _globalTodoNeedsFullLoad = true;
// paint. A change reloads only its scope; everything else stays as painted.
const _globalTodoDirtyScopes = new Set();
const _globalTodoDriverMutating = new Set();
+// A to-do the home asked to show; applied once by the next full load.
+let _globalTodoPendingFocus = null;
function _globalTodoContext(pid, showProject = false) {
const group = _globalTodoGroups.find((item) => item.project.project_id === pid);
@@ -28,7 +30,9 @@ function _globalTodoContext(pid, showProject = false) {
}
function _globalTodoCreateContext() {
- return _globalTodoContext('') || {
+ const pid = _globalTodoMode === 'project' && _globalTodoScopeProject(_globalTodoActiveScope)
+ ? (_globalTodoActiveScope || '') : '';
+ return _globalTodoContext(pid) || _globalTodoContext('') || {
pid: '',
tasks: [],
agents: [],
@@ -55,7 +59,8 @@ async function _loadGlobalTodoGroup(project) {
if (!globalRes?.ok || !Array.isArray(globalRes.tasks)) throw new Error('load_failed');
if (!globalRes.tasks.length) return null;
if (!Array.isArray(agentRes?.agents)) throw new Error('load_failed');
- return { project, tasks: globalRes.tasks, agents: agentRes.agents.filter((a) => a.enabled !== false), driverEnabled: !!globalDriver?.config?.enabled };
+ return { project, tasks: globalRes.tasks, agents: agentRes.agents.filter((a) => a.enabled !== false),
+ driverEnabled: !!globalDriver?.config?.enabled, driverConfig: globalDriver?.config, driverDevice: globalDriver?.device };
}
const tasks = await window.orkas.invoke('projects.tasks.list', { projectId: pid });
if (!tasks?.ok || !Array.isArray(tasks.tasks)) throw new Error('load_failed');
@@ -70,6 +75,8 @@ async function _loadGlobalTodoGroup(project) {
tasks: tasks.tasks,
agents: bindings.agentDetails || [],
driverEnabled: !!driver?.config?.enabled,
+ driverConfig: driver?.config,
+ driverDevice: driver?.device,
};
}
@@ -82,7 +89,7 @@ async function loadGlobalTodos() {
try {
const res = await window.orkas.invoke('projects.list', {});
if (!res?.ok || !Array.isArray(res.projects)) throw new Error('load_failed');
- const projects = res.projects.slice().sort((a, b) => a.name.localeCompare(b.name));
+ const projects = res.projects;
const globalGroup = await _loadGlobalTodoGroup(_globalTodoScopeProject(''));
const groups = globalGroup ? [globalGroup] : [];
// Bound filesystem/IPC fan-out; a stale visit stops scheduling more work.
@@ -98,8 +105,10 @@ async function loadGlobalTodos() {
_globalTodoDirtyScopes.clear();
document.getElementById('todos-error').hidden = true;
_renderGlobalTodos();
+ _applyGlobalTodoPendingFocus();
} catch (_) {
if (seq !== _globalTodoLoadSeq || currentView !== 'todos') return;
+ _globalTodoPendingFocus = null;
_projectDetailLog.warn('load global todos failed');
document.getElementById('todos-error').hidden = false;
} finally {
@@ -145,11 +154,33 @@ async function _reloadGlobalTodoScopes(pids) {
}
}
-function _setGlobalTodoDriverButtons(pid, enabled, disabled = false) {
+function _globalTodoScopeName(project) {
+ return project.project_id ? project.name : t('todo.global');
+}
+
+function _setGlobalTodoDriverButtonState(button, group, disabled = false) {
+ const name = _todoDriverDeviceName(group.driverConfig, group.driverDevice);
+ const suffix = name ? ' · ' + name : '';
+ button.setAttribute('aria-pressed', String(!!group.driverEnabled));
+ button.disabled = disabled;
+ const scopeName = _globalTodoScopeName(group.project);
+ button.title = `${scopeName} · ${t('project.driver.toggle_hint')}${suffix}`;
+ const label = (button.dataset.showScope === '1' ? scopeName : t('project.driver.toggle')) + suffix;
+ button.setAttribute('aria-label', label);
+ const toggle = '<span class="project-driver-switch" aria-hidden="true"></span>';
+ if (button.dataset.showScope === '1') {
+ const folder = typeof uiIconHtml === 'function'
+ ? uiIconHtml(typeof projectIconName === 'function' ? projectIconName(group.project) : 'folder', 'todo-driver-scope-icon') : '';
+ button.innerHTML = toggle + folder + `<span>${escapeHtml(label)}</span>`;
+ } else {
+ button.innerHTML = toggle + `<span>${escapeHtml(label)}</span>`;
+ }
+}
+
+function _setGlobalTodoDriverButtons(pid, group, disabled = false) {
for (const button of document.querySelectorAll('.todo-scope-driver-toggle')) {
if ((button.dataset.pid || '') !== pid) continue;
- button.setAttribute('aria-pressed', String(enabled));
- button.disabled = disabled;
+ _setGlobalTodoDriverButtonState(button, group, disabled);
}
}
@@ -158,11 +189,14 @@ async function _toggleGlobalTodoDriver(group) {
if (_globalTodoDriverMutating.has(pid)) return;
const next = !group.driverEnabled;
_globalTodoDriverMutating.add(pid);
- _setGlobalTodoDriverButtons(pid, group.driverEnabled, true);
+ _setGlobalTodoDriverButtons(pid, group, true);
try {
const res = await window.orkas.invoke('projects.driver.set', { projectId: pid, enabled: next });
+ if (res?.ok === false || !res?.config) throw new Error('toggle_failed');
group.driverEnabled = !!res?.config?.enabled;
- _setGlobalTodoDriverButtons(pid, group.driverEnabled);
+ group.driverConfig = res.config;
+ group.driverDevice = res.device;
+ _setGlobalTodoDriverButtons(pid, group);
if (typeof uiToast === 'function') {
uiToast(t(group.driverEnabled ? 'project.driver.enabled_toast' : 'project.driver.disabled_toast'), {
variant: group.driverEnabled ? 'success' : 'info',
@@ -170,7 +204,7 @@ async function _toggleGlobalTodoDriver(group) {
}
} catch (err) {
_projectDetailLog.warn('toggle todo scope driver failed', err);
- _setGlobalTodoDriverButtons(pid, group.driverEnabled);
+ _setGlobalTodoDriverButtons(pid, group);
if (typeof uiAlert === 'function') uiAlert(t('project.todo.failed'));
} finally {
_globalTodoDriverMutating.delete(pid);
@@ -181,44 +215,59 @@ function _renderGlobalTodoDriverToggle(group, showScope) {
const pid = group.project.project_id || '';
const button = document.createElement('button');
button.type = 'button';
- button.className = 'btn btn-sm project-driver-toggle todo-scope-driver-toggle';
+ button.className = 'project-driver-toggle is-switch todo-scope-driver-toggle';
button.dataset.pid = pid;
- button.setAttribute('aria-pressed', String(!!group.driverEnabled));
- button.title = `${group.project.name} · ${t('project.driver.toggle_hint')}`;
- if (showScope) {
- const folder = typeof uiIconHtml === 'function'
- ? uiIconHtml('folder', 'todo-driver-scope-icon')
- : '';
- button.innerHTML = folder + `<span>${escapeHtml(group.project.name)}</span>`;
- } else {
- button.textContent = t('project.driver.toggle');
- }
+ button.dataset.showScope = showScope ? '1' : '0';
+ _setGlobalTodoDriverButtonState(button, group, _globalTodoDriverMutating.has(pid));
button.addEventListener('click', () => _toggleGlobalTodoDriver(group));
return button;
}
function _renderGlobalTodoDriverHint() {
- const hint = document.createElement('span');
- hint.className = 'form-hint';
- hint.textContent = t('project.driver.toggle_hint');
+ _bindProjectDriverHint();
+ const hint = document.createElement('button');
+ hint.type = 'button';
+ hint.className = 'project-driver-hint';
+ hint.setAttribute('aria-label', t('project.driver.toggle_hint'));
+ hint.setAttribute('aria-describedby', 'project-driver-tooltip');
+ hint.innerHTML = uiIconHtml('info', 'project-driver-hint-icon');
return hint;
}
+function _renderGlobalTodoDriverControl(group, showScope) {
+ const control = document.createElement('div');
+ control.className = 'todo-driver-control';
+ control.appendChild(_renderGlobalTodoDriverToggle(group, showScope));
+ control.appendChild(_renderGlobalTodoDriverHint());
+ return control;
+}
+
+// One explanation serves every scope switch, so the hint follows the shared
+// label instead of repeating after each switch.
function _renderGlobalTodoDriverBar(groups) {
const bar = document.createElement('div');
bar.className = 'todo-driver-bar';
+ const head = document.createElement('div');
+ head.className = 'todo-driver-bar-head';
const label = document.createElement('span');
label.className = 'todo-driver-bar-label';
label.textContent = t('project.driver.toggle');
- bar.appendChild(label);
- for (const group of groups) bar.appendChild(_renderGlobalTodoDriverToggle(group, true));
- bar.appendChild(_renderGlobalTodoDriverHint());
+ head.appendChild(label);
+ head.appendChild(_renderGlobalTodoDriverHint());
+ bar.appendChild(head);
+ const list = document.createElement('div');
+ list.className = 'todo-driver-bar-list todo-scroll-track';
+ list.dataset.track = 'status-driver';
+ for (const group of groups) list.appendChild(_renderGlobalTodoDriverToggle(group, true));
+ _bindTodoScrollTrack(list);
+ bar.appendChild(list);
return bar;
}
function _renderGlobalTodoScopeSwitcher(groups) {
const nav = document.createElement('nav');
- nav.className = 'todo-scope-switcher';
+ nav.className = 'todo-scope-switcher todo-scroll-track';
+ nav.dataset.track = 'project-scope';
nav.setAttribute('aria-label', t('todo.by_project'));
for (const group of groups) {
const pid = group.project.project_id || '';
@@ -228,10 +277,10 @@ function _renderGlobalTodoScopeSwitcher(groups) {
chip.dataset.pid = pid;
chip.setAttribute('aria-pressed', String(pid === _globalTodoActiveScope));
const folder = typeof uiIconHtml === 'function'
- ? uiIconHtml('folder', 'todo-scope-chip-icon')
+ ? uiIconHtml(typeof projectIconName === 'function' ? projectIconName(group.project) : 'folder', 'todo-scope-chip-icon')
: '';
chip.innerHTML = folder
- + `<span class="todo-scope-chip-name">${escapeHtml(group.project.name)}</span>`
+ + `<span class="todo-scope-chip-name">${escapeHtml(_globalTodoScopeName(group.project))}</span>`
+ `<span class="todo-scope-chip-count">${group.tasks.length}</span>`;
chip.addEventListener('click', () => {
if (_globalTodoActiveScope === pid) return;
@@ -240,12 +289,73 @@ function _renderGlobalTodoScopeSwitcher(groups) {
});
nav.appendChild(chip);
}
+ _bindTodoScrollTrack(nav);
return nav;
}
+// Single-row chip tracks (project switcher, status-view switches) scroll
+// sideways. Without a horizontal wheel, vertical wheel motion moves the track;
+// at either end the page keeps scrolling normally.
+function _bindTodoScrollTrack(track) {
+ track.addEventListener('wheel', (event) => {
+ if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
+ const before = track.scrollLeft;
+ track.scrollLeft += event.deltaY * (getComputedStyle(track).direction === 'rtl' ? -1 : 1);
+ if (track.scrollLeft !== before) event.preventDefault();
+ }, { passive: false });
+ track.addEventListener('scroll', () => _updateTodoScrollTrackFade(track), { passive: true });
+}
+
+// Fade whichever physical edge hides chips, so an overflowing track reads as
+// scrollable without a visible scrollbar.
+function _updateTodoScrollTrackFade(track) {
+ const max = track.scrollWidth - track.clientWidth;
+ const offset = Math.abs(track.scrollLeft);
+ const rtl = getComputedStyle(track).direction === 'rtl';
+ const beforeStart = max > 1 && offset > 1;
+ const beforeEnd = max > 1 && offset < max - 1;
+ track.classList.toggle('is-fade-left', rtl ? beforeEnd : beforeStart);
+ track.classList.toggle('is-fade-right', rtl ? beforeStart : beforeEnd);
+}
+
+function _captureTodoScrollTrack(host) {
+ const track = host.querySelector('.todo-scroll-track');
+ return track ? { key: track.dataset.track, left: track.scrollLeft } : null;
+}
+
+let _todoScrollTrackResizeObserver = null;
+let _todoScrollTrackObserved = null;
+
+// Restore the track position of the same view, then keep the active chip (if
+// any, e.g. a scope picked off-screen via focusTodo) in view.
+function _mountTodoScrollTrack(track, snapshot) {
+ if (snapshot?.key === track.dataset.track && snapshot.left) track.scrollLeft = snapshot.left;
+ const active = track.querySelector('[aria-pressed="true"].todo-scope-chip');
+ if (active) {
+ const bounds = track.getBoundingClientRect();
+ const chip = active.getBoundingClientRect();
+ if (chip.left < bounds.left || chip.right > bounds.right) {
+ active.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ }
+ }
+ _updateTodoScrollTrackFade(track);
+ if (typeof ResizeObserver !== 'function') return;
+ if (!_todoScrollTrackResizeObserver) {
+ _todoScrollTrackResizeObserver = new ResizeObserver(() => {
+ if (_todoScrollTrackObserved?.isConnected) _updateTodoScrollTrackFade(_todoScrollTrackObserved);
+ });
+ }
+ if (_todoScrollTrackObserved) _todoScrollTrackResizeObserver.unobserve(_todoScrollTrackObserved);
+ _todoScrollTrackObserved = track;
+ _todoScrollTrackResizeObserver.observe(track);
+}
+
function _renderGlobalTodos() {
const host = document.getElementById('todos-content');
if (!host) return;
+ const scroll = _captureTodoScroll(host);
+ const trackScroll = _captureTodoScrollTrack(host);
+ _closeProjectDriverHint();
host.innerHTML = '';
for (const button of document.querySelectorAll('[data-todo-group]')) {
button.setAttribute('aria-pressed', String(button.dataset.todoGroup === _globalTodoMode));
@@ -261,17 +371,26 @@ function _renderGlobalTodos() {
if (_globalTodoMode === 'status') {
// Composite identity is necessary even when imported tasks share an id.
const tasks = groups.flatMap((group) => group.tasks.map((task) => ({ ...task, project_id: group.project.project_id })));
- host.appendChild(_renderGlobalTodoDriverBar(groups));
+ const bar = _renderGlobalTodoDriverBar(groups);
+ host.appendChild(bar);
+ _mountTodoScrollTrack(bar.querySelector('.todo-scroll-track'), trackScroll);
host.appendChild(_renderTodoBoard(tasks, {
resolve: (task) => _globalTodoContext(task.project_id, true),
}, 'global:status'));
+ _restoreTodoScroll(host, scroll);
return;
}
const scopes = groups.map((group) => group.project.project_id || '');
// A scope that emptied out since the last paint drops off the switcher, so
// fall back to the first one rather than painting nothing.
if (!scopes.includes(_globalTodoActiveScope)) _globalTodoActiveScope = scopes[0];
- host.appendChild(_renderGlobalTodoScopeSwitcher(groups));
+ // The switcher scrolls on its own while the scope's Auto-advance control
+ // stays pinned at the end of the same row.
+ const row = document.createElement('div');
+ row.className = 'todo-scope-row';
+ const switcher = _renderGlobalTodoScopeSwitcher(groups);
+ row.appendChild(switcher);
+ host.appendChild(row);
for (const group of groups) {
const pid = group.project.project_id;
if ((pid || '') !== _globalTodoActiveScope) continue;
@@ -282,25 +401,47 @@ function _renderGlobalTodos() {
const board = _renderTodoBoard(group.tasks, _globalTodoContext(pid), key);
const actions = document.createElement('div');
actions.className = 'todo-scope-actions';
- const add = document.createElement('button');
- add.type = 'button';
- add.className = 'project-todo-menu todo-project-add';
- add.setAttribute('aria-label', t('project.todo.add') + ' · ' + group.project.name);
- add.innerHTML = typeof uiIconHtml === 'function' ? uiIconHtml('plus') : '+';
- add.addEventListener('click', () => {
- const context = _globalTodoContext(pid);
- if (!context) return;
- // A group-level + creates inside that group. The page-level + remains the
- // place for choosing a different project or the global scope.
- _openProjectTodoEditor(null, { ...context, projects: undefined });
- });
- actions.appendChild(_renderGlobalTodoDriverHint());
- actions.appendChild(_renderGlobalTodoDriverToggle(group, false));
- actions.appendChild(add);
- section.appendChild(actions);
+ actions.appendChild(_renderGlobalTodoDriverControl(group, false));
+ row.appendChild(actions);
section.appendChild(board);
host.appendChild(section);
}
+ _mountTodoScrollTrack(switcher, trackScroll);
+ _restoreTodoScroll(host, scroll);
+}
+
+/** Open the To-dos page on one to-do: switch to the by-project view and its
+ * scope and the row is highlighted once loaded. If it is gone by then (done or
+ * deleted meanwhile), the page simply opens. */
+function focusTodo(scope, taskId, opts = {}) {
+ const pid = String(scope || '');
+ const id = String(taskId || '');
+ _globalTodoPendingFocus = id ? { pid, id } : null;
+ if (id) {
+ _globalTodoMode = 'project';
+ _globalTodoActiveScope = pid;
+ }
+ setView('todos', null, opts.entryPoint ? { entryPoint: opts.entryPoint } : {});
+}
+
+function _applyGlobalTodoPendingFocus() {
+ const target = _globalTodoPendingFocus;
+ _globalTodoPendingFocus = null;
+ if (!target) return;
+ const host = document.getElementById('todos-content');
+ const row = Array.from(host?.querySelectorAll('.project-todo-item[data-tid]') || [])
+ .find((el) => el.dataset.tid === target.id);
+ if (!row) return;
+ // Reveal it even when the user had collapsed its column; this does not
+ // change the remembered collapse state.
+ const body = row.closest('.todo-column-body');
+ if (body && body.hidden) {
+ body.hidden = false;
+ body.parentElement?.querySelector('.todo-collapse')?.setAttribute('aria-expanded', 'true');
+ }
+ row.classList.add('is-highlighted');
+ row.scrollIntoView({ block: 'center' });
+ setTimeout(() => row.classList.remove('is-highlighted'), 2500);
}
// `pid` undefined reloads everything (sync refresh); '' or a project id
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index 1f3203ed..40eb10ec 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -28,15 +28,6 @@ const _wsInfoByTarget = {
project: { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },
};
-function _logWorkspaceOpenFolderResult(target, result, startedAt, errorCode = '') {
- if (result !== 'failure') return;
- _wsLog.warn('workspace open folder failed', {
- target,
- error_code: errorCode || 'unknown',
- duration_ms: Math.max(0, Date.now() - startedAt),
- });
-}
-
// ── Workspace display helpers ───────────────────────────────────────
/** Extract just the folder name from an absolute path. */
@@ -229,18 +220,14 @@ async function _resetWorkspace(target) {
async function _openWorkspaceFolder(target) {
const hint = _wsScopeHintFor(target);
- const startedAt = Date.now();
try {
const result = await window.orkas.invoke('workspace.openPath', hint);
if (result && result.ok) {
- _logWorkspaceOpenFolderResult(target, 'success', startedAt, '', result);
_wsLog.info('workspace opened', { target });
} else {
- _logWorkspaceOpenFolderResult(target, 'failure', startedAt, 'open_rejected');
_wsLog.warn('workspace open rejected', { target, error_code: 'open_rejected' });
}
} catch (err) {
- _logWorkspaceOpenFolderResult(target, 'failure', startedAt, 'invoke_failed');
_wsLog.error('workspace open failed', {
target,
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
@@ -420,6 +407,7 @@ function _showWorkspaceDropdown(anchor, target) {
});
menu.appendChild(openItem);
+ menu.dataset.uiOverlay = '';
menu.style.position = 'fixed';
menu.style.visibility = 'hidden';
document.body.appendChild(menu);
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index d017e450..06f1c665 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -2544,6 +2544,7 @@ function _aiSelectMount(el, config) {
const reposition = () => {
if (!state.open) return;
const rect = trigger.getBoundingClientRect();
+ popover.dataset.uiOverlay = '';
popover.style.position = 'fixed';
popover.style.left = rect.left + 'px';
popover.style.width = rect.width + 'px';
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 030d4898..1c7b13cf 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -1,4 +1,11 @@
-:root {
+
+.ui-overlay { --orkas-ui-layer: overlay; }
+.ui-overlay-waiting { opacity: 0 !important; pointer-events: none !important; }
+@property --orkas-ui-layer {
+ syntax: "*";
+ inherits: false;
+ initial-value: none;
+}:root {
/* See PC/docs/design/TOKENS.md (binding). New UI follows the cool-blue +
indigo scale below; token names are stable so the rest of the stylesheet
inherits without a sweep. New tokens land here in the same diff that
@@ -39,10 +46,6 @@
--radius-sm: 10px;
--font-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
}
-
-/* Canonical motion keyframes per PC/docs/design/TOKENS.md §6. Pre-existing
- feature-scoped keyframes (ctx-kb-spin / …) keep their
- names — new UI code references these short names. */
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(0.8); } }
@keyframes blink { 50% { opacity: 0; } }
@@ -62,16 +65,6 @@
}
* { box-sizing: border-box; margin: 0; padding: 0; }
-
-/* ─── Global scrollbar — thin, subtle. Without this rule, any scrollable
- container that doesn't have its own ::-webkit-scrollbar override (e.g.
- settings panels, sync usage breakdown, generic modal bodies) falls
- back to the OS default — on macOS that's a chunky ~15px bar that
- looks out of place against the app's compact, soft-shadowed UI.
- Per-element overrides further down the file (.projects-list,
- .conversation-list, .skills-grid-scroll, etc.) keep their tighter
- 4–6px widths via CSS specificity; this rule only catches the
- "no override declared" case. ─── */
::-webkit-scrollbar {
width: 8px;
height: 8px;
@@ -110,8 +103,6 @@ body {
height: 100vh;
width: 100vw;
}
-
-/* ─── Sidebar ─── */
.sidebar {
/* Width is overridden at runtime by sidebar-resize.js via `--sidebar-width`
(default 280px, persisted per-machine). The fallback here matches the JS
@@ -128,10 +119,6 @@ body {
border-right: 1px solid var(--border);
position: relative;
}
-
-/* Drag handle on the sidebar's right edge. Sits on top of the border so the
- visible chrome stays the existing 1px line; widens to a 6px hit-zone for
- the pointer. Double-click resets to default via sidebar-resize.js. */
.sidebar-resize-handle {
position: absolute;
top: 0;
@@ -139,6 +126,7 @@ body {
bottom: 0;
width: 6px;
cursor: col-resize;
+ --orkas-ui-layer: chrome;
z-index: 20;
background: transparent;
transition: background 0.15s;
@@ -153,10 +141,6 @@ body {
outline: 2px solid var(--primary);
outline-offset: -2px;
}
-
-/* While the user is dragging the handle the whole window adopts a
- col-resize cursor and we suppress text selection / iframe pointer events so
- the drag doesn't get hijacked by the chat panel or an artifact iframe. */
body.is-sidebar-resizing,
body.is-sidebar-resizing * {
cursor: col-resize !important;
@@ -246,8 +230,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 1px;
flex-shrink: 0;
}
-
-/* Sidebar search trigger — sits between the logo strip and the action list. */
.sidebar-search-btn {
display: flex;
align-items: center;
@@ -294,13 +276,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
height: 14px;
flex-shrink: 0;
}
-
-/* ── Global search overlay (Cmd+K) ─────────────────────────────────────── */
.search-overlay {
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.4);
backdrop-filter: blur(2px);
+ --orkas-ui-layer: overlay;
z-index: 300;
display: flex;
align-items: flex-start;
@@ -317,12 +298,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex-direction: column;
overflow: hidden;
}
-
-/* ── Toast notifications (P14) ───────────────────────────────────────── */
.ui-toast-host {
position: fixed;
top: 44px;
left: 50%;
+ --orkas-ui-layer: overlay;
z-index: 20000;
display: flex;
flex-direction: column;
@@ -450,7 +430,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: #f1f5f9;
color: var(--text);
}
-/* Category tabs above the result body: all / tasks / library. */
.search-tabs {
display: flex;
gap: 2px;
@@ -476,8 +455,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
font-weight: 500;
}
.search-tabs.is-hidden { display: none; }
-
-/* "查看更多" overflow button at the bottom of a section in the "all" tab. */
.search-show-more {
display: block;
width: calc(100% - 32px);
@@ -607,8 +584,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
padding: 0 1px;
border-radius: 2px;
}
-
-/* Brief glow when a chat-message is reached via global search */
.chat-message.search-flash > .chat-bubble {
animation: search-flash 1.6s ease-out;
}
@@ -667,9 +642,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--primary-text);
font-weight: 600;
}
-
-/* Sidebar running-count chips — visible when ≥1 group_chat is active. Commander
- shows the app-wide total; Tasks and Project surfaces show their own totals. */
.sidebar-btn-running-chip {
margin-left: auto;
padding: 0 6px;
@@ -686,9 +658,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex: 0 0 auto;
white-space: nowrap;
}
-
-/* Unread task reply. Sidebar-only, and intentionally identical to every
- renderer attention dot: shared size, semantic danger red, no halo. */
.task-unread-dot {
display: inline-block;
width: var(--attention-dot-size);
@@ -702,10 +671,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
#today-unread-dot,
#tasks-unread-dot,
#projects-unread-dot { margin-left: 4px; }
-
-/* The normal title flex fills the row, which would push a following dot to
- the far edge. Only unread sidebar rows shrink the title to its text so the
- dot stays immediately on the copy's right while long titles still ellipsize. */
.sidebar-conversation-nav .conv-item.has-unread .conv-item-title,
.sidebar-conversation-nav .conv-item.has-unread .conv-item-title-input {
flex: 0 1 auto;
@@ -723,12 +688,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-name-unread-group:has(.project-unread-dot:not([hidden])) .project-name {
flex: 0 1 auto;
}
-
-/* "新任务" uses default style — no special highlight.
- The primary class is kept for semantic grouping only. */
.sidebar-btn.primary {}
-
-/* Sidebar footer actions — 设置入口下沉到这里,留出顶部空间给主业务。*/
.sidebar-footer-actions {
position: relative;
display: flex;
@@ -795,26 +755,26 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 100%;
padding-right: 8px;
}
-
-/* Product announcements */
.sidebar-settings-alerts {
display: block;
order: 2;
flex: 0 0 auto;
box-sizing: border-box;
min-width: 0;
- max-width: min(92px, 50%);
+ max-width: min(92px, calc(50% - 7px));
margin-left: auto;
- padding: 1px 6px;
- border-radius: 999px;
+ margin-right: 8px;
+ padding: 6px 10px;
+ border: 1px solid rgba(91, 87, 214, 0.12);
+ border-radius: 8px;
font-size: 11px;
- font-weight: 600;
- line-height: 18px;
+ font-weight: 550;
+ line-height: 1.4;
overflow: hidden;
white-space: nowrap;
text-align: left;
- background: var(--surface-2);
- color: var(--text-2);
+ background: #f1f0fc;
+ color: #5753bd;
}
.sidebar-settings-alerts:empty { display: none; }
@media (prefers-reduced-motion: reduce) {
@@ -841,10 +801,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex-direction: column;
overflow: visible;
}
-
-/* The Today aggregate, Projects and the catch-all conversation list are one
- conversation navigation surface. The parent .sidebar-conversation-nav owns
- scrolling so all three move together. */
.sidebar-today-section {
border-top: 0;
}
@@ -904,12 +860,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
letter-spacing: 0.04em;
color: var(--muted);
}
-
-/* When the title sits inside a row, its own padding is owned by the row;
- collapse the per-element padding so the row's vertical rhythm stays clean. */
.sidebar-section-title-row .sidebar-section-title { padding: 0 4px; }
-.sidebar-section-body[hidden],
.today-list[hidden],
.projects-list[hidden],
.conversation-list[hidden] {
@@ -934,8 +886,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.sidebar-section-add:hover { background: var(--surface-2); color: var(--text); }
-/* ─── Projects list ─── */
-
.projects-list {
overflow: visible;
display: flex;
@@ -948,7 +898,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
display: flex;
align-items: center;
gap: 8px;
- padding: 5px 9px;
+ padding: 3px 9px;
border-radius: 6px;
cursor: pointer;
color: var(--text-2);
@@ -970,11 +920,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 18px;
color: var(--muted);
}
-/* Make sure clicks on the SVG / its paths bubble cleanly to .project-row's
- click handler (otherwise nested <path> targets can confuse `closest()`
- queries downstream). The icon itself is purely decorative — collapse /
- expand is driven by clicking anywhere on the row except the menu /
- rename input. */
.project-icon svg { pointer-events: none; }
.project-name {
@@ -1005,9 +950,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
padding: 2px 8px 4px 26px; /* align below the name (caret + icon offset) */
line-height: 1.3;
}
-
-/* ⋯ button styling: hidden by default, surfaces on row hover or while the
- menu is open. Mirrors the KB tree pattern (.ctx-row-menu-btn). */
.project-row-menu-btn {
visibility: hidden;
}
@@ -1015,8 +957,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-row.is-menu-open .project-row-menu-btn {
visibility: visible;
}
-
-/* Nested conv items inside a project — slight indent so the hierarchy reads. */
.project-conv-list {
display: flex;
flex-direction: column;
@@ -1036,13 +976,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: #94a3b8;
}
-/* ── Project detail panel ─────────────────────────────────────────────── */
-/* Chrome aligned with PC/docs/design/{TOKENS,PATTERNS}.md. Page header is
- P1 (title + count + subtitle + actions); composer reuses the shared
- .chat-input-area chrome via the `.is-project` modifier (full column width,
- slightly tighter padding); side-column cards are P4 (surface, hairline
- border, no shadow); binding / file rows use surface-2 with --border. */
-
.project-detail-view {
display: flex;
flex-direction: column;
@@ -1060,9 +993,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
display: flex;
flex-direction: column;
}
-
-/* P1 page header. Padding + title-font matched to `.chat-header` so every
- surface's top band reads as the same height (chat-header is the reference). */
.project-detail-header {
flex: 0 0 auto;
display: flex;
@@ -1121,18 +1051,19 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex-shrink: 0;
}
.project-detail-actions .btn[hidden] { display: none; }
-#project-add-agent-btn[hidden] { display: none; }
-.project-todo-agent-icon {
- flex: 0 0 18px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- border-radius: 50%;
+#panel-project .project-detail-header { align-items: center; }
+#panel-project .project-detail-actions { min-height: 34px; }
+#panel-project .project-detail-header-title-row { align-items: center; gap: 8px; }
+#panel-project .project-detail-title,
+#panel-project .project-detail-title-input {
+ font-size: 20px;
+ letter-spacing: -0.02em;
+ line-height: 1.3;
}
-.project-todo-agent-icon { color: var(--text-2); background: var(--surface-2); }
-.project-todo-assign-icon { width: 12px; height: 12px; }
+.project-header-icon-btn[hidden] { display: none; }
+.project-header-icon-btn:disabled { cursor: default; }
+.project-header-icon-btn.is-loading .project-header-icon { animation: spin 1s linear infinite; }
+#project-add-agent-btn[hidden] { display: none; }
.project-detail-grid {
flex: 1;
@@ -1146,8 +1077,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
box-sizing: border-box;
overflow: hidden;
}
-/* Narrow windows (or a pinned app sidebar) get the previous rail width back
- before the composer and task rows start losing room. */
@media (max-width: 1280px) {
.project-detail-grid { grid-template-columns: minmax(0, 1fr) 336px; }
}
@@ -1162,18 +1091,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
overflow-y: auto;
padding-right: 2px;
}
-
-/* Project composer uses the same width/centring rule as conversation detail. */
.chat-input-area.is-project {
max-width: 100%;
margin: 0 auto;
padding: 10px 16px;
width: 100%;
}
-/* Render the attachment strip INLINE above the project composer input (like the
- new-chat composer) instead of floating it absolutely above the box. The
- project composer sits near the top of the page, so the floated strip would
- render off-screen / behind the header and the chips would be invisible. */
.chat-input-area.is-project .chat-input-overlay {
position: static;
transform: none;
@@ -1196,32 +1119,26 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
min-height: 64px;
max-height: 220px;
}
-
-/* Task / automation workbench. The conversation rows inside the task panel
- keep their existing styles; this surface only gives the two modes a shared
- frame and a clearer tab hierarchy. */
.project-workbench {
flex: 1 0 360px;
min-height: 360px;
- margin-top: 22px;
+ margin-top: 16px;
display: flex;
flex-direction: column;
overflow: hidden;
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
}
.project-detail-tabs {
flex: 0 0 auto;
display: flex;
align-items: stretch;
+ gap: 16px;
min-height: 44px;
- padding: 0 16px;
border-bottom: 1px solid var(--border);
}
.project-detail-tabs > .project-detail-tab-group {
+ flex: 0 0 auto;
align-items: stretch;
- gap: 20px;
+ gap: 24px;
min-height: 0;
margin-bottom: -1px;
padding: 0;
@@ -1241,11 +1158,128 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: transparent;
}
.project-detail-tabs .project-detail-tab.is-active {
+ color: var(--text);
border-bottom-color: var(--primary);
background: transparent;
box-shadow: none;
}
-.project-detail-tab-group {
+.project-detail-tabs .project-detail-tab-count {
+ padding: 0 5px;
+ border-radius: 99px;
+ background: var(--surface-2);
+ color: var(--muted);
+ font-size: 10.5px;
+ font-weight: 600;
+ line-height: 16px;
+}
+.project-detail-tabs .project-detail-tab.is-active .project-detail-tab-count {
+ background: var(--primary-soft);
+ color: var(--primary-text);
+}
+.project-tab-tools {
+ flex: 1 1 auto;
+ min-width: 0;
+ align-self: center;
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ padding: 6px 0;
+}
+.project-tab-tools[hidden] { display: none; }
+.project-todo-filter { display: inline-flex; align-items: center; gap: 12px; }
+.project-todo-filter:empty { display: none; }
+.project-todo-filter::after {
+ content: '';
+ width: 1px;
+ height: 18px;
+ background: var(--border-strong);
+}
+.project-driver-toggle.is-switch {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 2px 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.4;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.project-driver-toggle.is-switch[aria-pressed="true"] { color: var(--text); background: transparent; }
+.project-driver-toggle.is-switch[aria-pressed]::before { content: none; }
+.project-driver-toggle.is-switch:disabled { cursor: default; opacity: 0.55; }
+.project-driver-toggle.is-switch:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
+.project-driver-switch {
+ position: relative;
+ flex: none;
+ width: 28px;
+ height: 16px;
+ border-radius: 999px;
+ background: var(--surface-3);
+ transition: background-color 0.18s ease;
+}
+.project-driver-switch::after {
+ content: '';
+ --orkas-ui-layer: chrome;
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.2);
+ transition: transform 0.18s ease;
+}
+.project-driver-toggle[aria-pressed="true"] .project-driver-switch { background: var(--primary); }
+.project-driver-toggle[aria-pressed="true"] .project-driver-switch::after { transform: translateX(12px); }
+html[dir="rtl"] .project-driver-switch::after { left: auto; right: 2px; }
+html[dir="rtl"] .project-driver-toggle[aria-pressed="true"] .project-driver-switch::after { transform: translateX(-12px); }
+.project-driver-hint {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ margin-inline-start: -6px;
+ color: var(--muted);
+ cursor: pointer;
+}
+.project-driver-hint:hover { color: var(--text-2); background: var(--surface-2); }
+.project-driver-hint:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
+.project-driver-hint-icon { width: 14px; height: 14px; }
+.project-driver-tooltip {
+ --orkas-ui-layer: overlay;
+ position: fixed;
+ z-index: 10;
+ width: 300px;
+ max-width: calc(100vw - 16px);
+ box-sizing: border-box;
+ padding: 8px 12px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+ color: var(--text-2);
+ font-size: 12px;
+ line-height: 1.5;
+ text-wrap: pretty;
+ overflow-wrap: anywhere;
+ overflow: auto;
+}
+.project-driver-tooltip[hidden] { display: none; }
+.project-detail-tab-group,
+.apps-type-tabs {
display: inline-flex;
align-items: center;
gap: 2px;
@@ -1302,7 +1336,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex: 1;
display: flex;
flex-direction: column;
- padding: 7px 16px 18px;
+ padding: 16px 0 0;
min-height: 0;
overflow-y: auto;
}
@@ -1315,11 +1349,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
justify-content: center;
text-align: center;
}
-
-/* Right rail sizes to its content. The two cards used to split the column
- in half, which left the Context card holding a tall empty textarea and the
- Resources card stretched past its last row. The rail itself scrolls when
- the cards outgrow the viewport. */
.project-detail-side {
min-width: 0;
min-height: 0;
@@ -1342,10 +1371,10 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-radius: var(--radius-md);
}
-/* Instructions are user-authored rules injected into every conversation in
- the project. They share the Context card with agent-written memory. The
- panel shows the saved text; `.project-instructions-input` lives in the
- editor dialog. */
+.project-side-card.is-highlighted {
+ border-color: var(--primary);
+ box-shadow: 0 0 0 3px var(--primary-soft);
+}
.project-context-help {
flex: 0 0 auto;
margin: 0 0 12px;
@@ -1375,8 +1404,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
text-overflow: ellipsis;
white-space: nowrap;
}
-/* Secondary by default: saving and sending are the only primary-filled
- actions on this surface. */
.project-context-action {
flex: 0 0 auto;
}
@@ -1407,8 +1434,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
line-height: 1.4;
}
.project-context-status:empty { min-height: 0; }
-
-/* Editor dialog — one text field, sized for writing a page of rules. */
.project-instructions-dialog {
max-width: 640px;
padding: 24px;
@@ -1465,9 +1490,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-bottom: 1px solid var(--border);
background: var(--surface);
}
-/* Card identity on one line, the two context/resource types on the next.
- One 44px strip could not hold a title, two tabs and an action without
- shrinking the tabs to 11px. */
.project-side-card-head-tabs {
flex-direction: column;
align-items: stretch;
@@ -1564,9 +1586,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-side-card-count:empty,
.project-side-tab-count:empty { display: none; }
-
-/* Underlined tabs, same size and rhythm as the workbench tabs in the main
- column — one tab idiom on the page instead of two pill sizes. */
.project-side-tabs {
flex: 0 0 auto;
display: flex;
@@ -1617,9 +1636,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
max-height: 320px;
padding: 0;
}
-/* Empty memory reads like the empty rules panel — guidance left-aligned with
- its call to action, not a centred placeholder. Keeps `.empty` so the open
- editor still hides it through the sibling rule below. */
+.project-memory-full { color: var(--warn-text); }
+.project-memory-full[hidden] { display: none; }
#project-memory-empty {
display: block;
flex: 0 0 auto;
@@ -1680,16 +1698,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex: 0 1 auto;
max-height: 320px;
}
-/* To-do lives in the normal project workbench as a third tab. The composer and
- right rail remain part of the project detail layout in every tab. */
-.project-todo-tab-head {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 0 4px 8px;
-}
-.project-todo-tab-head > .project-driver-toggle { flex: 0 0 auto; }
-.project-todo-tab-head > .btn:not(.project-driver-toggle) { flex: 0 0 auto; margin-left: auto; }
.project-todo-add { margin: 0 0 8px; }
.project-todo-add:not([hidden]) ~ .project-todo-list,
.project-todo-add:not([hidden]) ~ .empty {
@@ -1712,8 +1720,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
max-height: 320px;
overflow-y: auto;
}
-
-/* Project To-do card — compact task board (features/project_tasks.ts). */
.project-todo-item {
display: flex;
align-items: center;
@@ -1726,8 +1732,10 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-todo-item:hover {
background: var(--surface-2);
}
-/* Row status control: a compact dropdown (colored dot + label + caret) that
- opens the four-status menu. Replaces the click-to-toggle dot + strikethrough. */
+.todo-board .project-todo-item.is-highlighted {
+ background: var(--primary-soft);
+ box-shadow: inset 0 0 0 1px var(--primary);
+}
.project-todo-status-select.btn {
flex: 0 0 auto;
display: inline-flex;
@@ -1757,7 +1765,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-todo-status-select.is-review .project-todo-status-dot { background: var(--warn-text); }
.project-todo-status-select.is-done .project-todo-status-dot { background: var(--success); }
@keyframes project-driver-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.25; } }
-/* Compact auto-advance control in the To-do card head. */
.project-side-card-head-actions { display: flex; align-items: center; gap: 6px; }
.project-driver-toggle.btn {
padding: 1px 8px;
@@ -1770,8 +1777,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-radius: 4px;
}
.project-driver-toggle[aria-pressed="true"] { color: var(--primary); border-color: var(--primary); background: var(--primary-soft); }
-/* A persistent pulsing dot on the enabled control so the background loop reads as
- active, not just a pressed toggle. */
.project-driver-toggle[aria-pressed="true"]::before {
content: '';
display: inline-block;
@@ -1789,7 +1794,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
line-height: 1.3;
word-break: break-word;
}
-/* Row indicator: a paperclip + count when a task carries files. */
.project-todo-attach-badge { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 2px; padding: 0; border: 0; background: none; cursor: pointer; font-size: 11px; color: var(--muted); }
.project-todo-attach-badge:hover { color: var(--primary); }
.project-todo-attach-badge-icon { width: 13px; height: 13px; }
@@ -1811,8 +1815,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-todo-conversation:hover { color: var(--primary-text); background: var(--surface-2); }
.project-todo-conversation-icon { width: 13px; height: 13px; }
.project-todo-owner { flex: 0 0 auto; font-size: 11px; }
-/* Per-todo assignee chip. Assigned → Agent icon + name (always visible); unassigned
- → a faint icon that appears on row hover, like the delete button. */
+.project-todo-sync-state {
+ font-size: 12px;
+ font-weight: 400;
+ line-height: 1.5;
+ color: var(--danger);
+}
.project-todo-assign.btn {
flex: 0 0 116px;
display: inline-flex;
@@ -1830,7 +1838,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border: 1px solid transparent;
border-radius: 4px;
}
-.project-todo-assign:hover { border-color: var(--border-strong); background: var(--surface); }
.project-todo-assign .project-todo-assign-name {
flex: 1 1 auto;
min-width: 0;
@@ -1843,15 +1850,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 116px;
padding: 1px 7px 1px 4px;
justify-content: flex-start;
- color: var(--muted);
- opacity: 0;
+ color: var(--text-2);
+ opacity: 1;
}
-.project-todo-assign.is-empty.is-shared { color: var(--text-2); opacity: 1; }
-.project-todo-item:hover .project-todo-assign.is-empty { opacity: 1; }
.project-todo-assign.is-empty:hover { color: var(--primary); border-color: transparent; background: transparent; }
.project-todo-assign.btn:disabled { cursor: default; opacity: 1; }
.project-todo-assignee { order: 1; position: relative; display: inline-flex; min-width: 0; max-width: 116px; }
.project-todo-assign-clear {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 50%;
right: 3px;
@@ -1874,8 +1880,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-todo-assign-clear:focus-visible { opacity: 1; pointer-events: auto; }
.project-todo-assign-clear:hover { color: var(--text); background: var(--surface-2); }
.project-todo-assign-clear-icon { width: 12px; height: 12px; }
-/* Row overflow ("…") button: run / edit / delete collapse into it so the title
- keeps the row's width. Always visible; opens the shared context menu. */
.project-todo-menu {
flex: 0 0 auto;
display: inline-flex;
@@ -1892,11 +1896,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.project-todo-menu:hover { color: var(--text); background: var(--surface-2); }
.project-todo-menu-icon { width: 15px; height: 15px; }
-
-/* Shared global/project backlog board, using the project workbench tokens. */
.todo-page-actions { align-self: center; gap: 10px; }
-.todo-page-actions .project-detail-tab-group .btn { border: 0; background: transparent; }
-.todo-page-actions .project-detail-tab-group .btn[aria-pressed="true"] { background: var(--surface); color: var(--primary-text); box-shadow: 0 1px 3px rgba(15, 23, 42, .12); }
+.todo-page-actions .project-detail-tab-group .btn,
+.project-todo-shared-filter .btn { border: 0; background: transparent; }
+.todo-page-actions .project-detail-tab-group .btn[aria-pressed="true"],
+.project-todo-shared-filter .btn[aria-pressed="true"] { background: var(--surface); color: var(--primary-text); box-shadow: 0 1px 3px rgba(15, 23, 42, .12); }
.todos-workarea { flex: 1; min-height: 0; padding: 18px 28px 24px; display: flex; flex-direction: column; gap: 14px; }
.todo-editor-select { display: block; min-width: 0; width: 100%; }
.todo-editor-select .ai-select-trigger {
@@ -1910,19 +1914,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
font-weight: 400;
}
.todo-editor-select .ai-select-trigger:disabled { cursor: default; color: var(--muted); background: var(--surface-2); }
+#project-todo-agent.is-readonly .ai-select-trigger:disabled { color: var(--text); background: var(--surface); opacity: 1; }
.todos-scroll { flex: 1; min-height: 0; overflow: auto; }
-/* Lanes read as four separate cards on the page ground. The hairline frame +
- column rules made one board look like blocks stitched together. */
.todo-board { display: grid; grid-template-columns: repeat(4, minmax(190px, 1fr)); gap: 16px; align-items: stretch; overflow-x: auto; border: 0; border-radius: 0; background: transparent; }
.todo-board[hidden], .todo-column-body[hidden], .todo-load-error[hidden] { display: none; }
.project-todo-list { min-width: 0; width: 100%; overflow: auto; min-height: 0; }
.project-todo-list .todo-board { min-width: 0; width: 100%; box-sizing: border-box; }
-/* The board is a flex child of the scrolling list, so a column taller than the
- panel is shrunk to it instead of overflowing, and the list's own scrollbar
- never appears: 15 to-dos left 1379px of cards clipped and unreachable. Each
- column scrolls its own body, which also keeps the status header in place. */
.todo-column { min-width: 0; display: flex; flex-direction: column; min-height: 0; padding: 12px; border: 0; border-radius: var(--radius-md); background: var(--surface-2); overflow: hidden; }
-.todo-column-head { display: flex; align-items: center; min-height: 0; padding: 0 2px; gap: 4px; }
+.todo-column-head { flex: 0 0 auto; display: flex; align-items: center; min-height: 0; padding: 0 2px; gap: 4px; }
.todo-column-head .todo-collapse { padding: 2px 0; }
.todo-collapse { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; color: var(--text-2); font: inherit; font-size: 12px; font-weight: 600; border: 0; background: transparent; padding: 10px 2px; cursor: pointer; text-align: left; }
.todo-collapse .todo-disclosure-chevron { width: 12px; height: 12px; flex-shrink: 0; color: var(--muted); }
@@ -1932,14 +1931,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.todo-column.is-review > .todo-column-head .project-todo-status-dot { background: var(--warn-text); }
.todo-column.is-done > .todo-column-head .project-todo-status-dot { background: var(--success); }
.todo-column-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding: 12px 0 0; border-top: 0; }
-/* Cards keep their own height inside the scroller; as flex children they would
- otherwise be squashed to fit the column instead of scrolling. */
.todo-column-body > * { flex: 0 0 auto; }
.todo-column-empty { width: 100%; padding: 12px 0; font-size: 11px; text-align: center; }
-.todo-board .project-todo-item { position: relative; display: flex; flex-wrap: wrap; gap: 8px; padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); box-shadow: 0 1px 2px rgba(15, 23, 42, .03); cursor: default; }
+.todo-board .project-todo-item { position: relative; display: flex; flex-wrap: wrap; gap: 8px; padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); box-shadow: 0 1px 2px rgba(15, 23, 42, .03); cursor: pointer; }
.todo-board .project-todo-item:hover { border-color: var(--border-strong); }
.todo-board .project-todo-title { order: -2; flex: 0 0 100%; min-width: 0; min-height: 42px; padding: 0 24px 0 0; background: transparent; border: 0; font: inherit; font-size: 13px; font-weight: 400; line-height: 1.6; text-align: left; color: var(--text); cursor: pointer; white-space: pre-wrap; overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
+.todo-board .project-todo-item.is-expanded .project-todo-title { display: block; -webkit-line-clamp: unset; overflow: visible; }
.todo-board .project-todo-menu[data-action="todo-menu"] {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 9px;
right: 7px;
@@ -1953,6 +1952,10 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
pointer-events: auto;
}
.todo-card-meta { order: 1; flex: 0 0 100%; min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
+.todo-card-conflict-footer { order: 2; flex: 0 0 100%; min-width: 0; display: flex; align-items: center; gap: 8px; }
+.todo-card-conflict-footer .project-todo-sync-state { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
+.todo-card-conflict-footer .project-todo-status-select { flex: 0 0 auto; }
+.todo-card-meta > .project-todo-assignee { order: 0; }
.todo-board .project-todo-assignee { flex: 0 1 auto; width: auto; max-width: 110px; margin-left: 0; }
.todo-board .project-todo-assign { flex: 0 1 auto; width: auto; max-width: 110px; margin-left: 0; opacity: 1; }
.todo-board .project-todo-attach-badge { order: 2; }
@@ -1965,16 +1968,75 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.todo-card-project:not(button) { cursor: default; color: var(--muted); }
.todo-project-group { min-width: 0; }
.todo-scope-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 12px; }
-.todo-scope-actions .form-hint { margin-right: 4px; }
-/* Account page only: the board has no height ceiling here, so a lane sizes to
- its own content with a floor that keeps an empty one reading as a column.
- The project workbench board keeps stretching, where each lane body scrolls. */
#panel-todos .todo-board { align-items: start; }
#panel-todos .todo-column-body { min-height: 224px; }
-/* One scope at a time: the switcher picks which project the board below paints,
- so the page stops stacking a board per project. */
-.todo-scope-switcher { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
+#panel-project .todo-board { display: flex; align-items: stretch; }
+#panel-project .todo-column {
+ flex: 1 1 0;
+ min-width: 190px;
+ padding: 0;
+ border-radius: 0;
+ background: transparent;
+}
+#panel-project .todo-column-body { padding: 8px 0 16px; }
+#panel-project .todo-column-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 64px;
+ padding: 0 8px;
+ box-sizing: border-box;
+ border: 1px dashed var(--border-strong);
+ border-radius: var(--radius-sm);
+ font-size: 12px;
+}
+#panel-project .todo-column.is-collapsed {
+ flex: 0 0 40px;
+ min-width: 40px;
+ border-radius: var(--radius-sm);
+ background: var(--surface-2);
+}
+#panel-project .todo-column.is-collapsed > .todo-column-head { justify-content: center; padding: 0; }
+#panel-project .todo-column.is-collapsed .todo-collapse {
+ flex: 0 0 auto;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px 0;
+}
+#panel-project .todo-column.is-collapsed .todo-collapse-label { writing-mode: vertical-rl; letter-spacing: 0.1em; }
+#panel-project .todo-column.is-collapsed .todo-disclosure-chevron { display: none; }
+.todo-board .project-todo-status-select {
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity .12s;
+}
+.todo-board .project-todo-item:hover .project-todo-status-select,
+.todo-board .project-todo-item:focus-within .project-todo-status-select {
+ opacity: 1;
+ pointer-events: auto;
+}
+.todo-scope-row { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; }
+.todo-scope-row > .todo-scope-actions { flex: 0 0 auto; margin-bottom: 0; }
+.todo-scroll-track {
+ --todo-track-fade-left: 0px;
+ --todo-track-fade-right: 0px;
+ flex: 1 1 auto;
+ min-width: 0;
+ display: flex;
+ flex-wrap: nowrap;
+ gap: 8px;
+ padding: 3px;
+ margin: -3px;
+ overflow-x: auto;
+ scrollbar-width: none;
+ -webkit-mask-image: linear-gradient(to right, transparent 0, #000 var(--todo-track-fade-left), #000 calc(100% - var(--todo-track-fade-right)), transparent 100%);
+ mask-image: linear-gradient(to right, transparent 0, #000 var(--todo-track-fade-left), #000 calc(100% - var(--todo-track-fade-right)), transparent 100%);
+}
+.todo-scroll-track::-webkit-scrollbar { display: none; }
+.todo-scroll-track.is-fade-left { --todo-track-fade-left: 32px; }
+.todo-scroll-track.is-fade-right { --todo-track-fade-right: 32px; }
.todo-scope-chip {
+ flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 8px;
@@ -1990,16 +2052,31 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-radius: 9px;
}
.todo-scope-chip:hover { color: var(--text); border-color: var(--border-strong); }
+.todo-scope-chip:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; }
.todo-scope-chip[aria-pressed="true"] { color: var(--primary-text); background: var(--primary-soft); border-color: rgba(91, 87, 214, .18); }
.todo-scope-chip-icon { flex: 0 0 auto; width: 15px; height: 15px; }
.todo-scope-chip-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.todo-scope-chip-count { flex: 0 0 auto; font-family: var(--font-mono); font-size: 11px; color: var(--muted); }
.todo-scope-chip[aria-pressed="true"] .todo-scope-chip-count { color: inherit; }
-.todo-driver-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
-.todo-driver-bar-label { color: var(--muted); font-size: 11px; }
+.todo-driver-bar { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
+.todo-driver-bar-head { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 2px; min-height: 30px; padding-inline-end: 12px; border-inline-end: 1px solid var(--border); }
+.todo-driver-bar-head .project-driver-hint { margin-inline-start: 0; }
+.todo-driver-bar > .todo-scroll-track { margin-inline-end: 0; }
+.todo-driver-bar-label { color: var(--text-2); font-size: 12px; font-weight: 500; white-space: nowrap; }
.todo-scope-driver-toggle { flex: 0 0 auto; }
-.todo-driver-bar .todo-scope-driver-toggle { display: inline-flex; align-items: center; gap: 5px; }
-.todo-driver-scope-icon { width: 13px; height: 13px; }
+.todo-driver-bar .project-driver-toggle.is-switch {
+ max-width: 260px;
+ padding: 6px 12px 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ background: var(--surface);
+ color: var(--text-2);
+}
+.todo-driver-bar .project-driver-toggle.is-switch > span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.todo-driver-bar .project-driver-toggle.is-switch:hover:not(:disabled) { color: var(--text); border-color: var(--border-strong); }
+.todo-driver-bar .project-driver-toggle.is-switch[aria-pressed="true"] { color: var(--text); background: var(--surface); }
+.todo-driver-control { display: inline-flex; align-items: center; gap: 8px; }
+.todo-driver-scope-icon { flex: 0 0 auto; width: 13px; height: 13px; }
.todo-load-error { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px; color: var(--warn-text); font-size: 12px; }
.todo-editor-dialog {
width: min(560px, calc(100vw - 40px));
@@ -2042,10 +2119,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.todo-editor-composer.drag-over { border-color: var(--primary); background: var(--primary-soft); box-shadow: 0 0 0 3px var(--primary-soft); }
.todo-editor-composer .chat-input-overlay { position: static; transform: none; align-items: flex-start; pointer-events: none; }
.todo-editor-composer .chat-input-overlay > .chat-attachments { max-width: 100%; pointer-events: auto; }
-/* The content grows with its text from six lines up to what the dialog can
- hold under the modal's 85vh cap (480px covers the header, an attachment
- row, the fields and the actions), then scrolls inside. Shorter windows
- fall back to the dialog's own scroll. */
.todo-editor-composer textarea {
field-sizing: content;
min-height: 136px;
@@ -2071,9 +2144,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.todo-page-actions { align-items: flex-end; flex-direction: column; }
.todo-editor-field-grid { grid-template-columns: 1fr; }
}
-
-
-/* Project memory card — plain body-copy rows from the project's MEMORY.md. */
.project-memory-list { display: flex; flex-direction: column; gap: 0; }
.project-memory-item {
display: flex;
@@ -2142,8 +2212,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: rgba(0,0,0,0.1);
border-radius: 3px;
}
-
-/* 所有任务 pane */
.project-tasks-head {
display: flex;
align-items: center;
@@ -2162,24 +2230,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 4px;
}
.project-tasks-empty { font-size: 12.5px; padding: 0 4px; }
-
-/* 自动化 pane */
-.project-auto-tab-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 10px;
- padding: 0 4px 8px;
-}
-.project-auto-tab-head > .auto-sync-note {
- flex: 1 1 auto;
- min-width: 0;
- padding: 0;
-}
-.project-auto-tab-head > .btn {
- flex: 0 0 auto;
- margin-left: auto;
-}
.project-auto-tab-count {
font-family: var(--font-mono);
font-size: 11px;
@@ -2233,12 +2283,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
align-items: center;
gap: 4px;
}
-.project-agent-row-sharing {
- flex-shrink: 0;
- display: inline-flex;
- align-items: center;
- color: var(--muted);
-}
.project-agent-row-name {
min-width: 0;
overflow: hidden;
@@ -2376,9 +2420,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-library-tree .project-file-row > .skill-tree-node .ctx-kb-chip + .ctx-row-menu-btn {
margin-left: 0;
}
-
-/* P4 card chrome. Padding 14–16, surface bg, hairline border, no shadow.
- Stacked vertically in the side column. */
.project-detail-card {
background: var(--surface);
border: 1px solid var(--border);
@@ -2435,8 +2476,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
text-overflow: ellipsis;
white-space: nowrap;
}
-/* P6-aligned status pill. Three flavours: custom (primary-soft), marketplace
- (neutral surface-3), stale (warn). */
.project-binding-source {
flex-shrink: 0;
font-size: 10.5px;
@@ -2466,10 +2505,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--muted);
text-wrap: pretty;
}
-
-/* Modal picker for "+ Add agent / skill". Reuses .modal-overlay shell so
- it sits above the panel + dims the rest of the UI; never gets clipped
- at the panel edge like the prior popover. */
.modal.project-binding-picker-modal {
width: 560px;
max-width: 92vw;
@@ -2537,20 +2572,21 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: var(--surface);
}
.project-binding-picker-item:hover { border-color: var(--border-strong); }
-/* Clamp picker descriptions to 3 lines so a long builtin description
- (Software Implementation Engineer etc.) doesn't blow the row height
- and force the user to scroll past one card to see the next. */
+.project-binding-picker-item > .btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ min-width: 30px;
+ height: 24px;
+ padding: 4px 8px;
+}
.project-binding-picker-item .project-binding-desc {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
-/* "Add to project" picker — pick a row, then confirm.
- A wrapping row of equally-weighted buttons gave the dialog no hierarchy:
- every project looked like Cancel, and one stray click moved the task. The
- list is the thing being chosen from, so it gets the enclosing surface, and
- the footer keeps the real primary action next to a secondary Cancel. */
.modal.conv-project-picker {
display: flex;
flex-direction: column;
@@ -2560,7 +2596,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.conv-project-picker > * { flex-shrink: 0; }
.conv-project-picker > .modal-title { flex: none; }
-/* Lists yield height before the title and footer, even on short windows. */
.conv-project-agents {
min-width: 0;
margin: 20px 0 0;
@@ -2681,8 +2716,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 2px;
margin-top: 0;
}
-/* File row chrome aligned with P9 (tree node) — 5px 6px padding, 12.5px
- text, --radius-sm hover, file icon + mono size on the right. */
.project-file-row {
display: flex;
align-items: center;
@@ -2772,6 +2805,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.project-library-viewer-modal {
+ --orkas-ui-layer: overlay;
z-index: 1000;
background: rgba(15, 23, 42, 0.82);
backdrop-filter: none;
@@ -2852,8 +2886,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
justify-content: flex-end;
}
}
-
-/* Danger-styled confirm modal ornaments. */
.ui-dialog-title {
font-size: 16px;
font-weight: 600;
@@ -2874,10 +2906,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 1px;
padding-right: 0;
}
-
-/* Time-bucket headers inside #conversation-list (today / yesterday /
- last 7 / last 30 / older). Pagination is handled by the shared load-more
- control below, so every bucket heading remains a simple static label. */
.conv-list-section-header {
padding: 10px 10px 4px 10px;
font-size: 10.5px;
@@ -2891,16 +2919,17 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-conv-list .conv-list-section-header {
font-size: 10px;
}
-.conversation-list-load-more {
+.conversation-list-load-more,
+.chat-process-load-more {
align-self: stretch;
display: inline-flex;
align-items: center;
justify-content: center;
- gap: 7px;
+ gap: 6px;
width: calc(100% - 16px);
- min-height: 32px;
- margin: 6px 8px 9px;
- padding: 6px 12px;
+ min-height: 28px;
+ margin: 2px 8px;
+ padding: 4px 12px;
border: 0;
border-radius: 8px;
background: transparent;
@@ -2915,27 +2944,29 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
cursor: pointer;
transition: background 0.12s, color 0.12s, box-shadow 0.12s;
}
-/* A nested project list already adds spacing before the next project row.
- Avoid stacking the button's generic bottom margin on top of that gap. */
.project-conv-list > .conversation-list-load-more {
margin-bottom: 0;
}
-.conversation-list-load-more:hover:not(:disabled) {
+.conversation-list-load-more:hover:not(:disabled),
+.chat-process-load-more:hover:not(:disabled) {
background: rgba(91, 87, 214, 0.07);
color: var(--primary);
}
-.conversation-list-load-more:focus-visible {
+.conversation-list-load-more:focus-visible,
+.chat-process-load-more:focus-visible {
outline: none;
background: rgba(91, 87, 214, 0.07);
color: var(--primary);
box-shadow: inset 0 0 0 2px rgba(91, 87, 214, 0.2);
}
-.conversation-list-load-more:disabled {
+.conversation-list-load-more:disabled,
+.chat-process-load-more:disabled {
background: transparent;
color: var(--muted);
cursor: wait;
}
-.conversation-list-load-more[aria-busy="true"]::before {
+.conversation-list-load-more[aria-busy="true"]::before,
+.chat-process-load-more[aria-busy="true"]::before {
width: 11px;
height: 11px;
flex: 0 0 auto;
@@ -2948,8 +2979,9 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
@keyframes conversation-load-more-spin {
to { transform: rotate(360deg); }
}
-
@media (prefers-reduced-motion: reduce) {
+ .conversation-list-load-more[aria-busy="true"]::before,
+ .chat-process-load-more[aria-busy="true"]::before { animation-duration: 1.4s; }
.search-loading-spinner { animation: none; }
}
@@ -2958,7 +2990,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex-direction: column;
align-items: stretch;
gap: 3px;
- padding: 6px 9px;
+ padding: 4px 9px;
border: 1px solid transparent;
border-radius: 6px;
cursor: pointer;
@@ -2984,10 +3016,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
font-weight: 600;
}
.conv-item.active .conv-item-title { font-weight: 600; }
-
-/* Trailing label for abnormal states only (blocked …). Resting conversation
- rows have no dot; the only sidebar dot is the live execution pulse rendered
- by `.conv-status-badge`. */
.conv-item-status-label {
flex: 0 0 auto;
font-size: 11px;
@@ -3062,11 +3090,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
outline: none;
box-shadow: 0 0 0 2px rgba(91, 87, 214, 0.10);
}
-
-/* Clock icon shown to the left of the title when a conversation was
- created by an auto-task fire. Matches the sidebar "Automation" tab
- icon — same `clock` UI icon at 13px, muted by default, primary on
- hover/active so the conv item still pops. */
.conv-item-auto-icon {
flex: 0 0 auto;
display: inline-flex;
@@ -3080,8 +3103,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 13px;
height: 13px;
}
-/* Auto-tab expand panel: every conv in the list is by definition from-auto
- (filtered by origin_auto_task_id), so the per-row clock is pure noise. */
.auto-row-convs-list .conv-item-auto-icon { display: none; }
.conv-item-badge {
@@ -3135,20 +3156,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
50% { transform: scale(0.65); opacity: 0.45; }
}
-
-
-/* When the conv item is active, use a slightly brighter backdrop so the
- badge stays legible against the active background. Running badge no
- longer has a pill background, so only the queued variant adjusts. */
-
.conv-empty {
padding: 16px 10px;
text-align: center;
color: #94a3b8;
font-size: 12px;
}
-
-/* ─── Main Content ─── */
.main-content {
flex: 1;
display: flex;
@@ -3166,9 +3179,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.panel.active { display: flex; }
-
-/* Browser tab inside task details. Remote content occupies only the native
- host rectangle; tab/address/navigation chrome stays in the trusted UI. */
.web-assist-shell {
position: relative;
flex: 1 1 auto;
@@ -3316,10 +3326,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
white-space: nowrap;
}
.web-assist-status:empty { display: none; }
-/* Tab-strip actions share the quiet chrome of Add Tab next to them. A white
- bordered pill is this strip's selected-tab language, so the generic .btn
- look made them read as two more selected tabs. Hover tints downward because
- the strip itself is already --surface-2. */
.web-assist-activity-btn,
.web-assist-expand-btn {
flex: 0 0 auto;
@@ -3342,12 +3348,10 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.web-assist-activity-btn:hover:not(:disabled),
.web-assist-expand-btn:hover:not(:disabled) { color: var(--text); background: rgba(15, 23, 42, .08); }
.web-assist-activity-btn:disabled { opacity: .38; cursor: default; }
-/* In-app full screen for the Browser tab. Two classes outrank the narrow
- viewport drawer rules below, and !important outranks the width the resize
- handle writes inline — which stays in place for the return. */
.task-side-panel.is-web-assist-expanded {
position: fixed;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 60;
width: 100% !important;
min-width: 0;
@@ -3366,11 +3370,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex: 1 1 auto;
min-height: 0;
}
-.web-assist-download-prompt {
+.web-assist-permission-prompt {
position: absolute;
top: 12px;
left: 12px;
right: 12px;
+ --orkas-ui-layer: overlay;
z-index: 60;
padding: 16px;
border: 1px solid var(--border);
@@ -3382,11 +3387,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
max-height: calc(100% - 24px);
overflow-y: auto;
}
-.web-assist-download-prompt[hidden] { display: none; }
-.web-assist-download-origin { margin-top: 10px; overflow-wrap: anywhere; }
-.web-assist-download-filename { margin-top: 4px; color: var(--muted); overflow-wrap: anywhere; }
-.web-assist-download-description { color: var(--muted); line-height: 1.6; }
-.web-assist-download-error { color: var(--danger); }
+.web-assist-permission-prompt[hidden] { display: none; }
+.web-assist-permission-prompt { right: auto; width: min(360px, calc(100% - 24px)); box-sizing: border-box; }
+.web-assist-permission-message { overflow-wrap: anywhere; line-height: 1.6; }
+.web-assist-permission-error { color: var(--danger); }
+.web-assist-tab.has-permission-request .web-assist-tab-title::before {
+ content: ''; display: inline-block; width: 6px; height: 6px; margin-right: 6px;
+ border-radius: 50%; background: var(--primary); vertical-align: middle;
+}
.web-assist-download-prompt-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
.web-assist-activity-popover {
position: absolute;
@@ -3396,6 +3404,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
max-height: calc(100% - 8px);
display: flex;
flex-direction: column;
+ --orkas-ui-layer: overlay;
z-index: 60;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
@@ -3429,7 +3438,13 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
padding: 10px 0;
border-bottom: 1px solid var(--border);
}
-.web-assist-trail-row:last-child { border-bottom: 0; }
+.web-assist-trail-group { display: flow-root; }
+.web-assist-trail-group.is-contained {
+ content-visibility: auto;
+ contain-intrinsic-block-size: auto var(--activity-group-height);
+}
+.web-assist-trail-list > .web-assist-trail-row:last-child,
+.web-assist-trail-group:last-child > .web-assist-trail-row:last-child { border-bottom: 0; }
.web-assist-activity-marker { grid-row: 1 / 3; align-self: start; color: var(--primary); }
.web-assist-activity-marker .ui-icon { width: 16px; height: 16px; }
.web-assist-trail-time { font-size: 11px; font-variant-numeric: tabular-nums; }
@@ -3455,19 +3470,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex-wrap: wrap;
gap: 4px;
}
-.web-assist-download-allow {
- grid-column: 2 / -1;
- justify-self: start;
- flex: 0 0 auto;
- padding: 1px 6px;
- border: 1px solid var(--border-strong);
- border-radius: 4px;
- background: var(--surface);
- color: var(--text);
- font-size: 11px;
- cursor: pointer;
-}
-.web-assist-download-allow:disabled { cursor: default; opacity: 0.6; }
.web-assist-shell.is-loading .web-assist-status { color: var(--primary); }
.web-assist-icon-btn {
flex: 0 0 auto;
@@ -3517,24 +3519,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
min-height: 80px;
background: #fff;
}
-
-.web-assist-page-preview {
- position: absolute;
- inset: 0;
- width: 100%;
- height: 100%;
- object-fit: fill;
- pointer-events: none;
-}
.web-assist-native-host[hidden] { display: none; }
-
-/* Agent / skill details opened from another page are transient sub-pages.
- Keep the entry page mounted underneath so its sidebar selection, scroll,
- draft and other local UI state remain untouched until Back is pressed. */
.panel.resource-detail-overlay {
display: flex;
position: absolute;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 20;
background: var(--surface);
}
@@ -3558,8 +3548,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: var(--bg);
}
-/* ─── Skill tree (still used inside contexts panel + skill source-wrap) ─── */
-
.skill-tree-node {
display: flex;
align-items: center;
@@ -3580,12 +3568,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: var(--primary-soft);
color: var(--primary-text);
}
-
-/* Tree caret intentionally hidden — the folder icon (closed/open variants)
- already signals expanded state, and the whole row is the click target,
- so the ▶ glyph was redundant. Both the folder caret and the leaf
- `.skill-tree-caret-empty` placeholder collapse together, so alignment
- at any given depth remains consistent. */
.skill-tree-caret { display: none; }
.skill-tree-icon {
@@ -3598,8 +3580,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.skill-tree-icon svg { display: block; }
-
-/* Distinct colors per icon type */
.skill-tree-icon.icon-folder { color: #f59e0b; }
.skill-tree-icon.icon-file { color: #64748b; }
.skill-tree-icon.icon-file[data-ext="md"] { color: #3b82f6; }
@@ -3661,9 +3641,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
overflow: hidden;
background: #fff;
}
-
-/* Detail content container: the header owns the chrome; document sections use the
- same centered content width as the agent detail page. */
.skills-detail-content {
flex: 1;
display: block;
@@ -3678,16 +3655,10 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.skills-detail-content::-webkit-scrollbar { width: 6px; }
.skills-detail-content::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
-
-/* ─── Single-document detail layout ─── */
-
-/* Single-row headline matching `.agents-detail-header` + `.marketplace-detail-header`:
- back-button on the left, title + source chip middle, actions hugged to the right via
- `margin-left:auto`. The row stays `nowrap` so it visually reads as one chrome strip; long
- titles ellipsize rather than wrap (title gets `min-width:0` + overflow). */
.skills-doc-headline {
position: sticky;
top: 0;
+ --orkas-ui-layer: chrome;
z-index: 5;
display: flex;
align-items: center;
@@ -3714,7 +3685,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
white-space: nowrap;
flex: 0 1 auto; /* natural width + shrink for very long titles */
}
-/* Source chip stays glued to the title; actions hug the right via `margin-left:auto`. */
.skills-doc-headline > .skills-doc-source { flex-shrink: 0; }
.skills-doc-headline > .skills-doc-actions { flex-shrink: 0; margin-left: auto; }
.skills-doc-title.editable {
@@ -3725,9 +3695,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: #eff6ff;
color: var(--primary);
}
-
-/* Source tag in the skill detail header — matches `.agents-detail-source`
- palette so the two detail pages read as one chrome family. */
.skills-doc-source {
font-size: 11px;
font-weight: 600;
@@ -3751,7 +3718,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.skills-doc-source.is-user { border-color: rgba(100, 116, 139, 0.22); background: rgba(100, 116, 139, 0.04); color: #475569; }
.agents-detail-source.is-status,
.skills-doc-source.is-status { border-color: rgba(16, 185, 129, 0.24); background: rgba(16, 185, 129, 0.04); color: #047857; }
-/* Allow multiple chips in the detail header source slot. */
.skills-doc-source-row,
.agents-detail-source-row {
display: inline-flex;
@@ -3805,8 +3771,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
pointer-events: none;
opacity: 0.65;
}
-/* Editing-state chrome on the title — mirrors `.agents-detail-name.is-editing`
- so both detail pages read as one chrome family. */
.skills-doc-title.is-editing {
outline: none;
background: #fff;
@@ -3907,8 +3871,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
margin-bottom: 4px;
}
.skills-doc-section-body ul.skills-doc-list li:last-child { margin-bottom: 0; }
-
-/* "其他属性" — table-ish fallback for unknown frontmatter keys */
.skills-doc-extra-row {
display: flex;
gap: 8px;
@@ -3928,8 +3890,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
min-width: 0;
word-break: break-word;
}
-
-/* ─── Inline skill chat column ─── */
.skills-chat-col {
width: 380px;
flex-shrink: 0;
@@ -3991,16 +3951,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
font-size: 13px;
padding: 0;
}
-
-/* Skill / agent edit chat is a 1-on-1 conversation between the user and
- * the edit LLM — the group-chat sender chip ("智能体") and avatar are
- * meaningless here and looked inconsistent across entry points (search
- * landed on an assistant bubble that showed them; the edit-button entry
- * usually had no history yet so nothing showed). Hide both so the
- * header collapses to just the timestamp regardless of how the user
- * arrived. Note: appendChatMessage emits the avatar as a bare
- * `.avatar-circle` (no `.chat-msg-avatar-slot` wrapper — that wrapper
- * is only used by the streaming placeholder), so cover both shapes. */
.skills-chat-messages .chat-msg-header > .chat-msg-avatar-slot,
.skills-chat-messages .chat-msg-header > .avatar-circle,
.skills-chat-messages .chat-msg-from,
@@ -4083,17 +4033,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 14px;
height: 14px;
}
-
-/* SKILL.md body — sits inside a "使用说明" section now; padding/scroll
- moved to the parent .skills-detail-content. */
.skills-detail-body {
font-size: 14px;
line-height: 1.7;
color: #374151;
}
-/* ─── Skills grid view (default) ────────────────────────────────────── */
-
.skills-grid-view {
flex: 1;
display: flex;
@@ -4183,8 +4128,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 16px;
}
-/* ─── Skill card ─── */
-
.skill-card {
position: relative;
display: flex;
@@ -4261,9 +4204,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
visibility: hidden;
transition: background 0.1s, color 0.1s;
}
-
-/* Per-card enable toggle — sits between the source pill and ⋯ button.
- Always visible (unlike ⋯ which is hover-only). Disabled card desaturates. */
.skill-card .toggle-switch.is-compact {
flex-shrink: 0;
margin-top: 1px;
@@ -4306,14 +4246,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 6px;
flex-wrap: wrap;
}
-
-/* In-progress overlay for external-package actions (update/enable/disable/
- remove). Covers the card while orkas-pkg.cjs runs so the action is
- perceivable. `.skill-card` is already position:relative. */
.skill-card.is-busy { pointer-events: none; }
.skill-card-busy {
position: absolute;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 2;
display: flex;
align-items: center;
@@ -4332,8 +4269,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
-/* When platform chips (version/category) sit on the actions row, the play button still
- hugs the right edge — `margin-left:auto` handles the absent-chip case too. */
.skill-card-actions > .skill-card-use { margin-left: auto; }
.skill-card--global-group {
background: rgba(248, 250, 252, 0.82);
@@ -4409,14 +4344,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: rgba(148, 163, 184, 0.14);
box-shadow: none;
}
-
-/* AI-team grid only: a screen of filled primary "use" blocks reads as noise,
- so inside `.agent-card` the button rests as a ghost and fills only while
- its own card is hovered (or the button is keyboard-focused). Other reuses
- of `.agent-card-use` (detail dialog, connector cards) render a single
- button and keep the filled default; the project rail does the same ghost
- trick as the grid for the same reason. Rules sit after the shared
- family so the equal-specificity disabled override below wins by order. */
.agent-card .agent-card-use {
background: transparent;
color: var(--primary);
@@ -4442,15 +4369,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: #94a3b8;
border-color: rgba(148, 163, 184, 0.55);
}
-
-/* Same ghost-until-card-hover pattern for the other card grids: skill
- library use, connector connect/retry/use, marketplace install/update.
- Deliberate exclusions: `.btn-danger` (disconnect) is already a quiet
- outline button; a connector's `is-loading` connect stays filled because
- in-progress feedback must not fade out; marketplace installed/installing
- render as plain `.btn is-disabled`, not `.btn-primary`. Dialog buttons
- (`.agent-dialog-btn`, `.skill-dialog-btn`, marketplace detail) sit outside
- these card containers and keep the filled default. */
.skill-card .skill-card-use,
.connector-card .agent-card-use,
.connector-card .btn-primary:not(.is-loading),
@@ -4526,10 +4444,9 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
display: block;
}
-/* ─── Per-card ⋯ popover menu ─── */
-
.skill-row-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 1000;
min-width: 96px;
background: #fff;
@@ -4549,8 +4466,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.skill-row-menu-item.is-danger { color: #dc2626; }
.skill-row-menu-item.is-danger:hover { background: #fef2f2; }
-/* ─── Skills detail view (replaces grid) ────────────────────────────── */
-
.skills-detail-view {
flex: 1;
display: flex;
@@ -4563,13 +4478,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: #fff;
flex-shrink: 0;
}
-
-/* ─── "View source" collapsible (detail page bottom) ─── */
-
-/* "使用说明" label is a flex row so its right side can host the inline
- "查看源码" toggle. The toggle styles itself like a small secondary
- action — different enough from the label to read as clickable, subtle
- enough not to compete with the section title. */
.skills-usage-label {
display: flex;
align-items: center;
@@ -4625,28 +4533,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.skills-source-tree::-webkit-scrollbar { width: 4px; }
.skills-source-tree::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
-
-/* Inline file editor (skill edit mode). No L/R padding here — the textarea
- * owns its visual border + inner padding and sits flush with the section
- * edge, the same way `.skills-source-panel` above it does. T/B padding is
- * kept tiny so the toolbar status row has a little breathing room.
- *
- * Height: the editor body grows to fill whatever vertical space the
- * frontmatter sections + source panel above haven't taken. Three pieces:
- * (a) `.skills-detail-content` switches from `display: block` to flex
- * column AND turns off its own vertical scroll, so the editor can
- * own the full leftover height instead of leaving the page
- * scrollable around a fixed-height textarea.
- * (b) `.skills-usage-section` (the body's parent, which holds the source
- * panel + the body) becomes flex column + `flex: 1`, so it claims
- * all leftover space inside the content column.
- * (c) the body itself is a flex column with `flex: 1 + min-height: 0`,
- * so the textarea inside can claim leftover space via its own
- * `flex: 1` instead of being capped by the textarea's intrinsic
- * content height.
- * `:has()` keeps every rule scoped to edit mode — the read-only detail
- * view (frontmatter sections / markdown body) is intentionally block-flow
- * and document-shaped. */
.skills-detail-content:has(.skills-detail-body.skills-detail-editing) {
display: flex;
flex-direction: column;
@@ -4703,23 +4589,15 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: #fff;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
-
-/* ─── Markdown body styles ─── */
.markdown-body {
font-size: 13px;
line-height: 1.65;
color: #374151;
}
-.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {
- font-weight: 600;
- line-height: 1.35;
- margin: 1em 0 0.4em;
- color: var(--text);
-}
.markdown-body h1 { font-size: 1.35em; }
.markdown-body h2 { font-size: 1.18em; border-bottom: 1px solid var(--border); padding-bottom: 0.25em; margin-top: 1.2em; }
.markdown-body h3 { font-size: 1.06em; }
-.markdown-body h4 { font-size: 1em; }
+.markdown-body h4, .markdown-body h5, .markdown-body h6 { font-size: 1em; }
.markdown-body p { margin: 0.55em 0; }
.markdown-body ul, .markdown-body ol { padding-left: 1.5em; margin: 0.5em 0; }
.markdown-body li { margin: 0.2em 0; }
@@ -4771,8 +4649,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.markdown-body table { border-collapse: collapse; width: 100%; margin: 0.7em 0; font-size: 12.5px; }
.markdown-body th, .markdown-body td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; }
.markdown-body th { background: var(--bg); font-weight: 600; }
-
-/* ─── Chart bar ─── */
.chart-bar-container {
margin: 12px 0;
display: flex;
@@ -4787,7 +4663,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 12px;
}
.chart-bar-label {
- font-size: 12.5px;
+ font-size: inherit;
font-weight: 500;
color: var(--text-2);
overflow-wrap: anywhere;
@@ -4806,22 +4682,18 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.chart-bar-value {
min-width: 0;
- font-size: 12.5px;
+ font-size: inherit;
font-weight: 600;
color: var(--text);
text-align: right;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
-
-/* ─── Dashboard (`:::dashboard` directive — see utils.js renderDashboard).
- Presentation only: existing component trees keep their fields and data.
- See PC/docs/design/PATTERNS.md P17 for the shared visual contract. ─── */
.dashboard {
container-type: inline-size;
min-width: 0;
margin: 12px 0;
- font-size: 13px;
+ font-size: inherit;
line-height: 1.5;
color: var(--text);
--db-accent: var(--primary);
@@ -4899,7 +4771,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-card[data-tone="warning"] { border-inline-start: 2px solid var(--db-warn); padding-inline-start: 12px; }
.dashboard .db-card-title {
font-weight: 600;
- font-size: 13px;
+ font-size: inherit;
line-height: 1.4;
margin-bottom: 12px;
color: var(--text);
@@ -4910,8 +4782,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-top: 1px solid var(--border);
margin: 8px 0;
}
-
-/* Metrics share a quiet surface; tone remains visible even without a delta. */
.dashboard .db-metric {
display: flex;
flex-direction: column;
@@ -4927,7 +4797,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-metric[data-tone="negative"] { --db-metric-tone: var(--danger-hover); }
.dashboard .db-metric[data-tone="warning"] { --db-metric-tone: var(--warn-text); }
.dashboard .db-metric-label {
- font-size: 12px;
+ font-size: inherit;
color: var(--text-2);
text-transform: none;
letter-spacing: 0;
@@ -4945,7 +4815,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-metric-delta {
align-self: flex-start;
max-width: 100%;
- font-size: 12px;
+ font-size: inherit;
font-weight: 500;
color: var(--text-2);
overflow-wrap: anywhere;
@@ -4953,8 +4823,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-metric-delta[data-tone="positive"] { color: var(--db-good-text); }
.dashboard .db-metric-delta[data-tone="negative"] { color: var(--danger-hover); }
.dashboard .db-metric-delta[data-tone="warning"] { color: var(--warn-text); }
-
-/* Alert — color-coded banner. */
.dashboard .db-alert {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
@@ -4987,14 +4855,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-alert-title {
min-width: 0;
font-weight: 600;
- font-size: 13px;
+ font-size: inherit;
line-height: 1.35;
overflow-wrap: anywhere;
word-break: normal;
}
.dashboard .db-alert-body {
min-width: 0;
- font-size: 12.5px;
+ font-size: inherit;
line-height: 1.6;
color: var(--text-2);
margin-top: 4px;
@@ -5011,8 +4879,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-alert[data-level="error"] { background: var(--db-bad-soft); }
.dashboard .db-alert[data-level="error"] .db-alert-icon { background: var(--db-bad); }
.dashboard .db-alert[data-level="error"] .db-alert-icon::before { content: "!"; }
-
-/* Table — compact, numeric columns right-aligned. */
.dashboard .db-table-wrap {
overflow-x: auto;
min-width: 0;
@@ -5020,19 +4886,18 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-radius: var(--db-radius);
background: var(--db-surface);
}
-.dashboard .db-table { width: 100%; margin: 0; border-collapse: separate; border-spacing: 0; font-size: 12.5px; line-height: 1.6; }
+.dashboard .db-table { width: 100%; margin: 0; border-collapse: separate; border-spacing: 0; font-size: inherit; line-height: 1.6; }
.dashboard .db-table th,
.dashboard .db-table td { padding: 10px 12px; border: 0; border-bottom: 1px solid var(--db-border); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
.dashboard .db-table tr:last-child td { border-bottom: none; }
.dashboard .db-table th { background: var(--db-surface-soft); font-weight: 500; color: var(--text-2); }
.dashboard .db-table th[data-numeric="1"],
.dashboard .db-table td[data-numeric="1"] { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
-
-/* Timeline — left rail + per-item dot. */
.dashboard .db-timeline { list-style: none; margin: 0 0 0 4px; padding: 0 0 0 16px; border-left: 1px solid var(--border-strong); display: flex; flex-direction: column; gap: 16px; }
.dashboard .db-timeline-item { position: relative; margin: 0; padding: 0; min-width: 0; overflow-wrap: anywhere; }
.dashboard .db-timeline-item::before {
content: "";
+ --orkas-ui-layer: chrome;
position: absolute;
left: -20px;
top: 5px;
@@ -5042,11 +4907,9 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: var(--db-accent);
box-shadow: 0 0 0 2px var(--surface);
}
-.dashboard .db-timeline-time { font-size: 11.5px; color: var(--muted); }
-.dashboard .db-timeline-label { font-size: 13px; font-weight: 600; color: var(--text); }
-.dashboard .db-timeline-body { font-size: 12.5px; line-height: 1.6; color: var(--text-2); margin-top: 4px; }
-
-/* Code / Markdown / Image */
+.dashboard .db-timeline-time { font-size: 0.9em; color: var(--muted); }
+.dashboard .db-timeline-label { font-size: inherit; font-weight: 600; color: var(--text); }
+.dashboard .db-timeline-body { font-size: inherit; line-height: 1.6; color: var(--text-2); margin-top: 4px; }
.dashboard .db-code {
background: var(--db-surface-soft);
border: 1px solid var(--db-border);
@@ -5055,20 +4918,17 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
overflow-x: auto;
max-width: 100%;
font-family: var(--font-mono);
- font-size: 12px;
+ font-size: inherit;
line-height: 1.5;
margin: 0;
}
-.dashboard .db-markdown { min-width: 0; font-size: 13px; line-height: 1.65; overflow-wrap: anywhere; }
+.dashboard .db-markdown { min-width: 0; font-size: inherit; line-height: 1.65; overflow-wrap: anywhere; }
.dashboard .db-markdown p { margin: 0.3em 0; }
.dashboard .db-markdown > :first-child { margin-top: 0; }
.dashboard .db-markdown > :last-child { margin-bottom: 0; }
.dashboard .db-image { min-width: 0; margin: 0; }
.dashboard .db-image img { max-width: 100%; border-radius: var(--db-radius); display: block; border: 1px solid var(--db-border); }
-.dashboard .db-image-caption { font-size: 11.5px; color: var(--muted); margin-top: 4px; overflow-wrap: anywhere; }
-
-/* One series uses one color. Only categorical slices cycle through the palette.
- Cap SVG growth so wide replies do not magnify labels or create giant pies. */
+.dashboard .db-image-caption { font-size: 0.9em; color: var(--muted); margin-top: 4px; overflow-wrap: anywhere; }
.dashboard .db-chart { min-width: 0; overflow-x: auto; padding: 12px; background: var(--db-surface); }
.dashboard .db-chart-svg { width: 100%; max-width: 560px; height: auto; display: block; margin: 0 auto; }
.dashboard .db-chart:not([data-kind="pie"]) .db-chart-svg { min-width: 320px; }
@@ -5079,7 +4939,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-chart-dot { fill: var(--db-accent); stroke: var(--db-surface); stroke-width: 1.5; vector-effect: non-scaling-stroke; }
.dashboard .db-chart-bar-rect { fill: var(--db-accent); opacity: 0.85; }
.dashboard .db-chart-xlabel,
-.dashboard .db-chart-ylabel { font-size: 10px; fill: var(--text-2); font-family: inherit; font-variant-numeric: tabular-nums; }
+.dashboard .db-chart-ylabel { font-size: 12px; fill: var(--text-2); font-family: inherit; font-variant-numeric: tabular-nums; }
.dashboard .db-chart[data-kind="pie"] { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 20px; }
.dashboard .db-chart[data-kind="pie"] .db-chart-svg { flex: 0 1 200px; max-width: 200px; min-width: 0; margin: 0; }
.dashboard .db-chart-slice { stroke: var(--db-surface); stroke-width: 1.5; vector-effect: non-scaling-stroke; }
@@ -5090,19 +4950,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.dashboard .db-chart-slice[data-idx="4"], .dashboard .db-chart-legend li[data-idx="4"] { --db-category: var(--chart-category-5); }
.dashboard .db-chart-slice[data-idx="5"], .dashboard .db-chart-legend li[data-idx="5"] { --db-category: var(--chart-category-6); }
.dashboard .db-chart-slice { fill: var(--db-category); }
-.dashboard .db-chart-legend { list-style: none; padding: 0; margin: 0; flex: 1 1 120px; min-width: 0; display: flex; flex-direction: column; gap: 8px; font-size: 12px; }
+.dashboard .db-chart-legend { list-style: none; padding: 0; margin: 0; flex: 1 1 120px; min-width: 0; display: flex; flex-direction: column; gap: 8px; font-size: inherit; }
.dashboard .db-chart-legend li { display: flex; align-items: baseline; gap: 8px; margin: 0; color: var(--text-2); overflow-wrap: anywhere; }
.dashboard .db-chart-legend .db-chart-swatch { flex: 0 0 8px; width: 8px; height: 8px; border-radius: 2px; background: var(--db-category); }
.dashboard .db-chart-legend .db-chart-val { margin-left: auto; color: var(--text); font-variant-numeric: tabular-nums; }
.dashboard .db-chart-empty,
.dashboard .db-table-empty,
-.dashboard .db-timeline-empty { font-size: 12px; color: var(--muted); padding: 8px 10px; border: 1px dashed var(--db-border); border-radius: var(--db-radius); }
-
-/* Fallback when a `:::dashboard` block fails to parse — show the raw body
- so the user can copy it and diagnose, rather than silently dropping. */
+.dashboard .db-timeline-empty { font-size: inherit; color: var(--muted); padding: 8px 10px; border: 1px dashed var(--db-border); border-radius: var(--db-radius); }
.dashboard-parse-error { border-color: rgba(220, 38, 38, 0.4); }
-
-/* ─── Code view (for .py, .json etc.) ─── */
.code-view {
background: #f8fafc;
border: 1px solid var(--border);
@@ -5122,39 +4977,42 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: inherit;
font-size: inherit;
}
-
-/* ─── New chat landing (Surface B per PC/docs/design/PATTERNS.md) ─── */
.new-chat-center {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
- /* Center the landing stack when it fits. `safe` falls back to start when
- the viewport is shorter than the content, preserving full-page scroll. */
- justify-content: safe center;
- padding: 32px 32px 36px;
+ justify-content: flex-start;
+ padding: 32px 32px 0;
gap: 18px;
background: var(--bg);
min-height: 0;
overflow-y: auto;
- /* Keep the Commander landing surface centered while giving task cards
- enough room to stay useful in the default three-column layout. */
width: 100%;
}
.new-chat-center > .new-chat-header,
-.new-chat-center > .new-chat-input-wrapper,
-.new-chat-center > .new-chat-scenarios {
+.new-chat-center > .new-chat-input-wrapper {
width: 100%;
max-width: 900px;
- /* Children in this scrolling flex column must retain their intrinsic
- height. Otherwise the last module is compressed and its cards are
- clipped instead of making the parent scroll. */
flex: 0 0 auto;
}
+.new-chat-center > .home-below {
+ width: 100%;
+ max-width: 908px;
+ flex: 1 1 auto;
+ min-height: 160px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+ padding: 6px 4px 32px;
+ box-sizing: border-box;
+}
+.home-below > * { flex: 0 0 auto; }
.new-chat-header {
margin-bottom: 2px;
- padding-top: 36px;
+ padding-top: 24px;
text-align: center;
}
@@ -5167,19 +5025,219 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--text);
}
-.new-chat-subtitle {
- margin: 14px 0 0;
- font-size: 16px;
+.new-chat-input-wrapper { /* width set by parent rule above. */ }
+#panel-new-chat[data-home-state="pending"] .new-chat-header,
+#panel-new-chat[data-home-state="pending"] .home-paths,
+#panel-new-chat[data-home-state="pending"] #new-chat-scenarios {
+ visibility: hidden;
+}
+#panel-new-chat[data-home-state="populated"] .home-paths,
+#panel-new-chat[data-home-state="populated"] #new-chat-scenarios,
+#panel-new-chat:not([data-home-state="populated"]) .home-work {
+ display: none;
+}
+.home-paths {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ text-align: start;
+}
+.home-path {
+ min-width: 0;
+ padding-inline-end: 24px;
+}
+.home-path + .home-path {
+ padding-inline: 24px 0;
+ border-inline-start: 1px solid var(--border-strong);
+}
+.home-path-title {
+ margin: 0 0 6px;
+ color: var(--text);
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 1.5;
+}
+.home-path-body {
+ margin: 0;
+ color: var(--text-2);
+ font-size: 13px;
+ line-height: 1.7;
+}
+.home-path-note {
+ margin: 8px 0 0;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.7;
+}
+.home-connect-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--primary-text);
+ font: inherit;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ cursor: pointer;
+}
+.home-connect-link:hover { color: var(--primary-hover); }
+.home-connect-link:focus-visible {
+ border-radius: 2px;
+ outline: 2px solid var(--primary);
+ outline-offset: 2px;
+}
+.home-continue-label {
+ min-height: 28px;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 12px;
color: var(--text-2);
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.4;
+}
+.home-continue-rule {
+ height: 1px;
+ min-width: 0;
+ flex: 1;
+ background: var(--border);
+}
+.home-group + .home-group { margin-top: 20px; }
+.home-group-head {
+ min-height: 26px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 6px;
+}
+.home-group-title {
+ margin: 0;
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 600;
line-height: 1.5;
- text-wrap: pretty;
}
-
-.new-chat-input-wrapper { /* width set by parent rule above. */ }
-/* Capability areas as compact tiles between the introduction and the
- long-term-goal note; an odd last tile spans the row. */
-
-/* Quick start — concrete tasks with a preview of the expected deliverable. */
+.home-group-count {
+ margin-inline-start: 8px;
+ padding: 0 5px;
+ border-radius: 99px;
+ background: var(--surface-2);
+ color: var(--muted);
+ font-family: var(--font-mono);
+ font-size: 10.5px;
+ font-weight: 600;
+ line-height: 16px;
+ vertical-align: 1px;
+}
+.home-list {
+ overflow: hidden;
+ background: var(--surface);
+ border: 1px solid var(--border-strong);
+ border-radius: var(--radius-sm);
+}
+.home-row {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 11px 16px;
+ border: 0;
+ border-top: 1px solid var(--border);
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ text-align: start;
+ cursor: pointer;
+}
+.home-list > .home-row:first-child { border-top: 0; }
+.home-row:hover { background: var(--surface-2); }
+.home-row-status {
+ flex: 0 0 20px;
+ height: 20px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--muted);
+}
+.home-row-status-icon { width: 16px; height: 16px; }
+.home-row-status.is-progress { color: var(--primary); }
+.home-row-status.is-review,
+.home-row-status.is-waiting_input { color: var(--warn-text); }
+.home-row-status.is-completed { color: var(--success); }
+.home-row-status.is-failed { color: var(--danger); }
+.home-row:focus-visible {
+ outline: 2px solid var(--primary);
+ outline-offset: -2px;
+}
+.home-row-main {
+ min-width: 0;
+ flex: 1 1 auto;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+.home-row-title,
+.home-row-meta {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.home-row-title {
+ color: var(--text);
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.45;
+}
+.home-row-meta {
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.5;
+}
+.home-row-source {
+ margin-inline-end: 10px;
+ color: var(--text-2);
+}
+.home-row-action {
+ flex: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ color: var(--text-2);
+ font-size: 12px;
+ font-weight: 500;
+ white-space: nowrap;
+}
+.home-row:hover .home-row-action,
+.home-row:focus-visible .home-row-action { color: var(--primary-text); }
+.home-row-action-icon { width: 13px; height: 13px; }
+html[dir="rtl"] .home-row-action-icon { transform: scaleX(-1); }
+.home-text-btn {
+ min-height: 26px;
+ padding: 0 4px;
+ border: 0;
+ border-radius: 7px;
+ background: transparent;
+ color: var(--text-2);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 500;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.home-text-btn:hover { color: var(--primary-text); }
+.home-text-btn:focus-visible {
+ outline: 2px solid var(--primary);
+ outline-offset: 1px;
+}
+.home-group-more { margin-top: 4px; }
+@media (max-height: 760px) {
+ .new-chat-center { padding-top: 24px; gap: 14px; }
+ .new-chat-center > .home-below { gap: 16px; }
+ .home-path-note { margin-top: 4px; }
+ .home-continue-label { margin-bottom: 8px; }
+ .home-group + .home-group { margin-top: 12px; }
+ .home-row { padding-top: 8px; padding-bottom: 8px; }
+}
.new-chat-scenarios {
padding: 4px 0 0;
}
@@ -5254,9 +5312,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-color: rgba(91, 87, 214, 0.45);
box-shadow: 0 10px 26px -18px rgba(91, 87, 214, .5);
}
-
-/* Keep the established neutral icon treatment at rest. Hover turns the tile
- and card toward primary together while the dimensions stay fixed. */
.quick-tile {
width: 40px;
height: 40px;
@@ -5322,9 +5377,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--text-2);
font-weight: 600;
}
-
-/* Home-only quick-start refresh (2026-09-20): flatter tiles, calmer metadata
- and roomier cards, scoped to the landing panel. */
#panel-new-chat .new-chat-scenarios { padding-top: 8px; }
#panel-new-chat .quick-panel-more {
min-height: 28px;
@@ -5434,9 +5486,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--text);
font-family: inherit;
}
-
-/* Quick-start placeholders are selected on card click. Keep the normal input
- * weight and use a light brand tint to distinguish only the editable slot. */
#new-chat-input::selection {
background: rgba(91, 87, 214, 0.18);
color: var(--primary-text);
@@ -5458,8 +5507,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.new-chat-input-area .chat-input-overlay > .chat-attachments {
max-width: 100%;
}
-
-/* ─── Chat (matches agent-cowork board) ─── */
.chat-container {
display: flex;
flex-direction: row;
@@ -5480,8 +5527,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
container-type: inline-size;
--chat-input-reserve: 140px;
}
-
-/* ── Conversation header — Surface C top (PC/docs/design/PATTERNS.md). ── */
.chat-header {
flex: 0 0 auto;
display: flex;
@@ -5553,8 +5598,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
flex: 0 0 auto;
white-space: nowrap;
}
-/* Project name → project page. Same affordance as `.chat-msg-from.is-agent-link`;
- negative margins keep the hover pill from shifting the meta line. */
.chat-header-meta-project-link {
cursor: pointer;
padding: 1px 3px;
@@ -5574,8 +5617,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
display: inline-flex;
flex: 0 0 auto;
}
-/* The badge itself is an `.avatar-circle`; only the stacking ring + nudge
- live here so a row of actor avatars reads as one cluster. */
.chat-header-meta-member { box-shadow: 0 0 0 2px var(--surface); }
.chat-header-meta-member + .chat-header-meta-member { margin-left: -5px; }
.chat-header-actions {
@@ -5586,7 +5627,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 6px;
}
.chat-header-actions[hidden] { display: none !important; }
-.chat-header-menu-btn {
+.chat-header-menu-btn,
+.project-header-icon-btn {
flex: 0 0 auto;
width: 34px;
min-height: 34px;
@@ -5601,10 +5643,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
cursor: pointer;
transition: all 0.15s;
}
-.chat-header-menu-btn:hover {
+.chat-header-menu-btn:hover,
+.project-header-icon-btn:hover:not(:disabled) {
background: #f1f5f9;
}
-.chat-header-menu-icon {
+.chat-header-menu-icon,
+.project-header-icon {
width: 18px;
height: 18px;
}
@@ -5676,12 +5720,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
width: 13px;
height: 13px;
}
-
-/* ── Conversation info drawer (Surface C right) — PC/docs/design/PATTERNS.md
- §P12 (Drawer) + §P7 (Tab strip) + §P8 (Segmented bar). Header carries
- icon + title + refresh + close; tabs carry icon + label + count chip;
- body renderers (tasks / files / attachments) are rewritten in
- modules/conversation-info.js for this design pass. ── */
.task-side-panel {
position: relative;
flex: 0 0 max(400px, 30vw);
@@ -5695,12 +5733,14 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
background: var(--surface);
color: var(--text);
box-shadow: -12px 0 32px rgba(15, 18, 24, 0.04);
+ --orkas-ui-layer: chrome;
z-index: 20;
}
.task-side-panel[hidden] { display: none !important; }
.task-side-panel-resize {
position: absolute;
inset: 0 auto 0 -5px;
+ --orkas-ui-layer: chrome;
z-index: 4;
width: 9px;
cursor: col-resize;
@@ -5836,8 +5876,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12px;
}
.conversation-info-empty.is-error { color: var(--danger); }
-
-/* ── Attachments tab (flat list w/ kind thumbs) ── */
.ci-attach {
display: flex;
flex-direction: column;
@@ -5904,7 +5942,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 10.5px;
color: var(--muted);
}
-/* Tree rules for the Files tab (folder hierarchy with ⋯ menu). */
.ci-files {
display: flex;
flex-direction: column;
@@ -5937,9 +5974,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
gap: 3px;
}
-/* Outputs the workspace tree cannot hold: files written outside this
- conversation's folder, and `create_artifact` bundles. Each gets a labelled
- group so it reads as "also produced here", never as a workspace file. */
.conversation-info-group {
display: flex;
flex-direction: column;
@@ -6072,6 +6106,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
@media (max-width: 920px) {
.task-side-panel {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 0;
right: 0;
@@ -6082,10 +6117,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.task-side-panel-resize { display: none; }
}
-
-/* Inline "创建智能体" entry pinned to the end of #chat-history — divider
- lines on both sides with a small button in the middle. Hidden during
- streaming via inline display:none toggled in conversation.js. */
.conv-create-agent-inline {
display: flex;
align-items: center;
@@ -6146,14 +6177,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: transparent;
scroll-behavior: smooth;
}
-
-/* Turn navigator. Its compact index is paged independently from transcript
- bodies, so every user turn remains addressable without expanding the
- message-history read boundary. */
.chat-turn-nav {
position: absolute;
left: 12px;
top: calc(50% + 18px);
+ --orkas-ui-layer: chrome;
z-index: 12;
transform: translateY(-50%);
pointer-events: none;
@@ -6187,6 +6215,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-turn-nav-marker::before {
content: '';
+ --orkas-ui-layer: chrome;
position: absolute;
top: 50%;
left: 6.5px;
@@ -6224,15 +6253,14 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
outline-offset: -2px;
}
.chat-turn-nav-preview {
- /* Runtime token: conversation-turn-nav.js repositions the preview per
- marker; this default only covers the frame before the first hover. */
--turn-nav-preview-y: 50%;
+ --orkas-ui-layer: overlay;
position: absolute;
top: var(--turn-nav-preview-y, 50%);
left: 30px;
- width: clamp(200px, 26cqw, 260px);
+ width: clamp(260px, 38cqw, 420px);
max-width: calc(100cqw - 78px);
- max-height: 118px;
+ max-height: 160px;
overflow: hidden;
padding: 10px 12px;
border: 1px solid color-mix(in srgb, var(--primary) 14%, var(--border));
@@ -6249,7 +6277,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: -webkit-box;
overflow: hidden;
-webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
+ -webkit-line-clamp: 2;
font-size: 13px;
font-weight: 650;
line-height: 1.45;
@@ -6259,7 +6287,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow: hidden;
margin-top: 5px;
-webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
+ -webkit-line-clamp: 5;
color: var(--text-2);
font-size: 12px;
line-height: 1.45;
@@ -6317,14 +6345,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.office-preview-loading-spinner,
.chat-file-viewer-loading-spinner { animation: none; }
}
-
-/* While a new exchange is in flight, a DOM spacer (`.chat-scroll-spacer`)
- is appended as the last child of the messages container to reserve room
- so a short user message can scroll to the top of the viewport. Using a
- real element (not `padding-bottom: 100vh`) is what makes this play nice
- with flex-column parents like the skill/agent edit chat panels, where
- oversized intrinsic content on a flex child collapses the sibling input
- area. Height is set inline by JS (`_setChatScrollOffset`). */
.chat-scroll-spacer {
flex-shrink: 0;
pointer-events: none;
@@ -6347,11 +6367,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
bottom: 0;
left: 0;
right: 0;
- /* Top 20px fades in, bottom 32px is the old gap. The gradient masks any
- messages that scroll behind the floating input so the bubble "floats"
- cleanly without leaking conversation text into its backdrop. */
padding: 20px 32px 32px;
background: linear-gradient(to bottom, transparent 0%, var(--bg) 20%);
+ --orkas-ui-layer: chrome;
z-index: 10;
pointer-events: none;
}
@@ -6422,6 +6440,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-rich-editor.is-empty::before {
+ --orkas-ui-layer: chrome;
position: absolute;
content: attr(placeholder);
color: #94a3b8;
@@ -6521,12 +6540,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-send-btn .queue-save-icon { display: none; width: 18px; height: 18px; }
.chat-send-btn.queue-editing .send-icon { display: none; }
.chat-send-btn.queue-editing .queue-save-icon { display: block; }
-
-/* Queue panel above the input area.
- Aligned with .chat-input-area's centered 80% layout. The workspace chip
- no longer floats above the input bubble (it moved into .chat-bottom-bar
- inside the input area), so the queue's right edge can use the full 80%
- width without a reserved gutter. */
.chat-queue {
pointer-events: auto;
width: 80%;
@@ -6539,24 +6552,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 10px 12px;
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
}
-
-/* Narrower panels (skill / agent edit) don't have the 80%-centered shape
- of the main chat input; let the queue span the full panel width so it
- aligns with the message list / input above. They also have no
- workspace chip floating above the input area, so no right-side
- reservation is needed. */
.skills-chat-col .chat-queue,
.agents-chat-col .chat-queue {
width: auto;
max-width: none;
margin: 0 12px 8px;
}
-
-/* ─── Chat attachment chips (待发送附件 pool) ─────────────────────── */
-/* Lives inside .chat-input-overlay (floating strip above the input bubble).
- The overlay handles positioning + width allocation; this rule only owns
- the chip flow (wrap, gap). Multiple attachments overflow onto extra rows
- stacking UPWARD because the overlay is anchored to its bottom edge. */
.chat-attachments {
pointer-events: auto;
display: flex;
@@ -6616,7 +6617,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
white-space: nowrap;
}
-/* Body file references are one button aligned with the surrounding prose. */
.chat-attach-chip.is-inline {
vertical-align: baseline;
margin-inline: 4px;
@@ -6651,9 +6651,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1;
}
.chat-attach-chip .chat-attach-remove:hover { color: #ef4444; }
-
-/* Uploading state: dim the chip and show a small inline spinner so the user
- can see progress without blocking the rest of the UI. */
.chat-attach-chip.is-uploading {
opacity: 0.65;
}
@@ -6672,10 +6669,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
@keyframes chat-attach-spin {
to { transform: rotate(360deg); }
}
-
-/* Quote-reply preview sits above the textarea and can contain multiple
- independently removable messages. Cap its height so a large selection
- does not crowd the composer out of view. */
.chat-quote-preview {
display: flex;
flex-direction: column;
@@ -6761,9 +6754,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow: hidden;
text-overflow: ellipsis;
}
-
-/* "+" / mic / icon-only buttons inside the composer bottom bar. Box matches
- PC/docs/design/PATTERNS.md P11 (30×30, radius 7). */
.chat-attach-btn {
flex-shrink: 0;
width: 30px;
@@ -6784,7 +6774,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: var(--surface-2);
color: var(--text);
}
-/* 1px vertical divider between the attach button and the chip row. */
.chat-composer-divider {
flex: 0 0 auto;
width: 1px;
@@ -6792,15 +6781,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: 0 2px;
background: var(--border);
}
-
-/* Keep the right-side actions separated from the configuration chips. */
-
-
-
-/* Bottom row inside the input area, ordered per PC/docs/design/PATTERNS.md P11:
- [+] | divider | [model] [To] [workspace] [skill] [...] | [mic]
- [queue-delete while editing] [send/save].
- Wraps row-by-row on narrow windows so chips never overflow the input box. */
.chat-bottom-bar {
display: flex;
align-items: center;
@@ -6814,10 +6794,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-bottom-bar .chat-send-btn {
margin-left: auto;
}
-
-/* Shared model priority picker. It lives inside every model-backed composer,
- so the current first-choice model is visible where the task is submitted
- without adding another module to the surrounding page. */
.composer-model-chip {
min-width: 0;
max-width: 230px;
@@ -6893,6 +6869,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.composer-model-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 10002;
width: min(360px, calc(100vw - 16px));
padding: 6px;
@@ -7082,6 +7059,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.composer-model-menu-version-list {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 10003;
width: min(220px, calc(100vw - 16px));
padding: 6px;
@@ -7155,8 +7133,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12px;
text-align: center;
}
-
-/* Attachments inside message bubbles (history + optimistic append) */
.chat-msg-attachments {
display: flex;
flex-wrap: wrap;
@@ -7170,11 +7146,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex: 0 0 auto;
line-height: 1;
}
-
-/* Markdown-embedded media in chat bubbles — generated by utils.js
- inlineFormat from `![alt](src)`. Applies to any src (http, chat-media://,
- data:). Kept narrower than the bubble so long captions still wrap
- cleanly around it. */
.chat-image-shell {
position: relative;
display: block;
@@ -7184,6 +7155,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-image-shell.is-loading::after {
content: '';
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
background: linear-gradient(100deg, transparent 25%, rgba(255, 255, 255, 0.72) 45%, transparent 65%);
@@ -7290,6 +7262,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-md-video-load-failure {
position: absolute;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 2;
display: flex;
flex-direction: column;
@@ -7325,6 +7298,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(30, 41, 59, 0.96);
}
.chat-md-video-float {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 8px;
right: 8px;
@@ -7426,6 +7400,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #fff;
}
.chat-md-html-embed-loading {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
display: flex;
@@ -7439,6 +7414,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-md-html-frame {
position: absolute;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 1;
display: block;
width: 100%;
@@ -7477,12 +7453,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
opacity: 0 !important;
width: 0 !important;
}
-
-/* Fullscreen lightbox for images clicked in chat bubbles. Mounted once
- into <body> by chat-lightbox.js the first time it's opened. */
.chat-lightbox {
position: fixed;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 1000;
display: none;
align-items: center;
@@ -7490,6 +7464,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-lightbox.is-open { display: flex; }
.chat-lightbox-backdrop {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
background: rgba(15, 23, 42, 0.82);
@@ -7512,6 +7487,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-lightbox-loading {
position: absolute;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 1;
display: flex;
flex-direction: column;
@@ -7554,6 +7530,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
position: absolute;
top: 50%;
transform: translateY(-50%);
+ --orkas-ui-layer: chrome;
z-index: 2;
display: inline-flex;
align-items: center;
@@ -7575,6 +7552,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-lightbox-nav:disabled { opacity: 0.35; cursor: default; }
.chat-lightbox-nav:focus-visible { outline: 2px solid #60a5fa; outline-offset: 3px; }
.chat-lightbox-actions {
+ --orkas-ui-layer: chrome;
position: absolute;
top: -12px;
right: -12px;
@@ -7617,13 +7595,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-lightbox-share svg,
.chat-lightbox-add-library svg,
.chat-lightbox-reveal svg { display: block; }
-/* In-app file preview overlay (chat-file-viewer.js). Mounted once into
- <body> on first openChatFileViewer(). Same backdrop chrome as the image
- lightbox; differs in that the stage is a fixed sheet (header + body)
- instead of a free-floating image. */
.chat-file-viewer {
position: fixed;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 1000;
display: none;
align-items: center;
@@ -7631,6 +7606,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-file-viewer.is-open { display: flex; }
.chat-file-viewer-backdrop {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
background: rgba(15, 23, 42, 0.82);
@@ -7771,6 +7747,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
position: absolute;
top: calc(100% + 7px);
right: 0;
+ --orkas-ui-layer: chrome;
z-index: 20;
max-width: 180px;
padding: 5px 8px;
@@ -7812,8 +7789,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
overflow: hidden;
}
-/* iframe-based body (pdf / html / office) fills the body slot. The body itself
- handles scroll for non-iframe bodies (md / text). */
.chat-file-viewer-pdf,
.chat-file-viewer-html,
.chat-file-viewer-office {
@@ -7844,6 +7819,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #020617;
}
.chat-file-viewer-html-canvas-frame {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 0;
left: 50%;
@@ -7984,9 +7960,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-height: 100%;
box-sizing: border-box;
}
-/* Mirrors .is-markdown's flex layout: body becomes a flex column so the
- <pre> view or <textarea> editor (both direct children of the body) can
- fill the available height and own their own scroll. */
.chat-file-viewer.is-text .chat-file-viewer-body {
display: flex;
flex-direction: column;
@@ -8021,6 +7994,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
box-sizing: border-box;
position: absolute;
inset: 0;
+ --orkas-ui-layer: chrome;
z-index: 2;
width: 100%;
height: 100%;
@@ -8035,9 +8009,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-file-viewer-loading-resource {
visibility: hidden;
}
-
-/* Office layout generation can take a few seconds for image-heavy documents.
- Keep every preview surface visibly occupied instead of showing a blank body. */
.office-preview-loading {
box-sizing: border-box;
width: 100%;
@@ -8079,12 +8050,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
transition: none;
}
}
-
-/* In-app "My Apps" viewer. Uses chat-app://saved/... so multi-file app
- bundles keep relative CSS/JS/assets working without leaving Orkas. */
.saved-app-viewer {
position: fixed;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 1000;
display: none;
align-items: center;
@@ -8092,6 +8061,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.saved-app-viewer.is-open { display: flex; }
.saved-app-viewer-backdrop {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
background: rgba(15, 23, 42, 0.82);
@@ -8134,11 +8104,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border: 0;
background: #fff;
}
-
-/* Host-rendered previews for produced image / video / audio, sitting between
- the reply text and the deliverable rows. The players themselves are the
- markdown media shapes (.chat-md-img-shell / .chat-md-video-shell /
- .chat-md-audio-card), so this container only owns stacking and spacing. */
.chat-msg-produced-media {
display: flex;
flex-direction: column;
@@ -8147,12 +8112,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-width: 0;
margin-top: 10px;
}
-
-/* User-facing deliverables live at the bottom of the assistant bubble. Each
- file is a full-width horizontal footer row instead of a detached green chip;
- click behavior still opens the existing in-app preview. */
-/* Host-counted execution facts under a long turn's reply. Quiet on purpose:
- it is context for the summary above it, not a finding of its own. */
.chat-msg-run-facts {
width: 100%;
min-width: 0;
@@ -8280,7 +8239,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
white-space: nowrap;
}
-/* Created Agent/Skill footer; buttons share the app-navigation styles below. */
.chat-msg-created-agent {
display: flex;
flex-wrap: wrap;
@@ -8291,11 +8249,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-width: 0;
overflow-wrap: anywhere;
}
-
-/* Stream-time placeholder for hidden LLM blocks (quick-create `<agent>`
- container / agent-input-form fenced block). Shown while the model is
- still typing the structured payload; repainted away by
- `_streamingSetFinal` once the backend-cleaned text arrives. */
.stream-placeholder {
display: inline-block;
padding: 2px 8px;
@@ -8304,12 +8257,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(14, 165, 233, 0.06);
border-radius: 8px;
}
-
-
-/* Input-form widget (assistant-emitted parameter confirmation form).
- Lives inside the assistant .chat-bubble — see chat-input-form.js for
- the DOM it builds. Intentionally understated so it reads as a panel
- inside the reply, not a separate modal. */
.chat-input-form {
margin-top: 10px;
padding: 10px 12px;
@@ -8349,10 +8296,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-input-form .form-field-textarea { min-height: 56px; resize: vertical; }
.chat-input-form .form-field-select { cursor: pointer; }
-/* form fields use the shared AiSelect for dropdowns; default is
- * inline-block + min-width:180px which leaves it narrower than the
- * sibling textarea/text-input. Make it block-level so it fills the
- * form-field-ctrl column. */
.chat-input-form .form-field-ctrl > .ai-select {
display: block;
min-width: 0;
@@ -8396,10 +8339,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
gap: 6px;
}
-/* Card-style directory picker — single clickable surface that
- replaces the old "[Choose…] [Clear] /path" three-button row.
- See chat-input-form.js `field.type === 'directory'` for the DOM
- it builds: card → icon + path/hint + change pill. */
.chat-input-form .form-field-dir-card {
display: flex;
align-items: center;
@@ -8519,17 +8458,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
align-self: flex-start;
cursor: pointer;
}
-/* Submitted state — the same form widget, just non-editable. We tint the
- panel grey, dim disabled controls, and drop the action buttons in
- favour of a "已提交" stamp. The structure (title + per-field rows + ctl
- widgets) is identical to the editable form so the bubble layout stays
- stable across submit / refresh. */
.chat-input-form.is-submitted {
background: rgba(148, 163, 184, 0.12);
border-color: rgba(148, 163, 184, 0.35);
}
-/* Superseded (unsubmitted but no longer decidable) — same muted family as
- is-submitted, dimmed further so the live card below reads as the one to use. */
.chat-input-form.is-stale {
background: rgba(148, 163, 184, 0.12);
border-color: rgba(148, 163, 184, 0.35);
@@ -8562,9 +8494,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 11px;
color: var(--muted);
}
-
-/* Commander navigation card (open_app_view): a distinct action footer at the
- bottom of the bubble; navigation still happens only on the user's click. */
.chat-app-nav-row {
display: flex;
flex-wrap: wrap;
@@ -8637,9 +8566,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
@media (prefers-reduced-motion: reduce) {
.stream-thinking-dot { animation: none; }
}
-
-/* Marketplace install request card. Same inline-panel scale as input forms:
- the user explicitly approves before any marketplace resource is installed. */
.chat-marketplace-request {
margin-top: 10px;
width: min(360px, 100%);
@@ -8702,16 +8628,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-marketplace-request.is-busy {
opacity: 0.82;
}
-
-/* Interactive web-app artifact card — sandboxed `<iframe>` over the
- `chat-app://` protocol, embedded inside the assistant `.chat-bubble`.
- See modules/chat-artifact.js. Understated chrome (a title bar + reload)
- so it reads as an inline panel, not a separate window. */
.chat-artifact-host { margin-top: 10px; }
.chat-artifact-card {
width: 40cqw;
max-width: 100%;
- min-width: 280px;
+ min-width: min(280px, 100%);
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
@@ -8726,7 +8647,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-bottom: 1px solid var(--border);
font-size: 12px;
}
+.chat-app-type-tag { background:var(--surface-2); color:var(--muted); }
+.chat-app-type-tag[hidden] { display:none; }
+.chat-app-type-tag[data-app-type="cloud"] { background:var(--primary-soft); color:var(--primary-text); }
.chat-artifact-title {
+ min-width: 0;
font-weight: 600;
color: var(--text);
white-space: nowrap;
@@ -8769,8 +8694,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 13px;
line-height: 1.4;
}
-/* Card-header `⋯` popover (reload / open / save) + the My Apps
- panel's per-card `⋯` popover — both mirror `.agent-row-menu`'s look. */
.chat-artifact-menu-item,
.app-row-menu-item {
padding: 6px 14px;
@@ -8781,13 +8704,17 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-artifact-menu-item:hover,
.app-row-menu-item:hover { background: #f1f5f9; }
+.app-row-menu-item { display:block; width:100%; border:0; background:transparent; font-family:inherit; text-align:start; }
+.app-row-menu-item:focus-visible { outline:2px solid var(--primary); outline-offset:-2px; background:var(--surface-2); }
.app-row-menu-item.is-danger { color: #dc2626; }
.app-row-menu-item.is-danger:hover { background: #fef2f2; }
-
-/* In-app artifact viewer opened from a chat artifact card's `⋯` menu. */
+.app-row-menu-item:disabled,
+.app-row-menu-item.is-danger:disabled { color: #94a3b8; cursor: not-allowed; }
+.app-row-menu-item:disabled:hover { background: transparent; }
.chat-artifact-viewer {
position: fixed;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 1000;
display: none;
align-items: center;
@@ -8795,6 +8722,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.chat-artifact-viewer.is-open { display: flex; }
.chat-artifact-viewer-backdrop {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
background: rgba(15, 23, 42, 0.82);
@@ -8838,13 +8766,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border: 0;
background: #fff;
}
-
-/* ─── "My Apps" panel — user-kept create_artifact bundles (saved-apps.js) ───
- Page-header (P1) follows the .connectors-page-header / .contexts-page-header
- per-surface convention. Cards reuse the `.agents-grid-view` /
- `.agents-grid-scroll` / `.agents-empty` layout shells (those have no
- JS hook); only the grid + card need their own classes — `agents.js` binds a
- global `.agent-card` click handler so the names can't be shared. */
.apps-page-header {
display: flex;
align-items: center;
@@ -8855,7 +8776,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-bottom: 1px solid var(--border);
background: var(--surface);
}
-.apps-page-header-main { min-width: 0; }
+.apps-page-header-main { display:flex; align-items:center; flex-wrap:wrap; gap:12px 24px; flex:1; min-width:0; }
+.apps-header-types { display:flex; align-items:center; gap:16px; flex:1 1 240px; min-width:0; }
+.apps-type-tabs { flex:0 0 auto; gap:2px; min-height:32px; height:32px; padding:2px; border-radius:8px; max-width:100%; box-sizing:border-box; }
+.apps-type-tabs .btn { height:28px; padding:4px 10px; line-height:18px; white-space:nowrap; border:1px solid transparent; border-radius:6px; background:transparent; color:var(--text-2); font-weight:500; }
+.apps-type-tabs .btn:hover { background:var(--surface); }
+.apps-type-tabs .btn[aria-selected="true"] { background:var(--surface); border-color:var(--border-strong); color:var(--primary-text); }
+.apps-type-description { flex:1; min-width:0; font-size:12px; line-height:1.5; color:var(--text-2); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#apps-create-btn {
display: inline-flex;
align-items: center;
@@ -8879,17 +8806,26 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--text);
}
.apps-page-header-count {
+ flex: 0 0 4ch;
+ width: 4ch;
font-family: var(--font-mono);
font-size: 12.5px;
color: var(--muted);
}
-.apps-page-header-count:empty { display: none; }
+.apps-page-header-count:empty { visibility: hidden; }
.apps-page-header-sub {
margin: 2px 0 0;
font-size: 12.5px;
color: var(--muted);
line-height: 1.4;
}
+@media (max-width: 800px) {
+ .apps-page-header { display:grid; grid-template-columns:minmax(0, 1fr) auto; align-items:center; gap:12px 16px; }
+ .apps-page-header-main { display:contents; }
+ .apps-page-header-title-row { grid-column:1; grid-row:1; }
+ #apps-create-btn { grid-column:2; grid-row:1; }
+ .apps-header-types { grid-column:1 / -1; grid-row:2; }
+}
.apps-grid {
display: grid;
@@ -8902,6 +8838,130 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 8px 0 24px;
}
.apps-grid:empty { display: none; }
+.app-publication-quota { display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted); }
+#apps-publication-quota { flex:0 0 auto; margin-bottom:12px; }
+.app-publication-quota[hidden] { display:none; }
+.app-publication-quota.is-warning,.app-publication-warning { color:var(--warn-text); }
+.app-card-publication { display:flex; align-items:center; flex-wrap:wrap; gap:8px; margin-top:6px; }
+.app-card-published { display:inline-flex; max-width:100%; box-sizing:border-box; padding:2px 7px; border-radius:99px; font-size:11px; line-height:16px; font-weight:600; overflow-wrap:anywhere; color:var(--success-text); background:var(--success-soft); }
+.modal.app-publication-dialog { display:flex; flex-direction:column; width:min(520px,calc(100vw - 32px)); min-width:0; padding:0; overflow:hidden; }
+.app-publication-dialog>h3 { margin:0; padding:20px 24px 8px; font-size:16px; }
+.app-publication-body { display:flex; flex:1; min-height:0; flex-direction:column; gap:12px; padding:0 24px 4px; max-height:70vh; overflow:auto; }
+.app-publication-info { display:flex; flex-direction:column; gap:10px; font-size:12px; color:var(--muted); }
+.app-publication-info:empty { display:none; }
+.app-publication-name { font-size:14px; color:var(--text); overflow-wrap:anywhere; }
+.app-publication-description { font-size:13px; line-height:1.6; color:var(--text-2); overflow-wrap:anywhere; }
+.app-publication-dates { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; padding-top:16px; border-top:1px solid var(--border); }
+.app-publication-date { display:flex; min-width:0; flex-direction:column; gap:4px; }
+.app-publication-date-label { font-size:12px; color:var(--muted); }
+.app-publication-date-value { font-size:13px; color:var(--text-2); font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }
+.app-publication-links { display:flex; gap:8px; align-items:center; padding:8px; border:1px solid var(--border); border-radius:8px; background:var(--bg); }
+.app-publication-links>.btn { flex:none; }
+.app-publication-url { flex:1; min-width:0; overflow-wrap:anywhere; font-size:12px; padding:4px 0; color:var(--text-2); }
+.app-publication-dialog .modal-actions { flex-shrink:0; margin-top:0; padding:16px 24px; gap:8px; }
+.app-publication-warning,.app-publication-status,.app-data-status,.app-data-action-status { font-size:13px; line-height:1.6; }
+.app-publication-warning { padding:10px 12px; border:1px solid var(--border); border-radius:8px; }
+.app-publication-pv { font-size:14px; color:var(--text); }
+.app-publication-status:empty,.app-data-status:empty,.app-data-action-status:empty { display:none; }
+.app-data-action-status { margin:-6px 0 12px; }
+.app-publication-trend { overflow-x:auto; padding:12px 0; }
+.app-publication-chart { display:block; width:100%; min-width:320px; }
+.app-publication-gridline { stroke:var(--border); stroke-dasharray:4 4; }
+.app-publication-area { fill:var(--primary); opacity:.08; }
+.app-publication-line { fill:none; stroke:var(--primary); stroke-width:2; vector-effect:non-scaling-stroke; }
+.app-publication-point { fill:var(--primary); }
+.app-publication-chart-label { fill:var(--muted); font-size:11px; }
+.app-publication-progress { display:block; flex:none; width:100%; height:6px; appearance:none; border:0; border-radius:99px; overflow:hidden; background:var(--surface-2); color:var(--primary); }
+.app-publication-progress::-webkit-progress-bar { background:var(--surface-2); border-radius:99px; }
+.app-publication-progress::-webkit-progress-value { background:var(--primary); border-radius:99px; }
+.app-publication-dialog [hidden] { display:none !important; }
+#panel-apps > [hidden] { display:none !important; }
+.app-publication-page { display:flex; flex:1; flex-direction:column; width:100%; min-height:0; overflow:hidden; container:publication-page / inline-size; }
+.app-publication-page [hidden] { display:none !important; }
+.app-publication-header { background:var(--surface); }
+.app-publication-header h2 { margin:0; }
+.app-publication-header .header-actions { display:flex; flex:none; flex-wrap:wrap; justify-content:flex-end; align-items:center; gap:8px; max-width:100%; margin-inline-start:auto; }
+.app-publication-header .app-publication-back { flex:none; padding:4px 10px; line-height:1.2; }
+.app-publication-header .app-publication-update { margin:0; }
+.app-publication-content { flex:1; min-height:0; overflow:auto; padding:24px max(24px,calc((100% - 864px)/2)); box-sizing:border-box; }
+.app-publication-notices { display:flex; flex-direction:column; gap:8px; margin-bottom:16px; }
+.app-publication-notices > .app-publication-warning,.app-publication-notices > .app-publication-status { margin:0; }
+.app-publication-notices:not(:has(> :not(:empty))) { display:none; }
+.app-publication-warning-detail { display:block; color:var(--muted); overflow-wrap:break-word; }
+.app-publication-page .app-publication-info { gap:16px; font-size:13px; line-height:1.5; }
+.app-publication-overview,.app-publication-stats-card,.app-publication-data { min-width:0; padding:16px; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius-md); }
+.app-publication-content h3 { margin:0; font-size:14px; font-weight:600; line-height:1.5; color:var(--text); }
+.app-publication-page .app-publication-links { gap:8px; padding:0 0 16px; border:0; border-radius:0; background:transparent; }
+.app-publication-address { display:flex; flex:1; flex-direction:column; gap:4px; min-width:0; }
+.app-publication-page .app-publication-url { padding:0; font-size:13px; color:var(--text); }
+.app-publication-page .app-publication-dates { padding-top:14px; }
+.app-publication-page .app-publication-stats { min-height:48px; }
+.app-publication-stats { position:relative; }
+.app-publication-stats-loading { display:flex; align-items:center; justify-content:center; gap:8px; min-height:72px; color:var(--text-2); }
+.app-publication-stats[aria-busy="true"] > .app-publication-pv,.app-publication-stats[aria-busy="true"] > .app-publication-trend { opacity:.4; }
+.app-publication-stats-loading:not(:first-child) { --orkas-ui-layer:chrome; position:absolute; inset:0; background:color-mix(in srgb,var(--surface) 65%,transparent); }
+.app-publication-stats-loading::before { content:""; width:14px; height:14px; border:2px solid var(--border-strong); border-top-color:var(--primary); border-radius:50%; animation:spin 1s linear infinite; }
+.app-publication-stats > .header-actions { display:flex; align-items:center; gap:8px; }
+.app-publication-stats-failed { flex:0 1 auto; min-width:0; }
+.app-publication-stats > .header-actions > .btn { flex:none; white-space:nowrap; }
+.app-publication-page .app-publication-pv { font-size:13px; color:var(--text-2); font-variant-numeric:tabular-nums; }
+.app-publication-page .app-publication-trend { padding:8px 0 0; }
+.app-publication-page .app-publication-chart { min-width:240px; max-height:128px; }
+.app-data-tools { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin-bottom:14px; }
+.app-data-heading { display:flex; flex:1 1 160px; flex-wrap:wrap; align-items:center; gap:8px; min-width:0; }
+.app-data-tools .header-actions { display:flex; flex:none; gap:8px; margin-inline-start:auto; }
+.app-data-more { display:inline-flex; align-items:center; justify-content:center; gap:6px; min-width:28px; padding:4px 6px; }
+.app-data-more-icon { width:16px; height:16px; }
+.app-data-usage { margin-inline-end:auto; font-size:12px; }
+.app-data-workspace { min-width:0; border:1px solid var(--border); border-radius:var(--radius-sm); overflow:hidden; }
+.app-data-table-tabs { display:flex; gap:12px; overflow-x:auto; padding:0 12px; border-bottom:1px solid var(--border); }
+.app-data-table-tabs:empty { display:none; }
+.app-data-table-tabs .btn { flex:none; padding:10px 4px; border:0; border-bottom:2px solid transparent; border-radius:0; background:transparent; color:var(--text-2); }
+.app-data-table-tabs .btn.is-active { border-bottom-color:var(--primary); color:var(--primary-text); font-weight:600; }
+.app-data-range { display:flex; flex-wrap:wrap; align-items:center; gap:8px; padding:12px; border-bottom:1px solid var(--border); }
+.app-data-tools > .ai-select,.app-data-range > .ai-select { min-width:min(180px,100%); max-width:100%; }
+.app-data-range > button { max-width:100%; }
+.app-data-edit-actions { display:flex; gap:6px; margin-inline-start:auto; }
+.app-data-edit-status { padding:8px 12px; font-size:13px; color:var(--danger); overflow-wrap:anywhere; }
+.app-data-edit-status:empty { display:none; }
+.app-data-body { position:relative; min-width:0; }
+.app-data-body > .app-data-status:not(:empty) { padding:8px 12px; background:var(--bg); }
+.app-publication-data[aria-busy="true"] .app-data-status:not(:empty) { --orkas-ui-layer:chrome; position:absolute; inset:0; z-index:5; display:flex; align-items:center; justify-content:center; text-align:center; background:color-mix(in srgb,var(--surface) 80%,transparent); }
+.app-data-records { min-height:80px; max-height:480px; overflow:auto; }
+.app-data-records:not(:has(.app-data-row)) { display:grid; place-items:center; min-height:96px; }
+.app-data-grid { width:100%; border-collapse:separate; border-spacing:0; color:var(--text); font-size:13px; }
+.app-data-grid th { --orkas-ui-layer:chrome; position:sticky; top:0; z-index:1; padding:10px 12px; background:var(--bg); font-weight:600; text-align:start; white-space:nowrap; }
+.app-data-grid th,.app-data-grid td { vertical-align:middle; border-bottom:1px solid var(--border); border-inline-end:1px solid var(--border); }
+.app-data-grid th:last-child,.app-data-grid td:last-child { border-inline-end:0; }
+.app-data-grid tbody tr:last-child td { border-bottom:0; }
+.app-data-cell { min-width:180px; padding:4px; }
+.app-data-cell.is-number { min-width:100px; }
+.app-data-cell.is-number input { text-align:end; font-variant-numeric:tabular-nums; }
+.app-data-cell.is-boolean { min-width:72px; text-align:center; }
+.app-data-cell.is-multiline { min-width:260px; }
+.app-data-cell.is-readonly { color:var(--muted); }
+.app-data-cell.is-dirty { background:var(--primary-soft); box-shadow:inset 2px 0 var(--primary); }
+.app-data-grid .app-data-cell-input { display:block; width:100%; min-width:0; margin:0; padding:6px 8px; border:1px solid transparent; border-radius:var(--radius-sm); background:transparent; color:inherit; font:inherit; line-height:1.5; box-sizing:border-box; }
+.app-data-grid textarea.app-data-cell-input { resize:vertical; min-height:52px; max-height:240px; }
+.app-data-grid .app-data-cell-input:not([readonly]):not(:disabled):hover { border-color:var(--border-strong); }
+.app-data-grid .app-data-cell-input:focus-visible { outline:2px solid var(--primary); outline-offset:-2px; background:var(--surface); }
+.app-data-grid .app-data-cell-input[aria-invalid="true"] { border-color:var(--danger); }
+.app-data-grid input[type="checkbox"] { display:block; width:16px; height:16px; margin:6px auto; accent-color:var(--primary); }
+.app-data-grid .app-data-grid-actions { position:sticky; inset-inline-end:0; min-width:64px; padding:6px; background:var(--surface); text-align:center; border-inline-start:1px solid var(--border); }
+.app-data-grid th.app-data-grid-actions { --orkas-ui-layer:chrome; z-index:2; background:var(--bg); }
+.app-data-grid-actions .btn { border-color:transparent; background:transparent; }
+.app-data-paging { display:flex; justify-content:flex-end; flex-wrap:wrap; gap:8px; padding:10px 12px; border-top:1px solid var(--border); }
+@container publication-page (max-width:480px){
+ .app-publication-header { flex-wrap:wrap; }
+ .app-publication-content { padding:16px; }
+ .app-publication-page .app-publication-links { flex-wrap:wrap; }
+ .app-publication-address { flex-basis:100%; }
+ .app-publication-overview,.app-publication-stats-card,.app-publication-data { padding:14px; }
+ .app-publication-page .app-publication-dates { grid-template-columns:minmax(0,1fr); gap:12px; }
+ .app-data-tools { gap:6px; }
+ .app-data-tools h3 { flex:1; }
+ .app-data-usage { flex-basis:100%; order:2; }
+}
.app-card {
position: relative;
@@ -8947,13 +9007,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: flex;
align-items: flex-start;
gap: 10px;
- min-height: 28px;
-}
+ min-height: 28px; }
.app-card-title-block {
flex: 1;
min-width: 0;
}
.app-card-name {
+ padding-right: 32px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
@@ -8966,6 +9026,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-wrap: anywhere;
}
.app-card-more {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 12px;
right: 12px;
@@ -8988,6 +9049,17 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.app-card-more:hover { background: var(--surface-2); color: var(--text); }
.app-card-more:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
.app-card-more-icon { width: 17px; height: 17px; }
+.app-card.is-publishing { border-color: color-mix(in srgb, var(--primary) 30%, var(--border)); }
+.app-card-more:disabled { visibility: visible; opacity: .4; cursor: not-allowed; }
+.app-card-more:disabled:hover { background: transparent; color: var(--muted); }
+.app-card-publication .app-card-details:disabled { opacity: .45; cursor: not-allowed; text-decoration: none; }
+.app-card-publication[hidden] { display: none; }
+.app-card-publishing { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; min-width: 0; color: var(--primary-text); font-size: 12px; line-height: 18px; }
+.app-card-publishing-label { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 2px 8px; overflow-wrap: anywhere; }
+.app-card-publishing-label.is-unpublishing { flex-wrap: nowrap; justify-content: flex-start; align-items: center; gap: 6px; }
+.app-card.is-publishing .app-card-publishing-label [role="status"] { min-width: 0; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.app-card-publishing-percent { flex: none; color: var(--muted); font-variant-numeric: tabular-nums; }
+.app-card-publishing.is-warning { color: var(--muted); }
.app-card-meta {
margin-top: auto;
min-width: 0;
@@ -8996,6 +9068,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 18px;
}
.app-card-time { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.app-card-publication .app-card-details { max-width:100%; padding:0; border:0; border-radius:var(--radius-sm); background:transparent; color:var(--primary-text); font-size:12px; line-height:20px; white-space:normal; overflow-wrap:anywhere; }
+.app-card-publication .app-card-details:hover { background:transparent; text-decoration:underline; }
+.app-card-publication .app-card-details:focus-visible { outline:2px solid var(--primary); outline-offset:3px; }
.modal.apps-create-panel {
width: calc(100% - 40px);
@@ -9006,6 +9081,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.apps-create-panel .modal-header { gap: 14px; min-height: 0; margin-bottom: 16px; }
.apps-create-panel h2 { margin: 0; font-size: 18px; font-weight: 600; line-height: 1.4; }
+.apps-create-types { flex-wrap: wrap; margin-bottom: 20px; }
.apps-create-idea textarea { display: block; min-height: 112px; max-height: 240px; resize: vertical; line-height: 1.6; }
.apps-create-section { margin: 20px 0 10px; }
.apps-create-panel .apps-create-section h3 { font-size: 12px; font-weight: 400; color: var(--muted); }
@@ -9167,8 +9243,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--danger);
border-color: rgba(220, 38, 38, 0.3);
}
-
-/* Conversation board dependency and dispatch information. */
.chat-queue-dep {
background: rgba(100, 116, 139, 0.12);
color: var(--muted);
@@ -9183,8 +9257,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-queue-item:focus-within .chat-queue-edit {
display: inline-block;
}
-
-/* Pinned board header doubles as the collapse toggle (2026-08-23). */
.chat-queue-header.chat-task-board-toggle {
cursor: pointer;
user-select: none;
@@ -9281,8 +9353,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-queue-agent-items .drop-target[data-drop-edge="after"] {
box-shadow: 0 2px 0 var(--primary);
}
-
-/* Aborted assistant bubble marker */
.stream-aborted-note {
margin-top: 6px;
font-size: 12px;
@@ -9298,9 +9368,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
max-width 把气泡撑破;min-width: 0 让 max-width 真正生效。 */
min-width: 0;
}
-
-/* Main-task and edit-chat AI replies share the 80% transcript cap as their
- actual width. User messages remain content-sized up to the same cap. */
.chat-history > .chat-message.assistant,
.skills-chat-messages > .chat-message.assistant,
.agents-chat-messages > .chat-message.assistant {
@@ -9317,14 +9384,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
align-self: flex-start;
align-items: flex-start;
}
-
-/* Inline delete-file confirmation card. The main-side `delete_file` tool
- * emits a `delete_file.confirmation_required` push when an LLM calls it;
- * the renderer (`modules/delete-file-confirm.js`) appends one of these
- * cards to `#chat-history`. Visual goal: catch the eye (red accent,
- * monospace path) without modal-blocking the rest of the UI. Auto-hides
- * itself after the user clicks either button (the card stays in the DOM
- * with the result line so the user sees a record of the choice). */
.delete-confirm-card {
/* Default = main group chat (#chat-history): match the input composer's
* width (`.chat-input-area` is max-width:80% + margin:0 auto). Edit-chat
@@ -9403,9 +9462,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.delete-confirm-card.is-cancelled .delete-confirm-result {
color: #6b7280;
}
-/* Token died before the click landed (main cancelled or GC'd it). The card
- * stays readable but is visibly retired, so it can't be mistaken for a live
- * prompt. */
.delete-confirm-card.is-stale {
border-left-color: var(--border-strong, #e5e7eb);
background: var(--surface-2, #eef1f8);
@@ -9416,11 +9472,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.delete-confirm-card.is-stale .delete-confirm-result {
color: var(--warn-text, #b45309);
}
-
-/* Group-chat message header — sender name + timestamp on one row,
- * **above the bubble**, outside it. Name uses normal text weight in the
- * primary text color; time is smaller and muted with a comfortable gap.
- * User-side messages drop the name chip and right-align the time. */
.chat-msg-header {
display: flex;
align-items: center;
@@ -9461,16 +9512,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
-
-/* `@<token>` mentions inside a chat bubble — paint in accent blue so users
- * can scan a long reply for "who's this routed to". Skipped automatically
- * inside <code>/<pre>/<a> nodes by the renderer's DOM walker. */
.msg-mention {
color: var(--primary);
font-weight: 500;
}
-
-/* Compact message actions stay inline and wrap within the message width. */
.chat-msg-actions {
display: flex;
flex-wrap: wrap;
@@ -9482,10 +9527,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-msg-actions:empty {
display: none;
}
-
-/* Message-share dialog. The entry points live in conversation.js; hosted
- upload/render behavior is isolated in modules/share.js. */
.modal-overlay.chat-share-overlay {
+ --orkas-ui-layer: overlay;
z-index: 1010;
background: rgba(15, 23, 42, 0.38);
backdrop-filter: blur(3px);
@@ -9634,11 +9677,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
opacity: 1;
pointer-events: auto;
}
-/* Recovery is a primary action, not hover-only chrome. Keeping retry controls
- * interactive also avoids the circular hit-test where the transparent action
- * wrapper must first receive hover before its child button can receive the
- * click. Chromium otherwise reports the surrounding message-action row as
- * intercepting the retry button. */
.chat-bubble-actions[data-mode="failure-only"],
.chat-bubble-actions[data-mode="failed"],
.chat-bubble-actions[data-mode="assistant-retry"] {
@@ -9696,8 +9734,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(255, 255, 255, 0.82);
box-shadow: none;
}
-
-/* ─── Cross-task message selection / reference transfer ─────────────── */
.chat-main-pane.is-message-selecting .chat-msg-actions {
visibility: hidden;
}
@@ -9728,6 +9764,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: transparent;
cursor: pointer;
box-shadow: 0 1px 4px rgba(15, 23, 42, 0.08);
+ --orkas-ui-layer: chrome;
z-index: 2;
}
@@ -9781,8 +9818,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-message-selection-spacer { flex: 1; }
.chat-reference-target-modal {
- width: min(468px, calc(100vw - 40px));
- max-height: min(620px, calc(100vh - 56px));
+ width: min(744px, calc(100vw - 40px));
+ height: min(604px, calc(100vh - 56px));
display: flex;
flex-direction: column;
overflow: hidden;
@@ -9811,15 +9848,77 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
letter-spacing: -0.01em;
}
.chat-reference-target-modal > .chat-reference-target-body {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 184px minmax(0, 1fr);
+ padding: 0;
+ overflow: hidden;
+}
+.chat-reference-scopes {
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 16px 12px;
+ border-inline-end: 1px solid var(--border);
+ background: var(--bg);
+}
+.chat-reference-scope {
+ width: 100%;
+ min-height: 36px;
+ display: flex;
+ align-items: center;
+ flex: 0 0 auto;
+ padding: 8px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 12.5px;
+ line-height: 1.4;
+ text-align: start;
+ cursor: pointer;
+}
+.chat-reference-scope span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.chat-reference-scope:hover { background: var(--surface-2); }
+.chat-reference-scope[aria-pressed="true"] {
+ background: var(--primary-soft);
+ color: var(--primary-text);
+}
+.chat-reference-scope-label {
+ margin: 20px 8px 8px;
+ color: var(--text-2);
+ font-size: 11px;
+ line-height: 1.4;
+}
+.chat-reference-project-scopes {
+ flex: 1;
min-height: 0;
- padding: 14px 16px 16px;
overflow-y: auto;
}
+.chat-reference-browse,
+.chat-reference-create {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 16px;
+}
+.chat-reference-browse[hidden],
+.chat-reference-create[hidden] { display: none; }
.chat-reference-new-task {
width: 100%;
height: 38px;
display: flex;
align-items: center;
+ flex: 0 0 auto;
gap: 7px;
padding: 0 12px;
border: 1px solid var(--border);
@@ -9829,7 +9928,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-family: inherit;
font-size: 12.5px;
font-weight: 550;
- text-align: left;
+ text-align: start;
cursor: pointer;
transition: border-color 120ms ease, background 120ms ease;
}
@@ -9844,40 +9943,60 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-reference-new-task-label {
min-width: 0;
flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
.chat-reference-new-task:hover {
border-color: color-mix(in srgb, var(--primary) 35%, var(--border));
background: color-mix(in srgb, var(--primary) 3%, #fff);
}
-.chat-reference-new-task:disabled { cursor: wait; opacity: 0.62; }
-.chat-reference-existing { margin-top: 14px; }
.chat-reference-existing-head {
display: flex;
align-items: baseline;
justify-content: space-between;
+ flex: 0 0 auto;
gap: 12px;
- margin: 0 2px 8px;
+ margin: 0 2px;
}
.chat-reference-existing-head h3 {
+ min-width: 0;
margin: 0;
+ overflow: hidden;
color: var(--text);
font-size: 13px;
font-weight: 600;
line-height: 1.4;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
.chat-reference-existing-head span {
- color: var(--muted);
+ flex: 0 0 auto;
+ color: var(--text-2);
font-size: 11px;
line-height: 1.4;
}
.chat-reference-target-search-wrap {
+ position: relative;
display: block;
- margin-bottom: 8px;
+ flex: 0 0 auto;
+}
+.chat-reference-target-search-icon {
+ --orkas-ui-layer: chrome;
+ position: absolute;
+ top: 50%;
+ inset-inline-start: 10px;
+ display: inline-flex;
+ color: var(--muted);
+ font-size: 14px;
+ pointer-events: none;
+ transform: translateY(-50%);
}
.chat-reference-target-search {
width: 100%;
height: 34px;
padding: 7px 10px;
+ padding-inline-start: 32px;
border: 1px solid var(--border);
border-radius: 9px;
outline: none;
@@ -9894,27 +10013,37 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 9%, transparent);
}
.chat-reference-target-list {
+ flex: 1;
+ min-height: 0;
display: flex;
flex-direction: column;
gap: 2px;
- min-height: 76px;
+ overflow-y: auto;
}
+.chat-reference-target-list > * { flex: 0 0 auto; }
.chat-reference-target-item {
width: 100%;
display: flex;
align-items: center;
gap: 8px;
- min-height: 44px;
- padding: 7px 8px;
+ min-height: 54px;
+ padding: 8px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--text);
- text-align: left;
+ text-align: start;
cursor: pointer;
}
.chat-reference-target-item:hover { background: rgba(15, 23, 42, 0.045); }
+.chat-reference-scope:focus-visible,
+.chat-reference-target-item:focus-visible,
+.chat-reference-load-more:focus-visible,
+.chat-reference-create-back:focus-visible {
+ outline: 2px solid var(--primary);
+ outline-offset: -2px;
+}
.chat-reference-current-task {
flex: 0 0 auto;
padding: 2px 6px;
@@ -9929,44 +10058,100 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: flex;
flex: 1;
flex-direction: column;
- gap: 1px;
+ gap: 2px;
}
.chat-reference-target-main strong {
overflow: hidden;
color: var(--text);
font-size: 13px;
font-weight: 550;
- line-height: 1.35;
+ line-height: 1.5;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-reference-target-main small {
overflow: hidden;
- color: var(--muted);
+ color: var(--text-2);
font-size: 11px;
- line-height: 1.35;
+ line-height: 1.5;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-reference-row-arrow {
flex: 0 0 auto;
- margin-left: auto;
+ margin-inline-start: auto;
color: #94a3b8;
font-size: 17px;
font-weight: 400;
line-height: 1;
}
+.chat-reference-load-more {
+ align-self: center;
+ margin: 10px 0 4px;
+ padding: 8px 12px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--primary-text);
+ font-family: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+}
+.chat-reference-load-more:hover { background: var(--surface-2); }
.chat-reference-target-empty {
- padding: 22px 10px;
- color: var(--muted);
- font-size: 12px;
+ padding: 40px 12px;
+ color: var(--text-2);
+ font-size: 12.5px;
+ line-height: 1.5;
text-align: center;
}
+.chat-reference-target-empty strong {
+ display: block;
+ margin-bottom: 6px;
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 600;
+}
+.chat-reference-create-back {
+ align-self: flex-start;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--primary-text);
+ font-family: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+}
+.chat-reference-create h3 {
+ margin: 0;
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.4;
+}
+.chat-reference-create p {
+ margin: 0;
+ color: var(--text-2);
+ font-size: 12.5px;
+ line-height: 1.5;
+}
+.chat-reference-target-footer {
+ flex: 0 0 auto;
+ padding: 12px 20px;
+ border-top: 1px solid var(--border);
+ color: var(--text-2);
+ font-size: 11px;
+ line-height: 1.4;
+}
@media (max-width: 620px) {
- .chat-reference-target-modal { width: calc(100vw - 24px); max-height: calc(100vh - 32px); }
+ .chat-reference-target-modal { width: calc(100vw - 24px); height: calc(100vh - 32px); }
.chat-reference-target-modal > .chat-reference-target-header { padding: 16px 16px 13px; }
- .chat-reference-target-modal > .chat-reference-target-body { padding: 12px; }
+ .chat-reference-target-modal > .chat-reference-target-body { grid-template-columns: 144px minmax(0, 1fr); }
+ .chat-reference-scopes { padding: 12px 8px; }
+ .chat-reference-browse,
+ .chat-reference-create { padding: 12px; }
}
.chat-reference-bundle {
@@ -9985,6 +10170,20 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-y: auto;
}
.chat-reference-message { min-width: 0; font-size: 12px; line-height: 1.4; }
+.chat-reference-message.is-locatable {
+ display: block;
+ width: 100%;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-size: 12px;
+ text-align: left;
+ cursor: pointer;
+}
+.chat-reference-message.is-locatable:hover .chat-reference-author { text-decoration: underline; }
+.chat-reference-message.is-locatable:hover .chat-reference-text { color: var(--text); }
.chat-reference-author { display: block; margin-bottom: 1px; color: #2563eb; font-size: 12px; font-weight: 500; }
.chat-reference-text {
display: block;
@@ -10030,9 +10229,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
vertical-align: -1px;
animation: marketplace-upload-spin 0.8s linear infinite;
}
-
-/* Plan announcement card — rendered as the leading line of the bubble
- * when commander emits its initial plan_set message. */
.chat-plan-announce {
display: flex;
align-items: center;
@@ -10086,60 +10282,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-message.assistant[data-placeholder="1"] .chat-bubble {
transition: none;
}
-
-/* ─── Turn narration (external-CLI turns) ───
- A Claude Code turn persists one record per native message; the transcript
- renders the turn as one bubble. Text of the earlier segments (the opening
- line, progress notes written between tool loops) sits above the body as
- muted narration blocks; the last segment's text is the body. */
-.chat-bubble > .chat-turn-narration {
- margin: 0 0 10px;
- padding: 1px 0 1px 10px;
- border-left: 2px solid var(--border);
- color: var(--text-2);
- font-size: 13px;
- line-height: 1.55;
-}
-.chat-bubble > .chat-turn-narration .markdown-body {
- font-size: inherit;
- line-height: inherit;
- color: inherit;
-}
-/* A long turn folds all but the last couple of narration blocks behind one
- line. Presentation only — the blocks stay in the DOM. */
-.chat-bubble > .chat-turn-narration--folded {
- display: none;
-}
-.chat-bubble > .chat-turn-narration-toggle {
- display: block;
- width: fit-content;
- margin: 0 0 10px;
- padding: 1px 0 1px 10px;
- border: 0;
- border-left: 2px solid var(--border);
- border-radius: 0;
- background: none;
- color: var(--text-2);
- font: inherit;
- font-size: 13px;
- line-height: 1.55;
- text-align: left;
- cursor: pointer;
-}
-.chat-bubble > .chat-turn-narration-toggle::before {
- content: '▸';
- display: inline-block;
- margin-right: 5px;
-}
-.chat-bubble > .chat-turn-narration-toggle[data-expanded="1"]::before {
- content: '▾';
-}
-.chat-bubble > .chat-turn-narration-toggle:hover {
- color: var(--text);
- border-left-color: var(--border-strong);
-}
-
-/* ─── Streaming (process + final) ─── */
.stream-thinking {
display: inline-flex;
align-items: center;
@@ -10192,7 +10334,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.stream-process[data-process-state="active"] .stream-process-caret {
display: none;
}
-/* Same caret family as the tree nodes (chevron-right → rotate 90° when expanded). */
.stream-process-caret {
display: inline-flex;
align-items: center;
@@ -10233,11 +10374,28 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12.5px;
line-height: 1.55;
color: var(--muted);
- font-family: inherit;
+ font-family: inherit;
+}
+.stream-process-body:empty { display: none; }
+.stream-process-body > :last-child { margin-bottom: 0; }
+.stream-process.runtime-only .stream-process-summary { cursor: default; }
+.stream-process > .chat-process-load-more {
+ width: auto;
+ min-height: 26px;
+ margin: 8px 0 2px 10px;
+ padding: 4px 6px;
+ border-radius: 6px;
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.4;
+ color: var(--muted);
+ text-align: left;
}
-.stream-process-body:empty { display: none; }
-.stream-process-body > :last-child { margin-bottom: 0; }
-.stream-process.runtime-only .stream-process-summary { cursor: default; }
+.stream-process > .chat-process-load-more:hover:not(:disabled),
+.stream-process > .chat-process-load-more:focus-visible {
+ color: var(--primary);
+}
+.chat-process-load-more[hidden] { display: none; }
.stream-process-line {
display: flex;
@@ -10251,10 +10409,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
--stream-process-operation-color: var(--muted);
margin: 6px 0;
}
-/* Operations disclosure: a quiet inline row — no box or fill in its resting
- state (a bordered chip repeated between every paragraph read as noise).
- Hover gets a soft surface tint and open keeps only a color lift; rows share
- the group color via --stream-process-operation-color. */
.stream-process-compact-summary {
display: inline-flex;
align-items: center;
@@ -10329,9 +10483,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-wrap: anywhere;
word-break: break-word;
}
-/* Commentary keeps the full markdown pipeline. Settled history compacts its
- block scale below; active work deliberately inherits ordinary bubble
- markdown so the narration reads like the assistant's current prose. */
.stream-process-commentary-text.markdown-body {
white-space: normal;
font-size: inherit;
@@ -10375,7 +10526,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12.5px;
line-height: 1.4;
}
-/* Folding process history at the first body token does not finish execution. */
.chat-message[data-activity-start]:not([data-activity-done="1"]) > .chat-bubble > .stream-process-loading {
display: flex;
}
@@ -10388,26 +10538,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
width: 4px;
height: 4px;
}
-/* Four-tier hierarchy. The constraint: every content line stays visually
- lighter than the disclosure summary, because these rows are supporting
- detail rather than the primary reply.
- Tiers:
- 1. Core — milestones / tool calls / plans / file edits;
- slate-500 + 500 weight. Distinguishable at a glance
- but still a notch below the header.
- 2. Normal — reasoning, live preview, stdout, context, meta, ordinary
- agent-response waiting;
- slate-400.
- Same as the body baseline so unrecognized lines
- read as plain text, not "missing styling".
- 3. Warn — awaiting approval, retry / provider fallback, cli stderr.
- Kept as its own hue (light amber) because (a) red would over-alarm
- benign cli progress messages routed through stderr,
- and (b) folding into Normal loses the "someone is
- waiting on you" signal at the rail level.
- 4. Error — hard error / failed tool; red-500 + 500 weight.
- `_eventProcessKind` maps events into these classes; old persisted
- glyph-prefixed rows are normalized at render time. */
.stream-process-line.kind-bound { color: var(--text-2); font-weight: 500; }
.stream-process-line.kind-tool { color: var(--text-2); font-weight: 500; }
.stream-process-line.kind-plan { color: var(--text-2); font-weight: 500; }
@@ -10422,20 +10552,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.stream-process-line.kind-warn { color: var(--warn); }
.stream-process-line.kind-err { color: var(--danger); font-weight: 500; }
.stream-process-line.kind-info { color: var(--primary-text); }
-/* All ordinary rows inside an "Operations N" disclosure share its color.
- Warning/error rows retain their semantic colors so failures stay visible. */
.stream-process-compact-body .stream-process-line:not(.kind-warn):not(.kind-err) {
color: var(--stream-process-operation-color);
}
.stream-process-compact-body .stream-process-line:not(.kind-warn):not(.kind-err):hover {
color: var(--text);
}
-
-/* Live work reads like the assistant's in-progress body, not archived detail:
- remove the history rail and use normal bubble typography for prose. Command
- and action rows remain inside the established quiet, collapsed "Operations"
- disclosure. On settlement the outer data-process-state changes to
- `complete`, so the untouched rules above restore the vertical rail. */
.stream-process[data-process-state="active"] .stream-process-body {
margin: 8px 0 0;
padding: 0;
@@ -10453,9 +10575,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.stream-process[data-process-state="active"] .stream-process-commentary .markdown-body p {
margin: 0.4em 0;
}
-/* Active narration intentionally keeps the stronger live color above, while
- tool/command rows stay compact in both runtime modes. Reset only typography
- here so semantic operation, warning, and error colors remain untouched. */
.stream-process[data-process-state="active"] .stream-process-compact-body {
font-size: 12.5px;
line-height: 1.55;
@@ -10478,10 +10597,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-wrap: anywhere;
}
.stream-process-line.is-continuation { padding-left: 19px; }
-
-/* Expandable tool-result row: pointer/keyboard hint + subtle activation state.
- Used for CLI tool-event(result) rows whose full output spilled to
- disk; activation reveals a `.stream-process-line-full` <pre> sibling. */
.stream-process-line.is-expandable { align-items: flex-start; cursor: pointer; }
.stream-process-expandable-content {
min-width: 0;
@@ -10542,16 +10657,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: inherit;
color: inherit;
}
-
-/* Tighten spacing inside chat bubbles — the bubble already has its own
- padding, so we don't want the first heading / paragraph to add margin. */
.chat-bubble .markdown-body > :first-child { margin-top: 0; }
.chat-bubble .markdown-body > :last-child { margin-bottom: 0; }
.chat-bubble .markdown-body p { margin: 0.4em 0; }
.chat-bubble .markdown-body h1,
.chat-bubble .markdown-body h2,
.chat-bubble .markdown-body h3 { margin: 0.8em 0 0.4em; }
-.chat-bubble .markdown-body table { font-size: 0.9em; }
+.chat-bubble .markdown-body table { font-size: inherit; }
.chat-bubble pre {
background: #f1f5f9;
@@ -10560,20 +10672,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: 12px 0;
border: 1px solid rgba(0,0,0,0.05);
max-width: 100%;
- /* 气泡内代码块优先自动换行而不是横向滚动:macOS overlay 滚动条默认不可见,
- 横向滚用户极易以为被截断;气泡宽度有限,阅读体验上换行也明显更好。 */
white-space: pre-wrap;
overflow-wrap: anywhere;
+ font-size: inherit;
}
-
-/* Forward-quote blockquotes in user bubbles — clamp to 2 lines to keep the
- sent-message bubble compact. The receiving agent still gets the full text
- (the markdown is sent intact via bus.enqueue); this only affects the
- sender's view of their own outgoing bubble. Why user bubbles only:
- `applyQuotePrefix` is the sole producer of these blockquotes, and it
- only runs on the renderer's send path → the result always lands in a
- user-role bubble. Assistant blockquotes (citations, web fetches, etc.)
- stay unclamped so the model's quoted content remains fully readable. */
.chat-message.user .chat-bubble blockquote {
display: -webkit-box;
-webkit-box-orient: vertical;
@@ -10581,16 +10683,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-clamp: 2;
overflow: hidden;
}
-
-/* Plain Markdown tables scroll themselves. Dashboard tables use .db-table-wrap
- for scrolling and need native table layout to fill their frame. */
.chat-bubble .markdown-body table:not(.db-table) { display: block; max-width: 100%; overflow-x: auto; }
.chat-bubble .markdown-body img { max-width: 100%; }
.chat-bubble .markdown-body .chat-md-img { width: 100%; height: 100%; }
.chat-bubble code {
font-family: 'JetBrains Mono', 'Menlo', 'Monaco', monospace;
- font-size: 0.9em;
+ font-size: inherit;
background: rgba(0,0,0,0.04);
padding: 2px 4px;
border-radius: 4px;
@@ -10622,17 +10721,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
-
-/* Overlay strip floating above the input bubble. Holds attachments only.
- The workspace chip moved into `.chat-bottom-bar` next to the
- recipient/project chips, so this strip's geometry simplified —
- attachments take the full width and wrap freely; no right-side
- reservation needed.
-
- `pointer-events: none` on the wrapper keeps clicks falling through to
- the input box while still letting individual chip children (which set
- `pointer-events: auto` via .chat-attachments) receive hits. */
.chat-input-overlay {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 0;
left: 0;
@@ -10648,9 +10738,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex: 1 1 auto;
min-width: 0;
}
-
-/* Composer surfaces reserve one shared vertical stack. Long task/question or
- attachment lists scroll inside it while the message composer stays usable. */
#panel-conversation .chat-input-wrapper {
display: flex;
flex-direction: column;
@@ -10690,11 +10777,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: var(--surface);
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
}
-/* The card is read top down before anything is clicked — who is asking, the
- question, then one line per option — so each step gets its own size and its
- own air. The inherited form styling was built for short field labels: it
- packs a 12px label against an 11px description with a negative margin, which
- collapses the three steps into one grey block. */
.cli-question-panel .form-title {
font-size: 14px;
line-height: 1.5;
@@ -10710,9 +10792,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.cli-question-panel .form-field-checkgroup .btn { white-space: normal; text-align: left; }
.cli-question-panel .form-field-textarea { resize: none; }
-/* Option descriptions arrive as one line per option, so line-height is the only
- thing separating one option's reason from the next. `--text-2` keeps them
- legible beside the buttons they explain instead of fading into the card. */
.cli-question-panel .form-field-desc {
font-size: 12.5px;
line-height: 1.7;
@@ -10721,10 +10800,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
white-space: pre-line;
overflow-wrap: anywhere;
}
-/* Real space between options, not line-height: at a narrow dock a description
- wraps, and leading alone cannot say whether the next line continues this
- option or starts the next one. The name carries the card's text colour so a
- description can be matched back to the button that bears the same label. */
.cli-question-panel .form-field-desc-option + .form-field-desc-option {
margin-top: 6px;
}
@@ -10733,21 +10808,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--text);
font-weight: 500;
}
-/* Send sits under the answer box, with decline beside it: a blocking request
- must stay declinable, and the CLI is holding its turn until one is pressed. */
.cli-question-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
-
-/* The card sits inside the composer dock, a few pixels from the app's own send
- control, so it stays in the tinted register the rest of the app uses for a
- selected state (see `.project-driver-toggle[aria-pressed="true"]`) instead of
- the full-strength fill a modal's confirm button gets. Two tiers of the one
- hue: a picked option is the lighter one, send carries the solid border and
- the heavier weight so it still reads as the affirmative action. */
.cli-question-panel .form-field-checkgroup .btn.is-selected {
background: var(--primary-soft);
border-color: color-mix(in srgb, var(--primary) 38%, #fff);
@@ -10765,8 +10831,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.cli-question-panel .btn-primary:hover {
background: color-mix(in srgb, var(--primary) 26%, #fff);
}
-/* `.btn-primary:disabled` re-asserts the solid fill, so the disabled send needs
- selectors that outrank it — including its `:disabled:hover` pair. */
.cli-question-panel .btn-primary:disabled,
.cli-question-panel .btn-primary:disabled:hover {
background: color-mix(in srgb, var(--primary) 14%, #fff);
@@ -10797,26 +10861,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #fff;
}
-/* Composer chips share P3's border, radius, and type. Menu triggers
- (recipient / workspace / model) stay transparent at rest; selected-content
- chips 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: 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-recipient-chip {
flex-shrink: 0;
display: inline-flex;
@@ -10918,12 +10962,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
outline: 2px solid rgba(220, 38, 38, 0.18);
outline-offset: 1px;
}
-
-/* ─── Workspace chip (user working directory selector) ─── */
-
-/* Workspace chip — P3 chrome, same family as recipient / project / skill.
- Open state uses primary-soft. The chip is JS-injected by user-workspace.js
- right after the recipient chip in the composer bottom bar (per design P11). */
.workspace-chip {
border: 1px solid var(--border);
background: transparent;
@@ -10975,6 +11013,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.workspace-menu {
+ --orkas-ui-layer: overlay;
z-index: 9999;
box-sizing: border-box;
min-width: min(200px, calc(100vw - 16px));
@@ -11038,17 +11077,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.skill-picker {
position: fixed;
width: 340px;
- /* Rows carry a two-line description, so 380px showed about four of them and
- the list read as truncated. The placement helper clamps this to the space
- the anchor actually leaves, so the cap only has to stop the box from
- becoming a full-height panel on a tall window. */
max-height: min(560px, 70vh);
background: #fff;
border: 1px solid var(--border);
border-radius: 12px;
box-shadow: 0 12px 36px rgba(15, 23, 42, 0.18);
- /* Body-level picker used by composer recipient chips, including inside
- ui-dialog modals such as the automation task dialog. */
+ --orkas-ui-layer: overlay;
z-index: 14000;
display: flex;
flex-direction: column;
@@ -11136,10 +11170,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-y: auto;
padding: 4px;
}
-
-/* Coding-CLI entry pinned under the roster. `flex-shrink: 0` is what keeps it
- on screen once the placement helper caps the box: the list is the scroll
- container above it, so the rows give up the space, not this row. */
.skill-picker-footer {
flex-shrink: 0;
border-top: 1px solid var(--border);
@@ -11170,13 +11200,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-shrink: 0;
color: var(--muted);
}
-
-/* Two lines: the action, then the CLIs it means. The subject line is the whole
- point of the entry -- "connect a coding agent" alone never said Claude Code.
- `flex: 1` is what puts the chevron on the trailing edge: `hydrateUiIcons`
- wraps each icon in a span of its own, so the arrow's class lands on the inner
- <svg> and an auto margin there has no free space to absorb -- the copy has to
- claim the room instead. */
.skill-picker-cli-copy {
display: flex;
flex: 1;
@@ -11222,6 +11245,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding-right: 36px;
}
.recipient-picker-check {
+ --orkas-ui-layer: chrome;
position: absolute;
right: 10px;
top: 50%;
@@ -11268,10 +11292,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
font-size: 11px;
}
-
-/* Banner shown above the picker list when the active context is a project
- with zero bound agents — anchors the empty state without hiding the
- commander entry below. */
.skill-picker-empty-hint {
padding: 8px 10px;
font-size: 11.5px;
@@ -11288,12 +11308,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: #94a3b8;
font-size: 12px;
}
-
-/* ─── Library (contexts) — Surface D per PC/docs/design/PATTERNS.md ─── */
-
-/* Page header (P1) above the tree+viewer layout. Padding + title-font
- matched to `.chat-header` (reference) so every surface's top band reads
- as the same height. */
.contexts-page-header {
flex: 0 0 auto;
padding: 14px 22px 12px;
@@ -11399,9 +11413,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.contexts-project-select .ai-select-option-icon,
#contexts-project-select-listbox .ai-select-option-icon { color: var(--muted); }
#contexts-project-select-listbox .ai-select-item.active .ai-select-option-icon { color: var(--primary-text); }
-
-/* Library tree icons are intentionally larger than inline attachment icons:
- they are the primary file-type signal in this navigation surface. */
.contexts-tree .skill-tree-node {
font-size: 13px;
}
@@ -11413,8 +11424,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
width: 20px;
height: 20px;
}
-
-/* Image file viewer — centered image with caption. */
.ctx-viewer-image-wrap {
display: flex;
flex-direction: column;
@@ -11436,8 +11445,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-align: center;
word-break: break-all;
}
-
-/* PDF viewer — full-height iframe, Chromium's PDFium handles rendering. */
.ctx-viewer-pdf,
.ctx-viewer-office {
width: 100%;
@@ -11446,9 +11453,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #fafafa;
display: block;
}
-
-/* DOCX inline preview (mammoth HTML output). Reuse markdown-body typography
- but constrain width for readability. */
.ctx-viewer-docx {
padding: 20px 32px;
max-width: 840px;
@@ -11476,8 +11480,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin-top: 18px;
margin-bottom: 8px;
}
-
-/* PDF / docx / other binary file viewer — card with icon + "open in system". */
.ctx-viewer-binary {
display: flex;
flex-direction: column;
@@ -11508,10 +11510,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
max-width: 420px;
line-height: 1.6;
}
-
-/* KB status chip on 已整理 tree file rows. Sits right before the delete
- button (which has margin-left:auto). Invisible when file is `ready` —
- we only render chrome for the interesting states. */
.skill-tree-node .ctx-kb-chip {
margin-left: auto;
display: inline-flex;
@@ -11544,10 +11542,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: inline-block;
}
@keyframes ctx-kb-spin { to { transform: rotate(360deg); } }
-
-/* Per-row ⋯ menu trigger (folders + files). Hidden by default, hover-only —
- reveal when row is hovered, when menu is open, or for the root header
- button (commenter / always-visible entry point). */
.ctx-row-menu-btn {
flex-shrink: 0;
margin-left: auto;
@@ -11573,10 +11567,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.ctx-root-menu-btn {
font-size: 18px;
}
-
-/* Per-row ⋯ popover menu — fixed position; mirrors agent-row-menu visual. */
.ctx-row-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 1000;
min-width: 156px;
max-width: 240px;
@@ -11610,10 +11603,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.ctx-row-menu-item.is-disabled:hover { background: transparent; }
.ctx-row-menu-item.is-danger { color: #dc2626; }
.ctx-row-menu-item.is-danger:hover { background: #fef2f2; }
-
-/* Drag-drop visuals — applied to row when something is dragged over it,
- to the source row while it's being dragged, and to the tree container
- itself when its empty area is the drop target (= move to root). */
.skill-tree-node.is-drag-over {
outline: 1px solid var(--primary);
outline-offset: -1px;
@@ -11651,9 +11640,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
outline-offset: -6px;
background: var(--surface);
}
-
-/* Multi-select stays out of row menus: two or more selected entries surface
- one compact action bar with the same single consolidated transfer action. */
.library-batch-bar {
flex: 0 0 auto;
display: flex;
@@ -11686,9 +11672,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.library-batch-clear:hover { background: var(--surface-2); color: var(--text); }
.library-batch-clear-icon { width: 14px; height: 14px; }
-
-/* One shared Move/Copy dialog for global and project Libraries. */
-.library-transfer-overlay { z-index: 13000; }
+.library-transfer-overlay { --orkas-ui-layer: overlay; z-index: 13000; }
.modal.library-transfer-dialog {
width: min(620px, 92vw);
max-height: min(720px, 88vh);
@@ -11792,10 +11776,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 12px 18px 16px;
border-top: 1px solid var(--border);
}
-
-/* Inline rename input in the tree — replaces the file's label span after
- "+ 文本" creates an 未命名.md, so the user can retype the name without a
- separate modal. Styled to visually continue the label's footprint. */
.ctx-tree-rename-input {
flex: 1;
min-width: 0;
@@ -11808,8 +11788,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--text);
outline: none;
}
-
-/* Library picker — modal for "save into Library at this location". */
.kb-picker { min-width: 420px; max-width: 520px; }
.kb-picker-tree {
max-height: 260px;
@@ -11950,11 +11928,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 14px;
line-height: 1.7;
}
-
-/* In edit/preview mode the markdown surface owns the remaining viewer
- height. Keep the toolbar at the top and stretch the editor to the bottom
- instead of leaving the body at its 380px content minimum. This shared rule
- covers both the global Library pane and the project Library modal. */
.contexts-viewer-body:has(.ctx-editor-toolbar) {
display: flex;
flex-direction: column;
@@ -12013,8 +11986,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-color: var(--primary, #3b82f6);
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.12);
}
-
-/* KB new-text markdown editor — toolbar above the textarea / preview */
.ctx-editor-toolbar {
display: flex;
align-items: center;
@@ -12079,10 +12050,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-height: 380px;
overflow: auto;
}
-
-/* KB todo list — interactive checkboxes inside the read-mode markdown view.
- `renderMarkdown` already emits `<li class="task-item"><input type=checkbox>
- …</li>`; contexts.js layers click handling + the `is-done` toggle on top. */
.ctx-viewer-md li.task-item { list-style: none; margin-left: -16px; }
.ctx-viewer-md li.task-item input[type="checkbox"] {
margin-right: 6px;
@@ -12095,8 +12062,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted, #94a3b8);
text-decoration: line-through;
}
-
-/* ─── Agents ─── */
.agents-container {
flex: 1;
display: flex;
@@ -12189,13 +12154,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 11px;
color: var(--muted);
}
-
-/* ─── Modal ─── */
.modal-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.5);
+ --orkas-ui-layer: overlay;
z-index: 100;
align-items: center;
justify-content: center;
@@ -12217,9 +12181,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.modal h3 { margin: 0; font-size: 16px; line-height: 1.4; font-weight: 600; }
-
-/* Shared dialog chrome. Workflow dialogs may choose a wider body, but title,
- body copy, dismiss controls, and footer actions use one visual contract. */
.modal-header {
display: flex;
align-items: flex-start;
@@ -12251,9 +12212,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 14px;
line-height: 1.6;
}
-
-/* Shared close control for modal dialogs. Keep position/layout on the
- individual dialog; dimensions, icon, hover, and focus stay global. */
.modal-close-btn {
flex: 0 0 auto;
width: 32px;
@@ -12384,7 +12342,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.agent-cli-select-row {
display: flex;
- align-items: center;
+ align-items: flex-start;
gap: 10px;
min-width: 0;
}
@@ -12452,11 +12410,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
spilling out of its button. */
overflow-wrap: anywhere;
}
-
-/* Choice list for a question dialog. Same visual contract as the native
- question card in the composer dock (`.chat-input-form .form-field-checkgroup`):
- options wrap, each one is as wide as its own label, and they stay separate
- from cancel/confirm on the action row. */
.ui-dialog-choices {
display: flex;
flex-wrap: wrap;
@@ -12475,8 +12428,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.modal-actions .ui-choice-leading {
margin-right: auto;
}
-
-/* ── Skill-modal import-method tabs ───────────────────────────────────── */
.skill-modal-tabs {
display: flex;
gap: 4px;
@@ -12517,10 +12468,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
word-break: break-all;
overflow-wrap: anywhere;
}
-
-/* Custom confirm/alert dialog (replaces native confirm/alert).
- Must sit above full-screen app overlays. */
-.ui-dialog-overlay { z-index: 13000; }
+.ui-dialog-overlay { --orkas-ui-layer: overlay; z-index: 13000; }
.ui-dialog {
min-width: 320px;
max-width: 480px;
@@ -12557,11 +12505,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-y: auto;
flex-shrink: 0;
}
-
-/* Empty-credit gate. Two paid actions carry equal weight, the referral entry is
- a separate free path (its own band, not a fourth button), and dismissal drops
- to a quiet footer. Scoped to this dialog so shared `.ui-dialog` chrome and
- every other confirm/alert keep their current look. */
.credits-empty-dialog .credits-empty-head {
align-items: flex-start;
}
@@ -12675,8 +12618,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
outline: 2px solid var(--primary);
outline-offset: 2px;
}
-
-/* Narrow window: the invite row stacks so the action keeps its full label. */
@media (max-width: 560px) {
.credits-empty-invite {
flex-wrap: wrap;
@@ -12763,6 +12704,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
position: absolute;
left: 0;
top: 0;
+ --orkas-ui-layer: overlay;
z-index: 13001;
width: 360px;
max-width: calc(100vw - 24px);
@@ -12830,8 +12772,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
width: min(360px, calc(100vw - 24px));
}
}
-
-/* ─── Buttons ─── */
.btn {
padding: 8px 16px;
border: 1px solid var(--border);
@@ -12894,9 +12834,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
opacity: 0.85;
animation: marketplace-upload-spin 0.8s linear infinite;
}
-
-/* Detail-page action button row (shared across skills / agents / contexts).
- `margin-left: auto` keeps buttons right-aligned even after flex-wrap. */
.detail-actions {
display: flex;
gap: 6px;
@@ -12905,8 +12842,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
align-items: center;
}
.detail-actions.is-hidden { display: none; }
-
-/* ─── Empty State ─── */
.empty {
display: flex;
align-items: center;
@@ -12918,14 +12853,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.muted { color: var(--muted); }
-
-/* ─── Access denied banner (shown when password is missing/wrong) ─── */
.access-denied {
display: none;
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.82);
backdrop-filter: blur(6px);
+ --orkas-ui-layer: overlay;
z-index: 200;
align-items: center;
justify-content: center;
@@ -12965,9 +12899,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12.5px;
}
-/* ─── Agents panel (mirrors Skills three-column layout) ─── */
-/* ─── Agents grid view (mirrors skills grid) ────────────────────────── */
-
.agents-grid-view {
flex: 1;
display: flex;
@@ -13060,8 +12991,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 13px;
}
-/* ─── Agent card ─── */
-
.agent-card {
position: relative;
display: flex;
@@ -13152,6 +13081,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.agent-card-more {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 12px;
right: 12px;
@@ -13208,14 +13138,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin-top: 8px;
flex-wrap: wrap;
}
-/* When no chip is present, the play button still hugs the right edge.
- `margin-left: auto` plays nice with the absent-chip case. */
.agent-card-actions > .agent-card-use { margin-left: auto; }
-/* `.agent-card-use` shared with `.skill-card-use` / `.btn-icon-use` above. */
-
-/* ─── Agents detail view (replaces grid) ────────────────────────────── */
-
.agents-detail-view {
flex: 1;
display: flex;
@@ -13232,6 +13156,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.agent-row-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 1000;
min-width: 96px;
background: #fff;
@@ -13276,10 +13201,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-height: 0;
overflow-y: auto;
}
-
-/* Compact header matches the marketplace detail density (.marketplace-detail-header):
- tighter padding + title 16px so the in-app agent / skill detail and the marketplace
- detail read as one chrome family. Body sections below keep their original spacing. */
.agents-detail-header {
padding: 14px 20px;
border-bottom: 1px solid var(--border);
@@ -13348,8 +13269,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.agents-detail-name-input[hidden] {
display: none;
}
-
-/* Source chip stays glued to the name; actions hug the right via `margin-left:auto`. */
.agents-detail-title-row > .agents-detail-source,
.agents-detail-title-row > .agents-detail-source-row { flex-shrink: 0; }
.agents-detail-title-row > .detail-actions { flex-shrink: 0; margin-left: auto; }
@@ -13360,10 +13279,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.agents-detail-name.is-editing:focus {
box-shadow: 0 0 0 2px var(--primary) inset;
}
-
-/* Sits on the same row as the agent name, mirroring the skill detail
- header layout (.skills-doc-source). The title row centers all
- children, so no per-chip align-self override is needed. */
.agents-detail-source {
font-size: 11px;
font-weight: 600;
@@ -13380,10 +13295,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.agents-detail-source.is-builtin { border-color: rgba(100, 116, 139, 0.22); background: rgba(100, 116, 139, 0.04); color: #475569; }
.agents-detail-source.is-custom { border-color: color-mix(in srgb, var(--primary) 30%, transparent); background: color-mix(in srgb, var(--primary) 7%, var(--surface)); color: var(--primary-text); }
-
-/* ── Body: simple vertical stack of sections, each full-width ── */
-/* Padding matches `.skills-detail-content` + `.marketplace-detail-header` so the three
- detail surfaces (app agent / app skill / marketplace preview) share one chrome density. */
.agents-detail-body {
flex: 1;
min-height: 0;
@@ -13399,9 +13310,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
gap: 6px;
}
-
-/* The workflow section stretches to fill remaining vertical space so the
- box itself gets bigger, not the surrounding chrome. */
.agents-detail-section-workflow {
flex: 1;
min-height: 200px;
@@ -13417,9 +13325,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
letter-spacing: 0.6px;
color: var(--primary-text);
}
-
-/* Shared look-and-feel for the two editable text boxes. Only dimensions
- differ — workflow is bigger than description. */
.agents-detail-desc,
.agents-detail-workflow {
width: 100%;
@@ -13432,23 +13337,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(15, 23, 42, 0.02);
border: 1px solid transparent;
}
-
-/* Description is plain text — keep newlines visible. Always expands to full
- content height; the outer `.agents-detail-body` handles overflow. Three-
- 段式 descriptions are commonly 5-10 lines and need to be readable in one
- go (no inner scroll). */
.agents-detail-desc { white-space: pre-wrap; }
-
-/* Workflow is markdown-rendered in readonly mode (normal flow), but raw text
- in edit mode — only then do we need pre-wrap. Workflow keeps its own
- scrollbar because it can be long (20-100 lines) and we don't want the whole
- page to grow that much. */
.agents-detail-workflow { overflow-y: auto; }
.agents-detail-workflow.is-editing { white-space: pre-wrap; }
.agents-detail-workflow::-webkit-scrollbar { width: 4px; }
.agents-detail-workflow::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.15); border-radius: 3px; }
-
-/* Workflow: fills its section. */
.agents-detail-workflow {
flex: 1;
min-height: 0;
@@ -14344,8 +14237,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
gap: 8px;
}
}
-
-/* Edit-mode treatment (same for both fields). */
.agents-detail-desc.is-editing,
.agents-detail-workflow.is-editing {
padding: 12px;
@@ -14364,8 +14255,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: #9ca3af;
font-style: italic;
}
-
-/* ─── Agent inline edit chat column ─── */
.agents-chat-col {
width: 380px;
flex-shrink: 0;
@@ -14461,16 +14350,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
width: 14px;
height: 14px;
}
-
-/* ═══ Settings panel ═══════════════════════════════════════════════════ */
-
-/* ── Settings page shell ────────────────────────────────────────────────
- Layout (2026-09 redesign): a non-scrolling nav (title + horizontal tabs)
- above a scrolling body. Every tab pane is a `.settings-page` made of
- `.settings-section`s; each section is a `.settings-section-title` plus one
- `.settings-sheet` — a bordered white surface whose `.settings-row`s are
- separated by hairlines instead of nested cards. Keep all rules namespaced
- under `.settings-*` so the redesign never leaks into other panels. */
.settings-container {
flex: 1 1 auto;
min-height: 0;
@@ -14500,8 +14379,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 24px 0 64px;
}
.settings-tab-pane[hidden] { display: none; }
-
-/* Legacy group label (still used by dynamically rendered sections). */
.settings-section-head {
font-size: 11px;
font-weight: 600;
@@ -14511,8 +14388,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: 24px 4px 8px;
}
.settings-section-head:first-child { margin-top: 0; }
-
-/* Page title row. */
.settings-header {
display: flex;
align-items: flex-end;
@@ -14534,10 +14409,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1.5;
margin-top: 4px;
}
-
-/* Horizontal category tabs (TOKENS/PATTERNS P7). The nav carries the bottom
- border; the active tab overlaps it with a 2px primary underline. Arrow-key
- switching lives in sync_settings.js::initSettingsTabs. */
.settings-tabs {
display: flex;
gap: 28px;
@@ -14576,8 +14447,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
height: 16px;
flex: 0 0 auto;
}
-/* Generic inline status dot. Sidebar footer buttons draw their dot on the
- label span so their own ::after can remain reserved for the status badge. */
.has-dot:not(.sidebar-footer-btn)::after {
content: '';
display: inline-block;
@@ -14590,8 +14459,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.has-dot:not(.sidebar-footer-btn).is-red::after { background: var(--danger); }
.has-dot:not(.sidebar-footer-btn).is-orange::after { background: var(--warn); }
-
-/* Per-pane heading. */
.settings-page-head { margin-bottom: 22px; }
.settings-page-head h1 {
margin: 0;
@@ -14607,8 +14474,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1.5;
color: var(--muted);
}
-
-/* Section = title row + sheet. */
.settings-section { margin-top: 26px; }
.settings-section:first-child,
.settings-page-head + .settings-section,
@@ -14637,11 +14502,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
}
.settings-section-hint { font-size: 12px; color: var(--muted); white-space: nowrap; }
-/* A standalone section-title (e.g. #settings-section-cloud) that precedes a
- section: pull the section up so the pair reads as one block, and keep the
- usual section gap above the title itself. */
-
-/* Sheet: bordered surface; rows divide with hairlines. */
.settings-sheet {
background: var(--surface);
border: 1px solid var(--border);
@@ -14650,8 +14510,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.settings-sheet[hidden] { display: none; }
.settings-sheet > .settings-empty { padding: 22px 18px; text-align: center; }
-
-/* Inline note (e.g. "keys stay on this device"). */
.settings-note {
display: flex;
align-items: flex-start;
@@ -14667,14 +14525,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-note-icon { width: 15px; height: 15px; flex: 0 0 auto; margin-top: 2px; color: var(--muted); }
.settings-foot-note { margin: 10px 2px 0; font-size: 12px; line-height: 1.5; color: var(--muted); }
-/* Inline alert rows (subscription warning, credits warning). */
-
-/* Quiet link-style action for credit details, storage details, and API docs. */
-
-/* Pill tag (version, plan). */
-
-/* Meter (credits / storage). */
-
.settings-mono {
display: block;
margin-top: 6px;
@@ -14684,11 +14534,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
overflow-wrap: anywhere;
}
.settings-mono:empty { display: none; }
-
-/* ── Account pane ─────────────────────────────────────────────────────── */
-/* Paid-tier badge — gradient per PATTERNS anti-pattern exception. */
.settings-row-copy > .settings-project-usage-list { display: grid; gap: 6px; margin-top: 12px; }
.settings-project-usage-list:empty { display: none; }
+.settings-project-usage-group { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; min-width: 0; }
+.settings-project-usage-group + .settings-project-usage-group { margin-top: 10px; }
+.settings-project-usage-heading, .settings-project-usage-group > span { grid-column: 1 / -1; }
+.settings-project-usage-heading { color: var(--text-2); font-weight: 600; }
.settings-project-usage-item {
display: flex; align-items: center; gap: 10px; width: 100%; min-width: 0;
padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm);
@@ -14700,27 +14551,19 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-project-usage-icon { display: flex; flex: 0 0 auto; color: var(--primary); font-size: 17px; }
.settings-project-usage-name { flex: 1; min-width: 0; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.settings-project-usage-count { flex: 0 0 auto; color: var(--text-2); font-size: 12px; font-variant-numeric: tabular-nums; }
-/* Rows inside the benefits wrapper always follow the status row, so they all
- carry a top hairline (the sibling rule below can't see across the wrapper). */
-
-
-
-/* Invite card (account tab). */
-/* Sync status pill (data tab). Variants: default = success / is-syncing =
- primary / is-error = danger / is-paused = neutral. Follows P6 pill shape. */
-/* Single grid hoisted to the section so all rows share the same column
- * tracks (otherwise per-row autos sized each row independently and the
- * size column didn't right-align across rows). Two columns now: name
- * (1fr, left-aligned) and size (auto, right-aligned). */
-/* `display: contents` makes each row's children promote to direct grid
- * items of the section, so the three columns line up across every row. */
-
-/* Expanded conflict: local↔cloud line diff. */
.settings-recycle-body {
display: flex;
flex-direction: column;
gap: 10px;
}
+.settings-recycle-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 8px 18px;
+ border-bottom: 1px solid var(--border);
+}
.settings-recycle-scroll {
max-height: min(320px, 42vh);
min-height: 72px;
@@ -14800,6 +14643,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-width: 0;
font-size: 12px;
}
+.settings-recycle-detail-row.is-auto-task {
+ grid-template-columns: minmax(0, 1fr);
+ padding: 3px 0;
+}
.settings-recycle-detail-category {
color: var(--muted);
white-space: nowrap;
@@ -14842,11 +14689,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: -4px 4px 12px;
line-height: 1.5;
}
-/* ── Rows ───────────────────────────────────────────────────────────────
- `.settings-row` = one setting: copy (title + description) on the left,
- control / action on the right. Inside a `.settings-sheet` rows divide with a
- hairline; a row only draws its top line when a *visible* row precedes it, so
- JS-hidden rows (hidden attribute) never leave a stray double border. */
.settings-row {
display: flex;
align-items: center;
@@ -14874,9 +14716,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-row-copy > .settings-status { display: block; margin-top: 3px; font-size: 12px; line-height: 1.5; }
.settings-row-copy > .settings-status:empty { display: none; }
.settings-row > .ai-select.settings-row-select { flex: 0 0 auto; width: 200px; max-width: 45%; }
-/* Stacked variant: control sits under the copy (radio lists). */
.settings-row-stack { flex-direction: column; align-items: stretch; gap: 12px; }
-/* Whole-row button (memory entry). */
.settings-row-btn {
width: 100%;
border: 0;
@@ -14893,17 +14733,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-sheet .memory-entry-card:hover { border-color: transparent; }
.settings-sheet .memory-entry-icon { width: 34px; height: 34px; }
.settings-sheet .memory-entry-title { font-size: 13px; }
-
-/* Switch — reuse the global .toggle-switch pill, brand colours in settings. */
.settings-switch { gap: 0; }
.settings-switch input[type="checkbox"] { width: 36px; height: 20px; }
.settings-switch input[type="checkbox"]::after { top: 2px; left: 2px; width: 16px; height: 16px; }
.settings-switch input[type="checkbox"]:checked { background: var(--primary); box-shadow: inset 0 0 0 1px rgba(91, 87, 214, 0.5); }
.settings-switch input[type="checkbox"]:checked:hover { background: var(--primary-hover); }
.settings-switch input[type="checkbox"]:checked::after { transform: translateX(16px); }
-
-/* Legacy card group — still used by the feedback dialog and stripped OSS
- builds; keep the chrome so nothing regresses outside the redesigned panes. */
.settings-group {
background: var(--surface);
border: 1px solid var(--border);
@@ -14932,11 +14767,22 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding-top: 16px;
border-top: 1px solid var(--border);
}
-
-/* ── Data pane ────────────────────────────────────────────────────────── */
.settings-data-root-row .settings-mono { margin-top: 8px; }
-
-/* ── General pane ─────────────────────────────────────────────────────── */
+#settings-task-cleanup-age { flex: 0 0 160px; }
+#settings-task-cleanup-body > .settings-row,
+#settings-task-cleanup-body > .settings-cleanup-list { border-top: 1px solid var(--border); }
+.settings-cleanup-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
+.settings-cleanup-list { max-height: 300px; overflow-y: auto; padding: 8px 18px; }
+.settings-cleanup-item { display: flex; align-items: center; gap: 10px; padding: 10px 0; font-size: 13px; }
+.settings-cleanup-item + .settings-cleanup-item { border-top: 1px solid var(--border); }
+.settings-cleanup-item input { flex: 0 0 auto; accent-color: var(--primary); }
+.settings-cleanup-title { flex: 1; min-width: 0; overflow-wrap: anywhere; font-size: 13px; }
+.settings-cleanup-item time { flex: 0 0 auto; }
+@media (max-width: 700px) {
+ #settings-task-cleanup .settings-row { flex-wrap: wrap; gap: 12px; }
+ #settings-task-cleanup-age { flex-basis: 100%; }
+ #settings-task-cleanup .settings-cleanup-actions { margin-inline-start: auto; }
+}
.settings-mode-list { display: flex; flex-direction: column; gap: 4px; margin: -2px 0 0; }
.settings-mode-opt {
display: flex;
@@ -14951,16 +14797,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-mode-desc { font-size: 12px; color: var(--text-2); line-height: 1.4; }
.settings-mode-opt:has(input:checked) .settings-mode-label { color: var(--primary-text); }
.settings-mode-opt:has(input:checked) { background: rgba(91, 87, 214, 0.06); }
-
-@media (max-width: 640px) {
- .settings-row { flex-wrap: wrap; padding: 14px 16px; }
- .settings-row > .ai-select.settings-row-select { max-width: 100%; width: 100%; }
- .settings-nav { padding: 18px 20px 0; }
- .settings-body { padding: 0 20px; }
- .settings-tabs { gap: 18px; }
-}
-
-/* Old inline toggle label (kept for any remaining `label.settings-toggle`). */
.settings-lang-opt {
display: inline-flex;
align-items: center;
@@ -14989,8 +14825,14 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1.5;
}
.settings-task-notification-permission .btn { flex: 0 0 auto; }
-
-/* ── Models pane ──────────────────────────────────────────────────────── */
+@media (max-width: 640px) {
+ .settings-project-usage-group { grid-template-columns: minmax(0, 1fr); }
+ .settings-row { flex-wrap: wrap; padding: 14px 16px; }
+ .settings-row > .ai-select.settings-row-select { max-width: 100%; width: 100%; }
+ .settings-nav { padding: 18px 20px 0; }
+ .settings-body { padding: 0 20px; }
+ .settings-tabs { gap: 18px; }
+}
.settings-subnav {
display: flex;
gap: 22px;
@@ -15026,8 +14868,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-list-head .settings-section-sub { margin-top: 3px; }
.settings-add-btn { flex: 0 0 auto; white-space: nowrap; }
.settings-add-btn::before { content: '+'; margin-right: 4px; font-weight: 600; }
-
-/* Add dialog (#settings-add-modal). */
.settings-add-modal { width: min(480px, 92vw); }
.settings-add-modal-body { margin-top: 2px; }
.settings-add-form[hidden] { display: none; }
@@ -15043,7 +14883,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-form-row > label .form-hint { display: block; margin: 2px 0 0; }
.settings-form-status { min-height: 18px; margin-top: 2px; }
.settings-add-form-actions { margin-top: 14px; }
-/* Shared input style — used inside modals too. */
.form-input {
width: 100%;
padding: 10px 12px;
@@ -15167,6 +15006,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.feedback-image-item.has-preview.is-uploading .feedback-image-thumb::after {
content: "";
+ --orkas-ui-layer: chrome;
position: absolute;
width: 22px;
height: 22px;
@@ -15201,6 +15041,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: #b91c1c;
}
.feedback-image-remove {
+ --orkas-ui-layer: chrome;
position: absolute;
right: 6px;
bottom: 5px;
@@ -15218,8 +15059,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #f1f5f9;
color: #0f172a;
}
-
-/* ── Custom dropdown (AiSelect) ────────────────────────────────────────── */
.ai-select {
position: relative;
display: inline-block;
@@ -15278,8 +15117,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
top: calc(100% + 4px);
left: 0;
right: 0;
- /* Base layer for body-portaled popovers. `_aiSelectMount` also raises
- this dynamically against currently open app overlays. */
+ --orkas-ui-layer: overlay;
z-index: 14000;
background: #fff;
border: 1px solid var(--border, #e5e7eb);
@@ -15334,8 +15172,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
font-size: 12px;
}
-
-/* Compact AiSelect — inline use inside narrow rows like entry pickers. */
.ai-select-compact {
min-width: 120px;
display: inline-block;
@@ -15363,11 +15199,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.ai-select-compact .ai-select-caret { width: 10px; height: 10px; }
.ai-select-compact .ai-select-popover { min-width: 180px; }
-
-/* ── Entries list (priority, drag-reorderable) ───────────────────────────
- Rendered by settings.js for the five model lists. Since the 2026-09
- redesign the list is a `.settings-sheet`: rows are flat, divided by
- hairlines, with rank → copy → actions → ↑/↓ sort buttons. */
.settings-empty {
color: var(--muted);
font-size: 13px;
@@ -15401,7 +15232,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
cursor: grab;
}
.entry-row:hover { border-color: var(--border-strong); }
-/* P4 active variant — the default row keeps a soft primary tint. */
.entry-row.is-default {
border-color: rgba(91, 87, 214, 0.18);
background: var(--primary-soft);
@@ -15547,11 +15377,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.entry-actions .icon-btn.danger { color: var(--danger); }
.entry-actions .icon-btn.danger:hover { background: rgba(220, 38, 38, 0.10); }
.entry-actions .btn.btn-danger { color: var(--danger); }
-
-/* Keyboard alternative to drag-reorder: ↑ / ↓ move one slot via the same
- reorder IPC (settings.js::_settingsMoveEntry). */
-
-/* ── Add-account modal ─────────────────────────────────────────────────── */
.add-account-modal { width: min(520px, 92vw); }
.add-account-body { margin: 12px 0; }
.method-chooser {
@@ -15587,13 +15412,12 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin-left: 0;
margin-bottom: 12px;
}
-
-/* ── OAuth flow modal ──────────────────────────────────────────────────── */
.oauth-flow-modal {
position: relative;
width: min(520px, 92vw);
}
.oauth-flow-close-btn {
+ --orkas-ui-layer: chrome;
position: absolute;
top: 18px;
right: 18px;
@@ -15646,15 +15470,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 13px;
}
.oauth-input:focus { outline: none; border-color: var(--primary, #2563eb); }
-
-/* :disabled — the shared .btn already carries padding / radius / color from
- line 3100 block; keep only the semantic state here. */
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
-
-/* ─── Devtools (仅开发环境) ─────────────────────────────────────────────── */
.devtools-container {
display: flex;
flex-direction: column;
@@ -15666,8 +15485,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.devtools-header h2 { margin: 0 0 4px; font-size: 18px; }
.devtools-sub { font-size: 12px; color: var(--muted); margin-bottom: 4px; }
-
-/* Cards — 每个子模块一张卡片,纵向排布。 */
.devtools-card {
border: 1px solid var(--border, #e5e7eb);
border-radius: 10px;
@@ -15701,8 +15518,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex: 1 1 auto;
}
.devtools-card-actions { display: flex; gap: 6px; margin-left: auto; }
-
-/* 系统信息区 */
.devtools-sysinfo-grid {
display: grid;
grid-template-columns: auto 1fr;
@@ -15720,11 +15535,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
white-space: nowrap;
}
-
-/* 刷新 / 重启区 */
.devtools-relaunch-row { display: flex; }
-
-/* LLM archive list/detail layout; left column aligns with skills, agents, and library. */
.devtools-body {
display: grid;
grid-template-columns: 280px 1fr;
@@ -15803,12 +15614,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: 0;
}
.dev-only-btn { opacity: 0.75; }
-
-/* ── Reusable toggle switch (per-user enabled flag for agents / skills) ──
- iOS-style pill: 32×18, soft inner-shadow off-track, blue-600 on-track,
- 8% drop-shadow on the thumb, 0.18s ease-out for both colour + thumb travel.
- Sized down (28×16) when nested in compact contexts via `.toggle-switch.is-compact`
- — used on skill list cards where we omit the label entirely. */
.toggle-switch {
display: inline-flex;
align-items: center;
@@ -15836,6 +15641,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.toggle-switch input[type="checkbox"]::after {
content: '';
+ --orkas-ui-layer: chrome;
position: absolute;
top: 2px;
left: 2px;
@@ -15865,14 +15671,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
cursor: not-allowed;
}
.toggle-switch .toggle-label { white-space: nowrap; }
-
-/* Compact variant for list-card placement — pure switch, no label, smaller. */
.toggle-switch.is-compact { gap: 0; }
.toggle-switch.is-compact input[type="checkbox"] { width: 28px; height: 16px; }
.toggle-switch.is-compact input[type="checkbox"]::after { width: 12px; height: 12px; }
.toggle-switch.is-compact input[type="checkbox"]:checked::after { transform: translateX(12px); }
-
-/* Visual demotion for any list / detail node bound to a disabled component. */
.is-disabled .toggle-switch .toggle-label { color: #9ca3af; }
.detail-disabled-banner {
display: block;
@@ -15884,8 +15686,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border: 1px solid #fde68a;
font-size: 12px;
}
-
-/* ── Agent orchestrator + skill allowlist (subagent execution) ── */
.agents-detail-section-orchestrator .agents-detail-toggle {
display: inline-flex;
align-items: center;
@@ -15902,8 +15702,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
cursor: not-allowed;
opacity: 0.6;
}
-
-/* ── Devtools archive list ── */
.devtools-list-badge {
display: inline-block;
font-size: 10px;
@@ -15913,14 +15711,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1.5;
vertical-align: middle;
}
-/* Session-kind badges (agent-edit / skill-edit / KB image vision). conv (主对话)
- intentionally has no badge — it's the default. */
.devtools-list-badge.is-kind-agent { background: #fef3c7; color: #92400e; }
.devtools-list-badge.is-kind-skill { background: #ecfccb; color: #4d7c0f; }
.devtools-list-badge.is-kind-extract-img { background: #fce7f3; color: #9d174d; }
.devtools-list-badge.is-kind-cli { background: #eef2ff; color: #3730a3; }
-
-/* ── Devtools skill-metrics table ── */
.devtools-skill-metrics-summary {
padding: 6px 14px 8px 14px;
font-size: 11px;
@@ -15947,6 +15741,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.devtools-skill-metrics-table th {
position: sticky;
top: 0;
+ --orkas-ui-layer: chrome;
z-index: 1;
font-weight: 600;
font-size: 10.5px;
@@ -16010,11 +15805,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: #fff;
border-color: transparent;
}
-
-/* ─── MathJax tweaks (chat bubbles) ────────────────────────────────────────
- Display math on long formulas exceeds bubble width; give it a horizontal
- scrollbar instead of clipping / stretching the bubble. Inline math just
- follows the line. `mjx-container` is MathJax 3's top-level wrapper. */
.markdown-body mjx-container[display="true"] {
overflow-x: auto;
overflow-y: hidden;
@@ -16024,8 +15814,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.markdown-body mjx-container {
font-size: 1em;
}
-
-/* ─── Avatar (icon-on-color circle) ───────────────────────────────────── */
.avatar-circle {
display: inline-flex;
align-items: center;
@@ -16053,8 +15841,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.agent-card-avatar { /* nothing extra — sized inline by renderAvatarHtml */ }
.agents-detail-avatar { /* same */ }
-
-/* Detail header tweak: align avatar + title vertically and make room. */
.agents-detail-avatar-slot {
display: inline-flex;
align-items: center;
@@ -16069,6 +15855,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 0;
}
.agents-detail-avatar-edit-badge {
+ --orkas-ui-layer: chrome;
position: absolute;
right: -4px;
bottom: -2px;
@@ -16086,10 +15873,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
height: 11px;
stroke-width: 2.4;
}
-
-/* ─── Avatar picker popover ───────────────────────────────────────────── */
.avatar-picker {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 10000;
display: flex;
flex-direction: column;
@@ -16150,11 +15936,15 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
outline-offset: 2px;
transform: scale(1.05);
}
-
-/* Runtime selector lives at the top of the detail body. Keep it aligned with
- the category/output selectors so the detail form reads as one system. */
-.agents-detail-runtime { display: block; }
-.agents-detail-runtime-select { max-width: 280px; }
+.agents-detail-runtime {
+ display: flex;
+ align-items: flex-start;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+.agents-detail-runtime-select {
+ flex: 0 0 200px; max-width: 280px;
+}
.agents-detail-runtime-select .ai-select-trigger { background: #fff; }
.agents-detail-cli-settings { max-width: 720px; }
@@ -16239,10 +16029,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex: 0 0 auto;
margin-left: auto;
}
-
-/* Wrapper for the multi-button cluster on the right side of agents-grid-header /
- skills-grid-header. Keeps the entries glued together while the parent
- header's `justify-content: space-between` still separates title from cluster. */
.header-actions { display: flex; gap: 8px; align-items: center; }
.header-entry-actions {
gap: 6px;
@@ -16268,8 +16054,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.header-entry-btn:active { background: var(--primary-soft); }
.header-entry-btn:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
.header-entry-icon { width: 14px; height: 14px; flex-shrink: 0; }
-/* The CLI entry names its subjects on a second line — "connect an agent" alone
- never told anyone this meant Claude Code / Codex. */
.header-entry-copy { display: flex; flex-direction: column; align-items: flex-start; }
.header-entry-copy small {
font-size: 10px;
@@ -16277,10 +16061,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--text-2);
line-height: 1.2;
}
-/* AI Team page header: bold title with a muted definition subtitle inline to
- its RIGHT (baseline-aligned); action buttons stay right-aligned. The title
- never shrinks; the subtitle truncates so a long definition can't push the
- buttons off the row. */
.agents-grid-header-titles { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
.agents-grid-title { flex-shrink: 0; }
.agents-grid-subtitle {
@@ -16293,9 +16073,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
white-space: nowrap;
}
-
-/* ─── Marketplace panel ─── */
-/* Full-page panel mirroring .agents-grid-view sizing: fill the parent .panel column. */
.marketplace-view {
flex: 1;
display: flex;
@@ -16371,6 +16148,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 13px;
}
.marketplace-search-clear {
+ --orkas-ui-layer: chrome;
position: absolute;
right: 5px;
top: 50%;
@@ -16401,8 +16179,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-bottom: 1px solid rgba(0,0,0,0.04);
flex-shrink: 0;
}
-/* When the chip strip is empty (e.g. agents/skills page before data loads),
- * collapse it entirely instead of showing a thin padded blank row. */
.marketplace-categories:empty { display: none; }
.marketplace-chip {
background: transparent;
@@ -16436,10 +16212,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
justify-content: center;
text-align: center;
}
-/* Reconcile-status banner (boot-time marketplace sync). Friendly muted-blue palette — the
- yellow / warning tint was misread as "something's wrong" when it actually just means
- "downloading default content in the background". The banner is **embedded under the panel
- header** (after the title row, before the body) so it doesn't crowd the panel chrome. */
.marketplace-reconcile-banner {
margin: 0 20px 8px;
padding: 8px 12px;
@@ -16449,8 +16221,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12px;
line-height: 1.5;
}
-/* Inline checkbox row inside the upload dialog. Used for the "用户默认安装" toggle so dev
- can flag the item as part of the fresh-install seed set (`default_install` server flag). */
.ui-dialog-checkbox-row {
display: flex;
align-items: center;
@@ -16464,7 +16234,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
margin: 0;
cursor: pointer;
}
-/* Dev upload modal: just a centered spinner + label while the multipart POST is in flight. */
.marketplace-upload-loading {
display: flex;
flex-direction: column;
@@ -16487,9 +16256,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
@keyframes marketplace-upload-spin {
to { transform: rotate(360deg); }
}
-/* Author badge: differentiates same-name uploads. Platform = filled blue; user = outlined.
- Shared across marketplace card + agents-tab card + skills-tab card so the same badge
- reads the same everywhere a marketplace-installed item appears. */
.marketplace-card-chip.is-platform,
.agent-card-chip.is-platform,
.skill-card-chip.is-platform {
@@ -16504,14 +16270,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(100, 116, 139, 0.04);
color: #475569;
}
-/* Open-tier source badges (external packages / global folders). */
.skill-card-chip.is-global { border-color: rgba(168, 85, 247, 0.22); background: rgba(168, 85, 247, 0.04); color: #7e22ce; }
-/* Open-tier cards are read-only and non-navigable — suppress the
- hover affordance so they don't read as clickable. */
.skill-card.is-readonly { cursor: default; }
.skill-card.is-readonly:hover { border-color: var(--border); box-shadow: none; }
-
-/* Inline spinner for install/uninstall buttons. Sits to the left of the button label. */
.marketplace-btn-spinner {
display: inline-block;
width: 10px;
@@ -16527,8 +16288,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-color: rgba(100, 116, 139, 0.4);
border-top-color: rgba(100, 116, 139, 0.9);
}
-/* Match agents / skills card grids: columns are at least 280px, then share remaining
- width evenly as the app window changes. */
.marketplace-grid {
display: grid;
width: 100%;
@@ -16537,8 +16296,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 8px 0 16px;
}
.marketplace-grid:empty { display: none; }
-/* Invisible IntersectionObserver target for infinite scroll. Real preload margin comes
- from `rootMargin` in JS — this just needs to be a reliably-observable element. */
.mp-load-more-sentinel { height: 1px; width: 100%; }
.marketplace-card {
border: 1px solid rgba(0,0,0,0.08);
@@ -16588,7 +16345,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
white-space: nowrap;
}
.marketplace-card-chip.muted { border-color: rgba(100, 116, 139, 0.18); background: rgba(100, 116, 139, 0.035); color: var(--muted); }
-/* Version chip — neutral grey to distinguish from category (accent) and author (platform/user). */
.marketplace-card-chip.is-version,
.agent-card-chip.is-version,
.skill-card-chip.is-version {
@@ -16603,9 +16359,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: rgba(16, 185, 129, 0.04);
color: #047857;
}
-/* Custom-source chip — neutral grey ring, no fill, so a custom card visibly
- * differs from marketplace cards (which carry the accent-tinted category chip)
- * inside the same category group. */
.agent-card-chip.is-custom,
.skill-card-chip.is-custom {
background: transparent;
@@ -16613,12 +16366,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border: 1px solid var(--border-strong);
padding: 1px 7px;
}
-
-/* Credit tags share the outlined tag geometry but use a dedicated gold palette
- so they stay distinct from primary-theme category tags. */
-/* Footer row: chips on the left flex-1, install/uninstall button hugged to the right via
- `flex-shrink:0` so it never collapses before the chips. Replaces the old vertically-stacked
- `.marketplace-card-meta` + `.marketplace-card-actions` arrangement. */
.marketplace-card-footer {
display: flex;
align-items: center;
@@ -16628,10 +16375,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.marketplace-card-footer > .marketplace-card-meta { flex: 1; }
.marketplace-card-footer > .marketplace-card-actions { flex-shrink: 0; }
.marketplace-card-actions { display: flex; }
-
-/* ─── Detail sub-view ─── */
-/* Mirrors the grid-view layout (full-panel flex column) so swapping the two display
- styles is the only thing needed to switch between browse and detail. */
.marketplace-grid-view,
.marketplace-detail-view {
flex: 1;
@@ -16640,8 +16383,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-height: 0;
background: #fff;
}
-/* Marketplace detail header — padding mirrors `.agents-detail-header` so the in-app and
- marketplace detail pages share one chrome density. */
.marketplace-detail-header {
display: flex;
align-items: center;
@@ -16650,9 +16391,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
-/* Single-row title block: [name v1.0.0] [chip chip] all in one line. `min-width:0` lets
- long names ellipsize rather than pushing the install / delete buttons off-screen; chips
- are `flex-shrink:0` so they hug the title rather than collapsing first. */
.marketplace-detail-title-wrap { display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0; }
.marketplace-detail-title { font-size: 16px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.marketplace-detail-version { font-size: 12px; color: var(--muted); margin-left: 8px; font-weight: 400; }
@@ -16667,10 +16405,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-color: rgba(91, 87, 214, 0.38);
}
.marketplace-detail-desc { padding: 12px 20px; color: var(--muted); font-size: 13px; line-height: 1.5; }
-/* Outer body container is just a flex slot — the inner `.agents-detail-body` /
- `.skills-detail-content` (rendered by `_mpAgentDetailHtml` / `_mpSkillDetailHtml`)
- owns padding + scroll, so the marketplace preview lines up pixel-for-pixel with the
- in-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 {
@@ -16699,8 +16433,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.marketplace-section-body { font-size: 13.5px; line-height: 1.55; }
.marketplace-section-body ul { padding-left: 20px; margin: 6px 0; }
.marketplace-section-body code { padding: 1px 5px; background: rgba(0,0,0,0.05); border-radius: 3px; font-size: 12.5px; }
-
-/* Skill detail: split view (file tree left, file body right). */
.marketplace-skill-split {
display: grid;
grid-template-columns: 240px 1fr;
@@ -16745,9 +16477,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.ui-dialog-form { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }
.ui-dialog-label { font-size: 12px; color: var(--muted); }
-
-/* Custom MCP server dialog — widens the base ui-dialog for the form rows;
- the warning reuses the muted tone with a touch more separation. */
.connector-custom-dialog { width: min(480px, 92vw); }
.connector-custom-dialog .form-row { margin-bottom: 10px; }
.connector-custom-warning { font-size: 12px; margin: 4px 0 2px; }
@@ -16757,13 +16486,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
border-radius: 6px;
font-size: 13px;
}
-
-/* Interactive CLI floating panel. Used for OAuth/setup prompts that need
- live stdin while keeping secrets out of chat history. */
.interactive-cli-host {
position: fixed;
right: 18px;
bottom: 18px;
+ --orkas-ui-layer: overlay;
z-index: 12850;
display: flex;
flex-direction: column-reverse;
@@ -17039,9 +16766,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
justify-self: start;
}
}
-
-/* ─── Auto tab (modules/auto.js) ─────────────────────────── */
-/* Share the to-do page header and project switcher. */
.auto-view {
flex: 1;
display: flex;
@@ -17071,18 +16795,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
gap: 14px;
}
-
-
-/* Composer chrome via .new-chat-input-wrapper / .new-chat-input-area —
- verbatim the commander tab's landing CTA composer. Local override drops
- the 720px max-width that centers the landing version so the box spans
- the auto form's column. */
.auto-composer-wrapper { width: 100%; max-width: none; }
-
-/* Create / edit modal — reused by the auto tab AND the project-detail
- page's automation tab via `window.openAutoTaskDialog`. Sized big enough
- for the composer + schedule row + project picker without scrolling on
- normal-height screens. */
.auto-task-dialog {
min-width: min(640px, calc(100vw - 32px));
width: min(720px, calc(100vw - 32px));
@@ -17102,13 +16815,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 12px;
line-height: 1.45;
}
-.auto-scroll > .auto-sync-note,
-.project-detail-tab-panel > .auto-sync-note {
+.auto-scroll > .auto-sync-note {
padding: 0 4px 2px;
}
+.project-detail-tab-panel > .auto-sync-note {
+ padding: 0 0 12px;
+}
.auto-sync-note[hidden] { display: none; }
-
-/* Schedule row: frequency + conditional cell + time on one line. */
.auto-schedule-row {
display: flex;
flex-wrap: wrap;
@@ -17130,9 +16843,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-width: 120px;
}
.auto-schedule-cell[hidden] { display: none; }
-/* The "Time" cell holds two _aiSelectMount dropdowns (HH + MM) with a ":"
- separator — chosen over the native <input type="time"> because Chrome's
- built-in picker popup clashes with the rest of the UI. */
.auto-time-row {
display: inline-flex;
align-items: center;
@@ -17147,10 +16857,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-size: 14px;
font-weight: 600;
}
-
-/* Date controls share the same closed-state chrome and body-portaled popover
- language as AiSelect. Keeping the text field editable preserves fast
- YYYY-MM-DD entry while the calendar button provides a styled picker. */
.auto-date-picker {
position: relative;
display: inline-flex;
@@ -17185,6 +16891,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.auto-date-picker-toggle {
position: absolute;
+ --orkas-ui-layer: chrome;
z-index: 1;
top: 1px;
right: 1px;
@@ -17211,6 +16918,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.auto-date-picker-icon { width: 15px; height: 15px; }
.auto-date-picker-popover {
position: absolute;
+ --orkas-ui-layer: overlay;
z-index: 14000;
box-sizing: border-box;
padding: 10px;
@@ -17354,8 +17062,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
#auto-hourly-interval-input,
#auto-end-count-input { min-width: 112px; width: 112px; }
-
-/* Title input — full-width, matches the schedule controls' chrome. */
#auto-title-input {
width: 100%;
padding: 8px 12px;
@@ -17377,11 +17083,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
#auto-end-select,
#auto-weekday-select,
#auto-monthly-day-select { min-width: 140px; }
-
-/* Enabled checkbox row. `.form-row label` would render display:block with a
- 6px margin-bottom — the chained specificity below (.form-row +
- .auto-enabled-label) wins so the label sits inline with the checkbox
- and the gap is the only spacing between them. */
.form-row .auto-enabled-label {
display: inline-flex;
align-items: center;
@@ -17400,7 +17101,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
accent-color: var(--primary);
cursor: pointer;
}
-/* The selected project's automations read as cards under the shared scope chips. */
.auto-list {
display: flex;
flex-direction: column;
@@ -17424,8 +17124,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
font-size: 12.5px;
}
-/* Cards also appear in the project detail Automation tab. Clicking one reveals
- its run history. */
.auto-row {
padding: 14px 16px;
display: flex;
@@ -17439,7 +17137,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.auto-row:hover { border-color: var(--border-strong); }
.auto-row:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
-/* Mute task details, including inline resources, while keeping actions readable. */
.auto-row.is-disabled .auto-row-main,
.auto-row.is-disabled .auto-row-side {
--text: var(--muted);
@@ -17453,9 +17150,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
align-items: center;
gap: 12px;
}
-
-/* Expanded panel: nested conv list under the task. Same `.conv-item`
- styling as the sidebar — the renderer is shared. */
.auto-row-convs {
border-top: 1px solid var(--border);
padding-top: 10px;
@@ -17463,10 +17157,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
gap: 6px;
}
-/* HTML `hidden` attribute → really hide. The author rule above sets
- `display: flex`, which would otherwise override the UA stylesheet's
- `[hidden] { display: none }` and leave the panel always visible (this
- was the "无法收起" bug — chevron flipped but panel stayed). */
.auto-row-convs[hidden] { display: none; }
.auto-row-convs-head {
font-size: 12px;
@@ -17537,9 +17227,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
}
.auto-row-meta-icon { width: 14px; height: 14px; flex-shrink: 0; stroke-width: 1.6; }
-
-/* Right-aligned meta block: schedule summary above, last-run below. The ⋯
- button floats over the corner on hover and does not consume layout space. */
.auto-row-side {
flex: 0 0 auto;
display: flex;
@@ -17562,6 +17249,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
font-variant-numeric: tabular-nums;
}
.auto-row-more {
+ --orkas-ui-layer: chrome;
position: absolute;
top: -6px;
right: -8px;
@@ -17587,10 +17275,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.auto-row.is-menu-open .auto-row-more { opacity: 1; pointer-events: auto; }
.auto-row-more:hover { background: var(--surface-2); color: var(--text); }
.auto-row.is-menu-open .auto-row-more { background: var(--surface-2); color: var(--text); }
-
-/* ⋯ popover menu — visual clone of `.agent-row-menu`. */
.auto-row-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 1000;
min-width: 112px;
background: var(--surface);
@@ -17624,18 +17311,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.auto-row-side { grid-column: 1; align-items: flex-start; text-align: left; min-width: 0; }
.auto-row-schedule { font-size: 12px; }
}
-
-/* Project-detail auto card hint */
.project-auto-hint {
margin-top: 8px;
font-size: 11px;
color: var(--muted);
}
-
-/* ─── Connectors panel ─── */
-/* The `.panel` base rule already sets display:none → flex toggle via `.active`; do NOT
- override `#panel-connectors` with `display: flex`, that breaks the setView() gating
- (id selector beats the class rule → panel stays visible regardless of `.active`). */
.connectors-grid-view, .connectors-detail-view {
flex: 1;
display: flex;
@@ -17648,9 +17328,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: none;
}
.connectors-grid-title { font-size: 16px; font-weight: 600; color: var(--text); }
-
-/* Surface E page header (P1). Padding + title-font matched to `.chat-header`
- (reference) so every surface's top band reads as the same height. */
.connectors-page-header {
flex: 0 0 auto;
padding: 14px 22px 12px;
@@ -17696,6 +17373,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
min-width: 0;
}
.connectors-search-icon {
+ --orkas-ui-layer: chrome;
position: absolute;
left: 10px;
width: 14px;
@@ -17791,10 +17469,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-align: center;
color: var(--muted);
}
-
-/* Card chrome — P4 from PC/docs/design/PATTERNS.md. 14px padding, surface,
- hairline border, radius 10. 32×32 brand-color square (brand hex from
- `_CONNECTOR_BRAND_TINT` in connectors.js, applied inline style). */
.connector-card {
display: flex;
flex-direction: column;
@@ -17881,9 +17555,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
text-overflow: ellipsis;
white-space: nowrap;
}
-/* Authorized but unverified: amber, not red — the grant is fine, we just couldn't reach the
- backend. Takes the place of `.connector-card-account`, so the green "connected" dot that
- element carries is structurally absent on a degraded card rather than merely recoloured. */
.connector-card-unverified {
display: block;
font-size: 11px;
@@ -17982,6 +17653,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.connector-card-menu-btn:hover { background: rgba(15, 23, 42, 0.08); color: #334155; }
.connector-card-menu-popover {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 1000;
background: #fff;
border: 1px solid rgba(15, 23, 42, 0.12);
@@ -18000,16 +17672,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.connector-card-menu-item:hover { background: rgba(15, 23, 42, 0.05); }
.connector-card-menu-item.is-danger { color: #dc2626; }
.connector-card-menu-item.is-danger:hover { background: rgba(220, 38, 38, 0.08); }
-
-/* Disabled-but-connected card: muted look so the user can tell at a glance which connector
- they've turned off, without removing it from the "Connected" group. */
.connector-card.is-disabled { opacity: 0.55; }
.connector-card.is-disabled .connector-card-icon { filter: saturate(0.4); }
-/* Inline spinner inside the "连接" button — shown post-deep-link return while the IPC is
- running through `/oauth/exchange` + MCP `initialize` + `list_tools` (3 network roundtrips,
- ~hundreds of ms to a few seconds). Button stays clickable; spinner just signals progress. */
-
.connector-card-foot {
margin-top: auto;
display: flex;
@@ -18033,12 +17698,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
padding: 4px 8px;
}
.connector-card-foot .btn-link:hover { color: #2563eb; }
-
-/* Tab count badge */
.connectors-tab { display: inline-flex; align-items: center; gap: 6px; }
.connectors-tab-count { font-size: 11px; }
-
-/* Legacy dot retained for the agent detail toggle list */
.connector-dot {
display: inline-block;
width: 8px;
@@ -18049,8 +17710,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.connector-dot-connected { background: #10b981; }
.connector-dot-connecting { background: #f59e0b; }
.connector-dot-error { background: #ef4444; }
-
-/* Detail view */
.connectors-detail-header {
padding: 14px 20px;
border-bottom: 1px solid var(--border);
@@ -18079,8 +17738,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.connector-tool-name { font-family: ui-monospace, monospace; font-size: 12px; }
.connector-tool-desc { font-size: 12px; overflow: hidden; text-overflow: ellipsis; }
-
-/* Connect / configure modal. All catalog-defined fields stay in one reviewable form. */
#connectors-connect-modal.modal-overlay {
position: fixed;
inset: 0;
@@ -18088,6 +17745,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
display: flex;
align-items: center;
justify-content: center;
+ --orkas-ui-layer: overlay;
z-index: 13000;
}
#connectors-connect-modal .modal-card {
@@ -18156,7 +17814,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
#connectors-connect-modal .connectors-connect-form { min-height: 0; }
#connectors-connect-modal .connectors-connect-fields { overflow-y: auto; min-height: 0; margin: 0 -4px; padding: 4px; }
#connectors-connect-modal .modal-actions { flex-shrink: 0; }
-/* Use the form's gaps, not the generic form-row / label margins as well. */
#connectors-connect-modal .form-row { display: flex; flex-direction: column; gap: 6px; margin: 0; }
#connectors-connect-modal .form-row label { margin: 0; font-size: 12.5px; font-weight: 600; color: var(--text); }
#connectors-connect-modal .connectors-required-mark { color: var(--danger); }
@@ -18184,8 +17841,8 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
line-height: 1.5;
display: inline-block;
}
-/* Keep the empty live region available to assistive technology without reserving a row. */
#connectors-connect-modal [data-act="callback-copy-status"]:empty {
+ --orkas-ui-layer: chrome;
position: absolute;
width: 0;
height: 0;
@@ -18218,14 +17875,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.connectors-search { width: min(240px, 100%); }
#connectors-connect-modal .modal-card { padding: 16px; }
}
-
-/* ── Chat-side markdown drawer ─────────────────────────────────────────
- The markdown editor retains its own sizing. Its body reuses `.ctx-*`
- classes from the contexts editor through the same mount component. */
.chat-md-drawer-panel {
- /* Wider than conversation-info — markdown is text-heavy and worth the
- real estate. Caps so the main chat column doesn't collapse on narrow
- windows. */
flex: 0 0 min(560px, 50vw);
width: min(560px, 50vw);
min-width: 420px;
@@ -18237,6 +17887,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: #fff;
color: var(--text);
box-shadow: -12px 0 28px rgba(15, 23, 42, 0.05);
+ --orkas-ui-layer: chrome;
z-index: 20;
}
.chat-md-drawer-panel[hidden] { display: none !important; }
@@ -18287,20 +17938,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
flex-direction: column;
padding: 0;
}
-/* The mount writes its toolbar / body / textarea inline; we let the
- existing ctx-* rules dictate visuals (single source of truth) and only
- reset the host container's padding here so the textarea can stretch
- edge-to-edge. */
.chat-md-drawer-body .ctx-editor-toolbar { padding: 8px 12px; border-bottom: 1px solid var(--border); }
.chat-md-drawer-body .ctx-editor-body { flex: 1 1 auto; min-height: 0; display: flex; }
.chat-md-drawer-body .ctx-viewer-md { padding: 12px 16px; flex: 1 1 auto; overflow: auto; }
.chat-md-drawer-body .ctx-viewer-editor { flex: 1 1 auto; min-height: 0; padding: 12px 16px; border: 0; outline: 0; resize: none; }
-
-/* ── VideoStudio review panel (modules/video-review-panel.js) ─────────
- Uses task-side-panel sizing and the markdown drawer header/body controls.
- Reading order top to bottom: what the user asked for, how far it got,
- then the evidence. Older productions in the same conversation collapse
- to one row each. */
.video-review-panel .chat-md-drawer-header { padding: 14px 14px 12px; }
.video-review-panel .chat-md-drawer-body { padding: 0; }
.video-review-summary {
@@ -18314,9 +17955,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
}
.video-review-summary b { font-size: 12px; font-weight: 600; color: var(--text); }
-/* Direct children of the flex-column drawer body must keep their own height
- instead of shrinking to fit it — the body scrolls, the content does not
- compress. */
.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; }
@@ -18334,8 +17972,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.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; }
-/* Four fixed-width steps: only plan_approved / preview.status / narration /
- draft.status decide their state — nothing here infers progress. */
.video-review-rail { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; }
.video-review-step {
display: flex;
@@ -18362,15 +17998,11 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.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; }
-/* Partial: produced-but-unfinished evidence (2/5 narration lines). Solid
- border and a warn dot — visibly in progress, without is-wait's emphasis,
- which is reserved for steps that ask the user for something. */
.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; }
-/* Collapsible blocks */
.video-review-section { border-top: 1px solid var(--border); }
.video-review-section-head {
width: 100%;
@@ -18404,8 +18036,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.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; }
-/* Scene rows: thumbnail left, approved copy + narration right, so a whole
- production fits on one screen instead of one card per screen. */
.video-review-scenes { border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
.video-review-scene {
display: grid;
@@ -18478,7 +18108,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--primary-text);
background: var(--primary-soft);
}
-/* Older productions in the same conversation */
.video-review-comp-fold {
width: 100%;
display: flex;
@@ -18528,10 +18157,9 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
color: var(--muted);
}
.video-review-empty b { font-size: 13px; font-weight: 600; color: var(--text-2); }
-
-/* ── Generic right-click context menu (modules/context-menu.js) ─────── */
.context-menu {
position: fixed;
+ --orkas-ui-layer: overlay;
z-index: 9999;
min-width: 160px;
padding: 4px;
@@ -18591,14 +18219,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.context-menu-item:focus-visible { background: var(--primary-soft); }
.context-menu-item.is-disabled { color: #94a3b8; cursor: not-allowed; }
.context-menu-item.is-disabled:hover { background: transparent; }
-
-/* ───────────────────────────── Memory ─────────────────────────────────────
- Personal cross-session memory page (#panel-memory) + the Settings › 数据
- entry card + import/export modals. Bound to design tokens (TOKENS.md /
- PATTERNS.md). The active-edit alpha rgba(91,87,214,.…) is the documented
- "primary-soft surface" border accent (TOKENS §Border accent). */
-
-/* Entry card in the Settings data pane (P4, whole card clickable). */
.memory-entry-card {
display: flex;
align-items: center;
@@ -18631,8 +18251,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-entry-desc { font-size: 12px; color: var(--muted); line-height: 1.5; }
.memory-entry-chevron { flex: 0 0 auto; color: var(--muted); display: inline-flex; align-items: center; }
.memory-entry-chevron .ui-icon { width: 16px; height: 16px; }
-
-/* Page shell. */
.memory-page { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.memory-flex { flex: 1; }
.memory-page .ui-icon,
@@ -18695,8 +18313,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-detail-desc { white-space: normal; }
.memory-col { padding-inline: 18px; padding-bottom: 140px; }
}
-
-/* Section. */
.memory-section { margin-top: 26px; }
.memory-section:first-of-type { margin-top: 0; }
.memory-section-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
@@ -18705,17 +18321,14 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-section-title { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: -0.01em; color: var(--text); }
.memory-section-file { font-family: var(--font-mono); font-size: 11.5px; color: var(--muted); }
.memory-section-sub { margin: 0 0 12px; font-size: 11.5px; color: var(--muted); line-height: 1.5; }
+.memory-section-sub.is-warn { margin-top: -6px; color: var(--warn-text); }
.memory-empty { padding: 14px; font-size: 12.5px; }
-
-/* Usage bar. */
.memory-usage { display: inline-flex; align-items: center; gap: 7px; }
.memory-usage-track { width: 90px; height: 4px; background: var(--surface-3); border-radius: 99px; overflow: hidden; }
.memory-usage-fill { display: block; height: 100%; background: var(--primary); border-radius: 99px; }
.memory-usage-text { font-family: var(--font-mono); font-size: 11px; color: var(--muted); }
.memory-usage.is-warn .memory-usage-fill { background: var(--warn); }
.memory-usage.is-warn .memory-usage-text { color: var(--warn); }
-
-/* Entry card. */
.memory-entry {
padding: 12px 14px;
background: var(--surface);
@@ -18764,8 +18377,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-icon-btn:hover { background: var(--surface-2); }
.memory-icon-btn.is-muted { color: var(--muted); }
-/* ───────────────────────── Credit details ───────────────────────── */
-
@media (max-width: 720px) {
.settings-orkas-api-group {
display: block;
@@ -18801,11 +18412,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.settings-orkas-api-editor-actions { grid-column: 1; }
}
-
-/* Modal. */
.memory-modal-overlay {
position: fixed;
inset: 0;
+ --orkas-ui-layer: overlay;
z-index: 12000;
display: flex;
align-items: center;
@@ -18831,8 +18441,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-modal-body { padding: 20px; flex: 1; overflow-y: auto; font-size: 14px; line-height: 1.6; }
.memory-modal-foot { padding: 14px 20px; border-top: 1px solid var(--border); display: flex; align-items: center; gap: 8px; }
.memory-export-foot-icon { color: var(--muted); display: inline-flex; align-items: center; }
-
-/* Import step 1. */
.memory-import-tabs { display: flex; gap: 6px; margin-bottom: 12px; align-items: center; }
.memory-tab {
padding: 6px 12px;
@@ -18863,8 +18471,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
}
.memory-import-textarea:focus { outline: none; border-color: var(--primary); }
.memory-import-stat { font-size: 11.5px; font-family: var(--font-mono); }
-
-/* Import step 2 — review. */
.memory-safety-banner {
display: flex;
align-items: center;
@@ -18908,8 +18514,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-import-row-body { flex: 1; min-width: 0; }
.memory-import-row-text { font-size: 13px; line-height: 1.5; color: var(--text); }
.memory-import-row-meta { margin-top: 6px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
-
-/* Segmented 偏好 / 事实 toggle. */
.memory-seg { display: inline-flex; background: var(--surface-2); border-radius: 6px; padding: 2px; border: 1px solid var(--border); }
.memory-seg-opt {
padding: 2px 9px;
@@ -18925,8 +18529,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-seg-opt.is-active { background: var(--surface); color: var(--primary-text); font-weight: 600; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }
.memory-kind-pill { font-size: 10.5px; color: var(--muted); padding: 2px 9px; border-radius: 99px; background: var(--surface-2); }
.memory-threat-pill { font-size: 10.5px; color: var(--danger); padding: 2px 9px; border-radius: 99px; background: rgba(220, 38, 38, 0.08); border: 1px solid rgba(220, 38, 38, 0.2); }
-
-/* Export. */
.memory-export-body { display: flex; flex-direction: column; gap: 8px; }
.memory-export-row { display: flex; align-items: center; gap: 12px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; }
.memory-export-icon { width: 36px; height: 36px; flex: 0 0 auto; border-radius: 9px; background: var(--primary-soft); color: var(--primary-text); display: inline-flex; align-items: center; justify-content: center; }
@@ -18939,11 +18541,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.memory-export-row .btn.is-copied { color: var(--success); border-color: var(--success); }
.memory-export-row .btn.is-copy-failed { color: var(--danger); border-color: var(--danger); }
-/* ── Open-source-driven · Quick task entry + marketplace 专区 ──
- * Driver-badge colors map 1:1 to the three driver types below. */
-
-/* Quick task thumbnail: a compact marketplace window with four project tiles. */
-
@media (max-width: 1120px) {
.new-chat-center { padding-left: 24px; padding-right: 24px; }
.quick-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@@ -18953,22 +18550,18 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.new-chat-center { padding: 24px 16px 28px; }
.new-chat-header { padding-top: 32px; }
.new-chat-greeting { font-size: 30px; }
- .new-chat-subtitle { margin-top: 6px; font-size: 15px; }
.new-chat-input-area { padding: 7px 14px; border-radius: 14px; }
.chat-bottom-bar .composer-model-chip:not(.is-compact) { max-width: 150px; }
.new-chat-input-area textarea,
.new-chat-input-area .chat-rich-editor { min-height: 80px; font-size: 16px; }
- .new-chat-input-area .chat-input-mirror { font-size: 16px; }
.quick-grid { grid-template-columns: 1fr; }
- /* Wrap rather than clip: the entry is the only path to the open-source list. */
.quick-panel-head { flex-wrap: wrap; row-gap: 4px; }
.quick-panel-title { min-width: 0; flex: 1 1 100%; white-space: normal; }
.quick-panel-more { margin-left: auto; }
.new-chat-scenario-chip,
#panel-new-chat .new-chat-scenario-chip { min-height: 88px; }
+ .new-chat-input-area .chat-input-mirror { font-size: 16px; }
}
-
-/* Marketplace 专区 */
.marketplace-tab--oss { display: inline-flex; align-items: center; gap: 6px; }
.marketplace-tab-new {
font-size: 10px; font-weight: 600; padding: 1px 6px; border-radius: 99px;
@@ -19016,8 +18609,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.mp-oss-installed-icon { width: 12px; height: 12px; }
.mp-oss-card { cursor: pointer; }
.mp-oss-card:hover { border-color: var(--border-strong); }
-
-/* driver badge (shared small component) */
.driver-badge {
display: inline-flex; align-items: center; gap: 4px;
font-size: 10.5px; font-weight: 600; padding: 2px 7px; border-radius: 99px;
@@ -19027,14 +18618,17 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.driver-badge--cli { color: #8b5cf6; background: color-mix(in srgb, #8b5cf6 12%, transparent); }
.driver-badge--mcp { color: #10b981; background: color-mix(in srgb, #10b981 12%, transparent); }
-/* ============================================================
- Credits native pages — F1 home topbar cluster (.home-topbar/.hc-*)
- and F2 usage page (.cu-*). Design handoff: design_handoff_credits/.
- Classes are prefixed to stay isolated from the rest of style.css;
- task-type swatch colors + a sans stack are scoped on the two roots.
- ============================================================ */
+.cu-guidance { display: flex; align-items: baseline; gap: 12px; margin-bottom: 16px; }
+.cu-guidance .settings-row-desc { margin: 0; min-width: 0; }
+.cu-guidance .settings-link-btn { flex: 0 0 auto; white-space: nowrap; }
-/* CSV/TSV previews keep literal cell content in a bounded, scrollable grid. */
+@media (max-width: 1200px) {
+ .cu-summary { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+}
+@media (max-width: 620px) {
+ .cu-guidance { flex-wrap: wrap; gap: 4px 12px; }
+ .cu-summary { grid-template-columns: minmax(0, 1fr); }
+}
.contexts-viewer-body:has(> .delimited-preview) { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
.delimited-preview { display: flex; flex-direction: column; flex: 1 1 auto; padding: 16px; min-width: 0; min-height: 0; }
.delimited-preview-toolbar { display: flex; flex: 0 0 auto; align-items: center; gap: 12px; margin-bottom: 12px; font-size: 12px; color: var(--text-2); }
@@ -19043,14 +18637,58 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.delimited-preview td, .delimited-preview th { border: 1px solid var(--border); padding: 6px 10px; white-space: pre-wrap; overflow-wrap: anywhere; min-width: 70px; max-width: 480px; vertical-align: top; text-align: left; }
.delimited-preview th { position: sticky; left: 0; background: var(--surface-2); min-width: 35px; color: var(--text-2); font-weight: normal; }
.delimited-preview .chat-file-viewer-text { flex: 1 1 0; margin: 0; padding: 0; min-height: 0; overflow: auto; }
-
-/* Keep code, addresses and native locale names legible in the Arabic UI. */
html[dir="rtl"] :is(pre, code, input[type="email"], input[type="url"]) {
direction: ltr;
unicode-bidi: isolate;
}
html[dir="rtl"] .ai-select-item-label { unicode-bidi: plaintext; text-align: start; }
html[dir="rtl"] .sidebar-search-label { text-align: start; }
+.local-cli-upgrade-control {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ margin-top: 0;
+}
+.local-cli-upgrade-control .agents-detail-cli-note { margin: 0; }
+.local-cli-upgrade-btn:not(.chat-app-nav-btn) {
+ height: 100%;
+ min-height: 34px;
+ padding: 8px 12px;
+ line-height: 16px;
+ white-space: nowrap;
+}
+.agent-cli-select-row > .ai-select .ai-select-trigger,
+.agents-detail-runtime-select .ai-select-trigger { line-height: 16px; }
+#agent-modal-ext-cli-upgrades { display: flex; flex-wrap: wrap; gap: 8px; min-width: 0; }
+#agent-modal-ext-cli-upgrade-warning:not([hidden]) { margin-top: 8px; }
+.local-cli-upgrade-control.chat-app-nav-row { margin-top: 14px; }
+.local-cli-upgrade-control.chat-app-nav-row .agents-detail-cli-note { align-self: center; }
+
+.agents-detail-runtime .local-cli-upgrade-control { flex: 1; }
+.project-todo-agent-icon {
+ flex: 0 0 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+}
+.project-todo-agent-icon { color: var(--text-2); background: var(--surface-2); }
+.project-todo-assign-icon { width: 12px; height: 12px; }
+.project-agent-row-sharing {
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ color: var(--muted);
+}
+.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {
+ font-weight: 600;
+ line-height: 1.35;
+ margin: 1em 0 0.4em;
+ color: var(--text);
+}
.chat-input-area.is-project .chat-rich-editor {
min-height: 64px;
@@ -19113,6 +18751,7 @@ html[dir="rtl"] .sidebar-search-label { text-align: start; }
flex: 0 1 auto;
}
.chat-input-mirror-wrap textarea {
+ --orkas-ui-layer: chrome;
position: relative;
z-index: 1;
background: transparent;
@@ -19126,6 +18765,7 @@ html[dir="rtl"] .sidebar-search-label { text-align: start; }
-webkit-text-fill-color: transparent;
}
.chat-input-mirror {
+ --orkas-ui-layer: chrome;
position: absolute;
inset: 0;
pointer-events: none;
@@ -19163,6 +18803,7 @@ html[dir="rtl"] .sidebar-search-label { text-align: start; }
.chat-input-rich-wrap .chat-rich-source,
.chat-input-area .chat-input-rich-wrap textarea.chat-rich-source,
.new-chat-input-area .chat-input-rich-wrap textarea.chat-rich-source {
+ --orkas-ui-layer: chrome;
position: absolute;
width: 1px;
height: 1px;
@@ -19225,6 +18866,7 @@ html[dir="rtl"] .sidebar-search-label { text-align: start; }
height: 16px;
}
.app-card-stripe {
+ --orkas-ui-layer: chrome;
position: absolute;
left: 0;
top: 0;
@@ -19508,6 +19150,7 @@ html[dir="rtl"] .sidebar-search-label { text-align: start; }
.chat-msg-attach.is-image .chat-msg-attach-thumb { cursor: zoom-in; }
.chat-artifact-menu,
.app-row-menu {
+ --orkas-ui-layer: overlay;
position: fixed;
z-index: 1000;
min-width: 176px;
diff --git a/src/renderer/views/browser-passkey/index.html b/src/renderer/views/browser-passkey/index.html
new file mode 100644
index 00000000..0d58697d
--- /dev/null
+++ b/src/renderer/views/browser-passkey/index.html
@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'self'; script-src 'self'; img-src data:; base-uri 'none'; form-action 'none'">
+ <link rel="stylesheet" href="../../style.css">
+ <link rel="stylesheet" href="passkey.css">
+ <script defer src="../../modules/icons.js"></script>
+ <script defer src="passkey.js"></script>
+</head>
+<body>
+ <main id="dialog" class="modal modal-standard passkey-dialog" aria-labelledby="title">
+ <header class="modal-header"><h1 class="modal-title" id="title"></h1></header>
+ <div class="modal-body passkey-body">
+ <div class="passkey-instructions">
+ <span id="camera" aria-hidden="true"></span>
+ <div><h2 id="heading"></h2><p id="instruction" class="passkey-instruction"></p></div>
+ </div>
+ <div class="passkey-visual">
+ <img id="qr" width="264" height="264" hidden>
+ <div id="waiting" class="passkey-waiting">
+ <span id="phone" aria-hidden="true"></span>
+ <span class="chat-history-inline-spinner" aria-hidden="true"></span>
+ </div>
+ </div>
+ <p id="status" class="passkey-status" role="status" aria-live="polite" aria-atomic="true"></p>
+ <p id="nearby" class="passkey-nearby"></p>
+ </div>
+ <footer class="modal-actions"><button id="cancel" class="btn" type="button"></button></footer>
+ </main>
+</body>
+</html>
diff --git a/src/renderer/views/browser-passkey/passkey.css b/src/renderer/views/browser-passkey/passkey.css
new file mode 100644
index 00000000..e4398fef
--- /dev/null
+++ b/src/renderer/views/browser-passkey/passkey.css
@@ -0,0 +1,37 @@
+body { background: var(--surface); }
+.passkey-dialog {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ min-width: 0;
+ max-width: none;
+ max-height: none;
+ border-radius: 0;
+ box-shadow: none;
+ overflow: auto;
+ padding: 20px;
+}
+.passkey-dialog .modal-header { margin-bottom: 20px; min-height: 0; }
+.passkey-body { flex: 1; min-height: 0; }
+.passkey-instructions { display: flex; gap: 12px; align-items: flex-start; }
+.passkey-instructions .ui-icon { width: 20px; height: 20px; margin-top: 2px; color: var(--text-2); }
+.passkey-instructions h2 { font-size: 13px; font-weight: 600; line-height: 1.6; }
+.passkey-instruction { color: var(--text); font-size: 13px; line-height: 1.5; text-wrap: pretty; }
+.passkey-visual {
+ display: grid;
+ place-items: center;
+ width: 264px;
+ height: 264px;
+ margin: 24px auto 0;
+ background: var(--surface);
+}
+.passkey-visual img { display: block; width: 264px; height: 264px; }
+.passkey-dialog:not([data-phase="scan"]) .passkey-visual { height: 200px; margin-top: 16px; }
+.passkey-visual [hidden] { display: none; }
+.passkey-waiting { display: flex; align-items: center; flex-direction: column; gap: 20px; color: var(--text-2); }
+.passkey-phone { width: 56px; height: 56px; }
+.passkey-status { margin-top: 8px; font-size: 13px; text-align: center; }
+.passkey-nearby { margin-top: 4px; color: var(--muted); font-size: 12px; line-height: 1.5; text-align: center; text-wrap: pretty; }
+.passkey-dialog .modal-actions { flex: none; margin-top: 16px; }
+.passkey-dialog .modal-actions .btn { min-width: 64px; }
diff --git a/src/renderer/views/browser-passkey/passkey.js b/src/renderer/views/browser-passkey/passkey.js
new file mode 100644
index 00000000..0d54ce3e
--- /dev/null
+++ b/src/renderer/views/browser-passkey/passkey.js
@@ -0,0 +1,33 @@
+(() => {
+ const find = id => document.getElementById(id);
+ find('camera').innerHTML = window.uiIconHtml('camera');
+ find('phone').innerHTML = window.uiIconHtml('smartphone', 'ui-icon passkey-phone');
+ let cancelled = false;
+ const cancel = () => {
+ if (cancelled) return;
+ cancelled = true;
+ find('cancel').disabled = true;
+ window.phonePasskeyDialog.cancel();
+ };
+ find('cancel').addEventListener('click', cancel);
+ document.addEventListener('keydown', event => {
+ if (event.key === 'Escape') { event.preventDefault(); cancel(); }
+ });
+ window.phonePasskeyDialog.onUpdate(state => {
+ find('dialog').dataset.phase = state.phase;
+ document.documentElement.lang = state.lang;
+ document.documentElement.dir = state.dir;
+ document.title = state.copy.title;
+ for (const id of ['title', 'heading', 'instruction', 'nearby', 'cancel']) find(id).textContent = state.copy[id];
+ find('status').textContent = state.copy[state.phase];
+ find('status').hidden = state.phase === 'scan';
+ find('nearby').hidden = state.phase === 'scan';
+ const showQr = state.phase === 'scan' && state.qr.startsWith('data:image/svg+xml;base64,');
+ find('qr').hidden = !showQr;
+ find('qr').alt = state.copy.qr_alt;
+ if (showQr) find('qr').src = state.qr;
+ else find('qr').removeAttribute('src');
+ find('waiting').hidden = showQr;
+ if (document.activeElement === document.body) find('cancel').focus();
+ });
+})();
diff --git a/src/renderer/views/browser-passkey/transport.html b/src/renderer/views/browser-passkey/transport.html
new file mode 100644
index 00000000..7e4133fd
--- /dev/null
+++ b/src/renderer/views/browser-passkey/transport.html
@@ -0,0 +1,2 @@
+<!doctype html>
+<html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; connect-src wss://cable.auth.com wss://cable.ua5v.com; base-uri 'none'; form-action 'none'"><title></title></head><body></body></html>
diff --git a/test/e2e/app_e2e_smoke.spec.ts b/test/e2e/app_e2e_smoke.spec.ts
index 708c4882..be6b5cbd 100644
--- a/test/e2e/app_e2e_smoke.spec.ts
+++ b/test/e2e/app_e2e_smoke.spec.ts
@@ -1,7 +1,8 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
-import { expect, OrkasTestApp, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, OrkasTestApp, test } from './fixtures/orkas';
+
test.describe('desktop shell', () => {
test('keeps background launches and second-instance activation off the desktop across relaunch', async ({}, testInfo) => {
@@ -151,7 +152,9 @@ test.describe('desktop shell', () => {
}
});
- test('opens the selected project and agent details', async ({ appPage, orkas }) => {
+ test('opens the selected project and agent details', async ({ marketplaceOrkas: orkas }) => {
+ const appPage = orkas.page;
+ if (!appPage) throw new Error('Orkas renderer is unavailable');
await orkas.invoke('projects.create', { name: 'E2E Visual Project' });
await orkas.invoke('agents.create', {
name: 'E2EVisualAgent',
@@ -164,7 +167,7 @@ test.describe('desktop shell', () => {
}).click();
await expect(appPage.locator('#project-detail-title')).toHaveText('E2E Visual Project');
- await appPage.locator('#agents-btn').click();
+ await openSidebarEntry(appPage, '#agents-btn');
const agentCard = appPage.locator('.agent-card', { hasText: 'E2EVisualAgent' });
await expect(agentCard).toBeVisible();
await agentCard.click();
@@ -172,7 +175,7 @@ test.describe('desktop shell', () => {
});
test('selects a one-time automation date with the keyboard', async ({ appPage }) => {
- await appPage.locator('#auto-btn').click();
+ await openSidebarEntry(appPage, '#auto-btn');
await appPage.locator('#auto-add-btn').click();
await expect(appPage.locator('input[type="date"]')).toHaveCount(0);
@@ -207,7 +210,7 @@ test.describe('desktop shell', () => {
] as const;
for (const [buttonId, panelId] of destinations) {
- await appPage.locator(`#${buttonId}`).click();
+ await openSidebarEntry(appPage, `#${buttonId}`);
await expect(appPage.locator(`#${buttonId}`)).toHaveClass(/\bactive\b/);
await expect(appPage.locator(`#${panelId}`)).toHaveClass(/\bactive\b/);
await expect(appPage.locator(`#${panelId}`)).toBeVisible();
diff --git a/test/e2e/app_templates_e2e_calibration.spec.ts b/test/e2e/app_templates_e2e_calibration.spec.ts
index f2a0df69..4477660c 100644
--- a/test/e2e/app_templates_e2e_calibration.spec.ts
+++ b/test/e2e/app_templates_e2e_calibration.spec.ts
@@ -1,8 +1,8 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
-import { expect } from './fixtures/orkas';
+import { openSidebarEntry, expect } from './fixtures/orkas';
import { test } from './fixtures/web-app-eval';
-import { exerciseProductInventory, exerciseFlashcards, exerciseSnake } from './fixtures/app-template-journeys';
+import { exerciseProductInventory, exerciseFlashcards, exerciseSnake, exerciseConverter } from './fixtures/app-template-journeys';
// Frozen outputs from the same Chinese starter and Codex model on 2026-09-15.
// The first output has a real inline-transform defect; the second uses a valid
@@ -42,7 +42,7 @@ for (const scenario of ['list-repaired', 'labeled-list', 'submit-label', 'filter
if (isList) orkas.createWorkspaceFile('web-app/orkas-app.json', readFileSync(path.join(fixtures, 'orkas-app.json'), 'utf8'));
const saved = await orkas.invoke<{ ok: boolean; id: string }>('savedApps.saveFromPath', { path: entry, title: scenario });
expect(saved.ok).toBe(true);
- await orkas.page.locator('#apps-btn').click();
+ await openSidebarEntry(orkas.page, '#apps-btn');
const preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
try {
const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
@@ -61,6 +61,48 @@ for (const scenario of ['list-repaired', 'labeled-list', 'submit-label', 'filter
});
}
+// Frozen outputs from the focused 2026-10-13 run. These controls protect the
+// user journey across stock units, readonly results, modal entry and pressed
+// difficulty buttons; replay and intentional mutations never count as live passes.
+for (const scenario of ['products', 'products-wrong-stock', 'converter', 'converter-wrong-result',
+ 'flashcards', 'flashcards-broken-unmaster', 'game', 'game-broken-pause'] as const) {
+ test(`generated layout oracle ${scenario}`, async ({ sdkOrkas: orkas }, info) => {
+ const id = scenario.split('-')[0];
+ let html = readFileSync(path.join(__dirname, 'fixtures/app-template-live-20261013', id, 'index.html'), 'utf8');
+ const mutate = (before: string, after: string) => {
+ expect(html).toContain(before);
+ html = html.replace(before, after);
+ };
+ if (scenario === 'products-wrong-stock') mutate("p.quantity.toLocaleString('zh-CN')", "(p.quantity===0?10:p.quantity).toLocaleString('zh-CN')");
+ if (scenario === 'converter-wrong-result') mutate('output.value=fmt(result);', 'output.value=fmt(result+1);');
+ if (scenario === 'flashcards-broken-unmaster') mutate('card.mastered=isMastered;', 'if(!isMastered)return;card.mastered=isMastered;');
+ if (scenario === 'game-broken-pause') mutate("clearInterval(timer);timer=null;state='paused';", "state='paused';");
+ const entry = orkas.createWorkspaceFile('generated-layout/index.html', html);
+ const saved = await orkas.invoke<{ ok: boolean; id: string }>('savedApps.saveFromPath', { path: entry, title: scenario });
+ expect(saved.ok).toBe(true);
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ let preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
+ const reopen = async () => {
+ await orkas.closePreview(preview);
+ preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
+ return preview.locator('.saved-app-viewer-frame').contentFrame();
+ };
+ try {
+ const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ const journey = id === 'products' ? exerciseProductInventory(frame, reopen)
+ : id === 'converter' ? exerciseConverter(frame)
+ : id === 'flashcards' ? exerciseFlashcards(frame, preview, name => info.outputPath(name))
+ : exerciseSnake(frame, preview);
+ if (scenario === 'products-wrong-stock') await expect(journey).rejects.toThrow('toBe');
+ else if (scenario === 'converter-wrong-result') await expect(journey).rejects.toThrow('toBeCloseTo');
+ else if (scenario === 'flashcards-broken-unmaster') await expect(journey).rejects.toThrow('Returning a card to review must clear mastery');
+ else if (scenario === 'game-broken-pause') await expect(journey).rejects.toThrow('Paused snake must stop moving');
+ else await journey;
+ expect(orkas.modelRequests).toHaveLength(0);
+ } finally { await orkas.closePreview(preview); }
+ });
+}
+
// Unchanged outputs from the 30-request-budget live run. Mutations below are
// calibration negatives only; never replace the original live evidence.
for (const scenario of ['products', 'products-broken-save', 'flashcards', 'flashcards-broken-answer',
@@ -81,7 +123,7 @@ for (const scenario of ['products', 'products-broken-save', 'flashcards', 'flash
if (id === 'products') orkas.createWorkspaceFile('web-app/orkas-app.json', readFileSync(path.join(dir, 'orkas-app.json'), 'utf8'));
const saved = await orkas.invoke<{ ok: boolean; id: string }>('savedApps.saveFromPath', { path: entry, title: scenario });
expect(saved.ok).toBe(true);
- await orkas.page.locator('#apps-btn').click();
+ await openSidebarEntry(orkas.page, '#apps-btn');
let preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
const reopen = async () => {
await orkas.closePreview(preview);
diff --git a/test/e2e/automation_e2e_crud.spec.ts b/test/e2e/automation_e2e_crud.spec.ts
index b41098cd..98a0777c 100644
--- a/test/e2e/automation_e2e_crud.spec.ts
+++ b/test/e2e/automation_e2e_crud.spec.ts
@@ -1,5 +1,5 @@
import type { Page } from '@playwright/test';
-import { expect, OrkasTestApp, test as base } from './fixtures/orkas';
+import { openSidebarEntry, expect, OrkasTestApp, test as base } from './fixtures/orkas';
const test = base.extend<{ cliModelOrkas: OrkasTestApp }>({
cliModelOrkas: async ({}, use, testInfo) => {
@@ -36,7 +36,7 @@ type AutoTask = {
};
async function openAutomation(page: Page): Promise<void> {
- await page.locator('#auto-btn').click();
+ await openSidebarEntry(page, '#auto-btn');
await expect(page.locator('#panel-auto')).toHaveClass(/\bactive\b/);
await expect(page.locator('#auto-add-btn')).toBeVisible();
}
@@ -56,6 +56,63 @@ test.describe('automation', () => {
timeout: process.platform === 'win32' ? 120_000 : 60_000,
});
+ test.describe('personal project Agent persistence', () => {
+ test('saves and edits a selected personal project Agent across relaunch', async ({ orkas }) => {
+ const project = await orkas.invoke<{ project: { project_id: string } }>('projects.create', {
+ name: 'Personal automation project',
+ });
+ const agent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
+ name: 'PersonalAutomationReviewer', description: 'Review project status', category: 'general',
+ });
+ // The open build keeps local project Agent bindings without hosted
+ // shared-to-private conversion or its private-roster implementation.
+ const bound = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.add', {
+ projectId: project.project.project_id, kind: 'agent', id: agent.agent.agent_id,
+ });
+ expect(bound.bindings.agents).toContain(agent.agent.agent_id);
+ let page = await orkas.relaunch();
+ await openAutomation(page);
+ await page.locator('#auto-add-btn').click();
+ await selectAiOption(page, '#auto-project-select', 'Personal automation project');
+ await page.locator('#auto-recipient-chip').click();
+ const picker = page.locator('#agent-picker');
+ await expect(picker).toBeVisible();
+ await picker.locator(`.skill-picker-item[data-id="${agent.agent.agent_id}"]`).click();
+ await expect(page.locator('#auto-recipient-name')).toHaveText('PersonalAutomationReviewer');
+ await page.locator('#auto-task-input').fill('Review personal project status');
+ await page.locator('#auto-title-input').fill('Personal Agent automation');
+ await page.locator('#auto-enabled-input').uncheck();
+ await page.locator('#auto-submit-btn').click();
+ await expect(page.locator('#auto-task-dialog-overlay')).toBeHidden();
+ const listed = await orkas.invoke<{ tasks: Array<AutoTask & { recipient: { id: string } }> }>(
+ 'autoTasks.list', { projectId: project.project.project_id },
+ );
+ expect(listed.tasks).toHaveLength(1);
+ expect(listed.tasks[0]).toMatchObject({
+ content: 'Review personal project status', enabled: false,
+ recipient: { kind: 'agent', id: agent.agent.agent_id },
+ });
+ page = await orkas.relaunch();
+ await openAutomation(page);
+ await page.locator(`#auto-list .todo-scope-chip[data-project-id="${project.project.project_id}"]`).click();
+ const row = page.locator(`.auto-row[data-task-id="${listed.tasks[0].id}"]`);
+ await expect(row).toBeVisible();
+ await row.hover();
+ await row.locator('.auto-row-more').click();
+ await page.locator('.auto-row-menu [data-action="edit"]').click();
+ await expect(page.locator('#auto-recipient-name')).toHaveText('PersonalAutomationReviewer');
+ await page.locator('#auto-task-input').fill('Review edited personal project status');
+ await page.locator('#auto-submit-btn').click();
+ await expect(page.locator('#auto-task-dialog-overlay')).toBeHidden();
+ expect((await orkas.invoke<{ tasks: AutoTask[] }>('autoTasks.list', {
+ projectId: project.project.project_id,
+ })).tasks).toEqual([expect.objectContaining({
+ id: listed.tasks[0].id, content: 'Review edited personal project status',
+ recipient: expect.objectContaining({ id: agent.agent.agent_id }),
+ })]);
+ });
+ });
+
test('switches automation projects and keeps the selected scope through project renames', async ({ orkas }, testInfo) => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
const project10 = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Automation 10' });
@@ -114,17 +171,26 @@ test.describe('automation', () => {
await expect(project10Scope).toHaveAttribute('aria-pressed', 'true');
await expect(group10.locator(`.auto-row[data-task-id="${task10.task.id}"]`)).toBeVisible();
- // Only the page-level Create button remains; selecting a scope does not
- // silently change where a new automation will be filed.
+ // Page-level creation starts in the visible scope, with an editable picker.
await expect(page.locator('#auto-list .auto-scope-add')).toHaveCount(0);
await page.locator('#auto-add-btn').click();
- await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', '');
+ await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', project10.project.project_id);
+ await expect(page.locator('#auto-row-project')).toBeVisible();
+ await selectAiOption(page, '#auto-project-select', 'Automation 2');
+ await page.locator('#auto-task-input').fill('Cancelled draft');
+ await page.evaluate(async () => (window as any).loadAutoList(true));
+ await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', project2.project.project_id);
+ await expect(page.locator('#auto-task-input')).toHaveText('Cancelled draft');
+ await page.locator('#auto-dialog-cancel-btn').click();
+ await page.locator('#auto-add-btn').click();
+ await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', project10.project.project_id);
+ await expect(page.locator('#auto-task-input')).toHaveText('');
+ await page.locator('#auto-task-dialog-overlay').screenshot({ path: testInfo.outputPath('automation-default-project-en.png') });
await page.locator('#auto-dialog-cancel-btn').click();
- // The project picker in the shared dialog still files the new task there.
+ // The default itself reaches storage without manually selecting a project.
await project2Scope.click();
await page.locator('#auto-add-btn').click();
- await selectAiOption(page, '#auto-project-select', 'Automation 2');
await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', project2.project.project_id);
await page.locator('#auto-task-input').fill('Prepare a project follow-up');
await page.locator('#auto-title-input').fill('Project follow-up');
@@ -153,6 +219,19 @@ test.describe('automation', () => {
await expect(scopeNames).toHaveText(['全局', 'Automation 1', 'Automation 2']);
await project10Scope.click();
await expect(group10.locator(`.auto-row[data-task-id="${task10.task.id}"]`)).toBeVisible();
+ await page.locator('#auto-add-btn').click();
+ await expect(page.locator('#auto-project-select')).toHaveAttribute('data-value', project10.project.project_id);
+ await selectAiOption(page, '#auto-project-select', '全局');
+ await page.locator('#auto-task-input').fill('Explicit global follow-up');
+ await page.locator('#auto-enabled-input').uncheck();
+ await page.setViewportSize({ width: 800, height: 850 });
+ await page.locator('#auto-task-dialog-overlay').screenshot({ path: testInfo.outputPath('automation-project-override-zh.png') });
+ await page.locator('#auto-submit-btn').click();
+ await expect(page.locator('#auto-task-dialog-overlay')).toBeHidden();
+ const globalTasks = await orkas.invoke<{ tasks: AutoTask[] }>('autoTasks.list', { projectId: null });
+ expect(globalTasks.tasks.find(task => task.content === 'Explicit global follow-up')).toMatchObject({ enabled: false });
+ expect(globalTasks.tasks.find(task => task.content === 'Explicit global follow-up')?.project_id).toBeUndefined();
+ await page.setViewportSize({ width: 1440, height: 900 });
await page.screenshot({ path: testInfo.outputPath('automation-project-groups.png') });
await page.setViewportSize({ width: 800, height: 850 });
await expect(group10.locator(`.auto-row[data-task-id="${task10.task.id}"]`)).toBeVisible();
@@ -230,6 +309,9 @@ test.describe('automation', () => {
test('shows a scheduled run as running before opening its conversation', async ({ modelOrkas }, testInfo) => {
const page = modelOrkas.page!;
modelOrkas.setModelMode('controlled-slow');
+ // This case owns a running scheduled task after the boot subscription is
+ // connected, rather than a fire during the deliberately deferred warmup.
+ await page.waitForFunction('typeof _autoEventsHandle !== "undefined" && _autoEventsHandle !== null');
const created = await modelOrkas.invoke<{ task: AutoTask }>('autoTasks.create', {
content: 'Summarize the release checks',
title: 'Scheduled status check',
diff --git a/test/e2e/chat_e2e_background_recovery.spec.ts b/test/e2e/chat_e2e_background_recovery.spec.ts
new file mode 100644
index 00000000..0bf401d3
--- /dev/null
+++ b/test/e2e/chat_e2e_background_recovery.spec.ts
@@ -0,0 +1,190 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { expect, test } from './fixtures/orkas';
+import { composerText } from './fixtures/composer';
+
+
+test('keeps a visible unfocused window streaming before the task completes', async ({ modelOrkas }, testInfo) => {
+ const page = modelOrkas.page!;
+ const nativeWindow = await modelOrkas.electronApp!.browserWindow(page);
+ await nativeWindow.evaluate(win => win.showInactive());
+ modelOrkas.setModelMode('controlled-slow');
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('Keep this task streaming while I use another window.');
+ await page.locator('#new-chat-send-btn').click();
+ await expect.poll(() => modelOrkas.modelRequests.length, { timeout: 30_000 }).toBe(1);
+ const reply = page.locator('#chat-history .chat-message.assistant [data-role="final"]');
+ await expect(reply).toContainText('Hello');
+ // Drive the same native lifecycle event as switching apps, independently
+ // of which window owns focus on the test host. No model or final event can
+ // supply the missing paint: the controlled stream remains open below.
+ await nativeWindow.evaluate(win => win.emit('blur'));
+ modelOrkas.releaseControlledModelChunk();
+ await expect(reply).toHaveText('Hello from the local E2E model.');
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ expect(await page.evaluate<boolean>('_conversationWindowActive')).toBe(true);
+ await page.screenshot({ path: testInfo.outputPath('visible-unfocused-stream.png') });
+ modelOrkas.finishControlledModelStream();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ expect(modelOrkas.modelRequests).toHaveLength(1);
+});
+
+// Real Electron IPC, execution bus, persistence and renderer; the endpoint is
+// the existing isolated local model fixture, with explicit stream barriers.
+for (const surface of ['hidden-window', 'other-panel', 'other-task'] as const) {
+ for (const completed of [false, true]) {
+ test(`restores ${completed ? 'saved result' : 'latest live text'} after ${surface} without executing again`, async ({ modelOrkas }) => {
+ const page = modelOrkas.page!;
+ modelOrkas.setModelMode('controlled-slow');
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('Keep this task running while I look elsewhere.');
+ await page.locator('#new-chat-send-btn').click();
+ // The first turn includes cold SDK imports on Windows before the local
+ // endpoint receives its request; peer stream cases use this same bound.
+ await expect.poll(() => modelOrkas.modelRequests.length, { timeout: 30_000 }).toBe(1);
+ await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
+ await expect(page.locator('#chat-history .chat-message.user')).toHaveCount(1);
+ const cid = await page.evaluate<string>('currentCid');
+ let hiddenText: string | null = null;
+ const messageFile = path.join(modelOrkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`);
+ const persisted = () => existsSync(messageFile)
+ ? readFileSync(messageFile, 'utf8').trim().split('\n').map(line => JSON.parse(line)) : [];
+ // Admission already saved the user input before it was rendered.
+ expect(persisted().filter(row => row.from === 'user')).toHaveLength(1);
+
+ if (surface === 'hidden-window') {
+ const nativeWindow = await modelOrkas.electronApp!.browserWindow(page);
+ // Chromium may retain visible for a hidden-at-launch document. Verify
+ // the native lifecycle channel independently of that document state.
+ await nativeWindow.evaluate(win => win.showInactive());
+ await nativeWindow.evaluate(win => win.hide());
+ await expect.poll(() => page.evaluate<boolean>('_conversationWindowActive')).toBe(false);
+ // Snapshot after the acknowledged hide. The first admitted prefix may
+ // arrive between the earlier composer checks and the native transition.
+ hiddenText = await page.locator('#chat-history [data-role="final"]').textContent();
+ } else if (surface === 'other-panel') {
+ await page.locator('#new-chat-btn').click();
+ } else {
+ const other = await modelOrkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Other task' });
+ await page.evaluate(async (otherCid) => {
+ await (window as any).loadConversations();
+ (window as any).setView('conversation', otherCid);
+ }, other.conversation.conversation_id);
+ await expect(page.locator('#chat-header-title')).toHaveText('Other task');
+ }
+
+ modelOrkas.releaseControlledModelChunk();
+ await expect.poll(async () => {
+ const result = await modelOrkas.invoke<any>('conversations.history', { cid, live: '1' });
+ return result.live_display.turns.at(-1)?.records.at(-1)?.text;
+ }).toBe('Hello from the local E2E model.');
+ if (surface === 'hidden-window') expect(await page.locator('#chat-history [data-role="final"]').textContent()).toBe(hiddenText);
+ if (surface === 'other-task') await expect(page.locator('#chat-history')).not.toContainText('Hello from the local E2E model.');
+
+ if (completed) {
+ modelOrkas.finishControlledModelStream();
+ await expect.poll(() => persisted().find(row => row.from === 'commander')?.text)
+ .toBe('Hello from the local E2E model.');
+ const reply = persisted().find(row => row.from === 'commander');
+ expect(reply.process.length).toBeGreaterThan(0);
+ }
+ if (surface === 'hidden-window') {
+ const nativeWindow = await modelOrkas.electronApp!.browserWindow(page);
+ await nativeWindow.evaluate(win => win.showInactive());
+ await expect.poll(() => page.evaluate<boolean>('_conversationWindowActive')).toBe(true);
+ } else {
+ await page.evaluate(cid => (window as any).setView('conversation', cid), cid);
+ }
+ const replies = page.locator('#chat-history .chat-message.assistant');
+ await expect(replies).toHaveCount(1);
+ await expect(replies).toContainText('Hello from the local E2E model.');
+ if (!completed) {
+ await expect(replies.locator('[data-role="final"]')).toHaveText('Hello from the local E2E model.');
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ modelOrkas.finishControlledModelStream();
+ }
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ expect(persisted().filter(row => row.from === 'commander')).toHaveLength(1);
+ expect(modelOrkas.modelRequests).toHaveLength(1);
+ });
+ }
+}
+
+test('recovers a lost terminal notification while a queued follow-up remains live', async ({ modelOrkas }) => {
+ const page = modelOrkas.page!;
+ const { agent } = await modelOrkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
+ name: 'TerminalRecoveryAgent', description: 'Deterministic terminal recovery fixture.', category: 'general',
+ });
+ modelOrkas.setModelMode('controlled-slow');
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-recipient-chip').click();
+ await page.locator(`#agent-picker [data-kind="agent"][data-id="${agent.agent_id}"]`).click();
+ const input = page.locator('#new-chat-input');
+ await input.fill(`${await composerText(input)}Complete the first task.`);
+ await page.locator('#new-chat-send-btn').click();
+ await expect.poll(() => modelOrkas.modelRequests.length, { timeout: 30_000 }).toBe(1);
+ const cid = await page.evaluate<string>('currentCid');
+ modelOrkas.releaseControlledModelChunk();
+ const replies = page.locator('#chat-history .chat-message.assistant');
+ await expect(replies.locator('[data-role="final"]')).toHaveText('Hello from the local E2E model.');
+ const firstTurn = await replies.getAttribute('data-turn-id');
+ expect(firstTurn).toBeTruthy();
+ await expect(replies.locator('[data-role="process-loading"]')).toBeVisible();
+ await page.evaluate(turnId => {
+ const w = window as any;
+ w.__terminalRecoveryHandler = w._handleGroupBusEvent;
+ w.__terminalRecoveryDropped = 0;
+ w._handleGroupBusEvent = function (cid: string, row: any, event: any, options: any) {
+ if (event?.type === 'message' && event.turn_end === true && event.msg?.turn_id === turnId) {
+ w.__terminalRecoveryDropped++;
+ return;
+ }
+ return w.__terminalRecoveryHandler(cid, row, event, options);
+ };
+ }, firstTurn);
+ try {
+ await page.locator('#chat-input').fill('Complete a separate follow-up task.');
+ await page.locator('#chat-input').press('Enter');
+ modelOrkas.finishControlledModelStream();
+ modelOrkas.setModelMode('controlled-slow');
+ await expect.poll(() => modelOrkas.modelRequests.length, { timeout: 30_000 }).toBe(2);
+ await expect.poll(() => page.evaluate<number>('window.__terminalRecoveryDropped')).toBeGreaterThan(0);
+ await page.evaluate(cid => (window as any)._recoverObservedConversationHistory(cid), cid);
+ const oldReply = replies.first();
+ await expect(oldReply).toHaveAttribute('data-turn-id', firstTurn!);
+ await expect(oldReply).toHaveAttribute('data-turn-end', '1');
+ await expect(oldReply.locator('[data-role="process-loading"]')).toBeHidden();
+ await expect(oldReply.locator('[data-role="final"]')).toHaveText('Hello from the local E2E model.');
+ const oldDuration = await oldReply.locator('.stream-process-runtime').textContent();
+ await expect(replies).toHaveCount(2);
+ await expect(replies.nth(1).locator('[data-role="process-loading"]')).toBeVisible();
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ const nextDuration = await replies.nth(1).locator('.stream-process-runtime').textContent();
+ await expect.poll(() => replies.nth(1).locator('.stream-process-runtime').textContent()).not.toBe(nextDuration);
+ // Replay the read and an old delta while the follow-up is still working.
+ await page.evaluate(async ({ cid, turnId, actor }) => {
+ const w = window as any;
+ await w._recoverObservedConversationHistory(cid);
+ w._handleGroupBusEvent(cid, null, { type: 'process', actor, turn_id: turnId, seg: 0,
+ data: { type: 'delta', text: 'Stale first-turn text' } });
+ }, { cid, turnId: firstTurn, actor: agent.agent_id });
+ await expect(replies).toHaveCount(2);
+ await expect(oldReply.locator('[data-role="process-loading"]')).toBeHidden();
+ await expect(oldReply.locator('.stream-process-runtime')).toHaveText(oldDuration!);
+ await expect(page.locator('#chat-history')).not.toContainText('Stale first-turn text');
+ modelOrkas.releaseControlledModelChunk();
+ modelOrkas.finishControlledModelStream();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ await expect(page.locator('#chat-history .stream-process-loading:visible')).toHaveCount(0);
+ expect(modelOrkas.modelRequests).toHaveLength(2);
+ const history = await modelOrkas.invoke<any>('conversations.history', { cid });
+ expect(history.history.filter((record: any) => record.from === agent.agent_id)).toHaveLength(2);
+ } finally {
+ await page.evaluate(() => {
+ const w = window as any;
+ w._handleGroupBusEvent = w.__terminalRecoveryHandler;
+ delete w.__terminalRecoveryHandler;
+ delete w.__terminalRecoveryDropped;
+ });
+ }
+});
diff --git a/test/e2e/chat_e2e_cli_recovery.spec.ts b/test/e2e/chat_e2e_cli_recovery.spec.ts
index 8fdff6b8..0262bc16 100644
--- a/test/e2e/chat_e2e_cli_recovery.spec.ts
+++ b/test/e2e/chat_e2e_cli_recovery.spec.ts
@@ -9,7 +9,7 @@ import {
import path from 'node:path';
import type { Page } from '@playwright/test';
-import { expect, test, type OrkasTestApp } from './fixtures/orkas';
+import { openSidebarEntry, expect, test, type OrkasTestApp } from './fixtures/orkas';
import { estimateBudgetTokens } from '../../src/main/util/token-estimate';
async function createCliAgent(
@@ -102,7 +102,7 @@ test.describe('CLI Agent runtime settings', () => {
info: { mode: 'custom', path: selectedProjectDir, exists: true },
});
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
const card = page.locator(`.agent-card[data-id="${agentId}"]`);
await expect(card).toBeVisible({ timeout: 30_000 });
await card.click();
@@ -185,13 +185,16 @@ test.describe('CLI Agent runtime settings', () => {
});
test('persists overrides, resets model-specific thinking, and restores CLI defaults', async ({ cliOrkas }) => {
+ // Three cold application launches are fixture preparation, not a single
+ // interaction's latency budget. Keep each model/element wait unchanged.
+ test.setTimeout(240_000);
const agentName = 'CodexRuntimeSettingsE2E';
const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'codex');
await cliOrkas.invoke('agents.update', {
agent_id: agentId,
updates: { icon: 'code', color: 'lime' },
});
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
const card = page.locator(`.agent-card[data-id="${agentId}"]`);
await expect(card).toBeVisible({ timeout: 30_000 });
await card.click();
@@ -291,7 +294,7 @@ test.describe('CLI Agent runtime settings', () => {
kind: 'cli', cli: 'codex', model_override: 'gpt-e2e-deep', thinking_level: 'low',
});
const relaunchedPage = await cliOrkas.relaunch();
- await relaunchedPage.locator('#agents-btn').click();
+ await openSidebarEntry(relaunchedPage, '#agents-btn');
await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="model"]'))
.toHaveAttribute('data-value', 'gpt-e2e-deep', { timeout: 30_000 });
@@ -324,7 +327,7 @@ test.describe('CLI Agent runtime settings', () => {
// Clear each override through the real candidates tagged as defaults, then
// prove the persisted runtime and the next native turn both omit the fields.
- await relaunchedPage.locator('#agents-btn').click();
+ await openSidebarEntry(relaunchedPage, '#agents-btn');
await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
await expect(relaunchedPage.locator('#agents-detail-cli-settings [data-role="thinking"]'))
.toHaveAttribute('data-value', 'low', { timeout: 30_000 });
@@ -355,7 +358,7 @@ test.describe('CLI Agent runtime settings', () => {
expect(avatarAfterSettingsReset).toEqual(avatarBeforeSettingsReset);
const defaultPage = await cliOrkas.relaunch();
- await defaultPage.locator('#agents-btn').click();
+ await openSidebarEntry(defaultPage, '#agents-btn');
await defaultPage.locator(`.agent-card[data-id="${agentId}"]`).click();
await expect(defaultPage.locator('#agents-detail-cli-settings [data-role="model"]'))
.toHaveAttribute('data-value', '', { timeout: 30_000 });
@@ -373,6 +376,38 @@ test.describe('CLI Agent runtime settings', () => {
expect(defaultInvocation?.effort).toBeUndefined();
});
+ test.describe('Claude body streaming', () => {
+
+ test('paints Claude body chunks after thinking before the full assistant record or result exists', async ({ cliOrkas }, testInfo) => {
+ const name = 'ClaudeStreamingBodyE2E';
+ const { page, agentId } = await createCliAgent(cliOrkas, name, 'claude');
+ const gate = cliOrkas.cliStatePath + '.claude-stream-stage';
+ writeFileSync(gate, '0');
+ const cid = await sendNewChat(page, `@${name} E2E_CLAUDE_STREAM_BODY`);
+ const body = page.locator('#chat-history .chat-message.assistant [data-role="final"]');
+ // The CLI withholds both the full text record and result. A renderer
+ // that paints only on completion cannot satisfy either prefix assertion.
+ await expect(body).toContainText('First paragraph.', { timeout: 30_000 });
+ await expect(body).not.toContainText('Second paragraph.');
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ writeFileSync(gate, '1');
+ await expect(body).toContainText('Second paragraph.');
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ await expect(page.locator('#chat-history .chat-message.assistant')).toHaveCount(1);
+ const live = await cliOrkas.invoke<any>('conversations.history', { cid });
+ expect(live.history.filter((row: any) => row.from === agentId)).toHaveLength(0);
+ await page.screenshot({ path: testInfo.outputPath('claude-streaming-body.png') });
+ writeFileSync(gate, '2');
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ await expect(body.locator('h2')).toHaveText('Report');
+ await expect(body.locator('p')).toHaveText(['First paragraph.', 'Second paragraph.']);
+ const saved = await cliOrkas.invoke<any>('conversations.history', { cid });
+ expect(saved.history.filter((row: any) => row.from === agentId).map((row: any) => row.text))
+ .toEqual(['## Report\n\nFirst paragraph.\n\nSecond paragraph.']);
+ expect(cliOrkas.readCliState().invocations.filter(run => run.cli === 'claude')).toHaveLength(1);
+ });
+ });
+
test('labels Claude aliases and remembers only the matching concrete model', async ({ cliOrkas }) => {
const agentName = 'ClaudeModelAliasE2E';
const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'claude');
@@ -383,7 +418,7 @@ test.describe('CLI Agent runtime settings', () => {
},
});
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
await page.locator(`.agent-card[data-id="${agentId}"]`).click();
const model = page.locator('#agents-detail-cli-settings [data-role="model"]');
await expect(model.locator('.ai-select-trigger'))
@@ -407,7 +442,7 @@ test.describe('CLI Agent runtime settings', () => {
});
const relaunchedPage = await cliOrkas.relaunch();
- await relaunchedPage.locator('#agents-btn').click();
+ await openSidebarEntry(relaunchedPage, '#agents-btn');
await relaunchedPage.locator(`.agent-card[data-id="${agentId}"]`).click();
const relaunchedModel = relaunchedPage.locator(
'#agents-detail-cli-settings [data-role="model"]',
@@ -656,6 +691,45 @@ test.describe('CLI failed-turn recovery', () => {
expect(codexRuns[1].prompt).not.toContain('E2E_CODEX_DEFAULT_OK');
});
+ test('continues a hung Codex resume in a fresh process with canonical recovery context and saves its replacement session', async ({ cliOrkas }, testInfo) => {
+ const agentName = 'CodexBootstrapRecoveryE2E';
+ const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'codex');
+ const cid = await sendNewChat(page, `@${agentName} Earlier requirement: use amber-field.`);
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_CODEX_DEFAULT_OK',
+ })).toHaveCount(1, { timeout: 30_000 });
+ await expect.poll(() => {
+ try { return JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.sessionId; }
+ catch { return null; }
+ }).toBe(cliOrkas.readCliState().invocations[0].sessionId);
+ writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), codexResumeHangs: 1 }));
+ await cliOrkas.electronApp!.evaluate(() => { process.env.ORKAS_CODEX_BOOTSTRAP_TIMEOUT_MS = '1500'; });
+ await sendFollowUp(page, `@${agentName} Continue the earlier requirement.`);
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_CODEX_DEFAULT_OK',
+ })).toHaveCount(2, { timeout: 30_000 });
+ await expect(page.locator('#chat-history .bubble-retry-btn')).toHaveCount(0);
+ const state = cliOrkas.readCliState();
+ const runs = state.invocations.filter(run => run.cli === 'codex');
+ expect(runs).toHaveLength(2); // The hung child never received the task.
+ expect(state.codexThreadRequests?.map(request => request.method)).toEqual(['thread/start', 'thread/resume', 'thread/start']);
+ expect(state.codexThreadRequests?.[1].pid).not.toBe(state.codexThreadRequests?.[2].pid);
+ expect(runs[1].resumeSessionId).toBeNull();
+ expect(runs[1].sessionId).not.toBe(runs[0].sessionId);
+ expect(runs[1].prompt).toContain('Earlier requirement: use amber-field.');
+ expect(runs[1].prompt).toContain('Continue the earlier requirement.');
+ await expect.poll(() => JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.sessionId)
+ .toBe(runs[1].sessionId);
+ await expect.poll(async () => JSON.stringify((await cliOrkas.invoke<{ history: unknown[] }>('conversations.history', { cid, limit: 20 })).history))
+ .toContain('cli-bootstrap-timeout');
+ await page.screenshot({ path: testInfo.outputPath('codex-bootstrap-recovered.png'), fullPage: true });
+ await sendFollowUp(page, `@${agentName} Check the saved requirement.`);
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_CODEX_DEFAULT_OK',
+ })).toHaveCount(3, { timeout: 30_000 });
+ expect(cliOrkas.readCliState().invocations[2].resumeSessionId).toBe(runs[1].sessionId);
+ });
+
test('steers a composer update into the active Codex App Server turn without starting another CLI run', async ({ cliOrkas }) => {
// Queue absorption retired the local queue rows and their per-row "Send
// now": steering the live turn is the composer steer button, visible only
@@ -690,6 +764,42 @@ test.describe('CLI failed-turn recovery', () => {
expect(codexRuns[0].steers?.[0].text).toContain('E2E_CODEX_SEND_NOW_UPDATE');
});
+ test.describe('native question history', () => {
+ for (const cli of ['claude', 'codex'] as const) {
+ test(`shows a native ${cli} answer once in the conversation and retains it after reload`, async ({ cliOrkas }, testInfo) => {
+ const name = cli === 'claude' ? 'ClaudeQuestionHistory' : 'CodexQuestionHistory';
+ const { page } = await createCliAgent(cliOrkas, name, cli);
+ const cid = await sendNewChat(page, `@${name} E2E_CLI_NATIVE_QUESTION`);
+ const card = page.locator('#chat-cli-questions');
+ await expect(card.getByRole('textbox', { name: 'Which scope?' })).toBeVisible({ timeout: 30_000 });
+ await card.getByRole('button', { name: 'Current', exact: true }).click();
+ await card.getByRole('button', { name: 'Send answer', exact: true }).click();
+ await expect(card).toBeHidden();
+ const answer = page.locator('#chat-history .chat-message.user', { hasText: 'Which scope?' });
+ await expect(answer).toHaveCount(1);
+ await expect(answer).toContainText('Current');
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_CLI_QUESTION_CONTINUED',
+ })).toBeVisible({ timeout: 30_000 });
+ const history = await cliOrkas.invoke<{ history: Array<{ from: string; text: string }> }>('conversations.history', { cid, limit: 20 });
+ expect(history.history.filter(row => row.from === 'user' && row.text === 'Which scope?\nCurrent')).toHaveLength(1);
+ await page.screenshot({ path: testInfo.outputPath('native-question-answer.png'), fullPage: true });
+ await Promise.all([
+ page.waitForEvent('domcontentloaded'),
+ cliOrkas.electronApp!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.reload()),
+ ]);
+ await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ await expect(answer).toHaveCount(1);
+ await expect(answer).toContainText('Current');
+ await expect(card).toBeHidden();
+ const runs = cliOrkas.readCliState().invocations.filter(item => item.cli === cli);
+ expect(runs).toHaveLength(1);
+ expect(runs[0].questionAnswers).toEqual(cli === 'claude'
+ ? { 'Which scope?': 'Current' } : { scope: { answers: ['Current'] } });
+ });
+ }
+ });
+
test('cancels a live Codex question without an answer and keeps it dismissed after switching and reload', async ({ cliOrkas }) => {
const { page } = await createCliAgent(cliOrkas, 'CancelQuestionCodex', 'codex');
const cid = await sendNewChat(page, '@CancelQuestionCodex E2E_CODEX_SEND_NOW_ACTIVE E2E_CODEX_ASYNC_QUESTION');
@@ -732,7 +842,7 @@ test.describe('CLI failed-turn recovery', () => {
const agentName = 'OpenCodeSendNowE2E';
const { page } = await createCliAgent(cliOrkas, agentName, 'opencode');
await sendNewChat(page, `@${agentName} E2E_CLI_SEND_NOW_ACTIVE`);
- await expect.poll(() => cliOrkas.readCliState().invocations.length).toBe(1);
+ await expect.poll(() => cliOrkas.readCliState().invocations.length, { timeout: 30_000 }).toBe(1);
await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
const input = page.locator('#chat-input');
diff --git a/test/e2e/chat_e2e_model_stream.spec.ts b/test/e2e/chat_e2e_model_stream.spec.ts
index 9129d30e..a408335d 100644
--- a/test/e2e/chat_e2e_model_stream.spec.ts
+++ b/test/e2e/chat_e2e_model_stream.spec.ts
@@ -187,7 +187,8 @@ test.describe('real chat pipeline with a local model', () => {
)))).toEqual(['text', 'tool:call-e2e-commentary-1', 'text', 'tool:call-e2e-commentary-2']);
};
- await expect.poll(() => modelOrkas.commentaryStage).toBe(1);
+ // Cold history/model startup shares the real Electron process on low-tier hosts.
+ await expect.poll(() => modelOrkas.commentaryStage, { timeout: 30_000 }).toBe(1);
await assertProse(1);
await expect(tool(1)).toHaveCount(1);
await openOperations();
@@ -521,6 +522,11 @@ test.describe('real chat pipeline with a local model', () => {
await expect(retry).toBeVisible({ timeout: 30_000 });
const requestsBeforeUserRetry = modelOrkas.modelRequests.length;
expect(requestsBeforeUserRetry).toBeGreaterThan(1);
+ // The selected negative mode deliberately returns500 for each attempt.
+ // Match those exact responses; all other HTTP failures remain rejected.
+ for (let index = 0; index < requestsBeforeUserRetry; index++) {
+ modelOrkas.expectApiFailure('POST', '/api/v1/chat/completions', 500);
+ }
modelOrkas.setModelMode('success');
await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
@@ -548,6 +554,7 @@ test.describe('real chat pipeline with a local model', () => {
test('turns provider authentication failures into private actionable guidance', async ({ modelOrkas }) => {
modelOrkas.setModelMode('auth-error');
+ modelOrkas.expectApiFailure('POST', '/api/v1/chat/completions', 401);
const page = await sendNewChat(modelOrkas, 'E2E show a safe credential failure.');
const retry = page.locator('#chat-history .bubble-retry-btn').last();
await expect(retry).toBeVisible({ timeout: 30_000 });
@@ -559,6 +566,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(failedBubble).not.toContainText('invalid_api_key');
await expect(failedBubble).not.toContainText('sk-e2e-private-secret');
await expect(failedBubble).not.toContainText('req_e2e_auth_failure');
+ expect(modelOrkas.modelRequests).toHaveLength(1);
});
test('treats a truncated partial model stream as failed and keeps retry recoverable', async ({ modelOrkas }) => {
@@ -609,7 +617,7 @@ test.describe('real chat pipeline with a local model', () => {
test('board-queues a second message while streaming and runs it in order', async ({ modelOrkas }) => {
modelOrkas.setModelMode('slow');
const page = await sendNewChat(modelOrkas, 'E2E first slow queued turn.');
- await expect.poll(() => modelOrkas.modelRequests.length).toBeGreaterThan(0);
+ await expect.poll(() => modelOrkas.modelRequests.length, { timeout: 30_000 }).toBeGreaterThan(0);
await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
await page.locator('#chat-input').fill('E2E second queued turn.');
diff --git a/test/e2e/chat_e2e_saved_tasks.spec.ts b/test/e2e/chat_e2e_saved_tasks.spec.ts
new file mode 100644
index 00000000..4aefcad4
--- /dev/null
+++ b/test/e2e/chat_e2e_saved_tasks.spec.ts
@@ -0,0 +1,118 @@
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+
+
+test('recovers the completed reply without leaving the page when terminal delivery is lost', async ({ modelOrkas: app }) => {
+ test.setTimeout(120_000);
+ const page = app.page!;
+ app.setModelMode('controlled-slow');
+ // Drop only terminal bus delivery. Streaming, host execution, persistence,
+ // and history reads remain real, so a cleanup that deletes the row fails.
+ await page.evaluate(() => {
+ const original = (window as any)._handleGroupBusEvent;
+ (window as any).__droppedTerminalMessages = 0;
+ (window as any)._handleGroupBusEvent = function(cid: string, row: unknown, event: any, opts: unknown) {
+ if (event?.type === 'message' && event.msg?.from !== 'user') {
+ (window as any).__droppedTerminalMessages++;
+ return;
+ }
+ return original(cid, row, event, opts);
+ };
+ });
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('Reply while I keep this page open.');
+ await page.locator('#new-chat-send-btn').click();
+ await expect.poll(() => app.modelRequests.length, { timeout: 30_000 }).toBe(1);
+ app.releaseControlledModelChunk();
+ const reply = page.locator('#chat-history .chat-message.assistant').filter({ hasText: 'Hello from the local E2E model.' });
+ await expect(reply).toHaveCount(1);
+ app.finishControlledModelStream();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ await expect(reply).toHaveCount(1);
+ await expect(reply).toHaveAttribute('data-msg-id', /.+/);
+ expect(await page.evaluate(() => (window as any).__droppedTerminalMessages)).toBeGreaterThan(0);
+ expect(app.modelRequests).toHaveLength(1);
+});
+
+// Local protocol responses drive real tools, persistence, and renderer navigation.
+test('keeps saved automation and todo shortcuts usable live and after restart', async ({ modelOrkas: app }, testInfo) => {
+ test.setTimeout(120_000);
+ if (!app.page) throw new Error('Orkas renderer is unavailable');
+ let page = app.page;
+ const project = await app.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Release review' });
+ app.setSavedTasksScenario(project.project.project_id, 'The tasks have been saved.');
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('Schedule a nightly review and add a release-note todo.');
+ await page.locator('#new-chat-send-btn').click();
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]'))
+ .toContainText('The tasks have been saved.', { timeout: 30_000 });
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ const cid = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');
+ expect(cid).toBeTruthy();
+ const { history } = await app.invoke<{ history: Array<{ saved_tasks?: Array<{ kind: string; task_id: string; title: string }> }> }>(
+ 'conversations.history', { cid, limit: 20 },
+ );
+ const links = history.flatMap(row => row.saved_tasks || []);
+ expect(links.map(link => [link.kind, link.title])).toEqual([
+ ['automation', 'Nightly review'], ['todo', 'Review release notes'],
+ ]);
+ const automation = links.find(link => link.kind === 'automation')!;
+ const todo = links.find(link => link.kind === 'todo')!;
+ await app.invoke('projects.tasks.create', { projectId: project.project.project_id, content: 'Another release check' });
+ await expect(page.locator('#chat-history [data-saved-task-key]')).toHaveCount(2);
+ await page.evaluate(() => (window as any).setLang('zh'));
+ await expect(page.locator('#chat-history [data-saved-task-key] .chat-msg-created-agent-label').first()).toContainText('打开');
+ await page.evaluate(() => (window as any).setLang('en'));
+ await expect(page.locator('#chat-history [data-saved-task-key] .chat-msg-created-agent-label').first()).toContainText('Open');
+ await page.locator('#chat-history [data-saved-task-key]', { hasText: 'Nightly review' }).click();
+ await expect(page.locator('#auto-task-dialog-overlay')).toBeVisible();
+ await expect(page.locator('#auto-title-input')).toHaveValue('Nightly review');
+ await expect(page.locator(`#auto-list .todo-scope-chip[data-project-id="${project.project.project_id}"]`))
+ .toHaveAttribute('aria-pressed', 'true');
+ await page.locator('#auto-dialog-cancel-btn').click();
+ await expect(page.locator(`#auto-list .auto-row[data-task-id="${automation.task_id}"]`)).toBeVisible();
+ // Remember another scope and status grouping before following the shortcuts again.
+ await page.locator('#auto-list .todo-scope-chip[data-project-id=""]').click();
+ await openSidebarEntry(page, '#todos-btn');
+ await page.locator('[data-todo-group="status"]').click();
+ const todoCard = page.locator(`#todos-content [data-tid="${todo.task_id}"]`);
+ await expect(todoCard).toBeVisible();
+ const restingStyle = await todoCard.evaluate(element => {
+ const style = getComputedStyle(element);
+ return { background: style.backgroundColor, shadow: style.boxShadow };
+ });
+ await page.evaluate((id) => (window as any).setView('conversation', id), cid);
+ await page.locator('#chat-history [data-saved-task-key]', { hasText: 'Review release notes' }).click();
+ await expect(todoCard).toBeInViewport();
+ await expect(todoCard).toHaveClass(/\bis-highlighted\b/);
+ // A class alone misses board styles overriding the actual highlight.
+ await expect(todoCard).not.toHaveCSS('background-color', restingStyle.background, { timeout: 1500 });
+ await expect(todoCard).not.toHaveCSS('box-shadow', restingStyle.shadow, { timeout: 1500 });
+ await expect(page.locator('#todos-content .is-highlighted')).toHaveCount(1);
+ await page.screenshot({ path: testInfo.outputPath('todo-shortcut-highlight-en.png') });
+ await expect(todoCard).not.toHaveClass(/\bis-highlighted\b/);
+ await expect(todoCard).toHaveCSS('background-color', restingStyle.background);
+ await expect(todoCard).toHaveCSS('box-shadow', restingStyle.shadow);
+ await expect(page.locator('[data-todo-group="project"]')).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.locator(`#todos-content .todo-scope-chip[data-pid="${project.project.project_id}"]`))
+ .toHaveAttribute('aria-pressed', 'true');
+ // Reopening the shortcut should reveal the highlight again in a narrow window.
+ await page.setViewportSize({ width: 1024, height: 720 });
+ await page.evaluate((id) => { (window as any).setLang('zh'); (window as any).setView('conversation', id); }, cid);
+ await page.locator('#chat-history [data-saved-task-key]', { hasText: 'Review release notes' }).click();
+ await expect(todoCard).toBeInViewport();
+ await expect(todoCard).not.toHaveCSS('background-color', restingStyle.background, { timeout: 1500 });
+ await page.screenshot({ path: testInfo.outputPath('todo-shortcut-highlight-zh-narrow.png') });
+ await page.evaluate((id) => (window as any).setView('conversation', id), cid);
+ await page.locator('#chat-history [data-saved-task-key]', { hasText: 'Nightly review' }).click();
+ await expect(page.locator('#auto-task-dialog-overlay')).toBeVisible();
+ await expect(page.locator(`#auto-list .todo-scope-chip[data-project-id="${project.project.project_id}"]`))
+ .toHaveAttribute('aria-pressed', 'true');
+ await page.locator('#auto-dialog-cancel-btn').click();
+ page = await app.relaunch();
+ await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ await expect(page.locator('#chat-history [data-saved-task-key]')).toHaveCount(2);
+ await page.locator('#chat-history [data-saved-task-key]', { hasText: 'Nightly review' }).click();
+ await expect(page.locator('#auto-title-input')).toHaveValue('Nightly review');
+ await expect(page.locator(`#auto-list .todo-scope-chip[data-project-id="${project.project.project_id}"]`))
+ .toHaveAttribute('aria-pressed', 'true');
+});
diff --git a/test/e2e/chat_e2e_send_responsiveness.spec.ts b/test/e2e/chat_e2e_send_responsiveness.spec.ts
index c5a38ef8..bbf8d6de 100644
--- a/test/e2e/chat_e2e_send_responsiveness.spec.ts
+++ b/test/e2e/chat_e2e_send_responsiveness.spec.ts
@@ -83,20 +83,26 @@ for (const injectedStallMs of [0, 600]) {
// Schedule the click immediately after Send inside the renderer. Sequential
// Playwright clicks could wait out the stall before starting the measurement.
- const switchMs = await page.evaluate(({ cidB, marker }) => new Promise<number>((resolve, reject) => {
+ const timing = await page.evaluate(({ cidB, marker }) => new Promise<{ switchMs: number; clickDelayMs: number; historyMs: number }>((resolve, reject) => {
const rowSelector = `#conversation-list .conv-item[data-cid="${cidB}"]`;
const startedAt = performance.now();
+ let clickedAt = startedAt;
const timeout = setTimeout(() => { observer.disconnect(); reject(new Error('Conversation switch did not finish')); }, 5000);
const observer = new MutationObserver(() => {
if (!document.querySelector('#chat-history')?.textContent?.includes(marker)) return;
observer.disconnect();
clearTimeout(timeout);
- resolve(performance.now() - startedAt);
+ const finishedAt = performance.now();
+ resolve({ switchMs: finishedAt - startedAt, clickDelayMs: clickedAt - startedAt, historyMs: finishedAt - clickedAt });
});
observer.observe(document.getElementById('chat-history')!, { childList: true, subtree: true, characterData: true });
document.getElementById('chat-send-btn')!.click();
- setTimeout(() => (document.querySelector(rowSelector) as HTMLElement).click(), 0);
+ setTimeout(() => {
+ clickedAt = performance.now();
+ (document.querySelector(rowSelector) as HTMLElement).click();
+ }, 0);
}), { cidB, marker });
+ const switchMs = timing.switchMs;
await expect.poll(() => modelOrkas.modelRequests.length).toBe(requestsBefore + 1);
const pulse = await app.evaluate(async () => {
// Drain one timer tick: even a stall ending at the request boundary must count.
@@ -115,13 +121,16 @@ for (const injectedStallMs of [0, 600]) {
);
expect(historyA.history.filter(message => message.from === 'user').map(message => message.text))
.toEqual(['Send while I read another conversation.']);
- console.log('[send-responsiveness]', JSON.stringify({ switch_ms: switchMs, main_loop_gap_ms: pulse.maxGapMs, injected_stall_ms: injectedStallMs }));
+ console.log('[send-responsiveness]', JSON.stringify({ switch_ms: switchMs, scheduled_click_ms: timing.clickDelayMs, history_ms: timing.historyMs, main_loop_gap_ms: pulse.maxGapMs, injected_stall_ms: injectedStallMs }));
if (injectedStallMs) {
expect(pulse.injected).toBe(true);
expect(() => checkLatencyBudget('main loop response negative control', { elapsedMs: pulse.maxGapMs }))
.toThrow('budget 500 ms');
} else {
- checkLatencyBudget('send A then open B', { elapsedMs: switchMs });
+ checkLatencyBudget('send A then open B', { elapsedMs: switchMs, phases: [
+ { phase: 'scheduled_click', ms: timing.clickDelayMs },
+ { phase: 'history_render', ms: timing.historyMs },
+ ] });
checkLatencyBudget('main loop response during send', { elapsedMs: pulse.maxGapMs });
}
});
diff --git a/test/e2e/chat_e2e_streaming_markdown.spec.ts b/test/e2e/chat_e2e_streaming_markdown.spec.ts
index 5149d286..939eca7d 100644
--- a/test/e2e/chat_e2e_streaming_markdown.spec.ts
+++ b/test/e2e/chat_e2e_streaming_markdown.spec.ts
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { expect, test, type Page } from '@playwright/test';
+import { classifyNativeCommentary } from '../../src/main/features/group_chat/message-display';
// Real renderer, DOMPurify, local MathJax and fonts. No account or model calls.
test.use({ launchOptions: { executablePath: process.env.ORKAS_E2E_BROWSER_PATH } });
@@ -10,7 +11,7 @@ const index = fs.readFileSync(path.join(renderer, 'index.html'), 'utf8');
const mathConfig = index.slice(index.indexOf('window.MathJax = {'), index.indexOf('</script>', index.indexOf('window.MathJax = {')));
const capturedLogs = new WeakMap<Page, Array<{ level: string; message: string }>>();
-test('renders process commentary formulas and retains completed formulas as the prose grows', async ({ page }, testInfo) => {
+test('renders process commentary formulas and retains completed formulas as the prose grows', async ({ page }) => {
await setup(page);
await page.evaluate(() => {
const w = window as any;
@@ -32,8 +33,6 @@ test('renders process commentary formulas and retains completed formulas as the
return w.commentaryMath.isConnected && w.commentary.querySelector('mjx-container') === w.commentaryMath;
})).toBe(true);
await expect(commentary).toContainText('Second result:');
- await page.locator('.stream-process').evaluate((element) => { (element as HTMLDetailsElement).open = true; });
- await commentary.screenshot({ path: testInfo.outputPath('process-formulas.png') });
});
test.afterEach(async ({ page }, testInfo) => {
@@ -66,7 +65,7 @@ async function setup(page: Page) {
capturedLogs.set(page, logs);
page.on('pageerror', e => logs.push({ level: 'error', message: e.message }));
page.on('console', m => logs.push({ level: m.type(), message: m.text() }));
- const scripts = ['icons', 'strip-structural-blocks', 'utils', 'math', 'composer-input', 'conversation'];
+ const scripts = ['icons', 'avatar', 'strip-structural-blocks', 'utils', 'math', 'composer-input', 'conversation'];
const fixture = test.info().outputPath('renderer.html');
fs.mkdirSync(path.dirname(fixture), { recursive: true });
fs.writeFileSync(fixture, `<!doctype html><html><head><meta charset="utf-8">
@@ -146,6 +145,46 @@ function isFontFallbackNotice(log: { level: string; message: string }) {
&& /\/vendor\/mathjax\/output\/chtml\/fonts\/woff-v2\/MathJax_[\w-]+\.woff$/.test(log.message);
}
+for (const formulas of [false, true]) {
+ test(`foreground snapshot keeps the readable reply while ${formulas ? 'formula' : 'prose'} repaint waits`, async ({ page }, testInfo) => {
+ await setup(page);
+ await page.evaluate(formulas => {
+ const w = window as any;
+ w.msg.dataset.fromActor = 'codex-agent';
+ w.msg.dataset.turnId = 'foreground';
+ w._stampRenderKey(w.msg, 'fixture', w._segmentRenderKey('foreground', 0));
+ w.prefix = formulas ? 'Readable \\(a+b\\). token-1.' : 'Readable reply token-1.';
+ w._streamingAppendFinalDelta(w.msg, w.prefix, 'final_answer');
+ }, formulas);
+ await settled(page);
+ await page.evaluate(formulas => {
+ const w = window as any;
+ w.observe(formulas ? 1 : 0);
+ const queue = w._queueStreamingPaint;
+ // Hold the scheduled body paint at the real recovery boundary. The DOM
+ // must remain readable even when frame scheduling is delayed on resume.
+ w._queueStreamingPaint = (msg: any, slot: string, paint: () => void) => {
+ if (slot === 'final') w.releaseRecoveredPaint = () => queue(msg, slot, paint);
+ else queue(msg, slot, paint);
+ };
+ w._restoreLiveDisplaySnapshot('fixture', { sequence: 2, turns: [{
+ actor: 'codex-agent', turn_id: 'foreground', records: [{
+ from: 'codex-agent', turn_id: 'foreground', seg: 0,
+ text: w.prefix + (formulas ? ' New \\(c+d\\). token-2.' : ' New text token-2.'), process: [],
+ }],
+ }] });
+ }, formulas);
+ await expect(page.locator('[data-role="final"]')).toBeVisible();
+ await expect(page.locator('[data-role="final"]')).toContainText('Readable');
+ await page.waitForTimeout(120);
+ await page.evaluate(() => (window as any).releaseRecoveredPaint());
+ await settled(page);
+ await expect(page.locator('[data-role="final"]')).toContainText('token-2');
+ await page.waitForTimeout(120);
+ await checkFrames(page, testInfo);
+ });
+}
+
test('coalesces across frames while preserving long Markdown, typing and the latest trailing text', async ({ page }, testInfo) => {
await setup(page);
const text = '## Report\n\nUse `code` and **emphasis**.\n\n| Item | Value |\n| --- | --- |\n| Revenue | 42 |\n\n```js\nconst value = 42;\n```\n\n'.repeat(80);
@@ -565,3 +604,167 @@ test('prose appends preserve loaded images and audio state, while later embeds r
const w = window as any; return w.audio === w.finalEl.querySelector('audio') && w.audio.currentTime === 0.25;
})).toBe(true);
});
+
+test('stored native classification survives live delivery, recovery and standalone history rendering', async ({ page }, testInfo) => {
+ await setup(page);
+ const record = classifyNativeCommentary({ id: 'native-0', ts: '2026-10-14T10:00:00',
+ from: 'claude', to: ['user'], turn_id: 'classified-turn', source_message_id: 'source', seg: 0,
+ text: 'Inspecting **the project**.', process: [{ type: 'progress', text: 'Read files' }] });
+ await page.evaluate(record => {
+ const w = window as any;
+ w.isGroupConversationBusy = () => true;
+ Object.assign(w.msg.dataset, { fromActor: 'claude', turnId: record.turn_id });
+ w._stampRenderKey(w.msg, 'fixture', w._segmentRenderKey(record.turn_id, 0));
+ w.msg.dataset.streamBuf = record.text;
+ w._appendProcessTextLines(w.msg.querySelector('[data-role="process"]'), 'Read files', 'tool', 'Read');
+ w._handleGroupBusEvent('fixture', w.msg, { type: 'process', actor: 'claude', turn_id: record.turn_id, seg: 0,
+ data: { type: 'native-message-finalized', phase: 'commentary', text: record.text } });
+ w._handleGroupBusEvent('fixture', w.msg, { type: 'process', actor: 'claude', turn_id: record.turn_id, seg: 1,
+ data: { type: 'delta', text: 'Final answer.' } });
+ }, record);
+ await expect(page.locator('.stream-process-commentary:not([hidden])')).toHaveCount(1);
+ await expect(page.locator('[data-role="final"]')).toHaveText('Final answer.');
+ await page.evaluate(record => {
+ const w = window as any;
+ w._restoreLiveDisplaySnapshot('fixture', { sequence: 4, turns: [{ actor: 'claude', turn_id: record.turn_id,
+ records: [record, { ...record, id: '', seg: 1, text: 'Final answer.', display_phase: 'pending', process: [] }] }] });
+ }, record);
+ await expect(page.locator('.stream-process-commentary')).toHaveCount(1);
+ await expect(page.locator('[data-role="final"]')).toHaveText('Final answer.');
+ await page.evaluate(record => {
+ const w = window as any;
+ w._streamingSetFinal(w.msg, 'Final answer.');
+ document.querySelector('#chat-history')!.replaceChildren();
+ // A history page may contain this record alone. Stored classification,
+ // rather than another message on the page, decides where its text belongs.
+ w.appendChatMessage(w._groupMsgToLegacy(record), false,
+ { archive: false, historyHydration: true, messageActions: 'errors-only' });
+ }, record);
+ await expect(page.locator('.stream-process')).not.toHaveAttribute('open');
+ await expect(page.locator('.chat-bubble > .markdown-body')).toHaveText('');
+ await page.locator('.stream-process-summary').click();
+ await expect(page.locator('.stream-process-commentary')).toHaveCount(1);
+ await expect(page.locator('.stream-process-commentary')).toHaveText('Inspecting the project.');
+ await page.screenshot({ path: testInfo.outputPath('stored-classification.png') });
+});
+
+for (const expanded of [false, true]) {
+test(`a forward history page preserves process open=${expanded}`, async ({ page }) => {
+ await setup(page);
+ await page.evaluate(expanded => {
+ const w = window as any;
+ const history = document.querySelector('#chat-history')!;
+ history.replaceChildren();
+ const makeRow = (seg: number, text: string) => {
+ const row = w._createStreamingAssistantMessage(history, { messageActions: 'errors-only' });
+ Object.assign(row.dataset, { fromActor: 'claude', turnId: 'paged-turn', msgId: `record-${seg}` });
+ w._stampRenderKey(row, 'fixture', w._segmentRenderKey('paged-turn', seg));
+ row._historyLegacyMessage = { content: text };
+ w._streamingSetFinal(row, text);
+ row.querySelector('.stream-process').remove();
+ w._renderPersistedProcess(row, [{ type: 'progress', text: `operation-${seg}` }]);
+ return row;
+ };
+ makeRow(0, 'Checking **the first page**.').querySelector('.stream-process').open = expanded;
+ const next = makeRow(1, 'The final answer.');
+ w._joinNewerHistoryTurn(history, next);
+ }, expanded);
+ await expect(page.locator('.chat-message')).toHaveCount(1);
+ await expect(page.locator('[data-role="final"]')).toHaveText('The final answer.');
+ await expect(page.locator('.stream-process')).toHaveCount(1);
+ expect(await page.locator('.stream-process').evaluate((el: HTMLDetailsElement) => el.open)).toBe(expanded);
+ if (!expanded) await page.locator('.stream-process-summary').click();
+ await expect(page.locator('.stream-process')).toContainText('Checking the first page.');
+ await expect(page.locator('.stream-process')).toContainText('operation-0');
+ await expect(page.locator('.stream-process')).toContainText('operation-1');
+ await expect(page.locator('.chat-turn-narration, .chat-turn-narration-toggle')).toHaveCount(0);
+});
+
+test(`an older history page preserves completed process open=${expanded}`, async ({ page }, testInfo) => {
+ await setup(page);
+ await page.evaluate(() => {
+ const w = window as any;
+ Object.assign(w.msg.dataset, { fromActor: 'claude', turnId: 'older-turn', msgId: 'record-2' });
+ w._stampRenderKey(w.msg, 'fixture', w._segmentRenderKey('older-turn', 2));
+ w._streamingSetFinal(w.msg, 'Completed answer.');
+ w.msg.querySelector('.stream-process').remove();
+ w._renderPersistedProcess(w.msg, [{ type: 'progress', text: 'Last operation' }]);
+ });
+ if (expanded) await page.locator('.stream-process-summary').click();
+ await page.evaluate(() => {
+ const w = window as any;
+ w._mergeNativeSegmentRecords([{ id: 'record-1', from: 'claude', turn_id: 'older-turn',
+ seg: 1, text: 'Earlier progress note.', process: [] }], 'fixture');
+ });
+ expect(await page.locator('.stream-process').evaluate((el: HTMLDetailsElement) => el.open)).toBe(expanded);
+ await expect(page.locator('[data-role="final"]')).toHaveText('Completed answer.');
+ await page.screenshot({ path: testInfo.outputPath('process-after-history-merge.png') });
+ if (!expanded) await page.locator('.stream-process-summary').click();
+ await expect(page.locator('.stream-process')).toContainText('Earlier progress note.');
+ await expect(page.locator('.stream-process')).toContainText('Last operation');
+});
+}
+
+for (const [locale, width, height] of [['zh', 1200, 780], ['en', 720, 500]] as const) {
+ test(`native message commentary shares one process disclosure (${locale}, ${width})`, async ({ page }, testInfo) => {
+ await page.setViewportSize({ width, height });
+ await setup(page);
+ const dictionary = JSON.parse(fs.readFileSync(path.join(renderer, 'locales', `${locale}.json`), 'utf8'));
+ await page.evaluate(({ dictionary, locale }) => {
+ const w = window as any;
+ w.t = (key: string, values: Record<string, unknown> = {}) => String(dictionary[key] || key)
+ .replace(/\{(\w+)\}/g, (_: string, name: string) => String(values[name] ?? `{${name}}`));
+ const history = document.querySelector('#chat-history') as HTMLElement;
+ history.style.width = '100%'; history.style.height = 'calc(100vh - 20px)';
+ document.querySelector('#composer')?.remove();
+ history.replaceChildren();
+ w.msg = w._createStreamingAssistantMessage(history, { messageActions: 'errors-only' });
+ w.msg.querySelector('[data-role="from-chip"]').textContent = 'Claude Code';
+ w.msg.dataset.turnId = 'native-fixture';
+ w.finalEl = w.msg.querySelector('[data-role="final"]');
+ w.records = [];
+ for (let seg = 0; seg < 19; seg++) {
+ const text = locale === 'zh' ? `正在核对第 ${seg + 1} 项:**检查执行结果**,保留完整过程记录。`
+ : `Checking step ${seg + 1}: **verify the execution result**, retaining the complete progress note.`;
+ w.records.push({ id: `segment-${seg}`, seg, text, process: [] });
+ w.msg.dataset.streamBuf = text;
+ w._appendProcessTextLines(w.msg.querySelector('[data-role="process"]'), `operation-${seg}`, 'tool', 'Read');
+ w._demoteBodyToNarration(w.msg, seg);
+ }
+ w.finalAnswer = locale === 'zh' ? '核对完成。最终结果保留在正文,过程可展开查看。'
+ : 'Review complete. The final result remains here; expand the execution details to inspect progress.';
+ w.records.push({ id: 'final', seg: 19, text: w.finalAnswer, process: [
+ { type: 'event', event: { stream: 'runtime', data: { duration_ms: 901000, phase: 'end' } } },
+ ] });
+ }, { dictionary, locale });
+ // Live grouping must not absorb the next segment's operation before its prose.
+ expect(await page.evaluate(() => Array.from((window as any).msg.querySelector('[data-role="process"]').children)
+ .filter((el: any) => !el.hidden).map((el: any) => el.classList.contains('stream-process-commentary') ? 'text' : 'operations')))
+ .toEqual(Array.from({ length: 19 }, () => ['text', 'operations']).flat());
+ await page.evaluate(() => {
+ const w = window as any;
+ w._streamingSetFinal(w.msg, w.finalAnswer);
+ const merged = w._mergeSegmentGroup(w.records).merged;
+ w.msg.querySelector('.stream-process').remove();
+ w._renderPersistedProcess(w.msg, merged.process, { parts: merged.process_parts });
+ });
+ await expect(page.locator('[data-role="final"]')).toHaveText(await page.evaluate(() => (window as any).finalAnswer));
+ await expect(page.locator('.stream-process')).not.toHaveAttribute('open');
+ await expect(page.locator('.chat-turn-narration, .chat-turn-narration-toggle')).toHaveCount(0);
+ await expect(page.locator('.stream-process-commentary')).toHaveCount(0); // lazy history
+ await page.screenshot({ path: testInfo.outputPath('native-process-collapsed.png') });
+ await page.locator('.stream-process-summary').focus();
+ await page.keyboard.press('Enter');
+ await expect(page.locator('.stream-process-commentary')).toHaveCount(19);
+ await expect(page.locator('.stream-process-commentary').first()).toBeVisible();
+ expect(await page.evaluate(() => {
+ const body = document.querySelector('.chat-bubble') as HTMLElement;
+ return body.scrollWidth <= body.clientWidth + 1;
+ })).toBe(true);
+ await page.screenshot({ path: testInfo.outputPath('native-process-expanded.png') });
+ await page.locator('.stream-process-summary').focus();
+ await page.keyboard.press('Enter');
+ await expect(page.locator('.stream-process-commentary').last()).not.toBeVisible();
+ await expect(page.locator('[data-role="final"]')).toBeVisible();
+ });
+}
diff --git a/test/e2e/chat_image_e2e_complete_frame.spec.ts b/test/e2e/chat_image_e2e_complete_frame.spec.ts
new file mode 100644
index 00000000..cb6d46dc
--- /dev/null
+++ b/test/e2e/chat_image_e2e_complete_frame.spec.ts
@@ -0,0 +1,117 @@
+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import sharp from 'sharp';
+import { expect } from './fixtures/orkas';
+import { test } from './fixtures/web-app-eval';
+
+
+// Visible source landmarks, rather than a CSS keyword, distinguish complete
+// framing from cover/crop. Keep them inset from rounded edges and viewer actions.
+const colors = ['#e53040', '#24b050', '#3050e0', '#e0b020'];
+async function assertCorners(png: Buffer, locations: Array<{ x: number; y: number }>, palette = colors) {
+ const image = await sharp(png).removeAlpha().raw().toBuffer({ resolveWithObject: true });
+ for (const [index, point] of locations.entries()) {
+ const x = Math.floor(point.x), y = Math.floor(point.y);
+ expect(x).toBeGreaterThanOrEqual(0);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(x).toBeLessThan(image.info.width);
+ expect(y).toBeLessThan(image.info.height);
+ const offset = (y * image.info.width + x) * image.info.channels;
+ const expected = palette[index].slice(1).match(/../g)!.map(hex => parseInt(hex, 16));
+ // Display color conversion may alter RGB; it cannot remove a landmark.
+ for (let channel = 0; channel < 3; channel++) {
+ expect(Math.abs(image.data[offset + channel] - expected[channel])).toBeLessThan(35);
+ }
+ }
+}
+
+test('preserves every corner from chat through native preview, resize and zoom reset', async ({ sdkOrkas: orkas }, info) => {
+ const created: any = await orkas.invoke('conversations.create', { title: 'Complete image framing' });
+ const cid = created.conversation.conversation_id;
+ const page = orkas.page!;
+ for (const [width, height] of [[1080, 1080], [1080, 2160], [2160, 1080]]) {
+ const points = [
+ { x: 200, y: 200 }, { x: width - 200, y: 200 },
+ { x: 200, y: height - 200 }, { x: width - 200, y: height - 200 },
+ ];
+ const png = await sharp(Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
+ <rect width="100%" height="100%" fill="#f5f5f5"/>
+ ${points.map((p, i) => `<rect x="${p.x - 40}" y="${p.y - 40}" width="80" height="80" fill="${colors[i]}"/>`).join('')}
+ </svg>`)).png().toBuffer();
+ const file = path.join(orkas.userWorkspaceRoot, `corners-${width}-${height}.png`);
+ writeFileSync(file, png);
+ appendFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`), JSON.stringify({
+ id: `corners-${width}-${height}`, from: 'commander', to: ['user'], ts: new Date().toISOString(),
+ text: `![Complete frame](${file})`,
+ }) + '\n');
+ await page.evaluate(async id => {
+ await (window as any).loadConversations();
+ await (window as any).setView('conversation', id);
+ }, cid);
+ const chatImage = page.locator('#chat-history img.chat-md-img').last();
+ await expect.poll(() => chatImage.evaluate((img: HTMLImageElement) => img.naturalWidth)).toBe(width);
+ await expect(chatImage).toHaveCSS('opacity', '1');
+ // Tall images require transcript scrolling. Element screenshots cannot
+ // reveal portions clipped by a scrolling ancestor; inspect each end in view.
+ const chatBox = (await chatImage.boundingBox())!;
+ expect(Math.abs(chatBox.width / chatBox.height - width / height)).toBeLessThan(0.01);
+ for (const [index, point] of points.entries()) {
+ await chatImage.evaluate(async (img, args) => {
+ const history = img.closest('.chat-history')! as HTMLElement;
+ const box = img.getBoundingClientRect(), parent = history.getBoundingClientRect();
+ const previous = history.style.scrollBehavior;
+ history.style.scrollBehavior = 'auto';
+ history.scrollTop += box.y + args.y * box.height / args.height - parent.y - parent.height / 2;
+ history.style.scrollBehavior = previous;
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ }, { y: point.y, height });
+ const box = (await chatImage.boundingBox())!;
+ const screenshot = await page.screenshot({ path: info.outputPath(`chat-${width}-${height}-${index}.png`), scale: 'css' });
+ await assertCorners(screenshot, [{ x: box.x + point.x * box.width / width, y: box.y + point.y * box.height / height }], [colors[index]]);
+ }
+ const preview = await orkas.openPreview(() => chatImage.click());
+ const image = preview.locator('.chat-lightbox-img');
+ await expect.poll(() => image.evaluate((img: HTMLImageElement) => [img.naturalWidth, img.naturalHeight])).toEqual([width, height]);
+ const native = await orkas.electronApp!.browserWindow(preview);
+ for (const size of [[740, 540], [480, 640]]) {
+ await native.evaluate((win, size) => win.setContentSize(size[0], size[1]), size);
+ await expect.poll(() => preview.evaluate(() => [innerWidth, innerHeight])).toEqual(size);
+ await preview.keyboard.press('+');
+ await expect(image).not.toHaveCSS('transform', 'matrix(1, 0, 0, 1, 0, 0)');
+ await preview.keyboard.press('0');
+ await expect(image).toHaveCSS('transform', 'matrix(1, 0, 0, 1, 0, 0)');
+ const box = (await image.boundingBox())!;
+ expect(box.x).toBeGreaterThanOrEqual(0);
+ expect(box.y).toBeGreaterThanOrEqual(0);
+ expect(box.x + box.width).toBeLessThanOrEqual(size[0]);
+ expect(box.y + box.height).toBeLessThanOrEqual(size[1]);
+ const screenshot = await preview.screenshot({ path: info.outputPath(`preview-${width}-${height}-${size[0]}.png`), scale: 'css' });
+ await assertCorners(screenshot, points.map(p => ({ x: box.x + p.x * box.width / width, y: box.y + p.y * box.height / height })));
+ }
+ // The preview resource must retain the exact source, not a thumbnail.
+ const served = await image.evaluate(async (img: HTMLImageElement) => Array.from(new Uint8Array(await (await fetch(img.src)).arrayBuffer())));
+ expect(Buffer.from(served)).toEqual(png);
+ if (width > height) {
+ const box = (await image.boundingBox())!;
+ await image.evaluate((img: HTMLImageElement) => { img.style.width = '100%'; img.style.height = '100%'; img.style.objectFit = 'cover'; });
+ const cropped = await preview.screenshot({ scale: 'css' });
+ await expect(assertCorners(cropped, points.map(p => ({ x: box.x + p.x * box.width / width, y: box.y + p.y * box.height / height })))).rejects.toThrow();
+ }
+ await orkas.closePreview(preview);
+ // Image links become previews too. A same-message link beside an identical
+ // embed is intentionally deduplicated, so exercise the link-only entry.
+ appendFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`), JSON.stringify({
+ id: `original-${width}-${height}`, from: 'commander', to: ['user'], ts: new Date().toISOString(),
+ text: `[Open original](${file})`,
+ }) + '\n');
+ await page.evaluate(async id => { await (window as any).setView('conversation', id); }, cid);
+ const originalImage = page.locator('#chat-history img.chat-md-img').last();
+ await expect(originalImage).toHaveAttribute('alt', 'Open original');
+ const original = await orkas.openPreview(() => originalImage.click());
+ const originalBytes = await original.locator('.chat-lightbox-img').evaluate(async (img: HTMLImageElement) =>
+ Array.from(new Uint8Array(await (await fetch(img.src)).arrayBuffer())));
+ expect(Buffer.from(originalBytes)).toEqual(png);
+ await orkas.closePreview(original);
+ expect(readFileSync(file)).toEqual(png);
+ }
+});
diff --git a/test/e2e/cli_upgrade_e2e_recovery.spec.ts b/test/e2e/cli_upgrade_e2e_recovery.spec.ts
new file mode 100644
index 00000000..4b19f6be
--- /dev/null
+++ b/test/e2e/cli_upgrade_e2e_recovery.spec.ts
@@ -0,0 +1,271 @@
+import { chmodSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+
+// Real Electron/IPC/discovery/updater flow with an isolated native installer.
+// No host package manager, real account or paid model is used.
+test('offers CLI upgrade on creation, details and execution failures', async ({ cliOrkas }, testInfo) => {
+ test.skip(process.platform === 'win32', 'Native POSIX installer fixture; Windows updater smoke is separate.');
+ test.setTimeout(120_000);
+ const app = cliOrkas; const page = app.page!;
+ const versionFile = path.join(app.root, 'upgrade-version');
+ const modeFile = path.join(app.root, 'upgrade-mode');
+ const updatesFile = path.join(app.root, 'upgrade-calls');
+ const bin = path.join(app.root, '.codex/packages/standalone/current/bin/codex');
+ mkdirSync(path.dirname(bin), { recursive: true });
+ writeFileSync(versionFile, '0.144.0'); writeFileSync(modeFile, 'success');
+ const source = `#!${process.env.ORKAS_TEST_NODE || process.execPath}\n
+const fs = require('node:fs'); const cp = require('node:child_process');
+const versionFile = ${JSON.stringify(versionFile)}; const modeFile = ${JSON.stringify(modeFile)};
+if (process.argv.includes('--version')) console.log(fs.readFileSync(versionFile, 'utf8'));
+else if (process.argv.includes('--help')) console.log('Commands:\\n update Upgrade Codex');
+else if (process.argv.includes('update')) {
+ fs.appendFileSync(${JSON.stringify(updatesFile)}, 'update\\n');
+ setTimeout(() => { if (fs.readFileSync(modeFile, 'utf8') === 'failure') process.exit(7);
+ fs.writeFileSync(versionFile, '0.159.3'); }, 2000);
+} else {
+ const child = cp.spawn(${JSON.stringify(app.fakeCodexPath)}, process.argv.slice(2), { stdio: 'inherit', env: process.env });
+ child.on('exit', code => process.exit(code || 0));
+}\n`;
+ writeFileSync(bin, source); chmodSync(bin, 0o755);
+ await app.electronApp!.evaluate((_electron, file) => { process.env.ORKAS_CODEX_PATH = file; }, bin);
+ await app.invoke('localAgents.detect', { type: 'codex' });
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await openSidebarEntry(page, '#agents-btn');
+ await page.locator('#agents-connect-cli-btn').click();
+ const creation = page.locator('#agent-modal-ext-cli-upgrades [data-cli="codex"]');
+ await expect(creation.locator('.local-cli-upgrade-btn')).toBeVisible();
+ await expect(creation.locator('button')).toHaveText('升级 CLI');
+ await expect(page.locator('#agent-modal-ext-cli-upgrade-warning')).toContainText('0.144.0');
+ await page.screenshot({ path: testInfo.outputPath('01-create-upgrade.png') });
+ await creation.locator('button').click();
+ await expect(creation.locator('button')).toHaveText('升级中…');
+ await expect(creation.locator('button')).toBeDisabled();
+ await expect(creation.locator('[role="status"]')).toBeEmpty();
+ await page.screenshot({ path: testInfo.outputPath('02-upgrade-progress.png') });
+ await expect(creation.locator('[role="status"]')).toHaveText('升级成功', { timeout: 30_000 });
+ await page.locator('#agent-modal-ext-cli-select .ai-select-trigger').click();
+ const codexChoice = page.locator('.ai-select-popover:visible .ai-select-item[data-value="codex"]');
+ await expect(codexChoice).toContainText('0.159.3');
+ await codexChoice.click();
+ await expect(page.locator('#agent-modal-ext-cli-select .ai-select-trigger')).toContainText('0.159.3');
+ await page.screenshot({ path: testInfo.outputPath('03-upgrade-success.png') });
+ expect(readFileSync(updatesFile, 'utf8')).toBe('update\n');
+ await page.locator('#agent-modal .modal-actions .btn').first().click();
+ const created = await app.invoke<{ agent: { agent_id: string } }>('agents.create', {
+ name: 'CodexUpgradeDemo', description: 'CLI 兼容性测试', runtime: { kind: 'cli', cli: 'codex' },
+ });
+ expect(created).toMatchObject({ ok: true, agent: { agent_id: expect.any(String) } });
+ await page.evaluate(async id => { await (window as any).openAgentDetail(id); }, created.agent.agent_id);
+ const detail = page.locator('#agents-detail-runtime .local-cli-upgrade-control');
+ await expect(detail.locator('button')).toBeVisible();
+ await expect(page.locator('#agents-detail-cli-settings [data-role="model"]')).toBeVisible({ timeout: 30_000 });
+ await page.screenshot({ path: testInfo.outputPath('04-details-upgrade.png') });
+ writeFileSync(modeFile, 'failure');
+ await detail.locator('button').click();
+ await expect(detail.locator('[role="status"]')).toContainText('升级失败', { timeout: 30_000 });
+ await page.screenshot({ path: testInfo.outputPath('05-upgrade-failure.png') });
+ writeFileSync(versionFile, '0.144.0'); writeFileSync(modeFile, 'success');
+ await app.invoke('localAgents.detect', { type: 'codex' });
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('@CodexUpgradeDemo 请检查 CLI 版本');
+ await page.locator('#new-chat-send-btn').click();
+ const recovery = page.locator('#chat-history .chat-message[data-failure-code="version_too_old"] .chat-bubble .chat-app-nav-row');
+ await expect(recovery.locator('button')).toHaveText('升级 Codex CLI', { timeout: 30_000 });
+ await page.screenshot({ path: testInfo.outputPath('06-execution-upgrade.png') });
+ await recovery.locator('button').click();
+ await expect(recovery.locator('button')).toHaveText('升级中…');
+ await expect(recovery.locator('[role="status"]')).toBeEmpty();
+ await page.screenshot({ path: testInfo.outputPath('07-execution-progress.png') });
+ await expect(recovery.locator('[role="status"]')).toHaveText('升级成功', { timeout: 30_000 });
+ await page.screenshot({ path: testInfo.outputPath('08-execution-success.png') });
+ // Upgrade is maintenance only: no task replay/model request follows it.
+ expect(app.readCliState().invocations).toHaveLength(0);
+ expect(readFileSync(updatesFile, 'utf8').trim().split('\n')).toHaveLength(3);
+ // Source/custom installations keep their owner instead of installing a second CLI.
+ const customBin = path.join(app.root, 'custom-codex');
+ writeFileSync(customBin, source); chmodSync(customBin, 0o755);
+ await app.electronApp!.evaluate((_electron, file) => { process.env.ORKAS_CODEX_PATH = file; }, customBin);
+ await app.invoke('localAgents.detect', { type: 'codex' });
+ await page.evaluate(async id => { await (window as any).openAgentDetail(id); }, created.agent.agent_id);
+ await detail.locator('button').click();
+ await expect(detail.locator('[role="status"]')).toHaveText('升级失败');
+ await expect(detail.locator('button')).toHaveText('升级 CLI');
+ await expect(page.getByText('查看升级说明', { exact: true })).toHaveCount(0);
+ expect(readFileSync(updatesFile, 'utf8').trim().split('\n')).toHaveLength(3);
+});
+
+test('adapts supported CLI defaults and keeps unavailable selections out of upgrade recovery', async ({ cliOrkas }, testInfo) => {
+ test.skip(process.platform === 'win32', 'Native POSIX fixture.');
+ const app = cliOrkas; const page = app.page!;
+ const bin = path.join(app.root, '.codex/packages/standalone/current/bin/codex');
+ const version = path.join(app.root, 'catalog-version'); const requests = path.join(app.root, 'catalog-rpc');
+ mkdirSync(path.dirname(bin), { recursive: true }); writeFileSync(version, '0.156.1');
+ writeFileSync(bin, `#!${process.env.ORKAS_TEST_NODE || process.execPath}\n
+const fs = require('node:fs'); const version = ${JSON.stringify(version)};
+if (process.argv.includes('--version')) { console.log(fs.readFileSync(version, 'utf8')); process.exit(0); }
+if (process.argv.includes('--help')) { console.log('Commands:\\n update Upgrade Codex'); process.exit(0); }
+if (process.argv.includes('update')) { setTimeout(()=>fs.writeFileSync(version, '0.159.3'), 300); }
+else require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
+ const m = JSON.parse(line); if (!m.method) return;
+ fs.appendFileSync(${JSON.stringify(requests)}, JSON.stringify(m) + '\\n');
+ const result = m.method === 'config/read' ? { config: { model: 'gpt-6.1-sol', model_provider: 'openai' } }
+ : m.method === 'account/read' ? { account: { type: 'chatgpt' } }
+ : m.method === 'model/list' ? { data: [{ id: 'gpt-6.1-sol', model: 'gpt-6.1-sol', displayName: 'GPT-6.1 Sol', isDefault: true },
+ { id: 'gpt-6-sol', model: 'gpt-6-sol', displayName: 'GPT-6 Sol' }] }
+ : m.method === 'thread/start' ? { threadId: 'compat-thread' }
+ : m.method === 'turn/start' ? { turn: { id: 'compat-turn' } }
+ : {};
+ if (['thread/start', 'turn/start'].includes(m.method) && m.params.model !== 'gpt-6-sol') process.exit(9);
+ if (m.id !== undefined) process.stdout.write(JSON.stringify({ id: m.id, result }) + '\\n');
+ if (m.method === 'turn/start') {
+ process.stdout.write(JSON.stringify({ method: 'item/agentMessage/delta', params: {
+ threadId: 'compat-thread', turnId: 'compat-turn', itemId: 'answer', delta: '兼容运行成功' } }) + '\\n');
+ process.stdout.write(JSON.stringify({ method: 'turn/completed', params: {
+ threadId: 'compat-thread', turn: { id: 'compat-turn', status: 'completed' } } }) + '\\n');
+ }
+});\n`); chmodSync(bin, 0o755);
+ await app.electronApp!.evaluate((_electron, file) => { process.env.ORKAS_CODEX_PATH = file; }, bin);
+ const detection = await app.invoke<any>('localAgents.detect', { type: 'codex' });
+ expect(detection.entry).toMatchObject({ available: true, version: '0.156.1' });
+ const created = await app.invoke<any>('agents.create', {
+ name: 'CodexModelCompatibility', description: 'CLI model compatibility fixture',
+ runtime: { kind: 'cli', cli: 'codex', model_override: 'gpt-6.1-sol' },
+ });
+ expect(created.ok).toBe(true);
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('@CodexModelCompatibility 检查版本兼容性');
+ await page.locator('#new-chat-send-btn').click();
+ const failure = page.locator('#chat-history .chat-message[data-failure-code="model_unsupported"]');
+ await expect(failure).toBeVisible({ timeout: 30_000 });
+ await expect(failure).toContainText('修改运行设置');
+ await expect(failure).not.toContainText('升级');
+ await expect(failure.locator('.local-cli-upgrade-btn')).toHaveCount(0);
+ await page.screenshot({ path: testInfo.outputPath('09-model-settings.png') });
+ const before = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(before.map(row => row.method)).toContain('account/read');
+ expect(before.filter(row => ['thread/start', 'thread/resume', 'turn/start'].includes(row.method))).toEqual([]);
+ const saved = await app.invoke<any>('agents.get', { agent_id: created.agent.agent_id });
+ expect(saved.agent.runtime.model_override).toBe('gpt-6.1-sol');
+ const inherited = await app.invoke<any>('agents.create', {
+ name: 'CodexCompatibleDefault', description: 'CLI compatible defaults fixture', runtime: { kind: 'cli', cli: 'codex' },
+ });
+ expect(inherited.ok).toBe(true);
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('@CodexCompatibleDefault 检查版本兼容性');
+ await page.locator('#new-chat-send-btn').click();
+ await expect(page.locator('#chat-history .chat-bubble').filter({ hasText: '兼容运行成功' })).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('#chat-history .local-cli-upgrade-btn')).toHaveCount(0);
+ const completed = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(completed.filter(row => row.method === 'turn/start').map(row => row.params.model)).toEqual(['gpt-6-sol']);
+ expect(readFileSync(version, 'utf8')).toBe('0.156.1');
+ await page.screenshot({ path: testInfo.outputPath('10-compatible-default.png') });
+});
+
+
+test('upgrades native Claude through its advertised alias and refreshes the detail version', async ({ cliOrkas }, testInfo) => {
+ test.skip(process.platform === 'win32', 'Native POSIX symlink installer fixture.');
+ const app = cliOrkas; const page = app.page!;
+ const directory = path.join(app.root, '.local/share/claude/versions');
+ const bin = path.join(app.root, '.local/bin/claude');
+ const next = path.join(directory, '2.1.113');
+ const calls = path.join(app.root, 'claude-update-calls');
+ mkdirSync(directory, { recursive: true }); mkdirSync(path.dirname(bin), { recursive: true });
+ for (const version of ['2.1.112', '2.1.113']) {
+ const file = path.join(directory, version);
+ writeFileSync(file, `#!${process.env.ORKAS_TEST_NODE || process.execPath}\n
+const fs = require('node:fs');
+if (process.argv.includes('--version')) console.log('${version} (Claude Code)');
+else if (process.argv.slice(2).join(' ') === 'update --help') console.log('Usage: claude update|upgrade [options]');
+else if (process.argv.includes('--help')) console.log('Usage: claude [options] [command]\\nCommands:\\n agents [options] List co');
+else if (process.argv.slice(2).join(' ') === 'update') {
+ fs.appendFileSync(${JSON.stringify(calls)}, 'update\\n');
+ setTimeout(() => { fs.unlinkSync(${JSON.stringify(bin)}); fs.symlinkSync(${JSON.stringify(next)}, ${JSON.stringify(bin)}); }, 1000);
+} else process.exit(8);
+`); chmodSync(file, 0o755);
+ }
+ symlinkSync(path.join(directory, '2.1.112'), bin);
+ await app.electronApp!.evaluate((_electron, file) => { process.env.ORKAS_CLAUDE_PATH = file; }, bin);
+ const detected = await app.invoke<any>('localAgents.detect', { type: 'claude' });
+ expect(detected.entry).toMatchObject({ available: true, version: '2.1.112' });
+ const created = await app.invoke<any>('agents.create', {
+ name: 'ClaudeUpgradeDemo', description: 'Native CLI update fixture', runtime: { kind: 'cli', cli: 'claude' },
+ });
+ expect(created.ok).toBe(true);
+ await page.evaluate(async id => {
+ await (window as any).setLang('zh'); await (window as any).openAgentDetail(id);
+ }, created.agent.agent_id);
+ const control = page.locator('#agents-detail-runtime .local-cli-upgrade-control');
+ await expect(control.locator('button')).toHaveText('升级 CLI');
+ await control.locator('button').click();
+ await expect(control.locator('button')).toHaveText('升级中…');
+ await expect(control.locator('[role="status"]')).toHaveText('升级成功', { timeout: 30_000 });
+ await expect(page.locator('#agents-detail-runtime .ai-select-trigger')).toContainText('2.1.113');
+ expect(readFileSync(calls, 'utf8')).toBe('update\n');
+ expect(app.readCliState().invocations).toHaveLength(0);
+ await page.screenshot({ path: testInfo.outputPath('12-claude-upgrade-success.png') });
+});
+
+
+test('keeps upgrade buttons bound to their CLI when Claude and Codex coexist', async ({ cliOrkas }) => {
+ test.skip(process.platform === 'win32', 'Native POSIX updater fixtures.');
+ const app = cliOrkas; const page = app.page!;
+ const calls = path.join(app.root, 'upgrade-routing-calls');
+ writeFileSync(calls, '');
+ const versions = { claude: path.join(app.root, 'routing-claude-version'), codex: path.join(app.root, 'routing-codex-version') };
+ const bins = { claude: path.join(app.root, '.local/share/claude/versions/current'),
+ codex: path.join(app.root, '.codex/packages/standalone/current/bin/codex') };
+ for (const cli of ['claude', 'codex'] as const) {
+ mkdirSync(path.dirname(bins[cli]), { recursive: true });
+ writeFileSync(versions[cli], cli === 'claude' ? '2.1.112' : '0.144.0');
+ writeFileSync(bins[cli], `#!${process.env.ORKAS_TEST_NODE || process.execPath}\n
+const fs = require('node:fs');
+if (process.argv.includes('--version')) console.log(fs.readFileSync(${JSON.stringify(versions[cli])}, 'utf8'));
+else if (process.argv.includes('--help')) console.log('Commands:\\n update Update CLI');
+else if (process.argv.slice(2).join(' ') === 'update') {
+ fs.appendFileSync(${JSON.stringify(calls)}, '${cli}\\n');
+ fs.writeFileSync(${JSON.stringify(versions[cli])}, '${cli === 'claude' ? '2.1.113' : '0.159.3'}');
+} else process.exit(8);
+`); chmodSync(bins[cli], 0o755);
+ }
+ await app.electronApp!.evaluate((_electron, paths) => {
+ process.env.ORKAS_CLAUDE_PATH = paths.claude; process.env.ORKAS_CODEX_PATH = paths.codex;
+ }, bins);
+ for (const type of ['claude', 'codex']) await app.invoke('localAgents.detect', { type });
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await openSidebarEntry(page, '#agents-btn');
+ await page.locator('#agents-connect-cli-btn').click();
+ // Connection recovery targets the CLI named in the outdated-version warning.
+ await expect(page.locator('#agent-modal-ext-cli-upgrade-warning')).toContainText('Codex');
+ await page.locator('#agent-modal-ext-cli-upgrades button').click();
+ await expect(page.locator('#agent-modal-ext-cli-upgrades [role="status"]')).toHaveText('升级成功');
+ expect(readFileSync(calls, 'utf8')).toBe('codex\n');
+ expect(readFileSync(versions.claude, 'utf8')).toBe('2.1.112');
+ await page.locator('#agent-modal .modal-actions .btn').first().click();
+ const created = await app.invoke<any>('agents.create', {
+ name: 'UpgradeRouting', description: 'CLI binding fixture', runtime: { kind: 'cli', cli: 'codex' },
+ });
+ expect(created.ok).toBe(true);
+ await page.evaluate(async id => { await (window as any).openAgentDetail(id); }, created.agent.agent_id);
+ // Change the real selector and require the replacement button to use the new binding.
+ await page.locator('#agents-detail-runtime .ai-select-trigger').click();
+ await page.locator('.ai-select-popover:visible .ai-select-item[data-value="cli:claude"]').click();
+ await expect(page.locator('#agents-detail-runtime .ai-select-trigger')).toContainText('Claude');
+ const detail = page.locator('#agents-detail-runtime .local-cli-upgrade-control');
+ await detail.locator('button').click();
+ await expect(detail.locator('[role="status"]')).toHaveText('升级成功');
+ expect(readFileSync(calls, 'utf8')).toBe('codex\nclaude\n');
+ writeFileSync(versions.claude, '1.9.0');
+ await app.invoke('localAgents.detect', { type: 'claude' });
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill('@UpgradeRouting 检查 CLI 版本');
+ await page.locator('#new-chat-send-btn').click();
+ const chip = page.locator('#chat-history .chat-message[data-failure-code="version_too_old"] .chat-bubble .local-cli-upgrade-control');
+ await expect(chip.locator('button')).toHaveText('升级 Claude Code CLI', { timeout: 30_000 });
+ await chip.locator('button').click();
+ await expect(chip.locator('[role="status"]')).toHaveText('升级成功');
+ expect(readFileSync(calls, 'utf8')).toBe('codex\nclaude\nclaude\n');
+ expect(readFileSync(versions.codex, 'utf8')).toBe('0.159.3');
+ expect(app.readCliState().invocations).toHaveLength(0);
+});
diff --git a/test/e2e/cli_usage_e2e_details.spec.ts b/test/e2e/cli_usage_e2e_details.spec.ts
new file mode 100644
index 00000000..13f09c19
--- /dev/null
+++ b/test/e2e/cli_usage_e2e_details.spec.ts
@@ -0,0 +1,58 @@
+import { chmodSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { expect, test } from './fixtures/orkas';
+
+
+test('shows compact remaining allowance for both CLIs without starting a task', async ({ cliOrkas }, testInfo) => {
+ const app = cliOrkas; const page = app.page!;
+ const requests = path.join(app.root, 'quota-requests');
+ writeFileSync(requests, '');
+ for (const cli of ['codex', 'claude'] as const) {
+ const script = path.join(app.root, `quota-${cli}.cjs`);
+ const source = `const fs = require('node:fs');
+if (process.argv.includes('--version')) console.log('${cli === 'codex' ? '0.160.0' : '2.1.296'}');
+else if (process.argv.includes('--help')) console.log('Usage: ${cli} --model --effort --safe-mode --bare');
+else require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
+ const m = JSON.parse(line); fs.appendFileSync(${JSON.stringify(requests)}, JSON.stringify(m) + '\\n');
+ let result = {};
+ if (m.method === 'model/list') result = { data: [{ id: 'model-example', isDefault: true }] };
+ if (m.method === 'account/rateLimits/read') result = { rateLimits: {
+ primary: { usedPercent: 17, windowDurationMins: 300, resetsAt: 1900000000 },
+ secondary: { usedPercent: 45, windowDurationMins: 10080, resetsAt: 1900100000 } } };
+ if (m.id !== undefined) console.log(JSON.stringify({ id: m.id, result }));
+ if (m.type === 'control_request') console.log(JSON.stringify({ type: 'control_response', response: {
+ request_id: m.request_id, subtype: 'success', response: m.request.subtype === 'get_usage' ? {
+ rate_limits_available: true, rate_limits: { five_hour: { utilization: 25, resets_at: '2030-03-17T00:00:00Z' },
+ seven_day: { utilization: 0, resets_at: null } } } : {} } }));
+});`;
+ const node = process.env.ORKAS_TEST_NODE || process.execPath;
+ const bin = path.join(app.root, `quota-${cli}${process.platform === 'win32' ? '.cmd' : ''}`);
+ writeFileSync(script, source);
+ writeFileSync(bin, process.platform === 'win32' ? `@echo off\r\n"${node}" "${script}" %*\r\n` : `#!${node}\n${source}`);
+ if (process.platform !== 'win32') chmodSync(bin, 0o755);
+ await app.electronApp!.evaluate((_electron, args) => { process.env[args.key] = args.bin; }, {
+ key: cli === 'codex' ? 'ORKAS_CODEX_PATH' : 'ORKAS_CLAUDE_PATH', bin,
+ });
+ await app.invoke('localAgents.detect', { type: cli });
+ const created = await app.invoke<any>('agents.create', {
+ name: `Quota_${cli}`, description: 'Account allowance fixture', runtime: { kind: 'cli', cli },
+ });
+ expect(created.ok).toBe(true);
+ await page.evaluate(async id => {
+ await (window as any).setLang('zh'); await (window as any).openAgentDetail(id);
+ }, created.agent.agent_id);
+ const section = page.locator('#agents-detail-cli-usage-section');
+ await expect(section).toBeVisible();
+ await expect(section).toContainText(cli === 'codex' ? '83%' : '75%');
+ await expect(section).toContainText('重置时间');
+ await expect(section.locator('.agents-detail-label')).toHaveText('剩余额度');
+ await expect(section.getByRole('button')).toHaveCount(0);
+ await expect(section).not.toContainText('同一 CLI');
+ await expect(section).not.toContainText('更新于');
+ await page.screenshot({ path: testInfo.outputPath(`quota-${cli}.png`) });
+ }
+ const observed = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(observed.some(r => r.method === 'account/rateLimits/read')).toBe(true);
+ expect(observed.some(r => r.request?.subtype === 'get_usage')).toBe(true);
+ expect(observed.filter(r => r.method === 'turn/start' || r.method === 'thread/start' || r.type === 'user')).toEqual([]);
+});
diff --git a/test/e2e/commander_e2e_orchestration.spec.ts b/test/e2e/commander_e2e_orchestration.spec.ts
index 23a86200..68be94a3 100644
--- a/test/e2e/commander_e2e_orchestration.spec.ts
+++ b/test/e2e/commander_e2e_orchestration.spec.ts
@@ -23,7 +23,8 @@ test.describe('Commander orchestration', () => {
timeout: process.platform === 'win32' ? 120_000 : 60_000,
});
- test('hands a finished deliverable to a shipped agent without an empty Commander tail', async ({
+ for (const protocol of ['responses', 'chat'] as const) {
+ test(`hands a finished deliverable to a shipped agent without an empty Commander tail (${protocol})`, async ({
modelOrkas,
}, testInfo) => {
if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
@@ -31,6 +32,9 @@ test.describe('Commander orchestration', () => {
const delegatedTask = 'Write the final launch announcement with a concise title and two paragraphs.';
const agentReply = 'E2E ContentWriter final delivery: Launch day is ready.';
const commanderNarration = 'I am handing this launch announcement to ContentWriter now.';
+ if (protocol === 'chat') {
+ await modelOrkas.setChatCommentaryScenario({ reads: [], finalText: '' });
+ }
modelOrkas.setAgentHandoffScenario(CONTENT_WRITER_ID, delegatedTask, agentReply, {
commanderNarration,
// Hold the nested Agent at a deterministic gate so assertions cannot
@@ -64,9 +68,10 @@ 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(page.locator('#chat-recipient-name')).toHaveText('ContentWriter');
const process = commanderBubbles.locator('.stream-process');
if (!(await process.evaluate((element) => (element as HTMLDetailsElement).open))) {
- await process.locator('summary').click();
+ await process.locator(':scope > summary').click();
}
await expect(commanderBubbles.locator('.stream-process-body')).toBeVisible();
await expect(commanderBubbles.locator('.stream-process-body')).toContainText('ContentWriter');
@@ -108,6 +113,7 @@ test.describe('Commander orchestration', () => {
await expect(page.locator(
`#chat-history .chat-message.assistant[data-from-actor="${CONTENT_WRITER_ID}"]`,
)).toHaveCount(1);
+ await expect(page.locator('#chat-recipient-name')).toHaveText('ContentWriter');
} finally {
modelOrkas.releaseAgentHandoffReply();
}
@@ -119,6 +125,7 @@ test.describe('Commander orchestration', () => {
timeout: 20_000,
});
await expect(agentBubble.locator('[data-role="final"]')).toContainText(agentReply);
+ await expect(page.locator('#chat-recipient-name')).toHaveText('Commander');
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
await expect(commanderBubbles).toHaveCount(1);
await expect.poll(() => modelOrkas.modelRequests.length).toBe(2);
@@ -141,14 +148,17 @@ test.describe('Commander orchestration', () => {
);
await expect(restoredCommanderBubble).toHaveCount(1);
await expect(restoredCommanderBubble).toContainText(commanderNarration);
- // Persisted process rows materialize when the user opens the disclosure.
- await restoredCommanderBubble.locator('.stream-process summary').click();
+ const restoredProcess = restoredCommanderBubble.locator('.stream-process');
+ if (!(await restoredProcess.evaluate(element => (element as HTMLDetailsElement).open))) {
+ await restoredProcess.locator(':scope > summary').click();
+ }
await expect(restoredCommanderBubble.locator('.stream-process-body')).toContainText('ContentWriter');
await expect(restoredCommanderBubble.locator('.stream-process-body')).not.toContainText(CONTENT_WRITER_ID);
await restoredCommanderBubble.locator('.stream-process-compact-summary').click();
await expect(restoredCommanderBubble.locator('.stream-process-compact-body').getByText(/Call agent.*ContentWriter/)).toBeVisible();
expect(modelOrkas.modelRequests).toHaveLength(requestsBeforeRelaunch);
});
+ }
test('keeps a narration-free hand-off free of Commander placeholders while the Agent runs', async ({
modelOrkas,
@@ -239,6 +249,14 @@ test.describe('Commander orchestration', () => {
const form = page.locator('#chat-history .chat-input-form');
await expect(form).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator('#chat-recipient-name')).toHaveText('DeepResearcher');
+ const pendingConversationId = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');
+ const callsBeforeReload = modelOrkas.modelRequests.length;
+ await page.reload();
+ await page.locator(`#conversation-list .conv-item[data-cid="${pendingConversationId}"]`).click();
+ await expect(form).toBeVisible();
+ await expect(page.locator('#chat-recipient-name')).toHaveText('DeepResearcher');
+ expect(modelOrkas.modelRequests).toHaveLength(callsBeforeReload);
const questionField = form.locator('.form-field', { hasText: 'Research question' });
await questionField.locator('.form-field-textarea').fill(researchQuestion);
await form.locator('.form-actions .btn-primary').click();
@@ -255,6 +273,7 @@ test.describe('Commander orchestration', () => {
);
await expect(commanderBubble).toHaveCount(1, { timeout: 20_000 });
await expect(commanderBubble).toBeVisible();
+ await expect(page.locator('#chat-recipient-name')).toHaveText('Commander');
await expect(page.locator('#chat-history')).not.toContainText('<handback');
await expect(page.locator('#chat-history')).not.toContainText('<orchestration-resume');
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
@@ -312,6 +331,11 @@ test.describe('Commander orchestration', () => {
).toHaveCount(0);
const requestsBeforeRetry = modelOrkas.modelRequests.length;
expect(requestsBeforeRetry).toBeGreaterThan(2);
+ // After the successful Commander request, this fixture deliberately fails
+ // every Agent attempt until the user invokes recovery.
+ for (let index = 1; index < requestsBeforeRetry; index++) {
+ modelOrkas.expectApiFailure('POST', '/api/v1/chat/completions', 500);
+ }
modelOrkas.allowAgentHandoffRetryRecovery();
await failedAgentBubble.hover();
@@ -403,6 +427,7 @@ test.describe('Commander orchestration', () => {
actorOrder.lastIndexOf(UI_DESIGNER_ID),
);
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ await expect(page.locator('#chat-recipient-name')).toHaveText('Commander');
await expect.poll(() => modelOrkas.modelRequests.length).toBe(4);
expect(JSON.stringify(modelOrkas.modelRequests)).toContain(writerTask);
expect(JSON.stringify(modelOrkas.modelRequests)).toContain(designerTask);
@@ -432,7 +457,7 @@ test.describe('Commander orchestration', () => {
// dispatch belongs to the synthesis row's process history, not a standalone
// answer. The temporary Commander row must retire while the Agent runs and
// must not reappear as a duplicate after settlement or restart.
- test('keeps pre-dispatch Commander commentary in one synthesis through restart', async ({
+ test('keeps pre-dispatch Commander commentary before Agent results and synthesis through restart', async ({
modelOrkas,
}) => {
if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
@@ -469,23 +494,26 @@ test.describe('Commander orchestration', () => {
await expect(synthesisBubble).toBeVisible({ timeout: 20_000 });
await expect(synthesisBubble).toHaveAttribute('data-msg-id', /\S+/, { timeout: 20_000 });
+ const narrationBubble = page.locator('#chat-history .chat-message.assistant[data-from-actor="commander"]', { hasText: narration });
+ await expect(narrationBubble).toHaveCount(1);
+ await expect(narrationBubble.locator('.stream-process-body')).toBeVisible();
await synthesisBubble.locator('.stream-process-summary').click();
- await expect(synthesisBubble.locator('.stream-process-body')).toContainText(narration);
+ await expect(synthesisBubble.locator('.stream-process-body')).not.toContainText(narration);
await expect(synthesisBubble).toHaveCount(1);
- // The final Commander answer has one stable segment identity; commentary
- // is nested in its process disclosure rather than duplicated as a row.
+ // Commander keeps distinct visible dispatch segments: the narration
+ // precedes the Agent; the final answer follows it without repeating text.
const commanderKeys = await page.locator(
'#chat-history .chat-message.assistant[data-from-actor="commander"]',
).evaluateAll((rows) => rows.map((row) => (row as HTMLElement).dataset.renderKey || ''));
- expect(commanderKeys).toHaveLength(1);
+ expect(commanderKeys).toHaveLength(2);
expect(commanderKeys.every((key) => key.startsWith('s:'))).toBe(true);
// The Agent reply remains before the final Commander synthesis.
const actorOrder = await page.locator(
'#chat-history .chat-message.assistant[data-from-actor]',
).evaluateAll((rows) => rows.map((row) => (row as HTMLElement).dataset.fromActor || ''));
- expect(actorOrder).toEqual([DEEP_RESEARCHER_ID, 'commander']);
+ expect(actorOrder).toEqual(['commander', DEEP_RESEARCHER_ID, 'commander']);
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
// Reload from persisted jsonl: the transcript must match what was streamed,
@@ -502,7 +530,10 @@ test.describe('Commander orchestration', () => {
);
await expect(persistedSynthesis).toHaveCount(1);
await persistedSynthesis.locator('.stream-process-summary').click();
- await expect(persistedSynthesis.locator('.stream-process-body')).toContainText(narration);
+ await expect(persistedSynthesis.locator('.stream-process-body')).not.toContainText(narration);
+ const restoredNarration = page.locator('#chat-history .chat-message.assistant[data-from-actor="commander"]', { hasText: narration });
+ await expect(restoredNarration).toHaveCount(1);
+ await expect(restoredNarration.locator('.stream-process-body')).toBeVisible();
await expect(page.locator(
`#chat-history .chat-message.assistant[data-from-actor="${DEEP_RESEARCHER_ID}"]`,
{ hasText: agentReply },
diff --git a/test/e2e/composer_e2e_interactions.spec.ts b/test/e2e/composer_e2e_interactions.spec.ts
index b91d912a..6180a166 100644
--- a/test/e2e/composer_e2e_interactions.spec.ts
+++ b/test/e2e/composer_e2e_interactions.spec.ts
@@ -3,6 +3,7 @@ import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from './fixtures/orkas';
+import { currentTurnSnapshots, lastUserRequestText, quotedSnapshots } from '../helpers/reference-context';
test.describe('persistent sidebar', () => {
test('keeps the open-source footer focused on local Settings', async ({ appPage }) => {
@@ -30,7 +31,7 @@ test.describe('new chat composer', () => {
'.composer-model-menu-group[data-model-group="official"]',
);
await expect(officialGroup.locator('.composer-model-menu-group-label'))
- .toHaveText('Official models');
+ .toHaveText('Orkas built-in models');
const officialRows = officialGroup.locator('.composer-model-menu-item');
await expect(officialRows).toHaveCount(2);
await expect(officialRows.locator('.composer-model-menu-title-name'))
@@ -45,7 +46,7 @@ test.describe('new chat composer', () => {
'.composer-model-menu-group[data-model-group="custom"]',
);
await expect(customGroup.locator('.composer-model-menu-group-label'))
- .toHaveText('User-configured models');
+ .toHaveText('Bring your own API Key');
await appPage.keyboard.press('Escape');
await appPage.locator('#settings-btn').click();
@@ -285,7 +286,7 @@ test.describe('new chat composer', () => {
await expect(modelGroup).toHaveCount(1);
await expect(modelGroup).toHaveAttribute('data-model-group', 'custom');
await expect(modelGroup.locator('.composer-model-menu-group-label'))
- .toHaveText('User-configured models');
+ .toHaveText('Bring your own API Key');
await expect(modelGroup.locator('.composer-model-menu-item'))
.toHaveCount(entriesBefore.entries.length);
@@ -615,7 +616,7 @@ test.describe('new chat composer', () => {
expect(orkas.readCliState().invocations).toHaveLength(0);
});
- test('resets multi-recipient sends to Commander and retains a later single CLI for follow-ups', async ({ cliOrkas }, testInfo) => {
+ test('resets multi-recipient sends to Commander and retains a later single CLI for follow-ups', async ({ cliModelOrkas: cliOrkas }, testInfo) => {
const page = cliOrkas.page!;
const recipients = [];
for (const name of ['ComposerAlpha', 'ComposerBeta']) {
@@ -642,7 +643,9 @@ test.describe('new chat composer', () => {
await expectComposerText(input, '@ComposerAlpha 你好, @ComposerBeta check the request');
await expect(page.locator('#new-chat-recipient-name')).toHaveText('ComposerAlpha, ComposerBeta');
await expect(page.locator('.skill-picker-item[data-id="__commander__"]')).toHaveAttribute('aria-checked', 'false');
- await expect(page.locator('[data-composer-model-chip="new-chat"]')).toBeDisabled();
+ // Two named actors make a planned send (D29); planning runs on the
+ // selected model, so its control stays available even for CLI-only sends.
+ await expect(page.locator('[data-composer-model-chip="new-chat"]')).toBeEnabled();
// Closing the panel restores the updated cursor; typed text stays after the chosen group.
await page.locator(`.skill-picker-item[data-id="${recipients[1].agent_id}"]`).press('Escape');
await expect(editor).toBeFocused();
@@ -679,6 +682,13 @@ test.describe('new chat composer', () => {
await followup.press('Enter');
await expect.poll(replies, { timeout: 30_000 }).toEqual([1, 2]);
await expect(page.locator('#chat-recipient-name')).toHaveText('ComposerBeta');
+ // The planner may keep a mentioned actor as context only; the floor then
+ // follows the one actor that actually received work (D29).
+ cliOrkas.setDispatchPlanReplies([JSON.stringify({
+ tasks: [{ key: 't1', assignee: 'a1', part: 'check the sources too', after: [] }],
+ references: ['a2'],
+ question: null,
+ })]);
await followup.fill('@ComposerBeta @ComposerBeta check the sources too @ComposerAlpha');
await followup.press('Enter');
await expect.poll(replies, { timeout: 30_000 }).toEqual([1, 3]);
@@ -849,18 +859,7 @@ test.describe('new chat composer', () => {
await appPage.locator(`.new-chat-scenario-chip[data-scenario="${item.id}"]`).click();
await expectComposerText(input, item.prompt);
await expect(appPage.locator('#new-chat-recipient-name'), item.id).toHaveText(item.agentName);
- await expect.poll(
- () => input.evaluate((element) => ({
- agentId: (element as HTMLDivElement).dataset.commanderAgentId,
- entryPoint: (element as HTMLDivElement).dataset.commanderEntryPoint,
- resourceId: (element as HTMLDivElement).dataset.commanderResourceId,
- })),
- { message: `${item.id} quick-start attribution` },
- ).toEqual({
- agentId: item.agentId,
- entryPoint: 'quick_start',
- resourceId: item.id,
- });
+
}
});
@@ -874,15 +873,21 @@ test.describe('new chat composer', () => {
const composer = rect('.new-chat-input-area');
const quickPanel = rect('#new-chat-scenarios');
const quickCard = rect('.new-chat-scenario-chip');
+ const below = document.querySelector<HTMLElement>('.home-below')!;
+ const belowStyle = getComputedStyle(below);
const landing = rect('.new-chat-center');
const landingChildren = [
'.new-chat-header',
'.new-chat-input-wrapper',
- '#new-chat-scenarios',
+ '.home-below',
];
return {
- widths: [header.width, composer.width, quickPanel.width],
+ widths: [header.width, composer.width],
+ belowWidth: below.getBoundingClientRect().width,
+ quickPanelWidth: quickPanel.width,
+ belowContentWidth: below.clientWidth - parseFloat(belowStyle.paddingLeft) - parseFloat(belowStyle.paddingRight),
+ quickPanelFits: quickPanel.left >= below.getBoundingClientRect().left && quickPanel.right <= below.getBoundingClientRect().right,
greetingFontSize: getComputedStyle(document.querySelector('.new-chat-greeting')!).fontSize,
greetingTextAlign: getComputedStyle(document.querySelector('.new-chat-header')!).textAlign,
composerHeight: composer.height,
@@ -935,6 +940,10 @@ test.describe('new chat composer', () => {
expect(Math.min(...layout.widths)).toBeGreaterThanOrEqual(895);
expect(Math.max(...layout.widths)).toBeLessThanOrEqual(902);
+ expect(layout.belowWidth).toBeGreaterThanOrEqual(900);
+ expect(layout.belowWidth).toBeLessThanOrEqual(910);
+ expect(Math.abs(layout.quickPanelWidth - layout.belowContentWidth)).toBeLessThanOrEqual(1);
+ expect(layout.quickPanelFits).toBe(true);
expect(layout.greetingFontSize).toBe('32px');
expect(layout.greetingTextAlign).toBe('center');
expect(layout.composerHeight).toBeLessThanOrEqual(150);
@@ -948,25 +957,29 @@ test.describe('new chat composer', () => {
expect(layout.quickCardContentFits).toBe(true);
expect(layout.ossEntryOnHeaderRow).toBe(true);
expect(layout.landingStartsInBounds).toBe(true);
- expect(layout.flexShrink).toEqual(['0', '0', '0']);
+ // The region below the composer is the one block that gives way in a
+ // short window (P15).
+ expect(layout.flexShrink).toEqual(['0', '0', '1']);
await appPage.setViewportSize({ width: 1280, height: 600 });
const shortViewport = await appPage.evaluate(() => {
const landing = document.querySelector('.new-chat-center')!;
- const header = document.querySelector('.new-chat-header')!;
+ const below = document.querySelector('.home-below')!;
const landingRect = landing.getBoundingClientRect();
- const headerRect = header.getBoundingClientRect();
- const overflows = landing.scrollHeight > landing.clientHeight;
- const startsInBounds = headerRect.top >= landingRect.top;
+ const startsInBounds = document.querySelector('.new-chat-header')!.getBoundingClientRect().top >= landingRect.top;
+ // The composer stays on the first screen; the region below it scrolls
+ // on its own, falling back to the page only below its minimum.
+ const composerVisible = document.querySelector('.new-chat-input-area')!.getBoundingClientRect().bottom
+ <= landingRect.bottom;
+ const overflows = below.scrollHeight > below.clientHeight || landing.scrollHeight > landing.clientHeight;
+ below.scrollTop = below.scrollHeight;
landing.scrollTop = landing.scrollHeight;
- const quickPanelRect = document.querySelector('#new-chat-scenarios')!.getBoundingClientRect();
- return {
- overflows,
- startsInBounds,
- endIsReachable: quickPanelRect.bottom <= landingRect.bottom + 0.5,
- };
+ const cards = below.querySelectorAll('.new-chat-scenario-chip');
+ const lastCard = cards[cards.length - 1].getBoundingClientRect();
+ const visibleBottom = Math.min(below.getBoundingClientRect().bottom, landing.getBoundingClientRect().bottom);
+ return { overflows, startsInBounds, composerVisible, endIsReachable: lastCard.bottom <= visibleBottom + 0.5 };
});
- expect(shortViewport).toEqual({ overflows: true, startsInBounds: true, endIsReachable: true });
+ expect(shortViewport).toEqual({ overflows: true, startsInBounds: true, composerVisible: true, endIsReachable: true });
await appPage.setViewportSize({ width: 1080, height: 800 });
await expect.poll(() => appPage.locator('.quick-grid').evaluate((element) => (
diff --git a/test/e2e/composer_e2e_state.spec.ts b/test/e2e/composer_e2e_state.spec.ts
index ca8844c6..f21c4d7b 100644
--- a/test/e2e/composer_e2e_state.spec.ts
+++ b/test/e2e/composer_e2e_state.spec.ts
@@ -4,6 +4,78 @@ import { analyzeWebAppLogs } from './fixtures/web-app-log-analysis';
const modifier = process.platform === 'darwin' ? 'Meta' : 'Control';
+test('project navigation restores separate drafts before detail loading and cannot undo another project’s text', async ({}, info) => {
+ const app = new OrkasTestApp(info, { configuredModel: false });
+ try {
+ await app.launch();
+ const a = await app.invoke<any>('projects.create', { name: 'Draft project A' });
+ const b = await app.invoke<any>('projects.create', { name: 'Draft project B' });
+ const ids = [a.project.project_id, b.project.project_id];
+ const page = app.page!;
+ await page.evaluate(id => (window as any).setView('project', id), ids[0]);
+ await expect(page.locator('#project-detail-title')).toHaveText('Draft project A');
+ const input = page.locator('#project-chat-input');
+ await input.fill('中文 A\nunsent draft');
+ const immediate = await page.evaluate(id => {
+ const w = window as any;
+ w.setView('project', id);
+ return w.composerText('project-chat-input');
+ }, ids[1]);
+ expect(immediate).toBe('');
+ await expect(page.locator('#project-detail-title')).toHaveText('Draft project B');
+ await input.press(`${modifier}+z`);
+ expect(await page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('');
+ await input.fill('B draft');
+ await page.evaluate(async id => { await (window as any).loadProjectDetail(id); }, ids[1]);
+ expect(await page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('B draft');
+ await page.evaluate(id => (window as any).setView('project', id), ids[0]);
+ await expect.poll(() => page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('中文 A\nunsent draft');
+ await input.press(`${modifier}+z`);
+ expect(await page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('中文 A\nunsent draft');
+ await page.locator('#new-chat-btn').click();
+ await page.evaluate(id => (window as any).setView('project', id), ids[1]);
+ await expect.poll(() => page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('B draft');
+ } finally { await app.dispose(); }
+});
+
+test('a delayed project send consumes its own draft and preserves another project’s new input', async ({}, info) => {
+ const app = new OrkasTestApp(info, { modelStub: true });
+ try {
+ await app.launch();
+ const a = await app.invoke<any>('projects.create', { name: 'Send project A' });
+ const b = await app.invoke<any>('projects.create', { name: 'Send project B' });
+ const ids = [a.project.project_id, b.project.project_id];
+ const page = app.page!;
+ await page.evaluate(id => (window as any).setView('project', id), ids[0]);
+ await expect(page.locator('#project-detail-title')).toHaveText('Send project A');
+ await page.locator('#project-chat-input').fill('Request for project A');
+ await page.evaluate(() => {
+ const w = window as any;
+ const original = w._chatAttachSnapshotForSend;
+ w._chatAttachSnapshotForSend = async (...args: any[]) => {
+ await new Promise(resolve => { w.releaseProjectSend = resolve; });
+ return original(...args);
+ };
+ w.delayedProjectSend = w._submitProjectChat();
+ });
+ await page.evaluate(id => (window as any).setView('project', id), ids[1]);
+ await expect(page.locator('#project-detail-title')).toHaveText('Send project B');
+ await page.locator('#project-chat-input').fill('B remains unsent');
+ await page.evaluate(async () => {
+ const w = window as any;
+ w.releaseProjectSend(); await w.delayedProjectSend;
+ });
+ await expect(page.locator('#project-detail-title')).toHaveText('Send project B');
+ expect(await page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('B remains unsent');
+ await page.evaluate(id => (window as any).setView('project', id), ids[0]);
+ await expect.poll(() => page.evaluate(() => (window as any).composerText('project-chat-input'))).toBe('');
+ const listed = await app.invoke<any>('conversations.list');
+ const sent = listed.conversations.filter((item: any) => item.title === 'Request for project A');
+ expect(sent).toHaveLength(1);
+ expect(sent[0].project_id).toBe(ids[0]);
+ } finally { await app.dispose(); }
+});
+
let previousKeepLogs: string | undefined;
test.beforeEach(() => {
previousKeepLogs = process.env.ORKAS_E2E_KEEP_LOGS;
diff --git a/test/e2e/context_e2e_continuity.spec.ts b/test/e2e/context_e2e_continuity.spec.ts
index 1d59357d..a8195597 100644
--- a/test/e2e/context_e2e_continuity.spec.ts
+++ b/test/e2e/context_e2e_continuity.spec.ts
@@ -1,5 +1,5 @@
-import { expect, test } from './fixtures/orkas';
-import { contextBudget } from '../../src/core-agent/src/agent/context-budget';
+import { expect, test, E2E_MODEL_CONTEXT_WINDOW, E2E_MODEL_MAX_OUTPUT_TOKENS } from './fixtures/orkas';
+import { contextBudget, MAX_PER_RESULT_INLINE_TOKENS } from '../../src/core-agent/src/agent/context-budget';
import { estimateTextTokens } from '../../src/core-agent/src/agent/session';
/**
@@ -11,7 +11,7 @@ import { estimateTextTokens } from '../../src/core-agent/src/agent/session';
* no pressure at all.
*
* Lower bound in aggregate: the active-process trigger derives from the model
- * window, and this fresh Orkas LLM (1M) task also borrows unused history room.
+ * window, and this fresh Orkas LLM task also borrows unused history room.
* The files must exceed that effective trigger together or compaction
* never fires — and a fixture that has quietly stopped applying pressure fails
* as "0 compactions", which reads like a compaction bug rather than a sizing
@@ -19,23 +19,18 @@ import { estimateTextTokens } from '../../src/core-agent/src/agent/session';
* failure, and the counts are recomputed here whenever either limit changes.
*/
-/** Mirrors `DEFAULT_INLINE_RESULT_TOKENS` in `src/main/util/tool-result-cap.ts`,
- * which cannot be imported here: it pulls in the Electron logger. The pressure
- * assertion below fails loudly if the real value ever drops below this. */
-const PER_RESULT_INLINE_TOKENS = 12_500;
+const PER_RESULT_INLINE_TOKENS = MAX_PER_RESULT_INLINE_TOKENS;
/** Stay under the spill line with room for the estimator's own error. */
const PER_FILE_TOKEN_TARGET = Math.floor(PER_RESULT_INLINE_TOKENS * 0.9);
/** Exceed the trigger by enough that a small threshold change does not silently
* drop the run below it. */
const AGGREGATE_PRESSURE_RATIO = 1.12;
-/** The deterministic provider reports deliberately tiny usage numbers, so the
- * session's estimator calibration settles at the production floor. Size the
- * fixture against the same calibrated trigger comparison. */
-const E2E_ESTIMATOR_CALIBRATION_FLOOR = 0.5;
+/** This scenario reports usage estimated from its actual request payload. */
+const E2E_ESTIMATOR_CALIBRATION = 1;
-/** The E2E model is Orkas LLM: a 1M window, and a fixed overhead large enough
+/** The E2E model uses the official planning limits, and a fixed overhead large enough
* to be realistic without needing the real prompt here. */
-const E2E_USABLE_INPUT_TOKENS = 1_048_576 - 8_192;
+const E2E_USABLE_INPUT_TOKENS = E2E_MODEL_CONTEXT_WINDOW - E2E_MODEL_MAX_OUTPUT_TOKENS;
const E2E_ACTIVE_TRIGGER = contextBudget({
usableInputTokens: E2E_USABLE_INPUT_TOKENS,
// Match AgentRunner's request ceiling before dividing the remaining room.
@@ -50,7 +45,7 @@ const SOURCE_COUNT = Math.max(
3,
Math.ceil(
(E2E_ACTIVE_TRIGGER * AGGREGATE_PRESSURE_RATIO)
- / (PER_FILE_TOKEN_TARGET * E2E_ESTIMATOR_CALIBRATION_FLOOR),
+ / (PER_FILE_TOKEN_TARGET * E2E_ESTIMATOR_CALIBRATION),
),
);
@@ -77,7 +72,7 @@ function pressureRow(label: string, index: number): string {
function assertFixturePressure(compactionCount: number): void {
const perFile = estimateTextTokens(contextPressureFixture('KEEP01', 'E2E_CTX_KEEP01=ALPHA-1'));
const aggregate = perFile * SOURCE_COUNT;
- const calibratedAggregate = aggregate * E2E_ESTIMATOR_CALIBRATION_FLOOR;
+ const calibratedAggregate = aggregate * E2E_ESTIMATOR_CALIBRATION;
const sizing = `per-file ~${perFile} tokens x ${SOURCE_COUNT} files = ~${aggregate}; `
+ `calibrated aggregate ~${calibratedAggregate}; derived active trigger ${E2E_ACTIVE_TRIGGER}; `
+ `per-result spill line ${PER_RESULT_INLINE_TOKENS}`;
@@ -213,7 +208,7 @@ test.describe('long-task context continuity', () => {
test('stops a stalled context compaction without a late response or replay', async ({
modelOrkas,
}) => {
- // Building pressure now reads 137 files before cancellation can be tested.
+ // Build pressure from the official window before testing cancellation.
// Allow setup to cross the real trigger; the cancellation gates stay at 10s.
test.setTimeout(120_000);
if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
diff --git a/test/e2e/context_menu_e2e_selection.spec.ts b/test/e2e/context_menu_e2e_selection.spec.ts
index ca808cc6..c555fc86 100644
--- a/test/e2e/context_menu_e2e_selection.spec.ts
+++ b/test/e2e/context_menu_e2e_selection.spec.ts
@@ -1,4 +1,6 @@
import { expect, test } from './fixtures/orkas';
+import path from 'node:path';
+
async function selectContents(
locator: import('@playwright/test').Locator,
@@ -13,16 +15,34 @@ async function selectContents(
}
test.describe('chat selection context menu', () => {
- test('owns only chat selections and exposes keyboard scratch-edit and copy failure results', async ({ modelOrkas }) => {
- if (!modelOrkas.page) throw new Error('Orkas renderer is unavailable');
- const page = modelOrkas.page;
+ test('owns only chat selections and exposes keyboard scratch-edit and copy failure results', async ({ orkas }) => {
+ if (!orkas.page) throw new Error('Orkas renderer is unavailable');
+ const page = orkas.page;
const prompt = 'E2E context menu selection text.';
- modelOrkas.setModelTextReplies(['E2E context menu reply.']);
- await page.locator('#new-chat-input').fill(prompt);
- await page.locator('#new-chat-send-btn').click();
+ const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>(
+ 'conversations.create', { title: 'Context menu selection' },
+ );
+ // This journey starts from settled history. Seed canonical records through
+ // the same resolver as history E2E, independently of cold model preparation.
+ await orkas.electronApp!.evaluate((_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const uid = req(`${input.root}/src/main/features/users.ts`).getActiveUserId();
+ const file = req(`${input.root}/src/main/util/project-layout.ts`).conversationMessageReadFile(uid, input.cid);
+ const rows = [
+ { id: 'selection-user', from: 'user', to: ['commander'], ts: '2026-10-15T08:00:00Z', text: input.prompt },
+ { id: 'selection-answer', from: 'commander', to: ['user'], ts: '2026-10-15T08:00:01Z', text: 'E2E context menu reply.' },
+ ];
+ req('node:fs').writeFileSync(file, rows.map(row => JSON.stringify(row)).join('\n') + '\n');
+ }, { root: path.resolve(__dirname, '../..'), cid: conversation.conversation_id, prompt });
+ await page.evaluate(async cid => {
+ const app = window as any;
+ await app.loadConversations();
+ app.setView('conversation', cid);
+ }, conversation.conversation_id);
const bubble = page.locator('#chat-history .chat-message.user').last();
await expect(bubble).toContainText(prompt);
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toContainText(
+ // Settled canonical history renders a normal bubble, without live stream slots.
+ await expect(page.locator('#chat-history .chat-message.assistant')).toContainText(
'E2E context menu reply.',
);
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
diff --git a/test/e2e/conversation_outputs_e2e_panel.spec.ts b/test/e2e/conversation_outputs_e2e_panel.spec.ts
index 4c0e3286..8110718d 100644
--- a/test/e2e/conversation_outputs_e2e_panel.spec.ts
+++ b/test/e2e/conversation_outputs_e2e_panel.spec.ts
@@ -11,7 +11,7 @@
//
// The first reply below deliberately does NOT paste a media link; the second
// one does, and must not gain a duplicate underneath it.
-import { appendFileSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
+import { appendFileSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
@@ -224,6 +224,31 @@ test('surfaces produced files, outside files, and artifacts for one conversation
// is one of those things.
await expect(page.locator('#conversation-info-tab-count-files')).toHaveText('4');
+ // Revealing a file that has moved away explains the recovery in the UI language,
+ // without the host reason or its local path. (UI review capture: zh, default window.)
+ const movedNotes = `${notesPath}.moved`;
+ const previousLang = await page.evaluate(() => (window as any).getLang());
+ try {
+ await page.evaluate(() => (window as any).setLang('zh'));
+ const escapedNotesPath = await page.evaluate(value => CSS.escape(value), notesPath);
+ const notesRow = panel.locator(`.conversation-info-file[data-file-path="${escapedNotesPath}"]`);
+ await expect(notesRow).toHaveCount(1);
+ const reports = panel.locator('details.conversation-info-dir');
+ if (!await reports.evaluate(node => (node as HTMLDetailsElement).open)) await reports.locator('> summary').click();
+ await notesRow.scrollIntoViewIfNeeded(); await notesRow.hover();
+ await notesRow.locator('.conversation-info-file-menu-btn').click();
+ renameSync(notesPath, movedNotes);
+ await page.locator('.ctx-row-menu-item[data-action="reveal"]').click();
+ const revealAlert = page.locator('.ui-dialog-overlay:visible');
+ await expect(revealAlert.locator('.ui-dialog-message')).toHaveText('无法打开所在文件夹,文件可能已被移动或删除。');
+ await expect(revealAlert).not.toContainText(listing.root);
+ await revealAlert.locator('.ui-dialog').screenshot({ path: testInfo.outputPath('ui-review', '11-folder-reveal-failed.png') });
+ await revealAlert.locator('[data-act="ok"]').click(); await expect(revealAlert).toHaveCount(0);
+ } finally {
+ try { renameSync(movedNotes, notesPath); } catch { /* not moved */ }
+ await page.evaluate(lang => (window as any).setLang(lang), previousLang);
+ }
+
// Opening the artifact from the panel reaches the same frame the bubble uses.
const artifactPreview = await orkas.openPreview(() => panel.locator('.conversation-info-file[data-artifact-id]').click());
await expect(artifactPreview.locator('.chat-artifact-viewer.is-open')).toBeVisible();
diff --git a/test/e2e/dialogs_e2e_behavior.spec.ts b/test/e2e/dialogs_e2e_behavior.spec.ts
index 8f872ff4..f48ea0bc 100644
--- a/test/e2e/dialogs_e2e_behavior.spec.ts
+++ b/test/e2e/dialogs_e2e_behavior.spec.ts
@@ -1,5 +1,8 @@
import { expect, test } from './fixtures/orkas';
+// These journeys test local dialog behavior; keep account boot independent of
+// the deliberately unreachable default endpoint and its retry timers.
+
test.describe('shared dialog behavior', () => {
test.describe('async actions', () => {
@@ -507,7 +510,7 @@ test('global requests show their source task across navigation, locales and narr
});
const permissionDialogTest = test;
-permissionDialogTest('unknown shell approval shows decision facts before the bounded preview in a narrow window', async ({ orkas: app }, testInfo) => {
+permissionDialogTest('unknown shell approval survives background clicks and shows decision facts in a narrow window', async ({ orkas: app }, testInfo) => {
const page = app.page!;
await page.setViewportSize({ width: 760, height: 600 });
await page.evaluate(() => (window as any).setLang('zh'));
@@ -528,6 +531,19 @@ permissionDialogTest('unknown shell approval shows decision facts before the bou
await expect(dialog).toContainText('D:\\project with spaces');
await expect(dialog.locator('[data-id="allow_run"]')).toHaveCount(0);
await expect(dialog.locator('[data-id="allow_once"]')).toBeInViewport();
+ // Background clicks must leave the approval pending and its actions usable.
+ // Exercise native pointer events, including a second click while the mode
+ // picker is open, so document-level handlers are part of the regression.
+ const overlay = page.locator('.modal-overlay', { has: dialog });
+ await overlay.click({ position: { x: 5, y: 5 } });
+ await expect(dialog).toBeVisible();
+ await dialog.locator('.bash-permission-mode-trigger').click();
+ await expect(overlay.locator('.bash-permission-mode-menu')).toBeVisible();
+ await overlay.dblclick({ position: { x: 5, y: 5 } });
+ await expect(overlay.locator('.bash-permission-mode-menu')).toBeHidden();
+ await expect(dialog).toBeVisible();
+ await expect(dialog.locator('[data-act="cancel"]')).toBeEnabled();
+ await expect(dialog.locator('[data-id="allow_once"]')).toBeEnabled();
const preview = dialog.locator('.bash-permission-details');
await expect(preview).not.toHaveAttribute('open');
await expect(preview.locator('pre')).toBeHidden();
diff --git a/test/e2e/fixtures/electron-cleanup.ts b/test/e2e/fixtures/electron-cleanup.ts
index e707052c..87f62ef7 100644
--- a/test/e2e/fixtures/electron-cleanup.ts
+++ b/test/e2e/fixtures/electron-cleanup.ts
@@ -16,6 +16,10 @@ export async function requestElectronQuit(app: ElectronApplication): Promise<voi
if (process.platform !== 'darwin' && app.windows().length === 0) {
const child = app.process();
if (child.exitCode !== null || child.signalCode !== null) return;
+ // Playwright owns the Node inspector connection. A naturally quitting
+ // Electron process can wait for that connection to detach before exiting.
+ await app.close();
+ if (child.exitCode !== null || child.signalCode !== null) return;
await new Promise<void>(resolve => child.once('exit', () => resolve()));
return;
}
@@ -35,6 +39,9 @@ export async function requestElectronQuit(app: ElectronApplication): Promise<voi
'electronApplication.evaluate: Execution context was destroyed, most likely because of a navigation.';
if (!closed && !inspectorDisposed) throw error;
}
+ // Complete the public Playwright close path after requesting deferred quit:
+ // it detaches the inspector and still waits for the actual process close.
+ await app.close();
await completion;
} finally {
app.off('close', onClose);
@@ -66,7 +73,8 @@ export async function closeElectronFixture(app: OwnedApplication, tracePath: str
options.phase?.(name, 'failed');
} finally { clearTimeout(timer); }
};
- await step('trace-stop', options.traceTimeoutMs ?? 5_000, () => app.context().tracing.stop({ path: tracePath }));
+ // Multi-locale journeys can produce large snapshot archives on low-tier hosts.
+ await step('trace-stop', options.traceTimeoutMs ?? 15_000, () => app.context().tracing.stop({ path: tracePath }));
await step('application-close', options.closeTimeoutMs ?? 20_000, () => app.close());
if (child.exitCode === null && child.signalCode === null) {
await step('owned-process-cleanup', 6_000, () => new Promise<void>((resolve, reject) => {
diff --git a/test/e2e/fixtures/empty-library-search.ts b/test/e2e/fixtures/empty-library-search.ts
new file mode 100644
index 00000000..0ca5d6e7
--- /dev/null
+++ b/test/e2e/fixtures/empty-library-search.ts
@@ -0,0 +1,20 @@
+import type { OrkasTestApp } from './orkas';
+
+/** Chat/Agent search journeys own their real indexes, not Library retrieval.
+ * Keep that unrelated semantic boundary explicitly model-free. */
+export async function installEmptyLibrarySearch(app: OrkasTestApp, root: string): Promise<void> {
+ if (!app.electronApp) throw new Error('Orkas Electron app is unavailable');
+ await app.electronApp.evaluate((_electron, root) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ (globalThis as any).__emptyLibrarySearchQueries = 0;
+ req(`${root}/src/main/features/kb_embed.ts`)._setEmbedChannelFactoryForTest(() => {
+ throw new Error('Real embedding is prohibited in the empty Library search fixture');
+ });
+ req(`${root}/src/main/features/search/index.ts`).__searchTestHooks.setLibraryContentSearchProvider({
+ embedQuery: async () => { (globalThis as any).__emptyLibrarySearchQueries++; return [1, 0]; },
+ searchGlobal: () => [],
+ listProjects: async () => [],
+ searchProject: () => [],
+ });
+ }, root);
+}
diff --git a/test/e2e/fixtures/orkas.ts b/test/e2e/fixtures/orkas.ts
index b410571a..fd467301 100644
--- a/test/e2e/fixtures/orkas.ts
+++ b/test/e2e/fixtures/orkas.ts
@@ -15,6 +15,7 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import type { AddressInfo } from 'node:net';
import AdmZip from 'adm-zip';
+import { estimateTextTokens } from '../../../src/core-agent/src/agent/session';
import { BackgroundServices } from './background-services';
import { closeElectronFixture, requestElectronQuit } from './electron-cleanup';
import { ownFixtureServer } from './server-cleanup';
@@ -32,10 +33,9 @@ const PC_ROOT = path.resolve(__dirname, '../../..');
// value is a fixture UID; it does not create an official account or session.
const LOCAL_USER_ID = 'account-e2e';
const { collectLogFiles } = require('./electron-log-files.cjs') as { collectLogFiles: (root: string) => string };
-/** Evidence files read per model round in the context-compaction scenario.
- * Four ~11.2K-token results stay well under the per-round inline allowance,
- * so the batch builds context instead of spilling to disk. */
-const CONTEXT_SOURCE_READS_PER_ROUND = 4;
+/** One read per round lets the runtime compact before admitting more evidence;
+ * parallel read-budget rejection is covered by the owning deterministic cases. */
+const CONTEXT_SOURCE_READS_PER_ROUND = 1;
const E2E_PNG_B64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
const E2E_MP4_BYTES = Buffer.from([
@@ -48,6 +48,8 @@ const E2E_MP4_BYTES = Buffer.from([
]);
type OrkasOptions = {
+ /** Opt in only for journeys that require an activatable native owner. */
+ nativeWindowVisible?: boolean;
/** Exercise native capture on machines/evaluators without GPU compositing. */
softwareRendering?: boolean;
captureRendererErrorWindows?: boolean;
@@ -79,6 +81,7 @@ export type CliStubInvocation = {
model?: string;
effort?: string;
toolExecuted?: boolean;
+ questionAnswers?: Record<string, unknown>;
steers?: Array<{ id: string | null; text: string; localImages: string[] }>;
};
@@ -89,6 +92,8 @@ export type CliStubState = {
invocations: CliStubInvocation[];
modelListCalls: number;
modelListResponses: number;
+ codexResumeHangs?: number;
+ codexThreadRequests?: Array<{ method: string; pid: number }>;
};
type ModelStubMode = 'success' | 'refusal' | 'http-error' | 'auth-error' | 'model-not-open' | 'slow' | 'very-slow' | 'controlled-slow' | 'truncated';
@@ -106,6 +111,7 @@ type ModelToolScenario =
}
| { kind: 'connector'; connectorId: string }
| { kind: 'agent-authoring'; finalText: string }
+ | { kind: 'saved-tasks'; next: number; projectId: string; finalText: string }
| {
kind: 'create-pdf';
sourceType: 'markdown' | 'html';
@@ -475,7 +481,7 @@ if (args.includes('--version') || args[0] === 'version') {
process.exit(0);
}
if (args.includes('--help')) {
- process.stdout.write('Usage: claude --model <model> --effort <level>\n');
+ process.stdout.write('Usage: claude --bare --model <model> --effort <level>\n');
process.exit(0);
}
const statePath = process.env.ORKAS_E2E_CLI_STATE;
@@ -504,10 +510,18 @@ const concreteModels = {
const concreteModel = concreteModels[requestedModel] || requestedModel || 'claude-sonnet-4-6';
const input = readline.createInterface({ input: process.stdin });
let handled = false;
+let questionInvocation = -1;
input.on('line', line => {
- if (handled) return;
let message;
try { message = JSON.parse(line); } catch { return; }
+ if (message.type === 'control_response' && message.response?.request_id === 'native-question' && questionInvocation >= 0) {
+ const state = readState();
+ state.invocations[questionInvocation].questionAnswers = message.response.response.updatedInput?.answers;
+ writeState(state);
+ send({ type: 'result', subtype: 'success', result: 'E2E_CLI_QUESTION_CONTINUED' });
+ return;
+ }
+ if (handled) return;
if (message.type === 'control_request' && message.request?.subtype === 'list_models') {
send({ type: 'control_response', response: {
subtype: 'success',
@@ -541,6 +555,41 @@ input.on('line', line => {
});
writeState(state);
send({ type: 'system', subtype: 'init', session_id: sessionId });
+ if (prompt.includes('E2E_CLAUDE_STREAM_BODY')) {
+ const id = 'claude-stream-body';
+ const partial = event => send({ type: 'stream_event', event });
+ partial({ type: 'message_start', message: { id } });
+ partial({ type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'Fixture reasoning.' } });
+ send({ type: 'assistant', message: { id, content: [{ type: 'thinking', thinking: 'Fixture reasoning.' }] } });
+ partial({ type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } });
+ partial({ type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: '## Report\n\nFirst paragraph.' } });
+ let stage = 0;
+ const timer = setInterval(() => {
+ let released = 0;
+ try { released = Number(fs.readFileSync(statePath + '.claude-stream-stage', 'utf8')); } catch {}
+ if (stage < 1 && released >= 1) {
+ stage = 1;
+ partial({ type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: '\n\nSecond paragraph.' } });
+ }
+ if (stage < 2 && released >= 2) {
+ stage = 2;
+ clearInterval(timer);
+ const text = '## Report\n\nFirst paragraph.\n\nSecond paragraph.';
+ partial({ type: 'content_block_stop', index: 1 });
+ send({ type: 'assistant', message: { id, content: [{ type: 'text', text }] } });
+ send({ type: 'result', subtype: 'success', result: text });
+ }
+ }, 25);
+ return;
+ }
+ if (prompt.includes('E2E_CLI_NATIVE_QUESTION')) {
+ questionInvocation = state.invocations.length - 1;
+ send({ type: 'control_request', request_id: 'native-question', request: {
+ subtype: 'can_use_tool', tool_name: 'AskUserQuestion', tool_use_id: 'native-question-tool',
+ input: { questions: [{ question: 'Which scope?', header: 'Scope', options: [{ label: 'Current' }, { label: 'All' }] }] },
+ } });
+ return;
+ }
send({
type: 'assistant', session_id: sessionId,
message: {
@@ -607,6 +656,14 @@ input.on('line', line => {
send({ id: message.id, result: { userAgent: 'orkas-e2e-codex' } });
return;
}
+ if (message.method === 'account/read') {
+ send({ id: message.id, result: { account: { type: 'chatgpt' } } });
+ return;
+ }
+ if (message.method === 'config/read') {
+ send({ id: message.id, result: { config: { model: 'gpt-e2e-default', model_reasoning_effort: 'low' } } });
+ return;
+ }
if (message.method === 'model/list') {
const state = readState();
state.modelListCalls += 1;
@@ -660,6 +717,13 @@ input.on('line', line => {
}
if (message.method === 'thread/start' || message.method === 'thread/resume') {
const state = readState();
+ state.codexThreadRequests = state.codexThreadRequests || [];
+ state.codexThreadRequests.push({ method: message.method, pid: process.pid });
+ if (message.method === 'thread/resume' && state.codexResumeHangs > 0) {
+ state.codexResumeHangs -= 1;
+ writeState(state);
+ return;
+ }
resumedThreadId = message.method === 'thread/resume'
? String(message.params?.threadId || '')
: '';
@@ -686,6 +750,13 @@ input.on('line', line => {
send({ method: 'turn/started', params: {
threadId, turn: { id: turnId, status: 'inProgress' },
} });
+ if (prompt.includes('E2E_CLI_NATIVE_QUESTION')) {
+ send({ id: 'native-question', method: 'item/tool/requestUserInput', params: {
+ threadId, turnId, itemId: 'native-question', isBlocking: true,
+ questions: [{ id: 'scope', question: 'Which scope?', header: 'Scope', options: [{ label: 'Current' }, { label: 'All' }] }],
+ } });
+ return;
+ }
if (prompt.includes('E2E_CODEX_ASYNC_QUESTION')) {
send({ method: 'item/completed', params: { threadId, turnId, item: {
id: 'async-question', type: 'agentMessage', delivery: 'async', text: 'Which scope?',
@@ -695,6 +766,13 @@ input.on('line', line => {
if (!prompt.includes('E2E_CODEX_SEND_NOW_ACTIVE')) finish('E2E_CODEX_DEFAULT_OK');
return;
}
+ if (message.id === 'native-question' && message.result) {
+ const state = readState();
+ state.invocations[invocationIndex].questionAnswers = message.result.answers;
+ writeState(state);
+ finish('E2E_CLI_QUESTION_CONTINUED');
+ return;
+ }
if (message.method === 'turn/steer') {
const state = readState();
const richInput = Array.isArray(message.params?.input) ? message.params.input : [];
@@ -734,6 +812,40 @@ function seedWorkspace(workspaceRoot: string, seedLanguage: OrkasOptions['seedLa
}
+/** First line of the D29 dispatch-planner prompt (PC/src/main/prompts/dispatch_planner.md). */
+const DISPATCH_PLANNER_MARKER = 'You split one user message from a group chat into tasks';
+
+/** Concatenated text of every message in a chat-completions request. */
+function requestPromptText(requestBody: Record<string, unknown>): string {
+ const messages = Array.isArray(requestBody.messages) ? requestBody.messages : [];
+ return messages.map((message) => {
+ const content = (message as { content?: unknown })?.content;
+ if (typeof content === 'string') return content;
+ return Array.isArray(content)
+ ? content.map((part) => String((part as { text?: unknown })?.text ?? '')).join('')
+ : '';
+ }).join('\n');
+}
+
+/** Deterministic stand-in for the D29 dispatch planner: every mentioned actor
+ * gets the whole message as its part, in mention order, each waiting for the
+ * previous one. Tests that need another split queue it explicitly. */
+function defaultE2eDispatchPlan(prompt: string): string {
+ const keys = prompt.split('\n')
+ .map((line) => { try { return JSON.parse(line); } catch { return null; } })
+ .filter((row) => row && typeof row.key === 'string' && row.mentioned === true)
+ .map((row) => String(row.key));
+ const message = (/<user-message>\n([\s\S]*?)\n<\/user-message>/.exec(prompt)?.[1] || '').trim() || 'do your part';
+ return JSON.stringify({
+ tasks: keys.map((key, i) => ({ key: `t${i + 1}`, assignee: key, part: message, after: i ? [`t${i}`] : [] })),
+ references: [],
+ question: null,
+ });
+}
+
+export const E2E_MODEL_CONTEXT_WINDOW = 64_000;
+export const E2E_MODEL_MAX_OUTPUT_TOKENS = 8_192;
+
export class OrkasTestApp {
readonly root: string;
readonly workspaceRoot: string;
@@ -768,6 +880,11 @@ export class OrkasTestApp {
}> = [];
readonly marketplaceRequests: Array<{ path: string; body: Record<string, unknown> }> = [];
readonly apiRequests: Array<{ method: string; path: string; channel: string }> = [];
+ readonly apiResponses: Array<{ method: string; path: string; status: number }> = [];
+ private expectedApiFailures: Array<{ method: string; path: string; status: number }> = [];
+ expectApiFailure(method: string, route: string, status: number): void {
+ this.expectedApiFailures.push({ method, path: route, status });
+ }
compactionRequestAborts = 0;
imageTaskPolls = 0;
videoTaskPolls = 0;
@@ -813,6 +930,7 @@ export class OrkasTestApp {
private readonly tracePaths: string[] = [];
private traceNumber = 0;
private readonly appClosePromises = new WeakMap<ElectronApplication, Promise<void>>();
+ private readonly appTraceStops = new WeakMap<ElectronApplication, Promise<void>>();
private activeUserId: string;
private readonly configuredModelSeededUsers = new Set<string>();
private modelToolScenario: ModelToolScenario | null = null;
@@ -823,6 +941,12 @@ export class OrkasTestApp {
private pendingCommentaryReply: (() => void) | null = null;
commentaryStage = 0;
private modelTextReplies: string[] = [];
+ private dispatchPlanReplies: string[] = [];
+ /** D29 dispatch-planner calls. Kept out of `modelRequests`, which counts
+ * actor turns. */
+ readonly dispatchPlannerRequests: Array<Record<string, unknown>> = [];
+ /** Set by `holdDispatchPlan()`; `reply` is the parked planner answer. */
+ private dispatchPlanHold: { reply: (() => void) | null } | null = null;
private libraryImageDescriptionReplies: string[] = [];
constructor(testInfo: TestInfo, private readonly options: OrkasOptions = {}) {
@@ -901,7 +1025,7 @@ export class OrkasTestApp {
...process.env,
ORKAS_WORKSPACE_ROOT: this.workspaceRoot,
ORKAS_E2E_USER_DATA_DIR: this.userDataRoot,
- ORKAS_E2E_HIDE_WINDOW: process.env.PWDEBUG === '1' || process.env.ORKAS_E2E_SHOW_WINDOW === '1' ? '0' : '1',
+ ORKAS_E2E_HIDE_WINDOW: this.options.nativeWindowVisible || process.env.PWDEBUG === '1' || process.env.ORKAS_E2E_SHOW_WINDOW === '1' ? '0' : '1',
CORE_AGENT_AUTH_DIR: this.authRoot,
ORKAS_API_BASE_URL: this.apiBaseUrl,
ORKAS_E2E_MARKETPLACE_API_BASE: this.marketplaceStub ? this.apiBaseUrl : '',
@@ -912,6 +1036,8 @@ export class OrkasTestApp {
no_proxy: 'localhost,127.0.0.1,::1',
TZ: 'UTC',
};
+ if (this.appLocale) environment.ORKAS_E2E_SYSTEM_LOCALE = this.appLocale;
+ else delete environment.ORKAS_E2E_SYSTEM_LOCALE;
// Automation shells can use Electron as their Node runtime and leak this
// switch into child processes. Playwright must launch Electron in app mode.
delete environment.ELECTRON_RUN_AS_NODE;
@@ -954,7 +1080,7 @@ export class OrkasTestApp {
...(process.platform === 'darwin' ? ['-AppleLanguages', `(${this.appLocale})`] : []),
] : [];
const app = await electron.launch({
- args: [...(this.options.softwareRendering ? ['--disable-gpu'] : []), ...(this.options.captureRendererErrorWindows ? ['--require', path.join(__dirname, 'preview-recovery-preload.cjs')] : []), '.', ...localeArgs],
+ args: [...(this.options.softwareRendering ? ['--disable-gpu'] : []), ...(this.options.captureRendererErrorWindows ? ['--require', path.join(__dirname, 'preview-recovery-preload.cjs')] : []), ...(this.appLocale ? ['--require', path.join(__dirname, 'system-locale-preload.cjs')] : []), '.', ...localeArgs],
cwd: PC_ROOT,
env: environment,
timeout: 30_000,
@@ -1025,8 +1151,8 @@ export class OrkasTestApp {
baseUrl: `${this.apiBaseUrl}/v1`,
model: 'e2e-chat-model',
apiKey: 'sk-e2e-local-model-xxxxxxxx',
- contextWindow: 64_000,
- maxTokens: 8_192,
+ contextWindow: E2E_MODEL_CONTEXT_WINDOW,
+ maxTokens: E2E_MODEL_MAX_OUTPUT_TOKENS,
});
await page.evaluate(async () => {
if (typeof (window as any).refreshModelGuard === 'function') {
@@ -1193,6 +1319,31 @@ export class OrkasTestApp {
this.modelTextReplies = replies.slice();
}
+ /** Queue exact planner replies (JSON text) for the next planned sends; when
+ * empty, the stub chains every mentioned actor in mention order. */
+ setDispatchPlanReplies(replies: string[]): void {
+ if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');
+ this.dispatchPlanReplies = replies.slice();
+ }
+
+ /** Park the next planner reply until `releaseDispatchPlan()`, so a test can
+ * act while a planned send is still being split. */
+ holdDispatchPlan(): void {
+ if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');
+ this.dispatchPlanHold = { reply: null };
+ }
+
+ /** True while a held planner request is parked (the send is mid-planning). */
+ get dispatchPlanParked(): boolean {
+ return !!this.dispatchPlanHold?.reply;
+ }
+
+ releaseDispatchPlan(): void {
+ const reply = this.dispatchPlanHold?.reply;
+ this.dispatchPlanHold = null;
+ reply?.();
+ }
+
setLibraryImageDescriptionReplies(replies: string[]): void {
if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');
if (!replies.length || replies.some((reply) => !reply.trim())) {
@@ -1220,6 +1371,12 @@ export class OrkasTestApp {
this.modelToolScenario = null;
}
+ setSavedTasksScenario(projectId: string, finalText: string): void {
+ if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');
+ this.modelToolScenarioRequestStart = this.modelRequests.length;
+ this.modelToolScenario = { kind: 'saved-tasks', next: 0, projectId, finalText };
+ }
+
setBashDenyScenario(command: string): void {
if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');
this.modelToolScenarioRequestStart = this.modelRequests.length;
@@ -1710,6 +1867,20 @@ export class OrkasTestApp {
failed = true;
}
+ const unexpectedApiFailures = this.apiResponses.filter(item => {
+ if (item.status < 400) return false;
+ const index = this.expectedApiFailures.findIndex(expected => expected.method === item.method
+ && expected.path === item.path && expected.status === item.status);
+ if (index < 0) return true;
+ this.expectedApiFailures.splice(index, 1);
+ return false;
+ });
+ failed ||= unexpectedApiFailures.length > 0 || this.expectedApiFailures.length > 0;
+ if (failed || process.env.ORKAS_E2E_KEEP_LOGS === '1') {
+ mkdirSync(this.testInfo.outputDir, { recursive: true });
+ writeFileSync(this.testInfo.outputPath('stub-responses.json'), JSON.stringify(this.apiResponses, null, 2));
+ }
+
if (failed) {
for (const [index, tracePath] of this.tracePaths.entries()) {
await this.testInfo.attach(`trace-${index + 1}`, {
@@ -1783,6 +1954,8 @@ export class OrkasTestApp {
`Renderer page error detected (${unresolvedRendererErrors.length}); see attached Electron diagnostics`,
);
}
+ expect(unexpectedApiFailures, 'Public fixture received unexpected failed HTTP responses').toEqual([]);
+ expect(this.expectedApiFailures, 'Expected HTTP failures were not exercised').toEqual([]);
if (cleanupError) throw cleanupError;
}
@@ -1805,14 +1978,12 @@ export class OrkasTestApp {
// Relaunch and timeout teardown may overlap. Keep one trace and quit per
// captured application, including the same failure for every waiting caller.
const closing = Promise.resolve().then(async () => {
- const tracePath = this.testInfo.outputPath(`trace-${++this.traceNumber}.zip`);
- this.tracePaths.push(tracePath);
try {
await closeElectronFixture({
process: () => app.process(),
- context: () => app.context(),
+ context: () => ({ tracing: { stop: () => this.stopAppTrace(app) } }),
close: () => requestElectronQuit(app),
- }, tracePath, {
+ }, '', {
phase: (phase, outcome) => this.recordCleanupPhase(phase, outcome),
});
} finally {
@@ -1826,6 +1997,22 @@ export class OrkasTestApp {
return closing;
}
+ /** Export while the browser context exists, before a case confirms native exit. */
+ async prepareForNativeShutdown(): Promise<void> {
+ if (!this.electronApp) throw new Error('Electron is unavailable');
+ await this.stopAppTrace(this.electronApp);
+ }
+
+ private stopAppTrace(app: ElectronApplication): Promise<void> {
+ const existing = this.appTraceStops.get(app);
+ if (existing) return existing;
+ const tracePath = this.testInfo.outputPath(`trace-${++this.traceNumber}.zip`);
+ this.tracePaths.push(tracePath);
+ const stopped = Promise.resolve().then(() => app.context().tracing.stop({ path: tracePath }));
+ this.appTraceStops.set(app, stopped);
+ return stopped;
+ }
+
private async ensureStubServer(): Promise<void> {
if (this.apiServer) return;
const marketplaceSkillZip = new AdmZip();
@@ -1867,6 +2054,9 @@ export class OrkasTestApp {
path: requestUrl.pathname,
channel: String(request.headers['orkas-channel'] || ''),
});
+ response.on('finish', () => {
+ this.apiResponses.push({ method: request.method || '', path: requestUrl.pathname, status: response.statusCode });
+ });
const isChat = requestUrl.pathname === '/api/v1/chat/completions';
const isResponses = requestUrl.pathname === '/api/v1/responses';
const isClientConfig = requestUrl.pathname === '/api/config/client';
@@ -1885,6 +2075,7 @@ export class OrkasTestApp {
isChat
|| isResponses
|| isImageCreate
+
|| isGenerationReferenceAuth
|| isGenerationReferenceUpload
|| isGenerationReferenceComplete
@@ -2148,6 +2339,10 @@ export class OrkasTestApp {
}));
return;
}
+ // Measure the wire payload before adding the fixture-only messages
+ // compatibility view, which duplicates Responses input for assertions.
+ const promptTokens = this.modelToolScenario?.kind === 'context-compaction'
+ ? Math.max(1, estimateTextTokens(JSON.stringify(requestBody))) : 12;
if (isResponses) {
const input = Array.isArray(requestBody.input) ? requestBody.input : [];
const messages: Array<Record<string, unknown>> = [];
@@ -2515,7 +2710,7 @@ export class OrkasTestApp {
{
...base,
choices: [],
- usage: { prompt_tokens: 12, completion_tokens: 4, total_tokens: 16 },
+ usage: { prompt_tokens: promptTokens, completion_tokens: 4, total_tokens: promptTokens + 4 },
},
];
const toolCallEvents = (
@@ -2574,7 +2769,7 @@ export class OrkasTestApp {
{
...base,
choices: [],
- usage: { prompt_tokens: 12, completion_tokens: 7, total_tokens: 19 },
+ usage: { prompt_tokens: promptTokens, completion_tokens: 7, total_tokens: promptTokens + 7 },
},
];
const advertisedToolNames = new Set(
@@ -2586,6 +2781,22 @@ export class OrkasTestApp {
finishImmediately(toolCallEvents(callId, 'tool_load', { groups: [group] }));
};
+ if (scenario?.kind === 'saved-tasks') {
+ const calls = [
+ { name: 'auto_tasks', args: { action: 'create', project_id: scenario.projectId, title: 'Nightly review', content: 'Review changes', enabled: false, schedule: { type: 'daily', hour: 0, minute: 0 } } },
+ { name: 'todo_tasks', args: { action: 'create', project: scenario.projectId, content: 'Review release notes' } },
+ { name: 'auto_tasks', args: { action: 'create', title: 'Rejected automation', content: '' } },
+ ];
+ const next = calls[scenario.next];
+ if (!next) finishImmediately(finalTextEvents(scenario.finalText));
+ else if (!advertisedToolNames.has(next.name)) requestToolGroup('load-saved-tasks', next.name === 'auto_tasks' ? 'management.automation' : 'management.projects');
+ else {
+ scenario.next++;
+ finishImmediately(toolCallEvents(`save-task-${scenario.next}`, next.name, next.args));
+ }
+ return;
+ }
+
// Scoped tool surface (production default): executors like `bash` and
// `write_file` stay dormant until the model loads their group. When a
// scenario's next step needs a tool the request did not offer, serve
@@ -2669,6 +2880,22 @@ export class OrkasTestApp {
}
const requestText = JSON.stringify(requestBody);
+ if (requestText.includes(DISPATCH_PLANNER_MARKER)) {
+ const index = this.modelRequests.lastIndexOf(requestBody);
+ if (index >= 0) this.modelRequests.splice(index, 1);
+ this.dispatchPlannerRequests.push(requestBody);
+ const plan = this.dispatchPlanReplies.shift() ?? defaultE2eDispatchPlan(requestPromptText(requestBody));
+ const reply = (): void => {
+ // A Stop aborts the planner request; its socket is gone by then.
+ if (!response.destroyed && !response.writableEnded) finishImmediately(finalTextEvents(plan));
+ };
+ if (this.dispatchPlanHold && !this.dispatchPlanHold.reply) {
+ this.dispatchPlanHold.reply = reply;
+ return;
+ }
+ reply();
+ return;
+ }
if (requestText.includes('Library image-understanding assistant')) {
const imageDescription = this.libraryImageDescriptionReplies.shift();
if (imageDescription !== undefined) {
@@ -3128,12 +3355,8 @@ export class OrkasTestApp {
].join('\n');
finishImmediately(finalTextEvents(summary));
} else if (scenario.nextSourceIndex < scenario.sources.length) {
- // Read a batch per round rather than one file per round. Reaching
- // the window-derived compaction trigger takes far more evidence
- // than a single file can carry (a lone oversized file would spill
- // to disk instead of building context), and serializing every read
- // would turn this into a dozen model round-trips. The batch stays
- // under the per-round inline allowance so nothing spills.
+ // Keep each read below admission limits while the real runtime
+ // accumulates enough evidence to compact between requests.
const batch = scenario.sources.slice(
scenario.nextSourceIndex,
scenario.nextSourceIndex + CONTEXT_SOURCE_READS_PER_ROUND,
@@ -3263,6 +3486,7 @@ export class OrkasTestApp {
this.controlledModelStream?.releaseChunk();
this.controlledModelStream?.releaseFinish();
this.controlledModelStream = null;
+ this.releaseDispatchPlan();
this.pendingCommentaryReply = null;
for (const timer of this.modelTimers) clearTimeout(timer);
this.modelTimers.clear();
@@ -3272,6 +3496,16 @@ export class OrkasTestApp {
}
}
+// Follow the visible sidebar journey: every navigation entry is always shown.
+export async function openSidebarEntry(page: Page, selector: string): Promise<void> {
+ const entry = page.locator(selector);
+ await expect(entry).toBeVisible();
+ await entry.click();
+ // Apps is lazy-loaded after sidebar navigation. Its public refresh hook is
+ // used by setup/recovery cases; a visible shell alone does not mean it exists.
+ if (selector === '#apps-btn') await page.waitForFunction(() => typeof (window as any).loadSavedApps === 'function');
+}
+
type OrkasFixtures = {
orkas: OrkasTestApp;
appPage: Page;
@@ -3279,6 +3513,7 @@ type OrkasFixtures = {
marketplaceOrkas: OrkasTestApp;
cliOrkas: OrkasTestApp;
connectorOrkas: OrkasTestApp;
+ cliModelOrkas: OrkasTestApp;
updateOrkas: OrkasTestApp;
metacognitionOrkas: OrkasTestApp;
};
@@ -3315,6 +3550,15 @@ export const test = base.extend<OrkasFixtures>({
await app.dispose();
}
},
+ cliModelOrkas: async ({}, use, testInfo) => {
+ const app = new OrkasTestApp(testInfo, { cliStub: true, modelStub: true });
+ try {
+ await app.launch();
+ await use(app);
+ } finally {
+ await app.dispose();
+ }
+ },
cliOrkas: async ({}, use, testInfo) => {
const app = new OrkasTestApp(testInfo, { cliStub: true });
try {
diff --git a/test/e2e/fixtures/system-locale-preload.cjs b/test/e2e/fixtures/system-locale-preload.cjs
new file mode 100644
index 00000000..cf9fe9e3
--- /dev/null
+++ b/test/e2e/fixtures/system-locale-preload.cjs
@@ -0,0 +1,5 @@
+// Process-local system-language input for first-boot locale cases. Chromium's
+// --lang controls browser language, but Windows keeps its OS language list.
+const { app } = require('electron');
+const locale = process.env.ORKAS_E2E_SYSTEM_LOCALE;
+if (locale) app.getPreferredSystemLanguages = () => [locale];
diff --git a/test/e2e/history_e2e_loading.spec.ts b/test/e2e/history_e2e_loading.spec.ts
index d3f3634d..1c2ca25b 100644
--- a/test/e2e/history_e2e_loading.spec.ts
+++ b/test/e2e/history_e2e_loading.spec.ts
@@ -4,6 +4,7 @@ import { cpSync, mkdirSync, readFileSync, writeFileSync, existsSync } from 'node
import { createPackageWithOptions } from '@electron/asar';
import { expect, test, OrkasTestApp } from './fixtures/orkas';
import { analyzeWebAppLogs } from './fixtures/web-app-log-analysis';
+import { installEmptyLibrarySearch } from './fixtures/empty-library-search';
const pcRoot = path.resolve(__dirname, '../..');
let previousKeepLogs: string | undefined;
@@ -35,6 +36,261 @@ test.afterEach(async ({}, info) => {
if (analysis.requiresReview) console.warn('History E2E log warnings:', JSON.stringify(analysis.findings));
});
+test('updates settled message actions in place when the user changes language', async ({}, info) => {
+ const app = new OrkasTestApp(info, { configuredModel: false });
+ try {
+ await app.launch();
+ const cid = (await app.invoke<any>('conversations.create', { title: 'Localized message actions' })).conversation.conversation_id;
+ await app.electronApp!.evaluate(async (_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ (process as any).localeEmbedAttempts = 0;
+ req(`${input.root}/src/main/features/kb_embed.ts`)._setEmbedChannelFactoryForTest(() => {
+ (process as any).localeEmbedAttempts += 1;
+ throw new Error('Real embedding is prohibited in the deterministic locale journey');
+ });
+ const uid = req(`${input.root}/src/main/features/users.ts`).getActiveUserId();
+ const file = req(`${input.root}/src/main/util/project-layout.ts`).conversationMessageReadFile(uid, input.cid);
+ const rows = [
+ { id: 'locale-user', from: 'user', to: ['commander'], ts: '2026-10-15T08:00:00Z', text: 'Keep this question' },
+ { id: 'locale-answer', from: 'commander', to: ['user'], ts: '2026-10-15T08:00:01Z', text: 'Keep this answer' },
+ { id: 'locale-failed', from: 'commander', to: ['user'], ts: '2026-10-15T08:00:02Z', text: 'Fixture failure',
+ failure_kind: 'model_output', failure_code: 'provider_error' },
+ ];
+ req('node:fs').writeFileSync(file, rows.map(row => JSON.stringify(row)).join('\n') + '\n');
+ }, { root: pcRoot, cid });
+ const page = app.page!;
+ await page.evaluate(async cid => {
+ const w = window as any;
+ await w.loadConversations();
+ w.setView('conversation', cid);
+ }, cid);
+ const answer = page.locator('[data-msg-id="locale-answer"]');
+ const quote = answer.locator('.bubble-quote-btn');
+ await expect(quote).toHaveText('Quote');
+ const statusLabels = page.locator(`.conv-item[data-cid="${cid}"] .conv-item-status-label`);
+ await expect(statusLabels).not.toHaveCount(0);
+ for (const label of await statusLabels.all()) await expect(label).toHaveText('Failed');
+ await page.evaluate(cid => {
+ (window as any).localeStatusNodes = [...document.querySelectorAll(
+ `.conv-item[data-cid="${CSS.escape(cid)}"] .conv-item-status-label`,
+ )];
+ }, cid);
+ await quote.focus();
+ await page.evaluate(() => {
+ (window as any).localeActionNodes = [...document.querySelectorAll('#chat-history .bubble-action-btn')];
+ });
+ const actions = [
+ ['quote', 'chat.quote_btn', 'chat.quote_btn_title'],
+ ['copy', 'chat.copy_btn', 'chat.copy_btn_title'],
+ ['select', 'chat.message_select', 'chat.message_select_title'],
+ ['archive', 'chat.archive_btn', 'chat.archive_btn_title'],
+ ['retry', 'chat.retry_btn', 'chat.retry_btn_title'],
+ ];
+ for (const language of ['zh', 'en']) {
+ await page.setViewportSize({ width: language === 'zh' ? 720 : 1200, height: 900 });
+ const table = JSON.parse(readFileSync(path.join(pcRoot, 'src/renderer/locales', `${language}.json`), 'utf8'));
+ await page.evaluate(async lang => { await (window as any).setLang(lang); }, language);
+ await expect(page.locator('html')).toHaveAttribute('lang', language === 'zh' ? 'zh-CN' : 'en');
+ for (const [name, labelKey, titleKey] of actions) {
+ const buttons = page.locator(`#chat-history .bubble-${name}-btn`);
+ const expectedCounts: Record<string, number> = { archive: 1, report: 2, retry: 1 };
+ expect(await buttons.count()).toBe(expectedCounts[name] ?? 3);
+ for (const button of await buttons.all()) {
+ await expect(button).toHaveText(table[labelKey]);
+ await expect(button).toHaveAttribute('title', table[titleKey]);
+ }
+ }
+ for (const label of await statusLabels.all()) await expect(label).toHaveText(table['chat.status.failed_short']);
+ expect(await page.evaluate(cid => (window as any).localeStatusNodes.every((node: Element, index: number) =>
+ node === document.querySelectorAll(`.conv-item[data-cid="${CSS.escape(cid)}"] .conv-item-status-label`)[index]), cid)).toBe(true);
+ await expect(quote).toBeFocused();
+ expect(await page.evaluate(() => (window as any).localeActionNodes.every((node: Element, index: number) =>
+ node === document.querySelectorAll('#chat-history .bubble-action-btn')[index]))).toBe(true);
+ await expect(answer.locator('.chat-bubble')).toContainText('Keep this answer');
+ await page.screenshot({ path: info.outputPath(`settled-actions-${language}.png`) });
+ }
+ await page.evaluate(() => {
+ Object.defineProperty(navigator, 'clipboard', { configurable: true,
+ value: { writeText: async (text: string) => { (window as any).localeCopiedText = text; } } });
+ });
+ const copy = answer.locator('.bubble-copy-btn');
+ await copy.click();
+ await expect(copy).toHaveText('Copied');
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ const chinese = JSON.parse(readFileSync(path.join(pcRoot, 'src/renderer/locales/zh.json'), 'utf8'));
+ await expect(copy).toHaveText(chinese['chat.copy_done']);
+ await expect(copy).toBeEnabled();
+ await expect(copy).toHaveText(chinese['chat.copy_btn']);
+ expect(await page.evaluate(() => (window as any).localeCopiedText)).toBe('Keep this answer');
+ const english = JSON.parse(readFileSync(path.join(pcRoot, 'src/renderer/locales/en.json'), 'utf8'));
+ await page.evaluate(() => {
+ (navigator.clipboard as any).writeText = async () => { throw new Error('Fixture clipboard denial'); };
+ });
+ await copy.click();
+ await expect(copy).toHaveText(chinese['chat.copy_failed']);
+ await page.evaluate(async () => { await (window as any).setLang('en'); });
+ await expect(copy).toHaveText(english['chat.copy_failed']);
+ await expect(copy).toBeEnabled();
+ await expect(copy).toHaveText(english['chat.copy_btn']);
+ expect(await app.electronApp!.evaluate(() => (process as any).localeEmbedAttempts)).toBe(0);
+ expect(app.modelRequests).toHaveLength(0);
+
+ } finally { await app.dispose(); }
+});
+
+test('opens a large settled turn before its process pages and retries without losing segmented events', async ({}, info) => {
+ const app = new OrkasTestApp(info, { configuredModel: false });
+ try {
+ await app.launch();
+ const cid = (await app.invoke<any>('conversations.create', { title: 'Paged process' })).conversation.conversation_id;
+ await app.electronApp!.evaluate(async (_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const uid = req(`${input.root}/src/main/features/users.ts`).getActiveUserId();
+ const file = req(`${input.root}/src/main/util/project-layout.ts`).conversationMessageReadFile(uid, input.cid);
+ const rows = [{ id: 'large-process', from: 'fixture-agent', to: ['user'], turn_id: 'paged-turn', seg: 0,
+ ts: '2026-10-12T08:00:00Z', text: 'Earlier segment', process: [
+ ...Array.from({ length: 1203 }, (_, i) => ({ type: 'progress', text: `Process event ${i}` })),
+ { type: 'event', event: { stream: 'runtime', data: { phase: 'segment_end', duration_ms: 1234 } } },
+ ] }, { id: 'later-process', from: 'fixture-agent', to: ['user'], turn_id: 'paged-turn', seg: 1,
+ ts: '2026-10-12T08:01:00Z', text: 'Complete answer \\(x^2\\)', process: [
+ { type: 'progress', text: 'Continuation event' },
+ { type: 'event', event: { stream: 'runtime', data: { phase: 'end', duration_ms: 2000 } } },
+ ] }];
+ req('node:fs').writeFileSync(file, rows.map((row: unknown) => JSON.stringify(row)).join('\n') + '\n');
+ }, { root: pcRoot, cid });
+ const response = await app.invoke<any>('conversations.history', { cid });
+ expect(Buffer.byteLength(JSON.stringify(response))).toBeLessThan(4096);
+ const page = app.page!;
+ await page.evaluate(async cid => { const w = window as any; await w.loadConversations(); w.setView('conversation', cid); }, cid);
+ const row = page.locator('#chat-history .chat-message').filter({ hasText: 'Complete answer' });
+ await expect(row).toHaveCount(1);
+ await expect(row.locator('mjx-container')).toHaveCount(1);
+ const body = row.locator('.stream-process-body');
+ await expect(body).toBeEmpty();
+ await page.evaluate(() => {
+ const w = window as any;
+ w.processFormula = document.querySelector('#chat-history mjx-container');
+ const original = w.apiFetch;
+ let failOnce = true;
+ w.apiFetch = (url: string, options: unknown) => {
+ if (url.includes('/process?') && failOnce) {
+ failOnce = false;
+ return Promise.resolve({ json: async () => ({ ok: false }) });
+ }
+ return original(url, options);
+ };
+ });
+ await row.locator('.stream-process-summary').click();
+ const more = row.locator('.chat-process-load-more');
+ await expect(more).toHaveClass(/is-error/);
+ await expect(body).toBeEmpty();
+ await more.click();
+ await expect(body).toContainText('Process event 199');
+ await expect(body).not.toContainText('Process event 200');
+ await expect(more).toHaveText(await page.evaluate(() => (window as any).t('sidebar.load_more_conversations')));
+ await expect(more).toHaveAttribute('aria-busy', 'false');
+ await more.scrollIntoViewIfNeeded();
+ await page.mouse.move(0, 0);
+ const button = await more.boundingBox();
+ const bubble = await row.locator('.chat-bubble').boundingBox();
+ if (button && bubble) {
+ const viewport = page.viewportSize()!;
+ const top = Math.max(0, button.y - 50);
+ const left = Math.max(0, bubble.x);
+ await page.screenshot({ path: info.outputPath('process-load-more.png'),
+ clip: { x: left, y: top, width: Math.min(bubble.width, viewport.width - left),
+ height: Math.min(150, viewport.height - top) } });
+ }
+ for (let n = 0; n < 7; n++) {
+ await expect(more).toBeEnabled();
+ await more.click();
+ await expect(more).toBeEnabled();
+ }
+ await expect(body).toContainText('Continuation event');
+ await expect(more).toBeHidden();
+ const events = await body.evaluate(node => [...node.textContent!.matchAll(/Process event (\d+)/g)].map(match => Number(match[1])));
+ expect(events).toEqual(Array.from({ length: 1203 }, (_, n) => n));
+ expect(await page.evaluate(() => (window as any).processFormula.isConnected)).toBe(true);
+ await row.locator('.stream-process-summary').click();
+ await row.locator('.stream-process-summary').click();
+ expect(await body.evaluate(node => [...node.textContent!.matchAll(/Process event (\d+)/g)].length)).toBe(1203);
+ } finally { await app.dispose(); }
+});
+
+
+test('discloses byte-bounded process and complete Unicode tool output through native IPC with recoverable paging', async ({}, info) => {
+ test.setTimeout(120_000);
+ const app = new OrkasTestApp(info, { configuredModel: false });
+ try {
+ await app.launch();
+ const cid = (await app.invoke<any>('conversations.create', { title: 'Byte bounded disclosure' })).conversation.conversation_id;
+ const original = await app.electronApp!.evaluate(async (_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const fs = req('node:fs'), crypto = req('node:crypto');
+ const uid = req(`${input.root}/src/main/features/users.ts`).getActiveUserId();
+ const file = req(`${input.root}/src/main/util/project-layout.ts`).conversationMessageReadFile(uid, input.cid);
+ const output = 'a'.repeat(256 * 1024 - 1) + '🌟工具\n<script>window.fixtureLeak=true</script>\n' + '工具🌟'.repeat(140_000) + '\nCOMPLETE';
+ const processItems = [
+ { type: 'event', event: { stream: 'tool', data: { phase: 'end', name: 'bash', id: 'byte-result', output } } },
+ ...Array.from({ length: 1000 }, (_, n) => ({ type: 'progress', text: `Bounded event ${n}` })),
+ { type: 'event', event: { stream: 'runtime', data: { phase: 'end', duration_ms: 1234 } } },
+ ];
+ fs.writeFileSync(file, JSON.stringify({ id: 'byte-turn', from: 'fixture-agent', to: ['user'],
+ ts: '2026-10-13T08:00:00Z', text: 'Complete bounded answer \\(x^2\\)', process: processItems }) + '\n');
+ const hash = (value: any) => crypto.createHash('sha256').update(value).digest('hex');
+ return { file, canonicalHash: hash(fs.readFileSync(file)), outputHash: hash(output), outputBytes: Buffer.byteLength(output) };
+ }, { root: pcRoot, cid });
+ const history = await app.invoke<any>('conversations.history', { cid });
+ expect(Buffer.byteLength(JSON.stringify(history))).toBeLessThan(4096);
+ const part = history.history[0].process_parts[0];
+ const first = await app.invoke<any>('conversations.processPage', { cid, message_id: part.message_id, ref: part.ref, cursor: 0 });
+ expect(Buffer.byteLength(JSON.stringify(first))).toBeLessThanOrEqual(1024 * 1024);
+ const resultPath = first.items[0].event.data.result_path;
+ const page = app.page!;
+ await page.evaluate(async cid => { const w = window as any; await w.loadConversations(); w.setView('conversation', cid); }, cid);
+ const row = page.locator('[data-msg-id="byte-turn"]');
+ await expect(row.locator('mjx-container')).toHaveCount(1);
+ await row.locator('.stream-process-summary').click();
+ const result = row.locator('.stream-process-line.is-expandable').first();
+ await expect(result).toHaveCount(1);
+ await row.locator('.stream-process-compact-summary').first().click();
+ await expect(result).toBeVisible();
+ await result.click();
+ const pre = row.locator('pre.stream-process-line-full');
+ const more = pre.locator('button.chat-process-load-more');
+ await expect(more).toHaveText(await page.evaluate(() => (window as any).t('sidebar.load_more_conversations')));
+ const body = () => pre.evaluate(node => [...node.childNodes].filter(child => child.nodeName !== 'BUTTON').map(child => child.textContent).join(''));
+ const head = await body();
+ expect(Buffer.byteLength(head)).toBeLessThanOrEqual(256 * 1024);
+ expect(head).not.toContain('\uFFFD');
+ await app.electronApp!.evaluate((_electron, file) => (process as any).mainModule.require('node:fs').renameSync(file, file + '.held'), resultPath);
+ await more.click();
+ await expect(more).toHaveClass(/is-error/);
+ expect(await body()).toBe(head);
+ await app.electronApp!.evaluate((_electron, file) => (process as any).mainModule.require('node:fs').renameSync(file + '.held', file), resultPath);
+ for (let n = 0; n < 10 && await more.isVisible(); n++) {
+ await more.click();
+ await expect(more).toHaveAttribute('aria-busy', 'false');
+ }
+ await expect(more).toBeHidden();
+ const complete = await body();
+ const verified = await app.electronApp!.evaluate((_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const hash = (value: any) => req('node:crypto').createHash('sha256').update(value).digest('hex');
+ return { outputHash: hash(input.complete), canonicalHash: hash(req('node:fs').readFileSync(input.file)) };
+ }, { file: original.file, complete });
+ expect(verified).toEqual({ outputHash: original.outputHash, canonicalHash: original.canonicalHash });
+ expect(Buffer.byteLength(complete)).toBe(original.outputBytes);
+ expect(await page.evaluate(() => (window as any).fixtureLeak)).toBeUndefined();
+ await expect(row.locator('mjx-container')).toHaveCount(1);
+ await more.evaluate(node => node.parentElement!.scrollTop = 0);
+ await page.screenshot({ path: info.outputPath('tool-output-pages.png') });
+ await result.click();
+ await expect(pre).toHaveCount(0);
+ expect(app.modelRequests).toHaveLength(0);
+ writeFileSync(info.outputPath('byte-disclosure-evidence.json'), JSON.stringify({ ...original, ...verified, firstPageBytes: Buffer.byteLength(JSON.stringify(first)) }, null, 2));
+ } finally { await app.dispose(); }
+});
test('pages a long transcript without unloading bodies or replacing formulas and selects unread pages completely', async ({}, testInfo) => {
test.setTimeout(150_000);
@@ -152,7 +408,10 @@ test('pages a long transcript without unloading bodies or replacing formulas and
await expect(page.locator('#chat-history .chat-message')).toHaveCount(10);
await expect(page.locator('[data-msg-id="window-23"]')).toHaveClass(/search-flash/);
await expect(page.locator('#chat-history-latest')).toBeVisible();
- await page.evaluate(async cid => (window as any)._loadNewerConversationHistory(cid), cid);
+ // Scrolling an offscreen button into view already invokes auto-paging and
+ // can consume its action before a pointer click. Activate the same native
+ // button by keyboard; the wheel journey below owns automatic continuation.
+ await page.locator('.chat-history-load-newer').press('Enter');
await expect(page.locator('[data-msg-id="window-39"]')).toHaveCount(1);
await page.locator('#chat-history-latest').click();
await expect(page.locator('[data-msg-id="window-129"]')).toHaveCount(1);
@@ -169,6 +428,7 @@ test('scrolls forward from a search hit and keeps a sent reply reachable when a
const app = new OrkasTestApp(testInfo, { modelStub: true });
try {
await app.launch();
+ await installEmptyLibrarySearch(app, pcRoot);
const cid = (await app.invoke<any>('conversations.create', { title: 'Search then send' })).conversation.conversation_id;
await app.electronApp!.evaluate(async (_electron, input) => {
const require = (process as any).mainModule.require.bind((process as any).mainModule);
@@ -254,6 +514,7 @@ test('scrolls forward from a search hit and keeps a sent reply reachable when a
const persisted = await app.invoke<any>('conversations.history', { cid, limit: 10 });
expect(persisted.history.filter((row: any) => row.from === 'user' && row.text === prompt)).toHaveLength(1);
expect(persisted.history.filter((row: any) => row.text === 'Hello from the local E2E model.')).toHaveLength(1);
+ expect(await app.electronApp!.evaluate(() => (globalThis as any).__emptyLibrarySearchQueries)).toBeGreaterThan(0);
writeFileSync(testInfo.outputPath('search-send-evidence.json'), JSON.stringify({ ids, replyTop, persisted: true }));
} finally { await app.dispose(); }
});
@@ -268,23 +529,45 @@ test('joins native turns across forward pages while new replies remain beyond th
const require = (process as any).mainModule.require.bind((process as any).mainModule);
const uid = require(`${input.root}/src/main/features/users.ts`).getActiveUserId();
const file = require(`${input.root}/src/main/util/project-layout.ts`).conversationMessageReadFile(uid, input.cid);
- const rows = Array.from({ length: 30 }, (_, i) => ({ id: `segment-${i}`, to: ['user'],
+ const rows = Array.from({ length: 50 }, (_, i) => ({ id: `segment-${i}`, to: ['user'],
from: i >= 8 && i <= 14 ? 'codex-fixture' : 'commander',
...(i >= 8 && i <= 14 ? { turn_id: 'native-window', seg: i - 8 } : {}),
ts: new Date(1_700_000_000_000 + i * 1000).toISOString(), text: `Segment ${i}: \\(x^2\\)`
- + ((i < 8 || (i > 14 && i < 29)) ? '\n\n' + 'A paragraph for scrolling.\n\n'.repeat(6) : '') }));
+ + ((i < 8 || (i > 14 && i < 49)) ? '\n\n' + 'A paragraph for scrolling.\n\n'.repeat(6) : '') }));
require('node:fs').writeFileSync(file, rows.map((row: unknown) => JSON.stringify(row)).join('\n') + '\n');
}, { root: pcRoot, cid });
const page = app.page!;
await page.evaluate(async cid => { const w = window as any; await w.loadConversations(); w.setView('conversation', cid); }, cid);
- await expect(page.locator('[data-msg-id="segment-29"]')).toHaveCount(1);
+ await expect(page.locator('[data-msg-id="segment-49"]')).toHaveCount(1);
await page.evaluate(async cid => (window as any).loadConversationHistory(cid, {
searchTarget: { msgId: 'segment-9', msgIndex: 9 },
}), cid);
await expect(page.locator('[data-msg-id="segment-9"] mjx-container')).toHaveCount(1);
+ const processDisclosure = page.locator('#chat-history [data-turn-id="native-window"] .stream-process');
+ if (await processDisclosure.evaluate(element => (element as HTMLDetailsElement).open)) await processDisclosure.locator('summary').click();
+ await expect(processDisclosure).toHaveJSProperty('open', false);
+ await page.evaluate(async cid => (window as any)._loadNewerConversationHistory(cid), cid);
+ await expect(page.locator('#chat-history [data-turn-id="native-window"]')).toHaveCount(1);
+ await expect(page.locator('[data-msg-id="segment-14"]')).toContainText('Segment 14:');
+ // Earlier native text belongs to the process trail; pagination must retain
+ // the user's collapse choice rather than restoring obsolete answer blocks.
+ await expect(processDisclosure).toHaveJSProperty('open', false);
+ await expect(page.locator('[data-msg-id="segment-14"] .chat-turn-narration')).toHaveCount(0);
+ await processDisclosure.locator('summary').click();
+ for (let i = 8; i < 14; i++) await expect(processDisclosure.locator('.stream-process-body')).toContainText(`Segment ${i}:`);
+ await expect(processDisclosure.locator('mjx-container')).toHaveCount(6);
+ const finalMath = page.locator('[data-msg-id="segment-14"] > .chat-bubble > .markdown-body mjx-container');
+ await expect(finalMath).toHaveCount(1);
+ // Public history retains the final body and the separate process trail;
+ // hosted conversation sharing and its serializer are excluded.
+ const finalBodyText = await page.locator(
+ '[data-msg-id="segment-14"] > .chat-bubble > .markdown-body',
+ ).innerText();
+ expect(finalBodyText).toContain('Segment 14:');
+ for (let i = 8; i < 14; i++) expect(finalBodyText).not.toContain(`Segment ${i}:`);
await page.evaluate(() => {
const w = window as any;
- w.segmentMath = document.querySelector('[data-msg-id="segment-9"] mjx-container');
+ w.segmentMath = document.querySelector('[data-msg-id="segment-14"] > .chat-bubble > .markdown-body mjx-container');
w.segmentFrames = { running: true, count: 0, invisible: 0 };
const frame = () => {
if (!w.segmentFrames.running) return;
@@ -299,53 +582,70 @@ test('joins native turns across forward pages while new replies remain beyond th
await expect(page.locator('[data-msg-id="segment-14"]')).toContainText('Segment 14:');
expect(await page.evaluate(() => (window as any).segmentMath.isConnected)).toBe(true);
expect(await page.evaluate(() => (window as any).segmentMath.getBoundingClientRect().height)).toBeGreaterThan(0);
- const segmentFrames = await page.evaluate(async () => {
- await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
- (window as any).segmentFrames.running = false;
- return (window as any).segmentFrames;
- });
- expect(segmentFrames.count).toBeGreaterThan(1);
- expect(segmentFrames.invisible).toBe(0);
- for (let i = 8; i < 14; i++) await expect(page.locator(`[data-msg-id="segment-14"] .chat-turn-narration[data-narration-seg="${i - 8}"]`)).toContainText(`Segment ${i}:`);
+
+ await expect(page.locator('[data-msg-id="segment-14"] .chat-turn-narration')).toHaveCount(0);
+ for (let i = 8; i < 14; i++) await expect(processDisclosure.locator('.stream-process-body')).toContainText(`Segment ${i}:`);
const referenceText = await page.evaluate(() => (window as any)._messageReferencePayload(
document.querySelector('[data-msg-id="segment-14"]'),
).text);
- for (let i = 8; i <= 14; i++) expect(referenceText).toContain(`Segment ${i}:`);
+ // Both the pinned source and public quote contract exclude process sections.
+ expect(referenceText).toContain('Segment 14:');
+ for (let i = 8; i < 14; i++) expect(referenceText).not.toContain(`Segment ${i}:`);
+ // Keep a real unread range after two10-record forward pages. The old30-row
+ // seed had already exhausted its cursor before this live-arrival assertion.
+ await expect(page.locator('.chat-history-load-newer')).toHaveCount(1);
+ await expect(page.locator('[data-msg-id="segment-49"]')).toHaveCount(0);
// Actual bus delivery while reading the old window: keep its gap boundary
// and do not let the next page duplicate the arriving newest record.
await page.evaluate(cid => {
const w = window as any;
- const live = w._ensureActorPlaceholder(cid, 'commander', null, 'late-turn', '', 1_700_000_029_000, 0);
- w._streamingAppendFinalDelta(live, 'Segment 29: ');
+ const live = w._ensureActorPlaceholder(cid, 'commander', null, 'late-turn', '', 1_700_000_049_000, 0);
+ w._streamingAppendFinalDelta(live, 'Segment 49: ');
w._handleGroupBusEvent(cid, live, {
- type: 'message', turn_end: true, msg: { id: 'segment-29', from: 'commander', to: ['user'],
+ type: 'message', turn_end: true, msg: { id: 'segment-49', from: 'commander', to: ['user'],
turn_id: 'late-turn', seg: 0,
- ts: new Date(1_700_000_029_000).toISOString(), text: 'Segment 29: \\(x^2\\)' },
+ ts: new Date(1_700_000_049_000).toISOString(), text: 'Segment 49: \\(x^2\\)' },
});
}, cid);
expect(await page.evaluate(() => {
const gap = document.querySelector('.chat-history-load-newer')!;
- const latest = document.querySelector('[data-msg-id="segment-29"]')!;
+ const latest = document.querySelector('[data-msg-id="segment-49"]')!;
return !!(gap.compareDocumentPosition(latest) & Node.DOCUMENT_POSITION_FOLLOWING);
})).toBe(true);
// Exercise the event handler and observe its result. The production scroll
// path also dispatches without awaiting the internal Promise; waiting on
// that cross-realm Promise through CDP can lose its execution context.
const beforeForward = await page.evaluate(() => performance.timeOrigin);
- await page.locator('.chat-history-load-newer').dispatchEvent('click');
- await expect(page.locator('[data-msg-id="segment-29"]')).toHaveCount(1);
+ // Advance each actual10-record cursor without rewriting window state.
+ for (let pageNumber = 0; pageNumber < 5; pageNumber++) {
+ const gap = page.locator('.chat-history-load-newer');
+ if (!await gap.count()) break;
+ const cursor = await gap.getAttribute('data-cursor');
+ await gap.dispatchEvent('click');
+ await expect.poll(async () => await gap.count()
+ ? gap.getAttribute('data-cursor') : 'closed').not.toBe(cursor);
+ await expect(page.locator('[data-msg-id="segment-49"]')).toHaveCount(1);
+ }
+ await expect(page.locator('[data-msg-id="segment-49"]')).toHaveCount(1);
await expect(page.locator('.chat-history-load-newer')).toHaveCount(0);
expect(await page.evaluate(() => performance.timeOrigin)).toBe(beforeForward);
await page.evaluate(async () => {
- document.querySelector('[data-msg-id="segment-29"]')!.scrollIntoView({ block: 'end', behavior: 'instant' });
+ document.querySelector('[data-msg-id="segment-49"]')!.scrollIntoView({ block: 'end', behavior: 'instant' });
});
expect(await page.evaluate(() => (window as any).segmentMath.isConnected)).toBe(true);
await page.evaluate(async () => {
document.querySelector('[data-msg-id="segment-14"]')!.scrollIntoView({ block: 'center', behavior: 'instant' });
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
- await expect(page.locator('[data-msg-id="segment-14"] mjx-container')).toHaveCount(2);
- for (let i = 8; i < 14; i++) await expect(page.locator(`[data-msg-id="segment-14"] .chat-turn-narration[data-narration-seg="${i - 8}"]`)).toContainText(`Segment ${i}:`);
+ const segmentFrames = await page.evaluate(() => {
+ (window as any).segmentFrames.running = false;
+ return (window as any).segmentFrames;
+ });
+ expect(segmentFrames.count).toBeGreaterThan(1);
+ expect(segmentFrames.invisible).toBe(0);
+ await expect(processDisclosure).toHaveJSProperty('open', true);
+ await expect(page.locator('[data-msg-id="segment-14"] mjx-container')).toHaveCount(7);
+ for (let i = 8; i < 14; i++) await expect(processDisclosure.locator('.stream-process-body')).toContainText(`Segment ${i}:`);
} finally { await app.dispose(); }
});
@@ -422,6 +722,8 @@ test('loads and projects history from ASAR with the shipped dependency layout',
const pkg = JSON.parse(readFileSync(path.join(pcRoot, 'package.json'), 'utf8'));
mkdirSync(source, { recursive: true });
cpSync(path.join(pcRoot, 'src/main'), path.join(source, 'src/main'), { recursive: true });
+ mkdirSync(path.join(source, 'bin'), { recursive: true });
+ cpSync(path.join(pcRoot, 'bin/tool-input-compat.cjs'), path.join(source, 'bin/tool-input-compat.cjs'));
for (const file of ['package.json', 'tsconfig.json']) cpSync(path.join(pcRoot, file), path.join(source, file));
for (const name of ['tsx', 'get-tsconfig', 'resolve-pkg-maps', 'esbuild', `@esbuild/${process.platform}-${process.arch}`,
'electron-log', 'async-mutex', 'tslib']) {
diff --git a/test/e2e/home_e2e_continuation.spec.ts b/test/e2e/home_e2e_continuation.spec.ts
new file mode 100644
index 00000000..c513430b
--- /dev/null
+++ b/test/e2e/home_e2e_continuation.spec.ts
@@ -0,0 +1,71 @@
+import { expect, test } from './fixtures/orkas';
+
+// Commander home (PATTERNS.md P15): an open to-do or a finished run the user
+// has not opened turns the New task view into its populated state. The
+// greeting and composer keep their place at the top in both states; the work
+// to pick up is listed below them. Opening a run takes the user to it and it
+// leaves the home; opening a to-do lands on the To-dos page on that to-do.
+// The empty state's layout is covered by the landing case in
+// composer_e2e_interactions.spec.ts.
+test.describe('Commander home continuation', () => {
+ test('lists open work below a composer that keeps its place, and drops a run once it is opened', async ({ orkas, appPage }) => {
+ await appPage.setViewportSize({ width: 1280, height: 720 });
+ const panel = appPage.locator('#panel-new-chat');
+ await expect(panel).toHaveAttribute('data-home-state', 'empty');
+ await expect(appPage.locator('.home-paths')).toBeVisible();
+ await expect(appPage.locator('#home-work')).toBeHidden();
+ // Layout position, so the composer's focus lift transition does not count.
+ const composerTop = () => panel.locator('.new-chat-input-area').evaluate((element) => (element as HTMLElement).offsetTop);
+ const emptyComposerTop = await composerTop();
+
+ const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', {
+ title: 'Weekly competitor brief',
+ });
+ const cid = created.conversation.conversation_id;
+ await orkas.invoke('projects.tasks.create', { content: 'Confirm the pricing table\nDetails in the brief' });
+ // What the sidebar records when a run finishes while the user is elsewhere.
+ await appPage.evaluate((id) => (window as any)._markConversationUnread(id, {
+ finishedAt: Date.now(), status: 'failed', entryPoint: 'chat_send',
+ }), cid);
+
+ await expect(panel).toHaveAttribute('data-home-state', 'populated');
+ const todos = appPage.locator('.home-group[data-section="todos"]');
+ const tasks = appPage.locator('.home-group[data-section="tasks"]');
+ await expect(todos.locator('.home-row-title')).toHaveText(['Confirm the pricing table']);
+ await expect(tasks.locator('.home-row-title')).toHaveText(['Weekly competitor brief']);
+ await expect(tasks.locator('.home-row-action')).toHaveText('See why');
+ await expect(appPage.locator('.home-group[data-section="automations"]')).toHaveCount(0);
+ await expect(appPage.locator('#new-chat-scenarios')).toBeHidden();
+ await expect(appPage.locator('.home-paths')).toBeHidden();
+
+ const layout = await appPage.evaluate(() => {
+ const landing = document.querySelector('#panel-new-chat .new-chat-center')!.getBoundingClientRect();
+ const greeting = document.querySelector('#panel-new-chat .new-chat-header')!.getBoundingClientRect();
+ const composer = document.querySelector('#panel-new-chat .new-chat-input-area')!.getBoundingClientRect();
+ const send = document.getElementById('new-chat-send-btn')!.getBoundingClientRect();
+ const work = document.getElementById('home-work')!.getBoundingClientRect();
+ return {
+ greetingOnScreen: greeting.height > 0 && greeting.top >= landing.top,
+ composerOnScreen: composer.top >= landing.top && composer.bottom <= landing.bottom,
+ sendOnScreen: send.bottom <= landing.bottom,
+ workBelowComposer: work.top >= composer.bottom,
+ };
+ });
+ expect(layout).toEqual({ greetingOnScreen: true, composerOnScreen: true, sendOnScreen: true, workBelowComposer: true });
+ // The state change did not move the composer.
+ expect(await composerTop()).toBe(emptyComposerTop);
+
+ await tasks.locator('.home-row').click();
+ await expect(appPage.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
+ await appPage.locator('#new-chat-btn').click();
+ await expect(panel).toHaveClass(/\bactive\b/);
+ // Opened means read: it is gone from the home, the to-do stays.
+ await expect(appPage.locator('.home-group[data-section="tasks"]')).toHaveCount(0);
+ await expect(todos.locator('.home-row')).toHaveCount(1);
+ await expect(panel).toHaveAttribute('data-home-state', 'populated');
+
+ await todos.locator('.home-row').click();
+ await expect(appPage.locator('#panel-todos')).toHaveClass(/\bactive\b/);
+ await expect(appPage.locator('#todos-content .project-todo-item.is-highlighted')).toHaveCount(1);
+ });
+});
diff --git a/test/e2e/interactive_cli_e2e_authorization.spec.ts b/test/e2e/interactive_cli_e2e_authorization.spec.ts
index 9b80d026..22055017 100644
--- a/test/e2e/interactive_cli_e2e_authorization.spec.ts
+++ b/test/e2e/interactive_cli_e2e_authorization.spec.ts
@@ -1,5 +1,5 @@
import path from 'node:path';
-import { expect, test, type OrkasTestApp } from './fixtures/orkas';
+import { openSidebarEntry, expect, test, type OrkasTestApp } from './fixtures/orkas';
const AUTH_URL = 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=DING-42';
@@ -223,7 +223,7 @@ test(`${scenario.id} ${scenario.format} failure reaches the connection alert wit
try {
const page = orkas.page!;
await page.evaluate(async () => { await (window as any).setLang('zh'); });
- await page.locator('#connectors-btn').click();
+ await openSidebarEntry(page, '#connectors-btn');
await page.locator('#connectors-search-input').fill(scenario.id);
const card = page.locator(`.connector-card[data-id="${scenario.id}"]`);
await card.locator('[data-act="connect"]').click();
diff --git a/test/e2e/interactive_cli_e2e_lifecycle.spec.ts b/test/e2e/interactive_cli_e2e_lifecycle.spec.ts
index 823a64fa..a8b1f7e6 100644
--- a/test/e2e/interactive_cli_e2e_lifecycle.spec.ts
+++ b/test/e2e/interactive_cli_e2e_lifecycle.spec.ts
@@ -5,7 +5,6 @@ const TEST_NODE = process.env.ORKAS_TEST_NODE || process.execPath;
function interactiveCommand(): string {
const script = [
- "process.stdout.write('Enter password: ');",
"let input = '';",
'let settle = null;',
"process.stdin.on('data', chunk => {",
@@ -20,9 +19,12 @@ function interactiveCommand(): string {
].join('');
if (process.platform === 'win32') {
const quote = (value: string) => `'${value.replace(/'/g, "''")}'`;
- return `& ${quote(TEST_NODE)} -e ${quote(script)}`;
+ return `[Console]::Write('Enter password: '); & ${quote(TEST_NODE)} -e ${quote(script)}`;
}
- return `${JSON.stringify(TEST_NODE)} -e ${JSON.stringify(script)}`;
+ // This case owns inference stopping at a known input prompt. Emit the
+ // fixture prompt before cold Node startup; the real child still owns
+ // stdin, duplicate-submit detection, exit and sensitive-output redaction.
+ return `printf '%s' 'Enter password: '; exec ${JSON.stringify(TEST_NODE)} -e ${JSON.stringify(script)}`;
}
test.describe('interactive CLI lifecycle', () => {
@@ -64,9 +66,9 @@ test.describe('interactive CLI lifecycle', () => {
await page.locator(`#conversation-list .conv-item[data-cid="${other.conversation.conversation_id}"]`).click();
await expect(page.locator('#chat-header-title')).toHaveText('Unrelated E2E task');
await expect(card).toHaveCount(0);
- const waiting = await modelOrkas.invoke<{ sessions: Array<{ status: string }> }>('interactiveCli.list');
+ const waiting = await modelOrkas.invoke<{ sessions: Array<{ status: string; prompt_kind?: string }> }>('interactiveCli.list');
expect(waiting.sessions).toHaveLength(1);
- expect(waiting.sessions[0].status).toBe('running');
+ expect(waiting.sessions[0]).toMatchObject({ status: 'running', prompt_kind: 'secret' });
await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
await expect(card).toBeVisible();
await expect(input).toHaveValue('secret-code-42');
@@ -96,6 +98,7 @@ test.describe('interactive CLI lifecycle', () => {
// The user-input boundary ends inference mechanically without a synthesis.
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
expect(modelOrkas.modelRequests).toHaveLength(2);
+ await expect(page.locator('#chat-history')).not.toContainText('E2E interactive CLI session finished.');
const interactiveTool = expect.objectContaining({
function: expect.objectContaining({ name: 'interactive_cli' }),
});
diff --git a/test/e2e/library_e2e_search.spec.ts b/test/e2e/library_e2e_search.spec.ts
index ad4ba31c..686ff2e2 100644
--- a/test/e2e/library_e2e_search.spec.ts
+++ b/test/e2e/library_e2e_search.spec.ts
@@ -1,7 +1,8 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+import { installEmptyLibrarySearch } from './fixtures/empty-library-search';
test.describe('library and global search', () => {
test('indexes a Library file and closes the model library search-to-read loop', async ({ modelOrkas }) => {
@@ -63,7 +64,7 @@ test.describe('library and global search', () => {
);
await modelOrkas.selectFilesOnNextDialog([source]);
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
await page.locator('#ctx-root-menu-btn').click();
await page.locator('#ctx-row-menu .ctx-row-menu-item[data-action="upload"]').click();
await expect(page.locator(`.ctx-tree-wrap[data-path="${fileName}"]`)).toBeVisible();
@@ -327,7 +328,7 @@ test.describe('library and global search', () => {
for (const name of ['first.md', 'second.md']) {
await orkas.invoke('contexts.write', { path: name, content: `Original ${name}` });
}
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
const selector = page.locator('#contexts-project-select-trigger');
const menu = page.locator('#contexts-project-select-listbox');
const editor = page.locator('#contexts-viewer-body textarea');
@@ -375,7 +376,7 @@ test.describe('library and global search', () => {
await orkas.invoke('projects.files.upload', {
projectId: alpha.project.project_id, name: fileName, data: Buffer.from('Alpha original').toString('base64'),
});
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
const selector = page.locator('#contexts-project-select-trigger');
await expect(selector).toContainText('Global');
await page.locator(`#contexts-tree [data-path="${fileName}"] > .skill-tree-node`).click();
@@ -433,7 +434,7 @@ test.describe('library and global search', () => {
const source = orkas.createFixtureFile(originalName, '# Library E2E\n\nUnique library preview body.\n');
await orkas.selectFilesOnNextDialog([source]);
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
await expect(page.locator('#panel-contexts')).toHaveClass(/\bactive\b/);
await page.locator('#ctx-root-menu-btn').click();
await page.locator('#ctx-row-menu .ctx-row-menu-item[data-action="upload"]').click();
@@ -456,7 +457,7 @@ test.describe('library and global search', () => {
await expect(row).toBeVisible();
const relaunchedPage = await orkas.relaunch();
- await relaunchedPage.locator('#contexts-btn').click();
+ await openSidebarEntry(relaunchedPage, '#contexts-btn');
row = relaunchedPage.locator(`.ctx-tree-wrap[data-path="${renamedName}"]`);
await expect(row).toBeVisible();
await row.hover();
@@ -486,7 +487,7 @@ test.describe('library and global search', () => {
content: '# Transfer proof\n\nThis file must have one durable owner.',
});
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
let sourceRow = page.locator(`.ctx-tree-wrap[data-path="${fileName}"]`);
await expect(sourceRow).toBeVisible();
await sourceRow.locator(':scope > .skill-tree-node').click();
@@ -526,7 +527,7 @@ test.describe('library and global search', () => {
expect(destination.tree.filter((entry) => entry.name === fileName)).toHaveLength(1);
page = await orkas.relaunch();
- await page.locator('#contexts-btn').click();
+ await openSidebarEntry(page, '#contexts-btn');
await expect(page.locator(`.ctx-tree-wrap[data-path="${fileName}"]`)).toHaveCount(mode === 'move' ? 0 : 1);
destination = await orkas.invoke<{
tree: Array<{ name: string }>;
@@ -537,6 +538,7 @@ test.describe('library and global search', () => {
test('searches a real agent and navigates to its detail page', async ({ orkas }) => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
+ await installEmptyLibrarySearch(orkas, path.resolve(__dirname, '../..'));
const page = orkas.page;
const name = 'SearchableE2EAgent';
const created = await orkas.invoke<{ ok: boolean; agent: { agent_id: string } }>('agents.create', {
@@ -565,5 +567,6 @@ test.describe('library and global search', () => {
// That is what lets the user return to where they were.
await expect(page.locator('#panel-agents')).toHaveClass(/\bresource-detail-overlay\b/);
await expect(page.locator('#agents-detail-name')).toHaveText(name);
+ expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__emptyLibrarySearchQueries)).toBeGreaterThan(0);
});
});
diff --git a/test/e2e/localization_e2e_language_switch.spec.ts b/test/e2e/localization_e2e_language_switch.spec.ts
index a45f85ed..82e33e1d 100644
--- a/test/e2e/localization_e2e_language_switch.spec.ts
+++ b/test/e2e/localization_e2e_language_switch.spec.ts
@@ -20,6 +20,8 @@ test.describe('localization', () => {
appPage.locator('html').getAttribute('lang')
)).toBe('pt-BR');
await expect(appPage.locator('#agents-btn')).toContainText('Equipe de IA');
+ await expect(appPage.locator('#agents-btn')).toBeVisible();
+ await expect(appPage.locator('#projects-section-toggle')).toHaveAttribute('aria-label', 'Recolher Projetos');
const portugueseFooter = await appPage.evaluate(() => {
const sidebar = document.querySelector('.sidebar') as HTMLElement | null;
const settings = document.querySelector('#settings-btn .sidebar-footer-label') as HTMLElement | null;
diff --git a/test/e2e/marketplace_e2e_install.spec.ts b/test/e2e/marketplace_e2e_install.spec.ts
index 3e3e1336..15bb54a5 100644
--- a/test/e2e/marketplace_e2e_install.spec.ts
+++ b/test/e2e/marketplace_e2e_install.spec.ts
@@ -1,4 +1,4 @@
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
type SkillSummary = {
id: string;
@@ -27,7 +27,7 @@ test.describe('Marketplace install lifecycle', () => {
sort_order: 10,
})]);
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
await page.locator('#agents-more-btn').click();
await expect(page.locator('#panel-marketplace')).toHaveClass(/\bactive\b/);
await expect(page.locator('.marketplace-chip[data-mp-cat="general"]')).toHaveText('General');
@@ -77,7 +77,7 @@ test.describe('Marketplace install lifecycle', () => {
if (!marketplaceOrkas.page) throw new Error('Orkas renderer is unavailable');
const page = marketplaceOrkas.page;
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
await page.locator('#agents-more-btn').click();
await page.locator('[data-mp-tab="skill"]').click();
diff --git a/test/e2e/projects_e2e_smoke.spec.ts b/test/e2e/projects_e2e_smoke.spec.ts
index ddc1ed46..b84d8995 100644
--- a/test/e2e/projects_e2e_smoke.spec.ts
+++ b/test/e2e/projects_e2e_smoke.spec.ts
@@ -184,7 +184,14 @@ test.describe('projects', () => {
await page.locator('#project-todo-save').click();
let todo = page.locator('.project-todo-item', { hasText: 'Run the desktop E2E regression' });
await expect(todo).toHaveAttribute('data-status', 'todo');
- await todo.locator('[data-action="todo-status"]').click();
+ // Project and account cards share the same current-status chip on hover.
+ const move = todo.locator('[data-action="todo-status"]');
+ await expect(move).toHaveText('Pending');
+ await page.locator('#project-detail-title').hover();
+ await expect(move).toHaveCSS('opacity', '0');
+ await todo.hover();
+ await expect(move).toHaveCSS('opacity', '1');
+ await move.click();
await page.locator('.context-menu-item', { hasText: 'Done' }).click();
await expect(todo).toHaveAttribute('data-status', 'done');
@@ -745,6 +752,46 @@ test.describe('projects', () => {
await expect(relaunchedPage.locator('#project-detail-title')).toHaveText(renamedName);
});
+ // The project page header keeps only the title; rename and delete live in its
+ // "⋯" menu, and "Done" stands in for the menu while the title is edited.
+ test('renames from the project header menu and keeps delete behind its confirmation', async ({ orkas }, testInfo) => {
+ const originalName = 'E2E Header Rename Before';
+ const renamedName = 'E2E Header Rename After';
+ await createProject(orkas, originalName);
+ const page = orkas.page!;
+ const more = page.locator('#project-action-more');
+ const done = page.locator('#project-action-rename');
+ const title = page.locator('#project-detail-title');
+ await expect(more).toBeVisible();
+ await expect(done).toBeHidden();
+ await more.click();
+ await expect(page.locator('.context-menu-item')).toHaveText(['Rename', 'Delete']);
+ await page.screenshot({ path: testInfo.outputPath('project-header-local-actions.png') });
+ await page.locator('.context-menu-item', { hasText: 'Rename' }).click();
+ const input = page.locator('#project-detail-title-input');
+ await expect(input).toBeFocused();
+ await expect(input).toHaveValue(originalName);
+ await expect(more).toBeHidden();
+ await expect(done).toHaveText('Done');
+ await page.locator('#panel-project .project-detail-header').screenshot({ path: testInfo.outputPath('project-header-rename-mode.png') });
+ await input.fill(renamedName);
+ await done.click();
+ await expect(title).toHaveText(renamedName);
+ await expect(done).toBeHidden();
+ await expect(more).toBeVisible();
+ await expect.poll(async () => (await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list'))
+ .projects.some((project) => project.name === renamedName)).toBe(true);
+
+ await more.click();
+ await page.locator('.context-menu-item', { hasText: 'Delete' }).click();
+ await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog-danger')).toBeVisible();
+ await page.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();
+ await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
+ await expect(title).toHaveText(renamedName);
+ const listed = await orkas.invoke<{ projects: Array<{ name: string }> }>('projects.list');
+ expect(listed.projects.some((project) => project.name === renamedName)).toBe(true);
+ });
+
test('keeps an unsaved rename draft without applying it during a background refresh', async ({
orkas,
}) => {
diff --git a/test/e2e/recycle_bin_e2e_recovery.spec.ts b/test/e2e/recycle_bin_e2e_recovery.spec.ts
index e095fce0..4c6e2680 100644
--- a/test/e2e/recycle_bin_e2e_recovery.spec.ts
+++ b/test/e2e/recycle_bin_e2e_recovery.spec.ts
@@ -1,9 +1,66 @@
-import { rmSync } from 'node:fs';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from './fixtures/orkas';
test.describe('recycle-bin recovery', () => {
+ test('shows legacy automation names in a compact batch on wide and narrow windows', async ({ orkas, appPage }, testInfo) => {
+ const batchId = 'legacy-automation-display';
+ const batchDir = path.join(orkas.workspaceRoot, 'account-e2e', 'local', 'recycle', batchId);
+ const names = ['Daily sales digest', 'Weekly project report', 'Inbox summary', 'Release checklist',
+ 'Monitor build results', 'Monthly review', 'Daily sales digest'];
+ const configs = names.map((title, index) => {
+ const id = `at_display${index}`;
+ const relPath = index % 2 ? `cloud/projects/p_launch/auto_tasks/${id}/config.json`
+ : `cloud/auto_tasks/${id}/config.json`;
+ const file = path.join(batchDir, 'files', relPath.slice('cloud/'.length));
+ mkdirSync(path.dirname(file), { recursive: true });
+ const text = JSON.stringify({ id, title, content: title, enabled: false,
+ ...(index % 2 ? { project_id: 'p_launch' } : {}) });
+ writeFileSync(file, text);
+ return { id, path: relPath, size: Buffer.byteLength(text) };
+ });
+ const metaFile = path.join(batchDir, 'batch.json');
+ writeFileSync(metaFile, JSON.stringify({
+ id: batchId, source: 'cloud_sync', reason: 'remote_tombstone', created_at_ms: Date.now(),
+ items: configs.map(({ path, size }) => ({ path, size })),
+ metadata: { project_rows: [{ project_id: 'p_launch', name: 'Client Launch' }] },
+ display_items: configs.map(config => ({ category: 'auto_task', id: config.id, title: config.id,
+ path: `cloud/auto_tasks/${config.id}/config.json` })),
+ }));
+ const original = readFileSync(metaFile, 'utf8');
+ await appPage.evaluate(async () => { await (window as any).setLang('zh'); });
+ await appPage.locator('#settings-btn').click();
+ await appPage.locator('[data-settings-tab="data"]').click();
+ const row = appPage.locator('.settings-recycle-row').filter({
+ has: appPage.locator(`[data-recycle-view="${batchId}"]`),
+ });
+ await expect(row.locator('.settings-recycle-name')).toHaveText('自动化 · 7 个任务');
+ await row.locator('[data-recycle-view]').click();
+ await expect(row.locator('.settings-recycle-detail-title')).toHaveText(names);
+ await expect(row.locator('.settings-recycle-details .settings-recycle-meta')).toHaveText([
+ 'Client Launch', 'Client Launch', 'Client Launch',
+ ]);
+ await expect(row.locator('.settings-recycle-detail-path')).toHaveCount(0);
+ await expect(row.locator('.settings-recycle-detail-category')).toHaveCount(0);
+ await expect(row.locator('.settings-recycle-detail-row').nth(1)).toHaveAttribute('title',
+ 'Weekly project report\nat_display1\nprojects/p_launch/auto_tasks/at_display1/config.json');
+ await appPage.setViewportSize({ width: 1000, height: 900 });
+ await row.screenshot({ path: testInfo.outputPath('automation-wide.png') });
+ await appPage.setViewportSize({ width: 620, height: 900 });
+ await expect(row.locator('[data-recycle-restore]')).toBeVisible();
+ await expect(row.locator('[data-recycle-delete]')).toBeVisible();
+ const bounds = await row.evaluate(el => ({ client: el.clientWidth, scroll: el.scrollWidth }));
+ expect(bounds.scroll).toBeLessThanOrEqual(bounds.client);
+ await row.screenshot({ path: testInfo.outputPath('automation-narrow.png') });
+ await row.locator('.settings-recycle-detail-title').last().scrollIntoViewIfNeeded();
+ await expect(row.locator('.settings-recycle-detail-title').last()).toBeInViewport();
+ await appPage.evaluate(async () => { await (window as any).setLang('en'); });
+ await expect(row.locator('.settings-recycle-name')).toHaveText('Automation · 7 tasks');
+ await expect(row.locator('.settings-recycle-detail-title')).toHaveText(names);
+ expect(readFileSync(metaFile, 'utf8')).toBe(original);
+ });
+
test('a corrupt snapshot reports failure without recreating an empty project', async ({ orkas }) => {
const created = await orkas.invoke<{
project: { project_id: string };
diff --git a/test/e2e/resources_e2e_crud.spec.ts b/test/e2e/resources_e2e_crud.spec.ts
index 2189587c..0ce708d6 100644
--- a/test/e2e/resources_e2e_crud.spec.ts
+++ b/test/e2e/resources_e2e_crud.spec.ts
@@ -1,4 +1,4 @@
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
type AgentSummary = { agent_id: string; name: string; enabled?: boolean };
type AgentDetail = AgentSummary & {
@@ -57,7 +57,7 @@ test.describe('agents and skills', () => {
await orkas.invoke('config.setLanguage', { language: 'pt' });
let page = await orkas.relaunch();
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
const card = page.locator('.agent-card[data-id="commander"]');
await expect(card.locator('.agent-card-name')).toHaveText('Commander');
await expect(card.locator('.agent-card-desc')).toContainText('camada de orquestração');
@@ -76,7 +76,7 @@ test.describe('agents and skills', () => {
).avatar).toEqual({ icon: 'crown', color: 'sky' });
page = await orkas.relaunch();
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
const relaunchedCard = page.locator('.agent-card[data-id="commander"]');
await expect(relaunchedCard.locator('.agent-card-name')).toHaveText('Commander');
await expect(relaunchedCard.locator('.avatar-circle'))
@@ -152,7 +152,7 @@ test.describe('agents and skills', () => {
'</agent>',
].join('\n'));
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
await page.locator('#create-agent-btn').click();
await page.locator('#agent-name-input').fill('EditChatWebResearcher');
await page.locator('#agent-desc-input').fill('Researches current sources from an edit conversation.');
@@ -196,7 +196,7 @@ test.describe('agents and skills', () => {
test('creates an agent, persists its enabled state, and deletes it', async ({ orkas }) => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
const page = orkas.page;
- await page.locator('#agents-btn').click();
+ await openSidebarEntry(page, '#agents-btn');
await expect(page.locator('#panel-agents')).toHaveClass(/\bactive\b/);
await page.locator('#create-agent-btn').click();
@@ -221,7 +221,7 @@ test.describe('agents and skills', () => {
}).toBe(false);
const relaunchedPage = await orkas.relaunch();
- await relaunchedPage.locator('#agents-btn').click();
+ await openSidebarEntry(relaunchedPage, '#agents-btn');
const card = relaunchedPage.locator(`.agent-card[data-id="${agent?.agent_id}"]`);
await expect(card).toHaveClass(/\bis-disabled\b/, { timeout: 30_000 });
await card.click();
@@ -246,7 +246,7 @@ test.describe('agents and skills', () => {
test('creates a skill, persists its enabled state, and deletes it', async ({ orkas }) => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
const page = orkas.page;
- await page.locator('#skills-btn').click();
+ await openSidebarEntry(page, '#skills-btn');
await expect(page.locator('#panel-skills')).toHaveClass(/\bactive\b/);
await page.locator('#create-skill-btn').click();
@@ -271,7 +271,7 @@ test.describe('agents and skills', () => {
}).toBe(false);
const relaunchedPage = await orkas.relaunch();
- await relaunchedPage.locator('#skills-btn').click();
+ await openSidebarEntry(relaunchedPage, '#skills-btn');
const card = relaunchedPage.locator(`.skill-card[data-id="${skill?.id}"]`);
await expect(card).toHaveClass(/\bis-disabled\b/, { timeout: 30_000 });
await card.click();
diff --git a/test/e2e/search_e2e_rebuild.spec.ts b/test/e2e/search_e2e_rebuild.spec.ts
index a24140fd..94a257d9 100644
--- a/test/e2e/search_e2e_rebuild.spec.ts
+++ b/test/e2e/search_e2e_rebuild.spec.ts
@@ -2,6 +2,8 @@ import path from 'node:path';
import { cpSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
import { createPackageWithOptions } from '@electron/asar';
import { expect, test, OrkasTestApp } from './fixtures/orkas';
+import { analyzeWebAppLogs } from './fixtures/web-app-log-analysis';
+import { installEmptyLibrarySearch } from './fixtures/empty-library-search';
const pcRoot = path.resolve(__dirname, '../..');
let previousKeepLogs: string | undefined;
@@ -21,8 +23,7 @@ test('shows preparation before full results, searches partial history, and resum
const app = new OrkasTestApp(testInfo, { configuredModel: false });
try {
await app.launch();
- await app.invoke('config.setLanguage', { language: 'zh' });
- await app.page!.evaluate(() => (window as any).setLang('zh'));
+ await installEmptyLibrarySearch(app, pcRoot);
const created = await app.invoke<{ conversation: { conversation_id: string } }>('conversations.create', {
title: 'Search recovery fixture',
});
@@ -69,8 +70,12 @@ test('shows preparation before full results, searches partial history, and resum
.toMatchObject({ ok: true, chat_index_complete: false, results: [] });
let page = app.page!;
+ // The preparation/loading assertions below intentionally verify Chinese.
+ // Establish that language through the real UI preference before searching.
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
// Hold only delivery of the real global request. Status uses the actual
- // renderer shim/preload/IPC handler; no search or status response is faked.
+ // renderer shim/preload/IPC handler; chat search/status remain real while
+ // the unrelated Library semantic provider is explicitly fixture-only.
await page.evaluate(() => {
const app = window as any;
const original = app.apiFetch;
@@ -100,6 +105,7 @@ test('shows preparation before full results, searches partial history, and resum
await page.locator('#search-close-btn').click();
page = await app.relaunch();
+ await installEmptyLibrarySearch(app, pcRoot);
// Startup owns resumption; no manual repair invocation after relaunch.
// Low-memory hosts start the deferred phase after 6s, then admit disk
// work after another 30s. Allow that documented boot budget, not a query
@@ -119,7 +125,35 @@ test('shows preparation before full results, searches partial history, and resum
await expect(page.locator('#search-body .search-result').first()).toBeVisible();
await expect(page.locator('#search-body [role="status"]')).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath('complete-search.png') });
+ await page.locator('#search-close-btn').click();
+
+ // A built index that loses verification (here a sync invalidation) while
+ // agent work keeps its repair waiting is not announced: opening search and
+ // searching stay quiet, and the status check queues the catch-up.
+ await app.electronApp!.evaluate((_electron, root) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ require(`${root}/src/main/util/boot_init.ts`).configureBootAdmission({ isRuntimeBusy: () => true });
+ const uid = require(`${root}/src/main/features/users.ts`).getActiveUserId();
+ require(`${root}/src/main/features/search/indexer.ts`).invalidateChatsIndex(uid);
+ }, pcRoot);
+ expect(await app.invoke('search.status'))
+ .toMatchObject({ ok: true, chat_index_complete: false, chat_index_building: false });
+ await page.locator('#sidebar-search-btn').click();
+ // Let the overlay's own status request settle before checking for silence.
+ await page.evaluate(() => (window as any).apiFetch('/api/search/status').then((r: any) => r.json()));
+ await expect(page.locator('#search-body [role="status"]')).toHaveCount(0);
+ await page.locator('#search-input').fill('prefixmarker');
+ await expect(page.locator('#search-body .search-result').first()).toBeVisible();
+ await expect(page.locator('#search-body [role="status"]')).toHaveCount(0);
+ await page.screenshot({ path: testInfo.outputPath('catch-up-search.png') });
+ await app.electronApp!.evaluate((_electron, root) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ require(`${root}/src/main/util/boot_init.ts`).configureBootAdmission({ isRuntimeBusy: () => false });
+ }, pcRoot);
+ await expect.poll(async () => app.invoke('search.status'), { timeout: 30_000 })
+ .toMatchObject({ ok: true, chat_index_complete: true });
expect(app.modelRequests).toHaveLength(0);
+ expect(await app.electronApp!.evaluate(() => (globalThis as any).__emptyLibrarySearchQueries)).toBeGreaterThan(0);
} finally { await app.dispose(); }
});
diff --git a/test/e2e/secondary_e2e_surfaces.spec.ts b/test/e2e/secondary_e2e_surfaces.spec.ts
index e6efeebf..33812364 100644
--- a/test/e2e/secondary_e2e_surfaces.spec.ts
+++ b/test/e2e/secondary_e2e_surfaces.spec.ts
@@ -1,5 +1,5 @@
import type { Page } from '@playwright/test';
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
async function openDataSettings(page: Page): Promise<void> {
await page.locator('#settings-btn').click();
@@ -131,22 +131,8 @@ test.describe('secondary user surfaces', () => {
await expect(persistedSection.locator('.memory-empty')).toBeVisible();
});
- test('opens the external-only coding-CLI dialog from the AI Team header', async ({ appPage }) => {
- await appPage.locator('#agents-btn').click();
- await appPage.locator('#agents-connect-cli-btn').click();
-
- await expect(appPage.locator('#agent-modal')).toHaveClass(/\bopen\b/);
- await expect(appPage.locator('#agent-modal [data-agent-panel="external"]')).toHaveClass(/\bis-active\b/);
- await expect(appPage.locator('#agent-modal-title')).toHaveText('Connect an agent');
- await expect(appPage.locator('#agent-modal-tabs')).toBeHidden();
- await expect(appPage.locator('#agent-modal-ext-cli-select')).toBeVisible();
-
- await appPage.locator('#agent-modal .modal-actions .btn').first().click();
- await expect(appPage.locator('#agent-modal')).not.toHaveClass(/\bopen\b/);
- });
-
test('opens Marketplace from Agents and switches every catalog tab', async ({ appPage }) => {
- await appPage.locator('#agents-btn').click();
+ await openSidebarEntry(appPage, '#agents-btn');
await appPage.locator('#agents-more-btn').click();
await expect(appPage.locator('#panel-marketplace')).toHaveClass(/\bactive\b/);
@@ -169,4 +155,21 @@ test.describe('secondary user surfaces', () => {
await expect(appPage.locator('#panel-agents')).toHaveClass(/\bactive\b/);
});
+ test('opens the external-only coding-CLI dialog from the AI Team header', async ({ appPage }) => {
+ // The page the sidebar's coding-agent card used to open, now reached from
+ // the AI Team header: the CLI panel alone, with no tab bar exposing the
+ // in-process create form.
+ await openSidebarEntry(appPage, '#agents-btn');
+ await appPage.locator('#agents-connect-cli-btn').click();
+
+ await expect(appPage.locator('#agent-modal')).toHaveClass(/\bopen\b/);
+ await expect(appPage.locator('#agent-modal [data-agent-panel="external"]')).toHaveClass(/\bis-active\b/);
+ await expect(appPage.locator('#agent-modal-title')).toHaveText('Connect an agent');
+ await expect(appPage.locator('#agent-modal-tabs')).toBeHidden();
+ await expect(appPage.locator('#agent-modal-ext-cli-select')).toBeVisible();
+
+ await appPage.locator('#agent-modal .modal-actions .btn').first().click();
+ await expect(appPage.locator('#agent-modal')).not.toHaveClass(/\bopen\b/);
+ });
+
});
diff --git a/test/e2e/sidebar_e2e_navigation.spec.ts b/test/e2e/sidebar_e2e_navigation.spec.ts
new file mode 100644
index 00000000..45e123d4
--- /dev/null
+++ b/test/e2e/sidebar_e2e_navigation.spec.ts
@@ -0,0 +1,73 @@
+import { expect, OrkasTestApp, test } from './fixtures/orkas';
+
+const NAV_ORDER = [
+ ['new-chat', 'new-chat', '新任务'],
+ ['todos', 'todos', '待办'],
+ ['auto', 'auto', '自动化'],
+ ['agents', 'agents', 'AI 团队'],
+ ['skills', 'skills', '技能库'],
+ ['connectors', 'connectors', '连接器'],
+ ['contexts', 'contexts', '资料库'],
+ ['apps', 'apps', '应用'],
+];
+
+test('shows every navigation entry in the release 1.8.0 order and opens each destination', async ({}, info) => {
+ const app = new OrkasTestApp(info, { marketplaceStub: true, seedLanguage: 'zh' });
+ try {
+ await app.launch();
+ const page = app.page!;
+ await page.setViewportSize({ width: 1100, height: 740 });
+ // The retired 日常运营 / 能力资源 groups leave no toggles behind.
+ await expect(page.locator('#operations-section-toggle, #capabilities-section-toggle')).toHaveCount(0);
+ const ids = await page.locator('.sidebar-actions > .sidebar-btn').evaluateAll(
+ (buttons) => buttons.map((button) => button.id),
+ );
+ expect(ids).toEqual(NAV_ORDER.map(([entry]) => `${entry}-btn`));
+ for (const [entry, , label] of NAV_ORDER) {
+ const button = page.locator(`#${entry}-btn`);
+ await expect(button).toBeVisible();
+ await expect(button.locator('[data-i18n]').first()).toHaveText(label);
+ }
+ await page.screenshot({ path: info.outputPath('sidebar-flat-navigation.png') });
+
+ for (const [entry, panel] of NAV_ORDER.slice(1)) {
+ await page.locator(`#${entry}-btn`).click();
+ await expect(page.locator(`#panel-${panel}`)).toBeVisible();
+ await expect(page.locator(`#${entry}-btn`)).toHaveClass(/\bactive\b/);
+ }
+ await page.locator('#new-chat-btn').click();
+ await expect(page.locator('#panel-new-chat')).toBeVisible();
+ await expect(page.locator('#new-chat-btn')).toHaveClass(/\bactive\b/);
+ } finally {
+ await app.dispose();
+ }
+});
+
+test('ignores retired navigation-group preferences across real Electron relaunches without resetting task sections', async ({}, info) => {
+ const app = new OrkasTestApp(info, { seedLanguage: 'zh' });
+ try {
+ await app.launch();
+ let page = app.page!;
+ // An upgraded installation still stores collapsed navigation groups.
+ await page.evaluate(() => localStorage.setItem('sidebar.sectionCollapsed', JSON.stringify({
+ operations: true, capabilities: true, today: true, projects: false, tasks: true,
+ })));
+ page = await app.relaunch();
+ for (const [entry] of NAV_ORDER) await expect(page.locator(`#${entry}-btn`)).toBeVisible();
+ await expect(page.locator('#today-section-toggle')).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#tasks-section-toggle')).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#projects-section-toggle')).toHaveAttribute('aria-expanded', 'true');
+
+ await page.locator('#projects-section-toggle').click();
+ await expect(page.locator('#projects-section-toggle')).toHaveAttribute('aria-expanded', 'false');
+ const stored = await page.evaluate(() => JSON.parse(localStorage.getItem('sidebar.sectionCollapsed') || '{}'));
+ expect(stored).toEqual({ today: true, projects: true, tasks: true });
+
+ page = await app.relaunch();
+ await expect(page.locator('#projects-section-toggle')).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#today-section-toggle')).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.locator('#auto-btn')).toBeVisible();
+ } finally {
+ await app.dispose();
+ }
+});
diff --git a/test/e2e/sidebar_e2e_pagination_spacing.spec.ts b/test/e2e/sidebar_e2e_pagination_spacing.spec.ts
new file mode 100644
index 00000000..50f1597e
--- /dev/null
+++ b/test/e2e/sidebar_e2e_pagination_spacing.spec.ts
@@ -0,0 +1,102 @@
+import { expect, test } from './fixtures/orkas';
+
+
+test('keeps task pagination close to its rows without losing focus or page navigation', async ({ orkas }, info) => {
+ const page = orkas.page!;
+ const { project } = await orkas.invoke<{ project: { project_id: string } }>('projects.create', {
+ name: 'Pagination layout',
+ });
+ for (const projectId of ['', project.project_id]) {
+ for (let index = 0; index < 11; index++) {
+ await orkas.invoke('conversations.create', {
+ projectId, title: `Task ${index}: 验证很长的任务标题 / A long conversation title for narrow sidebars`,
+ });
+ }
+ }
+ await page.evaluate(async (pid) => {
+ const w = window as any;
+ await w.loadProjects(true);
+ // The caches are production renderer inputs; the fixture uses real IPC
+ // records in isolated storage, without running a model or writing user data.
+ await w.loadConversationProject(pid, { reset: true });
+ await w.loadUnprojectedConversations({ reset: true });
+ }, project.project_id);
+ await page.evaluate((pid) => {
+ // Classic-script lexical state is deliberately scoped to this renderer.
+ (0, eval)(`_projectsExpanded[${JSON.stringify(pid)}] = true; renderProjectsSection();`);
+ }, project.project_id);
+
+ await page.evaluate((pid) => { (window as any).setView('project', pid); }, project.project_id);
+ await expect(page.locator('#project-tasks-list > .conversation-list-load-more')).toBeVisible();
+ const lists = ['#conversation-list', `[data-pid-children="${project.project_id}"]`, '#project-tasks-list'];
+ for (const [language, width, height] of [['zh', 1100, 740], ['en', 900, 600]] as const) {
+ await page.setViewportSize({ width, height });
+ await page.evaluate(async (lang) => { await (window as any).setLang(lang); }, language);
+ for (const list of lists) {
+ const more = page.locator(`${list} > .conversation-list-load-more`);
+ await expect(more).toBeVisible();
+ await more.scrollIntoViewIfNeeded();
+ const geometry = await more.evaluate((button) => {
+ const row = button.previousElementSibling!;
+ const rect = button.getBoundingClientRect();
+ const style = getComputedStyle(button);
+ return {
+ gap: rect.top - row.getBoundingClientRect().bottom,
+ height: rect.height,
+ footprint: rect.height + parseFloat(style.marginTop) + parseFloat(style.marginBottom),
+ fits: button.scrollWidth <= button.clientWidth,
+ };
+ });
+ // Compact pagination belongs to the list: at most a small sibling gap,
+ // with a usable target rather than a separate blank section.
+ expect(geometry.gap).toBeGreaterThanOrEqual(0);
+ expect(geometry.gap).toBeLessThanOrEqual(6);
+ expect(geometry.height).toBeGreaterThanOrEqual(24);
+ expect(geometry.footprint).toBeLessThanOrEqual(36);
+ expect(geometry.fits).toBe(true);
+ await more.focus();
+ await expect(more).toBeFocused();
+ await page.locator(list === '#project-tasks-list' ? '#panel-project' : '.sidebar').screenshot({
+ path: info.outputPath(`pagination-${language}-${lists.indexOf(list)}.png`),
+ });
+ }
+ }
+ // Pagination still appends the remaining row and removes the exhausted
+ // control; layout changes must not affect the real navigation contract.
+ for (const list of lists.slice(0, 2)) {
+ const more = page.locator(`${list} > .conversation-list-load-more`);
+ await more.click();
+ await expect(page.locator(`${list} > .conv-item`)).toHaveCount(11);
+ await expect(more).toHaveCount(0);
+ }
+ // The automation history shares the same row and pagination styles. Seed
+ // only its read cache; render with the shipped row component and handlers.
+ await page.locator('#auto-btn').click();
+ await expect.poll(() => page.evaluate(() => typeof (window as any)._autoRenderRow)).toBe('function');
+ await page.evaluate(() => {
+ (0, eval)(`
+ _autoTaskConversationPages.set('layout-history', {
+ initialized: true, items: conversations.slice(0, 10), total: 11, nextOffset: 10,
+ });
+ document.getElementById('auto-list').replaceChildren(_autoRenderRow({
+ id: 'layout-history', title: 'Execution history', content: 'Layout preview',
+ enabled: false, schedule: { type: 'daily', hour: 3, minute: 0 },
+ }, { expanded: true }));
+ document.getElementById('auto-empty').style.display = 'none';
+ `);
+ });
+ const historyMore = page.locator('#auto-list .conversation-list-load-more');
+ await expect(historyMore).toBeVisible();
+ const historyGeometry = await historyMore.evaluate((button) => {
+ const rect = button.getBoundingClientRect();
+ const style = getComputedStyle(button);
+ return {
+ gap: rect.top - button.previousElementSibling!.getBoundingClientRect().bottom,
+ footprint: rect.height + parseFloat(style.marginTop) + parseFloat(style.marginBottom),
+ };
+ });
+ expect(historyGeometry.gap).toBeGreaterThanOrEqual(0);
+ expect(historyGeometry.gap).toBeLessThanOrEqual(6);
+ expect(historyGeometry.footprint).toBeLessThanOrEqual(36);
+ await page.locator('#panel-auto').screenshot({ path: info.outputPath('pagination-auto-history.png') });
+});
diff --git a/test/e2e/sidebar_today_e2e_aggregate.spec.ts b/test/e2e/sidebar_today_e2e_aggregate.spec.ts
index abe515f2..05cd5b2f 100644
--- a/test/e2e/sidebar_today_e2e_aggregate.spec.ts
+++ b/test/e2e/sidebar_today_e2e_aggregate.spec.ts
@@ -1,15 +1,18 @@
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
-import { expect, test, type OrkasTestApp } from './fixtures/orkas';
+import { openSidebarEntry, expect, test, type OrkasTestApp } from './fixtures/orkas';
-// Sidebar "Today's Tasks" aggregate through the real IPC + renderer wiring:
-// the startup slice must carry today's rows from a collapsed project, the
-// aggregate must exclude older rows, and the unread cue must behave as one
-// task mirrored in two lists.
+// Sidebar "Recent Tasks" aggregate (today + yesterday) through the real IPC +
+// renderer wiring: the startup slice must carry today's and yesterday's rows
+// from a collapsed project, the aggregate must exclude older rows, and the
+// unread cue must behave as one task mirrored in two lists.
type Conversation = { conversation_id: string; project_id?: string };
+// Sidebar scenarios use the local account service as well as isolated storage;
+// an unavailable account endpoint must not introduce unrelated retry noise.
+
async function createConversation(orkas: OrkasTestApp, title: string, projectId = ''): Promise<Conversation> {
const result = await orkas.invoke<{ conversation: Conversation }>('conversations.create', { title, projectId });
return result.conversation;
@@ -40,6 +43,11 @@ function backdateConversations(workspaceRoot: string, cids: string[], iso: strin
let changed = false;
for (const row of rows) {
if (!cids.includes(row.conversation_id)) continue;
+ // These are previously active tasks, not empty legacy placeholders.
+ // The real startup ghost migration must retain their canonical history.
+ writeFileSync(path.join(path.dirname(file), `${row.conversation_id}.jsonl`),
+ JSON.stringify({ id: `${row.conversation_id}-activity`, from: 'user',
+ to: ['commander'], text: 'Deterministic sidebar activity', ts: iso }) + '\n');
row.created_at = iso;
row.updated_at = iso;
row.participant_summary_updated_at = iso;
@@ -52,7 +60,7 @@ function backdateConversations(workspaceRoot: string, cids: string[], iso: strin
}
test.describe('sidebar today aggregate', () => {
- test('lists today\'s tasks across a collapsed project and the Tasks list and mirrors unread state', async ({ orkas }) => {
+ test('lists recent tasks across a collapsed project and the Tasks list and mirrors unread state', async ({ orkas }) => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
const page = orkas.page;
@@ -62,8 +70,11 @@ test.describe('sidebar today aggregate', () => {
const projectOld = await createConversation(orkas, 'Project task from last week', pid);
const unprojectedToday = await createConversation(orkas, 'Loose task ran today');
const unprojectedOld = await createConversation(orkas, 'Loose task from last week');
+ const projectYesterday = await createConversation(orkas, 'Project task ran yesterday', pid);
const lastWeek = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
backdateConversations(orkas.workspaceRoot, [projectOld.conversation_id, unprojectedOld.conversation_id], lastWeek);
+ const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
+ backdateConversations(orkas.workspaceRoot, [projectYesterday.conversation_id], yesterday);
// Keep the project collapsed: the aggregate must not depend on expansion.
await page.evaluate(() => {
@@ -72,11 +83,18 @@ test.describe('sidebar today aggregate', () => {
const relaunched = await orkas.relaunch();
const todayRows = relaunched.locator('#today-list .conv-item');
- await expect(todayRows).toHaveCount(2);
+ await expect(todayRows).toHaveCount(3);
+ await expect(relaunched.locator(`#today-list .conv-item[data-cid="${projectYesterday.conversation_id}"]`)).toHaveCount(1);
await expect(relaunched.locator(`#today-list .conv-item[data-cid="${projectToday.conversation_id}"]`)).toHaveCount(1);
await expect(relaunched.locator(`#today-list .conv-item[data-cid="${unprojectedToday.conversation_id}"]`)).toHaveCount(1);
await expect(relaunched.locator(`#today-list .conv-item[data-cid="${projectOld.conversation_id}"]`)).toHaveCount(0);
await expect(relaunched.locator(`#today-list .conv-item[data-cid="${unprojectedOld.conversation_id}"]`)).toHaveCount(0);
+ // Older tasks remain valid records: age filtering, not ghost migration,
+ // excludes them from the aggregate.
+ const persisted = await orkas.invoke<{ conversations: Conversation[] }>('conversations.list');
+ expect(persisted.conversations.map((row) => row.conversation_id))
+ .toEqual(expect.arrayContaining([projectYesterday.conversation_id,
+ projectOld.conversation_id, unprojectedOld.conversation_id]));
// The project itself stays collapsed and the Tasks list still owns its
// own copy of the unprojected task.
await expect(relaunched.locator('#projects-list .conv-item')).toHaveCount(0);
@@ -106,3 +124,78 @@ test.describe('sidebar today aggregate', () => {
await expect(relaunched.locator(`.sidebar-conversation-nav .conv-item.active[data-cid="${projectToday.conversation_id}"]`)).toHaveCount(2);
});
});
+
+test.describe('manual task receipt and sidebar refresh', () => {
+ test('shows one task when a real list refresh precedes the run receipt', async ({ cliOrkas: orkas }) => {
+ const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('en'));
+ const { agent } = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
+ name: 'ReceiptRaceCodex', category: 'general', runtime: { kind: 'cli', cli: 'codex' },
+ });
+ const { project } = await orkas.invoke<{ project: { project_id: string } }>('projects.create', {
+ name: 'Receipt race project',
+ });
+ const pid = project.project_id;
+ await orkas.invoke('projects.bindings.add', { projectId: pid, kind: 'agent', id: agent.agent_id });
+ const content = 'E2E_CODEX_SEND_NOW_ACTIVE inspect receipt race';
+ const { task } = await orkas.invoke<{ task: { id: string } }>('projects.tasks.create', {
+ projectId: pid, content, owner_agent_id: agent.agent_id,
+ });
+ // Hold only the acknowledgement of the admitted execution. Creation,
+ // dispatch, persistence, list IPC and sidebar rendering all stay real.
+ await orkas.electronApp!.evaluate(({ ipcMain }, tid) => {
+ const original = (ipcMain as any)._invokeHandlers.get('orkas.invoke');
+ if (typeof original !== 'function') throw new Error('Fixture invoke handler unavailable');
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const state = { cid: '', calls: 0, release, restore: () => {
+ ipcMain.removeHandler('orkas.invoke'); ipcMain.handle('orkas.invoke', original);
+ } };
+ (globalThis as any).__receiptRace = state;
+ ipcMain.removeHandler('orkas.invoke');
+ ipcMain.handle('orkas.invoke', async (event, request) => {
+ const result = await original(event, request);
+ if (request?.channel === 'projects.tasks.run' && request.payload?.taskId === tid) {
+ state.cid = result.cid;
+ state.calls += 1;
+ await gate;
+ }
+ return result;
+ });
+ }, task.id);
+ let cid = '';
+ try {
+ await openSidebarEntry(page, '#todos-btn');
+ const card = page.locator('#todos-content .project-todo-item', { hasText: content });
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: 'Process now' }).click();
+ await expect.poll(async () => {
+ cid = await orkas.electronApp!.evaluate(() => (globalThis as any).__receiptRace.cid);
+ return !!cid;
+ }).toBe(true);
+ await page.evaluate(async () => (window as any).loadConversations());
+ const todayRow = page.locator(`#today-list .conv-item[data-cid="${cid}"]`);
+ await expect(todayRow).toHaveCount(1);
+ await expect(todayRow).not.toHaveClass(/\bactive\b/);
+ await orkas.electronApp!.evaluate(() => (globalThis as any).__receiptRace.release());
+ // The same row becomes active once the original run receipt arrives.
+ // No subsequent list reload may mask a duplicate introduced by it.
+ await expect(todayRow).toHaveClass(/\bactive\b/);
+ await expect(todayRow).toHaveCount(1);
+ const listed = await orkas.invoke<{ conversations: Conversation[] }>('conversations.list');
+ expect(listed.conversations.filter((row) => row.project_id === pid)).toHaveLength(1);
+ const execution = await orkas.invoke<{ tasks: Array<{ assignee: string }> }>('groupChat.tasks.list', { cid });
+ expect(execution.tasks).toHaveLength(1);
+ expect(execution.tasks[0].assignee).toBe(agent.agent_id);
+ expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__receiptRace.calls)).toBe(1);
+ await expect.poll(() => orkas.readCliState().invocations.filter((run) => run.prompt.includes(content)).length).toBe(1);
+ } finally {
+ await orkas.electronApp!.evaluate(() => {
+ const state = (globalThis as any).__receiptRace;
+ state.release(); state.restore(); delete (globalThis as any).__receiptRace;
+ });
+ if (cid) await orkas.invoke('groupChat.abort', { cid });
+ }
+ });
+});
diff --git a/test/e2e/task_board_e2e_scheduling.spec.ts b/test/e2e/task_board_e2e_scheduling.spec.ts
index 2c106a42..f5b3f6fa 100644
--- a/test/e2e/task_board_e2e_scheduling.spec.ts
+++ b/test/e2e/task_board_e2e_scheduling.spec.ts
@@ -2,9 +2,10 @@ import { expectComposerText } from './fixtures/composer';
/**
* Conversation task-board scheduling — real app, real bus, stubbed model.
*
- * Scenario value (D18, plan conversation-task-board.md): a user writing
- * "@A do X. @B do Y from it." in ONE message gets serial execution with a
- * visible dependency and a real hand-off. Multi-task coordination and the
+ * Scenario value (D29, plan conversation-task-board.md): a user writing
+ * "@A do X. @B do Y from it." in ONE message gets the planned split — here the
+ * fixture planner's in-order chain — with a visible dependency and a real
+ * hand-off. Multi-task coordination and the
* blocked/run-anyway recovery path stay visible on the board, then the board
* retracts when only an ordinary single run remains.
* The cases here reproduce live-app defects: the invisible chain handover
@@ -48,12 +49,12 @@ async function sendMultiMention(
const input = page.locator('#chat-input');
await input.fill(text);
await input.dispatchEvent('input');
- // D18 UI: a two-group composer text surfaces the serial/parallel toggle.
- await expect(page.locator('#chat-seq-toggle')).toBeVisible();
+ // D29: the dispatch planner decides order; there is no composer toggle.
+ await expect(page.locator('#chat-seq-toggle')).toHaveCount(0);
await page.locator('#chat-send-btn').click();
}
-test.describe('task board scheduling (D18 serial chain)', () => {
+test.describe('task board scheduling (D29 planned dependencies)', () => {
test.describe.configure({
timeout: process.platform === 'win32' ? 120_000 : 60_000,
});
@@ -239,18 +240,16 @@ test.describe('task board scheduling (D18 serial chain)', () => {
await input.fill('@ContentWriter write the intro piece. @UIDesigner build the deck from it.');
await input.dispatchEvent('input');
// The chip is this surface's only routing preview: it must name BOTH
- // assignees rather than a single picked recipient — and the landing page
- // now surfaces the serial/parallel order choice too (D23), defaulting to
- // the adjudicated written-order chain for a two-group text.
+ // assignees rather than a single picked recipient. Order is decided by
+ // the dispatch planner (D29), so no order toggle is offered.
await expect(page.locator('#new-chat-recipient-name')).toHaveText('ContentWriter, UIDesigner');
- await expect(page.locator('#new-chat-seq-toggle')).toBeVisible();
- await expect(page.locator('#new-chat-seq-toggle')).toHaveText('Run in order');
+ await expect(page.locator('#new-chat-seq-toggle')).toHaveCount(0);
await page.locator('#new-chat-send-btn').click();
await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
// Both assignees reach the board of the conversation this send created,
- // and the second one depends on the first (serial default, D18).
+ // and the second one depends on the first (the fixture plan's chain).
const rows = page.locator('#chat-task-board-list .chat-queue-item');
await expect(rows).toHaveCount(2, { timeout: 30_000 });
await expect(page.locator('#chat-task-board-list .chat-queue-dep')).toHaveCount(1);
@@ -263,23 +262,32 @@ test.describe('task board scheduling (D18 serial chain)', () => {
expect(app.modelRequests.length).toBeGreaterThanOrEqual(before + 2);
});
- test('runs a substantive preamble through Commander before the mentioned Agent (D22)', async ({
+ test('plans prose before a mention: Commander takes its part and the mentioned Agent waits for it (D29)', async ({
modelOrkas, boardPage,
}) => {
const app = modelOrkas;
const page = boardPage;
const before = app.modelRequests.length;
+ const plannerCalls = app.dispatchPlannerRequests.length;
app.setModelMode('controlled-slow');
+ app.setDispatchPlanReplies([JSON.stringify({
+ tasks: [
+ { key: 't1', assignee: 'commander', part: '写一个大纲', after: [] },
+ { key: 't2', assignee: 'a1', part: '基于大纲写正文', after: ['t1'] },
+ ],
+ references: [],
+ question: null,
+ })]);
const input = page.locator('#chat-input');
await input.fill('写一个大纲 @ContentWriter 基于大纲写正文');
await input.dispatchEvent('input');
- await expect(page.locator('#chat-recipient-name')).toHaveText('Commander, ContentWriter');
- await expect(page.locator('#chat-seq-toggle')).toBeVisible();
+ await expect(page.locator('#chat-recipient-name')).toHaveText('ContentWriter');
await page.locator('#chat-send-btn').click();
+ await expect.poll(() => app.dispatchPlannerRequests.length, { timeout: 15_000 }).toBe(plannerCalls + 1);
await expect.poll(() => app.modelRequests.length, { timeout: 15_000 }).toBe(before + 1);
- // Commander owns the preamble; the addressed Agent waits for its result.
+ // Commander runs its planned part; the addressed Agent waits for its result.
const board = page.locator('#chat-task-board');
const rows = page.locator('#chat-task-board-list .chat-queue-item');
await expect(board).toBeVisible();
@@ -301,6 +309,35 @@ test.describe('task board scheduling (D18 serial chain)', () => {
await expect(board).toBeHidden();
});
+ test('shows a send as running while it is planned, and Stop leaves no task (D29)', async ({
+ modelOrkas, boardPage,
+ }, testInfo) => {
+ const app = modelOrkas;
+ const page = boardPage;
+ const before = app.modelRequests.length;
+ const plannerCalls = app.dispatchPlannerRequests.length;
+ app.holdDispatchPlan();
+ await sendMultiMention(page, '@ContentWriter 写初稿,然后 @UIDesigner 做成幻灯片 STOP_WHILE_PLANNING');
+ await expect.poll(() => app.dispatchPlanParked, { timeout: 15_000 }).toBe(true);
+
+ // Planning takes seconds: the message is already in history and the send
+ // is visibly running, so the user can see it and stop it.
+ await expect(page.locator('#chat-history .chat-message.user').last()).toContainText('STOP_WHILE_PLANNING');
+ const sendBtn = page.locator('#chat-send-btn');
+ await expect(sendBtn).toHaveClass(/\bstreaming\b/);
+ await page.screenshot({ path: testInfo.outputPath('planning-in-progress.png') });
+ await sendBtn.click();
+ await expect(sendBtn).not.toHaveClass(/\bstreaming\b/, { timeout: 15_000 });
+ app.releaseDispatchPlan();
+
+ const cid = await page.evaluate<string>('currentCid');
+ const { tasks } = await app.invoke<{ tasks: Array<{ instruction: string }> }>('groupChat.tasks.list', { cid });
+ expect(tasks.filter((task) => task.instruction.includes('STOP_WHILE_PLANNING'))).toEqual([]);
+ expect(app.dispatchPlannerRequests.length).toBe(plannerCalls + 1);
+ expect(app.modelRequests.length).toBe(before);
+ await expect(page.locator('#chat-task-board')).toBeHidden();
+ });
+
test('stopping the running predecessor blocks the successor visibly; run-anyway releases it visibly', async ({
modelOrkas, boardPage,
}) => {
diff --git a/test/e2e/task_cleanup_e2e_history.spec.ts b/test/e2e/task_cleanup_e2e_history.spec.ts
new file mode 100644
index 00000000..44e837ac
--- /dev/null
+++ b/test/e2e/task_cleanup_e2e_history.spec.ts
@@ -0,0 +1,150 @@
+import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
+import path from 'node:path';
+import { test, expect } from './fixtures/orkas';
+
+test.describe('inline historical task cleanup', () => {
+ for (const inProject of [false, true]) test(`previews, cancels, excludes, cleans and restores ${inProject ? 'project' : 'personal'} history using real IPC and storage`, async ({ orkas }, testInfo) => {
+ const projectId = inProject ? (await orkas.invoke<any>('projects.create', { name: 'Cleanup project' })).project.project_id : '';
+ const dataRoot = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', ...(projectId ? ['projects', projectId] : []));
+ const root = path.join(dataRoot, 'chats');
+ const cids: string[] = [];
+ for (const title of ['Old completed task', 'Keep this completed task', 'Old failed task', 'Old pinned task', 'Unread completed task', 'Draft task', 'Attachment-only draft']) {
+ const { conversation } = await orkas.invoke<any>('conversations.create', { title, projectId });
+ cids.push(conversation.conversation_id);
+ }
+ const old = '2020-01-01T00:00:00Z';
+ const indexFile = path.join(root, '_index.json');
+ const index = JSON.parse(readFileSync(indexFile, 'utf8'));
+ for (const [i, cid] of cids.entries()) {
+ const row = index.find((r: any) => r.conversation_id === cid);
+ row.created_at = old; row.updated_at = old;
+ if (i === 3) row.pinned_at = old;
+ const dir = path.join(root, cid); mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(row));
+ writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ version: 1, status: 'idle', in_flight: [], last_active_at: old }));
+ writeFileSync(path.join(dir, 'tasks.json'), JSON.stringify([{ task_id: `t_${cid}`, cid, assignee: 'commander', instruction: 'Fixture task', created_by: 'user', source_msg_id: 'source', status: i === 2 ? 'failed' : 'done', created_at: old, ended_at: old }]));
+ writeFileSync(path.join(root, `${cid}.jsonl`), JSON.stringify({ id: 'source', from: 'user', content: 'Preserved history', ts: old }) + '\n');
+ }
+ const projectBefore = projectId ? readFileSync(path.join(dataRoot, 'project.json'), 'utf8') : '';
+ const attachment = (cid: string) => path.join(dataRoot, 'chat_attachments', cid, 'notes.txt');
+ for (const cid of [cids[0], cids[6]]) {
+ mkdirSync(path.dirname(attachment(cid)), { recursive: true });
+ writeFileSync(attachment(cid), 'Attachment contents');
+ }
+ writeFileSync(path.join(root, `${cids[0]}.jsonl`), JSON.stringify({ id: 'source', from: 'user', content: 'Preserved history', attachments: ['notes.txt'], ts: old }) + '\n');
+ writeFileSync(indexFile, JSON.stringify(index));
+ const page = await orkas.relaunch();
+ await page.evaluate(([unread, draft, pid]) => {
+ localStorage.setItem('task_unread_v1_account-e2e', JSON.stringify({ unread: [{ cid: unread, projectId: pid || null, finishedAt: Date.now(), status: 'completed' }], read: [] }));
+ localStorage.setItem(`draft_${draft}`, JSON.stringify({ text: 'Keep this unsent draft' }));
+ }, [cids[4], cids[5], projectId]);
+ await page.reload();
+ await page.locator('#settings-btn').click();
+ await page.locator('[data-settings-tab="data"]').click();
+ const section = page.locator('#settings-task-cleanup');
+ await expect(section).toContainText('Selected tasks: 2');
+ await expect(page.locator('#settings-section-local h2')).toHaveText('Data directory');
+ await expect(page.locator('#settings-section-local .settings-row-title')).toHaveCount(0);
+ await section.screenshot({ path: testInfo.outputPath('cleanup-preview.png') });
+ await section.locator('[data-cleanup-action="view"]').click();
+ await expect(section.locator('[data-cleanup-cid]')).toHaveCount(2);
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await expect(section.locator('[data-cleanup-action="confirm"]')).toBeVisible();
+ await section.locator('[data-cleanup-action="cancel"]').click();
+ expect(existsSync(path.join(root, `${cids[0]}.jsonl`))).toBe(true);
+ await section.locator(`[data-cleanup-cid="${cids[1]}"]`).uncheck();
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await page.setViewportSize({ width: 1000, height: 900 });
+ await section.screenshot({ path: testInfo.outputPath('cleanup-en.png') });
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await page.setViewportSize({ width: 620, height: 780 });
+ await expect(section.locator('[data-cleanup-action="confirm"]')).toHaveText('移入回收站(1)');
+ await expect(section.getByRole('combobox')).toContainText('90 天以前');
+ const geometry = await section.evaluate(el => ({ width: el.clientWidth, scroll: el.scrollWidth }));
+ expect(geometry.scroll).toBeLessThanOrEqual(geometry.width);
+ await section.screenshot({ path: testInfo.outputPath('cleanup-zh-narrow.png') });
+ // Hold the real deletion at IPC so the in-flight UI can be inspected
+ // deterministically, then release it to exercise storage and restoration.
+ await orkas.electronApp!.evaluate(({ ipcMain }) => {
+ const original = (ipcMain as any)._invokeHandlers.get('orkas.invoke');
+ ipcMain.removeHandler('orkas.invoke');
+ ipcMain.handle('orkas.invoke', async (event, request) => {
+ if (request.channel === 'conversations.cleanup.remove') {
+ ipcMain.removeHandler('orkas.invoke');
+ ipcMain.handle('orkas.invoke', original);
+ await new Promise<void>(resolve => ipcMain.once('cleanup-test-resume', () => resolve()));
+ }
+ return original(event, request);
+ });
+ });
+ await section.locator('[data-cleanup-action="confirm"]').click();
+ try {
+ await expect(section.getByRole('status')).toHaveCount(1);
+ await expect(section.getByRole('status')).toContainText('正在清理 0 / 1');
+ await expect(section.locator('[data-cleanup-action="stop"]')).toBeEnabled();
+ await section.screenshot({ path: testInfo.outputPath('cleanup-progress-zh.png') });
+ } finally {
+ await orkas.electronApp!.evaluate(({ ipcMain }) => { ipcMain.emit('cleanup-test-resume'); });
+ }
+ await expect(section).toContainText('已移入回收站 1 项');
+ expect(existsSync(path.join(root, `${cids[0]}.jsonl`))).toBe(false);
+ expect(existsSync(attachment(cids[0]))).toBe(false);
+ expect(readFileSync(attachment(cids[6]), 'utf8')).toBe('Attachment contents');
+ for (const cid of cids.slice(1)) expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(true);
+ if (projectId) expect(readFileSync(path.join(dataRoot, 'project.json'), 'utf8')).toBe(projectBefore);
+ const { batches } = await orkas.invoke<any>('recycle.list');
+ const prefix = projectId ? `cloud/projects/${projectId}` : 'cloud';
+ const batch = batches.find((b: any) => b.items.some((item: any) => item.path === `${prefix}/chats/${cids[0]}.jsonl`));
+ expect(batch).toBeTruthy();
+ const recycle = page.locator('#settings-recycle-group');
+ // The public build has one local list, including retained historical batches.
+ await expect(recycle.locator('[data-recycle-source="local"]')).toBeVisible();
+ await expect(recycle.locator('[data-recycle-tab]')).toHaveCount(0);
+ await recycle.locator(`[data-recycle-restore="${batch.id}"]`).click();
+ await page.evaluate(() => {
+ const state = { samples: [] as unknown[], observer: null as MutationObserver | null };
+ state.observer = new MutationObserver(() => {
+ const toasts = Array.from(document.querySelectorAll('.ui-toast')).map((el) => ({
+ text: el.textContent?.trim(), classes: el.className,
+ visible: el.getBoundingClientRect().height > 0 && el.getBoundingClientRect().width > 0
+ && getComputedStyle(el).visibility === 'visible',
+ }));
+ if (state.samples.length < 30 && toasts.length) state.samples.push({ at: performance.now(), toasts });
+ });
+ state.observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
+ (window as any).__cleanupRestoreToasts = state;
+ });
+ try {
+ await page.getByRole('dialog').getByRole('button', { name: '恢复', exact: true }).click();
+ // Observe the real transient UI from before the action. A later polling
+ // snapshot can miss a correctly displayed toast after it naturally closes.
+ await expect.poll(() => page.evaluate(() => (window as any).__cleanupRestoreToasts.samples.some(
+ (sample: any) => sample.toasts.some((toast: any) => toast.visible && /^已恢复 \d+ 个文件$/.test(toast.text)),
+ ))).toBe(true);
+ } finally {
+ const diagnostics = await page.evaluate(() => {
+ const state = (window as any).__cleanupRestoreToasts;
+ state.observer.disconnect();
+ return state.samples;
+ }).catch(() => ({ unavailable: true }));
+ await testInfo.attach('restore-toast-observations.json', {
+ body: JSON.stringify(diagnostics), contentType: 'application/json',
+ });
+ }
+ // History is restored before attachments and index reactivation. Wait for
+ // the whole restore operation rather than treating its first file as done.
+ await expect.poll(() => {
+ if (!existsSync(attachment(cids[0]))) return false;
+ const row = JSON.parse(readFileSync(indexFile, 'utf8')).find((item: any) => item.conversation_id === cids[0]);
+ return !!row && !row.deleted_at;
+ }).toBe(true);
+ await expect.poll(() => existsSync(path.join(root, `${cids[0]}.jsonl`))).toBe(true);
+ expect(readFileSync(path.join(root, `${cids[0]}.jsonl`), 'utf8')).toContain('Preserved history');
+ expect(readFileSync(attachment(cids[0]), 'utf8')).toBe('Attachment contents');
+ if (projectId) {
+ const restored = JSON.parse(readFileSync(indexFile, 'utf8')).find((row: any) => row.conversation_id === cids[0]);
+ expect(restored.project_id).toBe(projectId); expect(restored.deleted_at).toBeFalsy();
+ expect(readFileSync(path.join(dataRoot, 'project.json'), 'utf8')).toBe(projectBefore);
+ }
+ });
+});
diff --git a/test/e2e/todos_e2e_attachment_input.spec.ts b/test/e2e/todos_e2e_attachment_input.spec.ts
index e1fcf5eb..f22fc9d4 100644
--- a/test/e2e/todos_e2e_attachment_input.spec.ts
+++ b/test/e2e/todos_e2e_attachment_input.spec.ts
@@ -1,13 +1,6 @@
import { existsSync, readFileSync } from 'node:fs';
-import { expect, OrkasTestApp, test as base } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
-// Attachment input exercises local storage rather than GPU composition.
-const test = base.extend({
- orkas: async ({}, use, testInfo) => {
- const app = new OrkasTestApp(testInfo, { softwareRendering: true });
- try { await app.launch(); await use(app); } finally { await app.dispose(); }
- },
-});
for (const scope of ['global', 'project'] as const) {
test(`adds pasted and dropped files to a ${scope} todo and preserves their bytes on Save`, async ({ orkas }, info) => {
@@ -17,12 +10,10 @@ for (const scope of ['global', 'project'] as const) {
const projectId = project?.project.project_id || '';
if (projectId) {
await page.evaluate(async (pid) => { await (window as any).setView('project', pid); }, projectId);
- const todoTab = page.locator('[data-project-tab="todo"]');
- await expect(todoTab).toHaveAttribute('data-bound', '1');
- await todoTab.click();
+ await page.locator('[data-project-tab="todo"]').click();
await page.locator('#project-todo-add-btn').click();
} else {
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
await page.locator('#todos-add-btn').click();
}
const input = page.locator('#project-todo-input');
@@ -75,7 +66,7 @@ for (const scope of ['global', 'project'] as const) {
test('keeps ordinary text paste native and discards pasted draft attachments on Cancel', async ({ orkas }) => {
const page = orkas.page!;
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
await page.locator('#todos-add-btn').click();
const input = page.locator('#project-todo-input');
const textHandled = await input.evaluate((element) => {
diff --git a/test/e2e/todos_e2e_attachment_preview.spec.ts b/test/e2e/todos_e2e_attachment_preview.spec.ts
index 7a8a7ff3..f2f65993 100644
--- a/test/e2e/todos_e2e_attachment_preview.spec.ts
+++ b/test/e2e/todos_e2e_attachment_preview.spec.ts
@@ -1,10 +1,11 @@
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
for (const scope of ['global', 'project'] as const) {
test(`previews ${scope} todo attachments from the card and editor without editing or removing them`, async ({ orkas }, info) => {
const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('en'));
const project = scope === 'project' ? await orkas.invoke<any>('projects.create', { name: 'Preview project' }) : null;
const projectId = project?.project.project_id || '';
const created = await orkas.invoke<any>('projects.tasks.create', { projectId, content: 'Read the attached document' });
@@ -18,7 +19,7 @@ for (const scope of ['global', 'project'] as const) {
await (window as any).setView('project', pid);
}, projectId);
await page.locator('[data-project-tab="todo"]').click();
- } else await page.locator('#todos-btn').click();
+ } else await openSidebarEntry(page, '#todos-btn');
const card = page.locator(`.project-todo-item[data-tid="${taskId}"]:visible`);
const preview = await orkas.openPreview(() => card.locator('[data-action="todo-attachments"]').click());
await expect(preview.locator('.chat-file-viewer-body')).toContainText('Original attachment body');
@@ -37,7 +38,9 @@ for (const scope of ['global', 'project'] as const) {
await expect(chosen.locator('.chat-file-viewer-body')).toContainText('Second attachment body');
await chosen.close();
- await card.locator('[data-action="todo-edit"]').click();
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: 'Edit' }).click();
const chip = page.locator('#project-todo-attachments .chat-attach-chip[data-name="brief.txt"]');
const editorPreview = await orkas.openPreview(() => scope === 'project' ? chip.press('Enter') : chip.click());
await expect(editorPreview.locator('.chat-file-viewer-body')).toContainText('Original attachment body');
diff --git a/test/e2e/todos_e2e_board.spec.ts b/test/e2e/todos_e2e_board.spec.ts
index 33b4ebbf..bb545364 100644
--- a/test/e2e/todos_e2e_board.spec.ts
+++ b/test/e2e/todos_e2e_board.spec.ts
@@ -1,4 +1,5 @@
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+import path from 'node:path';
for (const scope of ['global', 'project'] as const) {
test(`gives long ${scope} todo content room while keeping editor actions reachable`, async ({ orkas }, info) => {
@@ -18,7 +19,9 @@ for (const scope of ['global', 'project'] as const) {
await page.locator('[data-project-tab="todo"]').click();
} else await page.locator('#todos-btn').click();
const card = page.locator(`.project-todo-item[data-tid="${taskId}"]:visible`);
- await card.locator('[data-action="todo-edit"]').click();
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item').filter({ hasText: /^Edit$/ }).click();
const field = page.locator('#project-todo-input');
await expect(field).toHaveValue(content);
await expect(page.locator('#project-todo-attachments')).toContainText('brief.txt');
@@ -58,6 +61,400 @@ for (const scope of ['global', 'project'] as const) {
// The assignment journey exercises both account-scoped agents and execution.
+for (const language of ['en', 'zh']) {
+test(`creates todos in the selected project and defaults status grouping to global (${language})`, async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(lang => (window as any).setLang(lang), language);
+ const { project: alpha } = await orkas.invoke<any>('projects.create', { name: 'Alpha' });
+ const { project: beta } = await orkas.invoke<any>('projects.create', { name: 'Beta' });
+ for (const projectId of ['', alpha.project_id, beta.project_id]) {
+ await orkas.invoke('projects.tasks.create', { projectId, content: `Existing ${projectId || 'global'}` });
+ }
+ await openSidebarEntry(page, '#todos-btn');
+ const picker = page.locator('#project-todo-project');
+ const input = page.locator('#project-todo-input');
+ const modal = page.locator('#todo-editor-modal');
+ const selectProject = async (pid: string) => {
+ await picker.locator('.ai-select-trigger').click();
+ await page.locator(`#project-todo-project-listbox .ai-select-item[data-value="${pid}"]`).click();
+ };
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${alpha.project_id}"]`).click();
+ await page.locator('#todos-add-btn').click();
+ await expect(picker).toHaveAttribute('data-value', alpha.project_id);
+ await expect(picker.locator('.ai-select-trigger')).toBeEnabled();
+ await selectProject(beta.project_id);
+ await input.fill('Cancelled draft');
+ await page.evaluate(async () => (window as any)._refreshGlobalTodos());
+ await expect(picker).toHaveAttribute('data-value', beta.project_id);
+ await expect(input).toHaveValue('Cancelled draft');
+ await page.locator('#project-todo-cancel').click();
+
+ await page.locator('#todos-add-btn').click();
+ await expect(picker).toHaveAttribute('data-value', alpha.project_id);
+ await expect(input).toHaveValue('');
+ await input.fill('Default Alpha task');
+ await page.setViewportSize({ width: language === 'en' ? 1440 : 1024, height: 900 });
+ await modal.screenshot({ path: testInfo.outputPath(`todo-default-project-${language}.png`) });
+ await page.locator('#project-todo-save').click();
+ await expect(modal).not.toHaveClass(/\bopen\b/);
+ const alphaTasks = await orkas.invoke<any>('projects.tasks.list', { projectId: alpha.project_id });
+ expect(alphaTasks.tasks.filter((task: any) => task.content === 'Default Alpha task')).toHaveLength(1);
+
+ await page.locator('[data-todo-group="status"]').click();
+ await page.locator('#todos-add-btn').click();
+ await expect(picker).toHaveAttribute('data-value', '');
+ await input.fill('Default global task');
+ await page.locator('#project-todo-save').click();
+ await expect(modal).not.toHaveClass(/\bopen\b/);
+ const globalTasks = await orkas.invoke<any>('projects.tasks.list', {});
+ expect(globalTasks.tasks.filter((task: any) => task.content === 'Default global task')).toHaveLength(1);
+ expect(globalTasks.tasks.some((task: any) => task.content === 'Default Alpha task')).toBe(false);
+
+ await page.locator('[data-todo-group="project"]').click();
+ await page.locator('#todos-add-btn').click();
+ await expect(picker).toHaveAttribute('data-value', alpha.project_id);
+ await selectProject(beta.project_id);
+ await input.fill('Explicit Beta task');
+ await page.locator('#project-todo-save').click();
+ await expect(modal).not.toHaveClass(/\bopen\b/);
+ const betaTasks = await orkas.invoke<any>('projects.tasks.list', { projectId: beta.project_id });
+ expect(betaTasks.tasks.filter((task: any) => task.content === 'Explicit Beta task')).toHaveLength(1);
+ await page.locator('#todos-content .todo-scope-chip[data-pid=""]').click();
+ await page.locator('#todos-add-btn').click();
+ await expect(picker).toHaveAttribute('data-value', '');
+ await page.locator('#project-todo-cancel').click();
+});
+}
+
+test('keeps todo card appearance and unfinished processing consistent across both entry points', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('zh'));
+ const project = await orkas.invoke<any>('projects.create', { name: 'Consistent cards' });
+ const pid = project.project.project_id;
+ const tasks = [];
+ for (const status of ['todo', 'progress', 'review', 'done']) {
+ const created = await orkas.invoke<any>('projects.tasks.create', {
+ projectId: pid, content: `Check ${status} work\nKeep its full brief`, status,
+ });
+ tasks.push(created.task);
+ }
+ const before = await orkas.invoke<any>('projects.tasks.list', { projectId: pid });
+ const appearance = (card: ReturnType<typeof page.locator>) => card.evaluate(element => {
+ const properties = ['display', 'gap', 'padding', 'borderRadius', 'backgroundColor', 'fontSize',
+ 'fontWeight', 'lineHeight', 'opacity', 'order'];
+ return ['.project-todo-title', '.todo-card-meta', '.project-todo-assign',
+ '.project-todo-status-select'].map(selector => {
+ const control = element.querySelector(selector)!;
+ const style = getComputedStyle(control);
+ return { text: control.textContent, style: Object.fromEntries(properties.map(key => [key, (style as any)[key]])) };
+ });
+ });
+ for (const width of [1440, 1024]) {
+ await page.setViewportSize({ width, height: 900 });
+ const appearances = [];
+ for (const entry of ['account', 'project']) {
+ if (entry === 'account') {
+ await openSidebarEntry(page, '#todos-btn');
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${pid}"]`).click();
+ } else {
+ await page.evaluate(async id => (window as any).setView('project', id), pid);
+ await page.locator('[data-project-tab="todo"]').click();
+ }
+ const host = page.locator(entry === 'account' ? '#todos-content' : '#project-todo-list');
+ await host.locator('.todo-column.is-done .todo-collapse').click();
+ for (const [index, task] of tasks.entries()) {
+ const card = host.locator(`.project-todo-item[data-tid="${task.id}"]`);
+ const statusControl = card.locator('[data-action="todo-status"]');
+ await page.mouse.move(0, 0);
+ await page.evaluate(() => (document.activeElement as HTMLElement)?.blur());
+ await expect(card.locator('.todo-card-meta')).toHaveCount(1);
+ // Both entry points reveal the status control only with the card's hover/focus controls.
+ await expect(statusControl).toHaveCSS('opacity', '0');
+ await expect(statusControl).toHaveCSS('pointer-events', 'none');
+ const layout = () => card.evaluate(element => {
+ const bounds = element.getBoundingClientRect();
+ const status = element.querySelector('[data-action="todo-status"]')!.getBoundingClientRect();
+ return { width: bounds.width, height: bounds.height, statusX: status.x - bounds.x, statusY: status.y - bounds.y };
+ });
+ const restingLayout = await layout();
+ await card.hover();
+ await expect(statusControl).toHaveCSS('opacity', '1');
+ await expect(statusControl).toHaveCSS('pointer-events', 'auto');
+ // Narrow boards may scroll horizontally to reveal a hovered card.
+ const hoveredLayout = await layout();
+ // Scrolling can change floating-point subtraction without moving a control.
+ for (const key of ['width', 'height', 'statusX', 'statusY'] as const) {
+ expect(hoveredLayout[key]).toBeCloseTo(restingLayout[key], 2);
+ }
+ expect(await card.evaluate(element => {
+ const footer = element.querySelector('.todo-card-meta')!.getBoundingClientRect();
+ const status = element.querySelector('[data-action="todo-status"]')!.getBoundingClientRect();
+ return Math.abs(footer.right - status.right);
+ })).toBeLessThanOrEqual(1);
+ if (entry === 'account') appearances[index] = await appearance(card);
+ else expect(await appearance(card)).toEqual(appearances[index]);
+ await card.locator('[data-action="todo-menu"]').click();
+ await expect(page.locator('.context-menu-item', { hasText: '立即处理' })).toHaveCount(task.status === 'done' ? 0 : 1);
+ await page.keyboard.press('Escape');
+ }
+ await host.screenshot({ path: testInfo.outputPath(`todo-cards-${entry}-${width}.png`) });
+ const firstCard = host.locator(`.project-todo-item[data-tid="${tasks[0].id}"]`);
+ const statusControl = firstCard.locator('[data-action="todo-status"]');
+ for (const locale of ['zh', 'en']) {
+ await page.evaluate(lang => (window as any).setLang(lang), locale);
+ await page.mouse.move(0, 0);
+ await page.evaluate(() => (document.activeElement as HTMLElement)?.blur());
+ await expect(statusControl).toHaveCSS('opacity', '0');
+ await expect.poll(() => host.locator('[data-action="todo-status"]').evaluateAll(elements =>
+ elements.map(element => getComputedStyle(element).opacity)))
+ .toEqual(tasks.map(() => '0'));
+ await host.screenshot({ path: testInfo.outputPath(`todo-resting-${entry}-${width}-${locale}.png`) });
+ await firstCard.locator('.project-todo-title').focus();
+ // Tab through the card's real controls to the status menu.
+ for (let step = 0; step < 5 && !(await statusControl.evaluate(el => el === document.activeElement)); step++) {
+ await page.keyboard.press('Tab');
+ }
+ await expect(statusControl).toBeFocused();
+ await expect(statusControl).toHaveCSS('opacity', '1');
+ await page.keyboard.press('Enter');
+ await expect(page.locator('.context-menu')).toBeVisible();
+ await page.keyboard.press('Escape');
+ await host.screenshot({ path: testInfo.outputPath(`todo-focused-${entry}-${width}-${locale}.png`) });
+ }
+ await page.evaluate(() => (window as any).setLang('zh'));
+ // Restore the collapse preference before the next visit.
+ await host.locator('.todo-column.is-done .todo-collapse').click();
+ }
+ }
+ expect(await orkas.invoke('projects.tasks.list', { projectId: pid })).toEqual(before);
+});
+
+test('binds auto-advance locally and lets another device disable then re-enable it', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('zh'));
+ // Completed backlog: this UI/IPC journey must not enqueue model work.
+ const created = await orkas.invoke<any>('projects.create', { name: 'Auto-advance device' });
+ const pid = created.project.project_id;
+ await orkas.invoke('projects.tasks.create', { projectId: pid, content: 'Completed project work', status: 'done' });
+ await orkas.invoke('projects.tasks.create', { content: 'Completed global work', status: 'done' });
+ const writeCloudConfig = (config: Record<string, unknown>) => orkas.electronApp!.evaluate(async (_electron, input) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ const fs = require('node:fs/promises'), path = require('node:path');
+ const uid = require(path.join(input.main, 'features/users.ts')).getActiveUserId();
+ const file = require(path.join(input.main, 'paths.ts')).projectDriverFile(uid, input.pid);
+ await fs.writeFile(file, JSON.stringify(input.config));
+ }, { main: path.resolve(__dirname, '../../src/main'), pid, config });
+ // Upgrading an enabled legacy project must display off until the user enables it.
+ await writeCloudConfig({ enabled: true, max_advances_per_day: 20 });
+ expect((await orkas.invoke<any>('projects.driver.get', { projectId: pid })).config.enabled).toBe(false);
+ await page.evaluate(async id => (window as any).setView('project', id), pid);
+ await page.locator('[data-project-tab="todo"]').click();
+ const toggle = page.locator('#project-driver-toggle');
+ await expect(toggle).toBeEnabled();
+ await expect(toggle).toHaveAttribute('aria-pressed', 'false');
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-pressed', 'true');
+ const local = await orkas.invoke<any>('projects.driver.get', { projectId: pid });
+ await expect(toggle).toHaveText('自动推进 · 本机');
+ expect(local.config).toMatchObject({ enabled: true, device_id: local.device.id, device_name: local.device.name });
+
+ await openSidebarEntry(page, '#todos-btn');
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${pid}"]`).click();
+ const scopeToggle = page.locator(`#todos-content .todo-scope-driver-toggle[data-pid="${pid}"]`);
+ await expect(scopeToggle).toHaveText('自动推进 · 本机');
+ await page.locator('#todos-content .todo-scope-chip[data-pid=""]').click();
+ const globalToggle = page.locator('#todos-content .todo-scope-driver-toggle[data-pid=""]');
+ await globalToggle.click();
+ await expect(globalToggle).toHaveText('自动推进 · 本机');
+ await page.locator('[data-todo-group="status"]').click();
+ await expect(scopeToggle).toHaveText('Auto-advance device · 本机');
+ await expect(globalToggle).toHaveText('全局 · 本机');
+ await page.evaluate(() => (window as any).setLang('en'));
+ await expect(scopeToggle).toContainText(' · This device');
+ await expect(globalToggle).toContainText(' · This device');
+ await page.evaluate(() => (window as any).setLang('zh'));
+
+ // A sync pull replaces the cloud config with another installation's opt-in.
+ await writeCloudConfig({ enabled: true, max_advances_per_day: 20,
+ device_id: 'another-installation', device_name: 'Office Mac' });
+ await page.evaluate(async id => (window as any)._refreshGlobalTodos(id), pid);
+ await expect(scopeToggle).toHaveText('Auto-advance device · Office Mac');
+ await page.locator('[data-todo-group="project"]').click();
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${pid}"]`).click();
+ await expect(scopeToggle).toHaveText('自动推进 · Office Mac');
+ await page.evaluate(async id => (window as any).setView('project', id), pid);
+ await page.locator('[data-project-tab="todo"]').click();
+ await expect(toggle).toHaveText('自动推进 · Office Mac');
+ await expect(toggle).toHaveAttribute('aria-pressed', 'true');
+ await toggle.screenshot({ path: testInfo.outputPath('auto-advance-remote-device.png') });
+ await page.evaluate(() => (window as any).setLang('en'));
+ await expect(toggle).toContainText(' · Office Mac');
+ await page.evaluate(() => (window as any).setLang('zh'));
+ await expect(toggle).toBeEnabled();
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-pressed', 'false');
+ await expect(toggle).toHaveText('自动推进');
+ expect((await orkas.invoke<any>('projects.driver.get', { projectId: pid })).config.enabled).toBe(false);
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-pressed', 'true');
+ await expect(toggle).toHaveText('自动推进 · 本机');
+ expect((await orkas.invoke<any>('projects.driver.get', { projectId: pid })).config.device_id).toBe(local.device.id);
+ await toggle.screenshot({ path: testInfo.outputPath('auto-advance-local-device.png') });
+});
+
+test('hides human responsibility and keeps optional Agent assignment on both boards and in the editor', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('zh'));
+ const project = await orkas.invoke<any>('projects.create', { name: 'Private responsibility' });
+ const pid = project.project.project_id;
+ const created = await orkas.invoke<any>('projects.tasks.create', { projectId: pid, content: 'Review private work' });
+ const global = await orkas.invoke<any>('projects.tasks.create', { content: 'Review global work' });
+ await openSidebarEntry(page, '#todos-btn');
+ for (const [scope, tid] of [['', global.task.id], [pid, created.task.id]]) {
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${scope}"]`).click();
+ const card = page.locator(`#todos-content .project-todo-item[data-tid="${tid}"]`);
+ await expect(card.getByText('E2E Member', { exact: true })).toHaveCount(0);
+ await expect(card.locator('.project-todo-assign')).toHaveText('未指定');
+ await expect(card.locator('.project-todo-assign')).toBeVisible();
+ }
+ await page.evaluate(async id => (window as any).setView('project', id), pid);
+ await page.locator('[data-project-tab="todo"]').click();
+ const card = page.locator(`#project-todo-list .project-todo-item[data-tid="${created.task.id}"]`);
+ await expect(card.getByText('E2E Member', { exact: true })).toHaveCount(0);
+ await expect(card.locator('.project-todo-assign')).toHaveText('未指定');
+ await card.screenshot({ path: testInfo.outputPath('private-todo-responsibility.png') });
+ for (const editing of [false, true]) {
+ if (editing) {
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: '编辑' }).click();
+ } else {
+ await page.locator('#project-todo-add-btn').click();
+ }
+ await expect(page.locator('#todo-editor-modal').getByText('E2E Member', { exact: true })).toHaveCount(0);
+ await expect(page.locator('#project-todo-agent .ai-select-trigger')).toContainText('未指定');
+ await expect(page.locator('#project-todo-agent .ai-select-trigger')).toBeEnabled();
+ await page.locator('#todo-editor-modal').screenshot({ path: testInfo.outputPath(`private-todo-${editing ? 'edit' : 'create'}.png`) });
+ if (editing) {
+ await page.setViewportSize({ width: 1024, height: 720 });
+ await page.evaluate(() => (window as any).setLang('en'));
+ await expect(page.locator('#todo-editor-modal').getByText('E2E Member', { exact: true })).toHaveCount(0);
+ await page.locator('#todo-editor-modal').screenshot({ path: testInfo.outputPath('private-todo-edit-en-narrow.png') });
+ await page.locator('#project-todo-input').fill('Reviewed private work');
+ await page.locator('#project-todo-save').click();
+ } else {
+ await page.locator('#project-todo-cancel').click();
+ }
+ }
+ const saved = await orkas.invoke<any>('projects.tasks.list', { projectId: pid });
+ expect(saved.tasks).toHaveLength(1);
+ expect(saved.tasks[0]).toMatchObject({ id: created.task.id, content: 'Reviewed private work' });
+ for (const task of [created.task, global.task, saved.tasks[0]]) {
+ expect(task).not.toHaveProperty('assignee_uid');
+ expect(task).not.toHaveProperty('assignee_name');
+ }
+ expect(saved.tasks[0].owner_agent_id).toBeUndefined();
+});
+
+test('reads full todo card text with repeatable mouse and keyboard disclosure on both boards', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(() => (window as any).setLang('zh'));
+ const project = await orkas.invoke<any>('projects.create', { name: '阅读待办' });
+ const pid = project.project.project_id;
+ // An expanded card must exceed the project viewport to exercise the header
+ // and scrolling boundary, rather than only checking text inside the button.
+ const text = '核对完整说明\n第一段:保留换行,说明详细目标。\n第二段:' + '长文本'.repeat(1000) + '\n最后一行:<literal> & 保留原文';
+ const created = await orkas.invoke<any>('projects.tasks.create', { projectId: pid, content: text });
+ const global = await orkas.invoke<any>('projects.tasks.create', { content: text });
+ const before = await orkas.invoke<any>('projects.tasks.list', { projectId: pid });
+ await openSidebarEntry(page, '#todos-btn');
+ for (const [scope, tid] of [['', global.task.id], [pid, created.task.id]]) {
+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${scope}"]`).click();
+ const card = page.locator(`#todos-content .project-todo-item[data-tid="${tid}"]`);
+ const title = card.locator('.project-todo-title');
+ await expect(title).toHaveAttribute('aria-expanded', 'false');
+ const collapsedHeight = await title.evaluate(element => element.clientHeight);
+ await title.click();
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ expect(await title.textContent()).toBe(text);
+ expect(await title.evaluate(element => element.clientHeight >= element.scrollHeight)).toBe(true);
+ expect(await title.evaluate(element => element.clientHeight)).toBeGreaterThan(collapsedHeight);
+ await expect(page.locator('#todo-editor-modal')).not.toHaveClass(/\bopen\b/);
+ // The footer control keeps its original action without closing the content.
+ const status = card.locator('[data-action="todo-status"]');
+ await status.scrollIntoViewIfNeeded();
+ // Let the scroll event dismiss existing popups before the next gesture,
+ // as when a reader scrolls down to the footer and then opens its menu.
+ await status.evaluate(() => new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
+ await status.click();
+ await expect(page.locator('.context-menu-item')).toHaveCount(4);
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ await page.keyboard.press('Escape');
+ await title.press('Space');
+ await expect(title).toHaveAttribute('aria-expanded', 'false');
+ await title.press('Enter');
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ await page.evaluate(async () => (window as any)._refreshGlobalTodos(''));
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ // Clicking the card padding is also a disclosure gesture.
+ await card.click({ position: { x: 3, y: 3 } });
+ await expect(title).toHaveAttribute('aria-expanded', 'false');
+ }
+ await page.evaluate(async (id) => (window as any).setView('project', id), pid);
+ await page.locator('[data-project-tab="todo"]').click();
+ const card = page.locator(`#project-todo-list .project-todo-item[data-tid="${created.task.id}"]`);
+ const title = card.locator('.project-todo-title');
+ const column = page.locator('#project-todo-list .todo-column.is-todo');
+ const header = column.locator('.todo-column-head');
+ const headerHeight = (await header.boundingBox())!.height;
+ await title.click();
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ expect((await header.boundingBox())!.height).toBeGreaterThanOrEqual(headerHeight - 1);
+ const body = card.locator('..');
+ await body.evaluate(element => { element.scrollTop = 0; });
+ const [headerBox, bodyStart, cardStart] = await Promise.all([
+ header.boundingBox(), body.boundingBox(), card.boundingBox(),
+ ]);
+ expect(bodyStart!.y).toBeGreaterThanOrEqual(headerBox!.y + headerBox!.height - 1);
+ expect(cardStart!.y).toBeGreaterThanOrEqual(headerBox!.y + headerBox!.height);
+ expect(await title.evaluate(element => element.clientHeight >= element.scrollHeight)).toBe(true);
+ await page.evaluate(async (id) => (window as any)._loadProjectTodos(id), pid);
+ await expect(title).toHaveAttribute('aria-expanded', 'true');
+ await page.screenshot({ path: testInfo.outputPath('expanded-todo-card.png') });
+ await body.evaluate(element => { element.scrollTop = element.scrollHeight; });
+ const [titleBox, bodyBox] = await Promise.all([title.boundingBox(), body.boundingBox()]);
+ expect(titleBox!.y + titleBox!.height).toBeLessThanOrEqual(bodyBox!.y + bodyBox!.height + 1);
+ expect(titleBox!.y + titleBox!.height).toBeGreaterThan(bodyBox!.y);
+ await page.screenshot({ path: testInfo.outputPath('expanded-todo-card-end.png') });
+ await title.click();
+ await expect(title).toHaveAttribute('aria-expanded', 'false');
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: '编辑' }).click();
+ await expect(page.locator('#project-todo-input')).toHaveValue(text);
+ // Long content gets the room the dialog has: the field grows to the dialog's
+ // height cap and scrolls inside, while the dialog itself does not scroll.
+ const editorRoom = () => page.evaluate(() => {
+ const dialog = document.querySelector('#todo-editor-modal .todo-editor-dialog') as HTMLElement;
+ const field = document.getElementById('project-todo-input') as HTMLTextAreaElement;
+ return {
+ lines: Math.floor(field.clientHeight / parseFloat(getComputedStyle(field).lineHeight)),
+ fieldScrolls: field.scrollHeight > field.clientHeight,
+ dialogScrolls: dialog.scrollHeight > dialog.clientHeight + 1,
+ };
+ });
+ const longRoom = await editorRoom();
+ expect(longRoom.lines).toBeGreaterThanOrEqual(8);
+ expect(longRoom).toMatchObject({ fieldScrolls: true, dialogScrolls: false });
+ await page.locator('#project-todo-cancel').click();
+ // An empty field still offers six lines.
+ await page.locator('#project-todo-add-btn').click();
+ await expect(page.locator('#project-todo-input')).toHaveValue('');
+ expect(await editorRoom()).toEqual({ lines: 6, fieldScrolls: false, dialogScrolls: false });
+ await page.locator('#project-todo-cancel').click();
+ expect(await orkas.invoke('projects.tasks.list', { projectId: pid })).toEqual(before);
+});
test('manages the same backlog from global and project boards without a duplicate project disclosure', async ({ orkas }, testInfo) => {
const page = orkas.page!;
@@ -87,7 +484,7 @@ test('manages the same backlog from global and project boards without a duplicat
owner_agent: agent.name,
owner_agent_id: agent.agent_id,
});
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
const content = page.locator('#todos-content');
const header = page.locator('#panel-todos .project-detail-header');
await expect(header.locator('.todo-page-actions')).toBeVisible();
@@ -104,7 +501,7 @@ test('manages the same backlog from global and project boards without a duplicat
await expect(content.locator('.todo-project-group')).toHaveCount(1);
await expect(content.locator('.todo-project-group')).toHaveAttribute('data-pid', a);
await expect(content.locator('.todo-project-head')).toHaveCount(0);
- await expect(content.locator('.todo-scope-actions .todo-project-add')).toHaveCount(1);
+ await expect(content.locator('.todo-scope-actions .todo-project-add')).toHaveCount(0);
await expect(content.locator('.todo-scope-actions .todo-scope-driver-toggle')).toHaveCount(1);
await expect(content.locator('.todo-column-head .project-todo-menu')).toHaveCount(0);
await expect(content.locator('.project-todo-item [data-action="todo-menu"]')).toHaveCount(4);
@@ -130,11 +527,12 @@ test('manages the same backlog from global and project boards without a duplicat
await expect(alphaGroup.locator('.todo-board')).toBeVisible();
await expect(doneToggle).toHaveAttribute('aria-expanded', 'true');
- // One project-level + replaces the four status-level buttons and creates in
- // the project whose title owns it.
- await alphaGroup.locator('.todo-project-add').click();
+ // The single page-level Create entry lets the user choose the target scope.
+ await page.locator('#todos-add-btn').click();
+ await page.locator('#project-todo-project .ai-select-trigger').click();
+ await page.locator(`#project-todo-project-listbox .ai-select-item[data-value="${a}"]`).click();
await expect(page.locator('#project-todo-project')).toHaveAttribute('data-value', a);
- await expect(page.locator('#project-todo-project .ai-select-trigger')).toBeDisabled();
+ await expect(page.locator('#project-todo-project .ai-select-trigger')).toBeEnabled();
await page.locator('#project-todo-cancel').click();
// Card controls follow reading order: Agent on the left, status on the right.
@@ -203,8 +601,9 @@ test('manages the same backlog from global and project boards without a duplicat
await expect(alphaGroup.getByText('确认视觉规范', { exact: true })).toBeInViewport();
await page.setViewportSize({ width: 1440, height: 900 });
- // The global page defaults to an account-level to-do. Dropped files use the
- // same attachment path as the + button in the composer.
+ // Status grouping defaults to an account-level to-do even after selecting a
+ // project. Dropped files use the same path as the composer's + button.
+ await page.locator('[data-todo-group="status"]').click();
await page.locator('#todos-add-btn').click();
await expect(page.locator('#project-todo-project')).toHaveAttribute('data-value', '');
await expect(page.locator('#project-todo-project .ai-select-label')).toHaveText('全局');
@@ -243,12 +642,13 @@ test('manages the same backlog from global and project boards without a duplicat
attachments: ['global-notes.txt'],
});
expect(globalTask.detail).toBeUndefined();
+ await page.locator('[data-todo-group="project"]').click();
await expect(content.locator('.todo-scope-chip')).toHaveCount(3);
await content.locator('.todo-scope-chip[data-pid=""]').click();
await expect(content.locator('.todo-project-group')).toHaveCount(1);
const globalGroup = content.locator('.todo-project-group[data-pid=""]');
await expect(globalGroup).toContainText('全局跟进发票');
- await expect(globalGroup.locator('.todo-scope-driver-toggle')).toBeVisible();
+ await expect(content.locator('.todo-scope-row .todo-scope-driver-toggle[data-pid=""]')).toBeVisible();
await expect(globalGroup.locator('.todo-column.is-progress .todo-column-empty')).toHaveCSS('text-align', 'center');
await expect(globalGroup.locator('.todo-board')).toBeVisible();
await content.locator(`.todo-scope-chip[data-pid="${a}"]`).click();
@@ -291,25 +691,37 @@ test('manages the same backlog from global and project boards without a duplicat
const activeTitleColor = await task.locator('.project-todo-title')
.evaluate((element) => getComputedStyle(element).color);
expect(completedTitleColor).toBe(activeTitleColor);
- const projectMeta = task.locator('.todo-card-project');
- const agentMeta = task.locator('.project-todo-assign');
- const statusMeta = task.locator('.project-todo-status-select');
- const [projectMetaBox, agentMetaBox, statusMetaBox] = await Promise.all([
- projectMeta.boundingBox(),
- agentMeta.boundingBox(),
- statusMeta.boundingBox(),
- ]);
- expect(projectMetaBox).not.toBeNull();
- expect(agentMetaBox).not.toBeNull();
- expect(statusMetaBox).not.toBeNull();
- expect(Math.abs((projectMetaBox!.y + projectMetaBox!.height / 2) - (agentMetaBox!.y + agentMetaBox!.height / 2))).toBeLessThan(4);
- expect(projectMetaBox!.x).toBeLessThan(agentMetaBox!.x);
- expect(agentMetaBox!.x).toBeLessThan(statusMetaBox!.x);
+ // Flex wrapping retains the public project, optional Agent and status reading order.
+ const metadata = await task.locator('.todo-card-meta').evaluate((element) => {
+ const box = (node: Element) => {
+ const rect = node.getBoundingClientRect();
+ return { x: rect.x, y: rect.y, right: rect.right, bottom: rect.bottom, height: rect.height };
+ };
+ return {
+ bounds: box(element),
+ controls: Array.from(element.querySelectorAll('.todo-card-project, .project-todo-assign, .project-todo-status-select')).map(box),
+ };
+ });
+ expect(metadata.controls).toHaveLength(3);
+ for (const control of metadata.controls) {
+ expect(control.height).toBeGreaterThan(0);
+ expect(control.x).toBeGreaterThanOrEqual(metadata.bounds.x - 1);
+ expect(control.right).toBeLessThanOrEqual(metadata.bounds.right + 1);
+ expect(control.y).toBeGreaterThanOrEqual(metadata.bounds.y - 1);
+ expect(control.bottom).toBeLessThanOrEqual(metadata.bounds.bottom + 1);
+ }
+ expect(metadata.bounds.height).toBeLessThanOrEqual(3 * Math.max(...metadata.controls.map(control => control.height)) + 24);
+ for (let index = 1; index < metadata.controls.length; index++) {
+ const previous = metadata.controls[index - 1], current = metadata.controls[index];
+ if (Math.abs(current.y - previous.y) < 4) expect(current.x).toBeGreaterThanOrEqual(previous.right);
+ else expect(current.y).toBeGreaterThanOrEqual(previous.bottom);
+ }
const globalCard = content.locator(`.project-todo-item[data-tid="${globalTask.id}"]`);
await expect(globalCard).toHaveAttribute('data-todo-scope', 'global');
await expect(globalCard.locator('span.todo-card-project')).toHaveText('全局');
await expect(globalCard.locator('.todo-card-project-icon')).toHaveCount(1);
await expect(globalCard.locator('button.todo-card-project')).toHaveCount(0);
+ await task.hover();
await task.locator('[data-action="todo-status"]').click();
const selectedStatusOption = page.locator('.context-menu-item', { hasText: '待确认' });
const selectedStatusCheck = selectedStatusOption.locator('.context-menu-trailing-icon');
@@ -380,7 +792,16 @@ test('manages the same backlog from global and project boards without a duplicat
expect(boardBox).not.toBeNull();
expect(boardBox!.x).toBeGreaterThanOrEqual(listBox!.x - 1);
expect(boardBox!.x + boardBox!.width).toBeLessThanOrEqual(listBox!.x + listBox!.width + 1);
- expect(await projectBoard.evaluate((board) => getComputedStyle(board).gridTemplateColumns.split(' ').length)).toBe(4);
+ // Four lanes in one row; the collapsed Completed lane narrows to a strip
+ // and the open lanes share the rest.
+ const projectLanes = await projectBoard.evaluate((board) => Array.from(board.children).map((lane) => {
+ const box = lane.getBoundingClientRect();
+ return { status: (lane as HTMLElement).dataset.status, top: Math.round(box.top), width: Math.round(box.width) };
+ }));
+ expect(projectLanes.map((lane) => lane.status)).toEqual(['todo', 'progress', 'review', 'done']);
+ expect(new Set(projectLanes.map((lane) => lane.top)).size).toBe(1);
+ expect(projectLanes[3].width).toBe(40);
+ expect(Math.min(...projectLanes.slice(0, 3).map((lane) => lane.width))).toBeGreaterThanOrEqual(190);
const projectCard = projectList.locator(`.project-todo-item[data-tid="${created.id}"]`);
await expect(projectList.locator('.todo-column.is-progress').getByText('完善价格页', { exact: true })).toBeVisible();
await expect(projectList.getByText('设计项目看板', { exact: true })).toHaveCount(0);
@@ -403,13 +824,13 @@ test('manages the same backlog from global and project boards without a duplicat
listRight: list.getBoundingClientRect().right,
boardRight: board.getBoundingClientRect().right,
lastRight: last.getBoundingClientRect().right,
- columnCount: getComputedStyle(board).gridTemplateColumns.split(' ').length,
+ rows: new Set(Array.from(board.children).map((lane) => Math.round(lane.getBoundingClientRect().top))).size,
boardOverflow: board.scrollWidth - board.clientWidth,
};
});
expect(narrowGeometry.boardRight).toBeLessThanOrEqual(narrowGeometry.listRight + 1);
expect(narrowGeometry.lastRight).toBeLessThanOrEqual(narrowGeometry.boardRight + 1);
- expect(narrowGeometry.columnCount).toBe(4);
+ expect(narrowGeometry.rows).toBe(1);
expect(narrowGeometry.boardOverflow).toBeGreaterThan(1);
await page.setViewportSize({ width: 1440, height: 900 });
// Counts include completed/legacy tasks and reconcile external writes even
@@ -425,15 +846,18 @@ test('manages the same backlog from global and project boards without a duplicat
await expect(todoTabCount).toHaveText('4');
await page.locator('[data-project-tab="todo"]').click();
await page.screenshot({ path: testInfo.outputPath('project-todos.png') });
- await projectList.getByText('完善价格页', { exact: true }).click();
+ const editedCard = projectList.locator('.project-todo-item', { hasText: '完善价格页' });
+ await editedCard.hover();
+ await editedCard.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: '编辑' }).click();
await page.locator('#project-todo-input').fill('完善价格页与导航');
await page.locator('#project-todo-save').click();
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
await expect(content.getByText('完善价格页与导航', { exact: true })).toBeVisible();
// Reopening the app reads persisted tasks and restores default disclosure states.
const reloaded = await orkas.relaunch();
- await reloaded.locator('#todos-btn').click();
+ await openSidebarEntry(reloaded, '#todos-btn');
// A fresh launch focuses the first scope; the rest stay one chip away.
await expect(reloaded.locator('#todos-content').getByText('全局跟进发票', { exact: true })).toBeVisible();
await reloaded.locator(`#todos-content .todo-scope-chip[data-pid="${b}"]`).click();
@@ -465,7 +889,7 @@ test('processes an assigned Codex todo from its card with one execution and no C
const { task } = await orkas.invoke<{ task: { id: string } }>('projects.tasks.create', {
projectId: pid, content, owner_agent_id: agent.agent_id,
});
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
const card = page.locator('#todos-content .project-todo-item', { hasText: content });
await card.hover();
await card.locator('[data-action="todo-menu"]').click();
@@ -511,7 +935,7 @@ test('assigns global and project todos in the editor and keeps cards and saved o
const { project } = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Assignment project' });
const pid = project.project_id;
await orkas.invoke('projects.bindings.add', { projectId: pid, kind: 'agent', id: agent.agent_id });
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
const agentControl = page.locator('#project-todo-agent');
const chooseAgent = async (value: string) => {
await expect(agentControl.locator('.ai-select-trigger')).toBeEnabled();
@@ -536,7 +960,9 @@ test('assigns global and project todos in the editor and keeps cards and saved o
await expect(card.locator('.project-todo-assign')).toContainText(agent.name);
let tasks = await orkas.invoke<{ tasks: any[] }>('projects.tasks.list', { projectId: scope });
expect(tasks.tasks.find((t) => t.content === title)).toMatchObject({ owner_agent_id: agent.agent_id, owner_agent: agent.name });
- await card.locator('[data-action="todo-edit"]').click();
+ await card.hover();
+ await card.locator('[data-action="todo-menu"]').click();
+ await page.locator('.context-menu-item', { hasText: '编辑' }).click();
await expect(agentControl).toHaveAttribute('data-value', agent.agent_id);
await chooseAgent('');
await page.locator('#project-todo-save').click();
@@ -571,7 +997,7 @@ test('assigns global and project todos in the editor and keeps cards and saved o
// column that cannot overflow is the oracle for "kept its own height": a body
// that fits by squashing its cards would scroll too, and would be just as
// unusable.
-test('reaches every to-do in a column taller than the board', async ({ connectorOrkas: orkas }, testInfo) => {
+test('reaches every to-do and keeps reading positions through background refreshes', async ({ connectorOrkas: orkas }, testInfo) => {
const page = orkas.page!;
await page.setViewportSize({ width: 1440, height: 900 });
await page.evaluate(() => (window as any).setLang('zh'));
@@ -581,7 +1007,7 @@ test('reaches every to-do in a column taller than the board', async ({ connector
for (let index = 1; index <= 15; index += 1) {
await orkas.invoke('projects.tasks.create', { projectId: pid, title: `待办 ${index}`, status: 'todo', detail });
}
- await orkas.invoke('projects.tasks.create', { projectId: pid, title: '对照待办', status: 'progress', detail });
+ const referenceTask = await orkas.invoke<any>('projects.tasks.create', { projectId: pid, title: '对照待办', status: 'progress', detail });
const measure = (sel: string, viewSel: string) => page.evaluate(({ sel, viewSel }) => {
const column = document.querySelector(`${sel} .todo-column.is-todo`) as HTMLElement;
const body = column.querySelector('.todo-column-body') as HTMLElement;
@@ -602,7 +1028,7 @@ test('reaches every to-do in a column taller than the board', async ({ connector
// The global page scrolls as one list, so a column there must not turn into a
// second scroller nested inside it.
- await page.locator('#todos-btn').click();
+ await openSidebarEntry(page, '#todos-btn');
await page.locator('[data-todo-group="status"]').click();
await expect(page.locator('#todos-content .todo-column.is-todo .project-todo-item')).toHaveCount(15);
const globalBefore = await measure('#todos-content', '#todos-content');
@@ -613,6 +1039,18 @@ test('reaches every to-do in a column taller than the board', async ({ connector
list.scrollTop = list.scrollHeight;
});
expect((await measure('#todos-content', '#todos-content')).lastVisible).toBe(true);
+ const globalList = page.locator('#todos-content');
+ const globalTop = await globalList.evaluate(element => element.scrollTop);
+ expect(globalTop).toBeGreaterThan(100);
+ // A sync reload and a real task-change push both update data while the
+ // reader stays at the same place in the account-wide list.
+ await page.evaluate(async () => (window as any)._refreshGlobalTodos());
+ expect(await globalList.evaluate(element => element.scrollTop)).toBeCloseTo(globalTop, 0);
+ await orkas.invoke('projects.tasks.update', {
+ projectId: pid, taskId: referenceTask.task.id, content: '同步后的对照待办\n' + detail,
+ });
+ await expect(globalList.locator('.todo-column.is-progress .project-todo-title')).toContainText('同步后的对照待办');
+ expect(await globalList.evaluate(element => element.scrollTop)).toBeCloseTo(globalTop, 0);
// The project board gives each column its own scroller instead.
await page.locator('#todos-content .project-todo-item').first().locator('.todo-card-project').click();
@@ -620,6 +1058,9 @@ test('reaches every to-do in a column taller than the board', async ({ connector
await page.locator('[data-project-tab="todo"]').click();
const body = page.locator('#project-todo-list .todo-column.is-todo .todo-column-body');
await expect(page.locator('#project-todo-list .todo-column.is-todo .project-todo-item')).toHaveCount(15);
+ // Completed starts as a narrow strip and the board fits; with every lane
+ // open the board also scrolls sideways.
+ await page.locator('#project-todo-list .todo-column.is-done .todo-collapse').click();
const before = await measure('#project-todo-list', '#project-todo-list .todo-column.is-todo');
expect(before.cards).toBe(15);
expect(before.cardHeight).toBeGreaterThanOrEqual(before.referenceHeight - 2);
@@ -634,5 +1075,19 @@ test('reaches every to-do in a column taller than the board', async ({ connector
expect(after.lastVisible).toBe(true);
expect(after.cardHeight).toBeGreaterThanOrEqual(after.referenceHeight - 2);
expect(after.headTop).toBe(before.headTop);
+ const projectTop = await body.evaluate(element => element.scrollTop);
+ const board = page.locator('#project-todo-list .todo-board');
+ await board.evaluate(element => { element.scrollLeft = 60; });
+ const boardLeft = await board.evaluate(element => element.scrollLeft);
+ expect(boardLeft).toBeGreaterThan(0);
+ await orkas.invoke('projects.tasks.update', {
+ projectId: pid, taskId: referenceTask.task.id, content: '再次更新的对照待办\n' + detail,
+ });
+ await expect(page.locator('#project-todo-list .todo-column.is-progress .project-todo-title')).toContainText('再次更新的对照待办');
+ expect(await body.evaluate(element => element.scrollTop)).toBeCloseTo(projectTop, 0);
+ expect(await board.evaluate(element => element.scrollLeft)).toBeCloseTo(boardLeft, 0);
+ await page.evaluate(async id => (window as any)._loadProjectTodos(id), pid);
+ expect(await body.evaluate(element => element.scrollTop)).toBeCloseTo(projectTop, 0);
+ expect(await board.evaluate(element => element.scrollLeft)).toBeCloseTo(boardLeft, 0);
await page.screenshot({ path: testInfo.outputPath('todo-column-scroll.png') });
});
diff --git a/test/e2e/window_close_e2e_confirmation.spec.ts b/test/e2e/window_close_e2e_confirmation.spec.ts
index 5048faec..474e6ffd 100644
--- a/test/e2e/window_close_e2e_confirmation.spec.ts
+++ b/test/e2e/window_close_e2e_confirmation.spec.ts
@@ -36,6 +36,7 @@ test('cancel keeps a task streaming; confirming close also protects a task in th
await native.evaluate(win => win.close());
await expect.poll(() => app.evaluate(() => (globalThis as any).closeDialogCalls.length)).toBe(2);
expect(page.isClosed()).toBe(false);
+ await modelOrkas.prepareForNativeShutdown();
const closed = page.waitForEvent('close');
await app.evaluate(() => {
setTimeout(() => (globalThis as any).confirmWindowClose({ response: 1, checkboxChecked: false }), 0);
diff --git a/test/e2e/woocommerce_e2e_setup.spec.ts b/test/e2e/woocommerce_e2e_setup.spec.ts
index 777a4f22..6e85b593 100644
--- a/test/e2e/woocommerce_e2e_setup.spec.ts
+++ b/test/e2e/woocommerce_e2e_setup.spec.ts
@@ -1,9 +1,9 @@
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
test('WooCommerce setup accepts a store URL without keys and retains manual fields across locales', async ({ orkas }) => {
const page = orkas.page!;
- await page.locator('#connectors-btn').click();
+ await openSidebarEntry(page, '#connectors-btn');
await page.locator('#connectors-search-input').fill('woocommerce');
await page.locator('.connector-card[data-id="woocommerce"] [data-act="connect"]').click();
const dialog = page.locator('#connectors-connect-modal');
diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.ts
index 92a00348..f6f67beb 100644
--- a/test/main/features/chat_attachments.test.ts
+++ b/test/main/features/chat_attachments.test.ts
@@ -31,7 +31,8 @@ beforeEach(async () => {
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
- process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ if (prevWs === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = prevWs;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -47,6 +48,32 @@ function draftAttDir(cid: string): string {
return path.join(tmpDir, UID, 'local', 'chat_attachment_drafts', cid);
}
+describe('cleanup attachment draft protection', () => {
+ it('keeps an unsent attachment across restart and admits only fully committed files', async () => {
+ const m = await loadMod();
+ fs.mkdirSync(attDir(), { recursive: true });
+ fs.writeFileSync(path.join(attDir(), 'draft.txt'), 'unsent');
+ const chats = path.join(tmpDir, UID, 'cloud', 'chats');
+ fs.mkdirSync(chats, { recursive: true });
+ fs.writeFileSync(path.join(chats, `${CID}.jsonl`), JSON.stringify({ attachments: ['different.txt'] }) + '\n');
+ expect(await m.hasPendingAttachmentsForCleanup(UID, CID)).toBe(true);
+ fs.appendFileSync(path.join(chats, `${CID}.jsonl`), JSON.stringify({ attachments: ['draft.txt'] }) + '\n');
+ expect(await m.hasPendingAttachmentsForCleanup(UID, CID)).toBe(false);
+ });
+ it('retains unknown large histories without reading them and accepts generated media references', async () => {
+ const m = await loadMod();
+ fs.mkdirSync(attDir(), { recursive: true });
+ fs.writeFileSync(path.join(attDir(), 'result.png'), PNG_1X1);
+ const chats = path.join(tmpDir, UID, 'cloud', 'chats');
+ fs.mkdirSync(chats, { recursive: true });
+ const history = path.join(chats, `${CID}.jsonl`);
+ fs.writeFileSync(history, JSON.stringify({ text: `![result](chat-media://cid/${CID}/result.png)` }) + '\n');
+ expect(await m.hasPendingAttachmentsForCleanup(UID, CID)).toBe(false);
+ fs.writeFileSync(history, ' '.repeat(4 * 1024 * 1024 + 1));
+ expect(await m.hasPendingAttachmentsForCleanup(UID, CID)).toBe(true);
+ });
+});
+
async function loadMod() {
return import('../../../src/main/features/chat_attachments');
}
@@ -808,6 +835,86 @@ describe('chat_attachments › purgeByCid', () => {
describe('chat_attachments › adoptDraftAttachments', () => {
const DRAFT = 'main_chat';
+ it('adopts the intact draft after a transient Windows lock releases on the event loop', async () => {
+ const m = await loadMod();
+ await m.uploadAttachment(UID, DRAFT, 'note.txt', Buffer.from('draft survives the lock'));
+ const actualFs = await vi.importActual<typeof import('node:fs')>('node:fs');
+ const actualPromises = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let locked = true;
+ let attempts = 0;
+ const checkLock = (from: fs.PathLike) => {
+ if (String(from) !== draftAttDir(DRAFT)) return;
+ attempts += 1;
+ if (locked) {
+ setTimeout(() => { locked = false; }, 0);
+ throw Object.assign(new Error('transient Windows directory lock'), { code: 'EPERM' });
+ }
+ };
+ vi.resetModules();
+ vi.doMock('node:fs', () => ({ ...actualFs, renameSync: (from, to) => {
+ checkLock(from);
+ return actualFs.renameSync(from, to);
+ } }));
+ vi.doMock('node:fs/promises', () => ({ ...actualPromises, rename: async (from, to) => {
+ checkLock(from);
+ return actualPromises.rename(from, to);
+ } }));
+ try {
+ const lockedModule = await loadMod();
+ const result = await lockedModule.adoptDraftAttachments(UID, DRAFT, CID);
+ expect(result).toMatchObject({ ok: true, count: 1, items: [{ sourceName: 'note.txt', targetName: 'note.txt' }] });
+ expect(attempts).toBeGreaterThan(1);
+ expect(locked).toBe(false);
+ expect(fs.readFileSync(path.join(cloudAttDir(CID), 'note.txt'), 'utf8')).toBe('draft survives the lock');
+ expect(fs.existsSync(draftAttDir(DRAFT))).toBe(false);
+ } finally {
+ vi.doUnmock('node:fs');
+ vi.doUnmock('node:fs/promises');
+ vi.resetModules();
+ }
+ });
+
+ it('leaves the complete draft recoverable when the Windows lock persists', async () => {
+ const m = await loadMod();
+ await m.uploadAttachment(UID, DRAFT, 'note.txt', Buffer.from('recoverable draft'));
+ const actualPromises = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let attempts = 0;
+ vi.resetModules();
+ vi.doMock('node:fs/promises', () => ({ ...actualPromises, rename: async (from, to) => {
+ if (String(from) === draftAttDir(DRAFT)) {
+ attempts += 1;
+ throw Object.assign(new Error('persistent Windows directory lock'), { code: 'EPERM' });
+ }
+ return actualPromises.rename(from, to);
+ } }));
+ try {
+ const lockedModule = await loadMod();
+ expect(await lockedModule.adoptDraftAttachments(UID, DRAFT, CID)).toMatchObject({ ok: false });
+ expect(attempts).toBeGreaterThan(1);
+ expect(fs.readdirSync(draftAttDir(DRAFT))).toEqual(['note.txt']);
+ expect(fs.readFileSync(path.join(draftAttDir(DRAFT), 'note.txt'), 'utf8')).toBe('recoverable draft');
+ expect(fs.existsSync(cloudAttDir(CID))).toBe(false);
+ } finally {
+ vi.doUnmock('node:fs/promises');
+ vi.resetModules();
+ }
+ });
+
+ it('consumes a shared draft only once across concurrent adoptions', async () => {
+ const m = await loadMod();
+ await m.uploadAttachment(UID, DRAFT, 'note.txt', Buffer.from('one complete attachment'));
+ const results = await Promise.all([
+ m.adoptDraftAttachments(UID, DRAFT, CID),
+ m.adoptDraftAttachments(UID, DRAFT, 'other-conversation'),
+ ]);
+ expect(results.every((result) => result.ok)).toBe(true);
+ expect(results.map((result) => result.ok ? result.count : -1).sort()).toEqual([0, 1]);
+ const destinations = [CID, 'other-conversation'].filter((cid) => fs.existsSync(cloudAttDir(cid)));
+ expect(destinations).toHaveLength(1);
+ expect(fs.readFileSync(path.join(cloudAttDir(destinations[0]), 'note.txt'), 'utf8')).toBe('one complete attachment');
+ expect(fs.existsSync(draftAttDir(DRAFT))).toBe(false);
+ });
+
it('renames draft dir to target cid when target does not exist', async () => {
const m = await loadMod();
await m.uploadAttachment(UID, DRAFT, 'note.txt', Buffer.from('hi'));
@@ -815,7 +922,7 @@ describe('chat_attachments › adoptDraftAttachments', () => {
expect(fs.existsSync(draftAttDir(DRAFT))).toBe(true);
expect(fs.existsSync(cloudAttDir(DRAFT))).toBe(false);
- const r = m.adoptDraftAttachments(UID, DRAFT, CID);
+ const r = await m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.count).toBe(2);
@@ -826,7 +933,7 @@ describe('chat_attachments › adoptDraftAttachments', () => {
it('returns count=0 without error when draft dir is absent', async () => {
const m = await loadMod();
- const r = m.adoptDraftAttachments(UID, DRAFT, CID);
+ const r = await m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.count).toBe(0);
@@ -835,7 +942,7 @@ describe('chat_attachments › adoptDraftAttachments', () => {
it('rejects same src == dst', async () => {
const m = await loadMod();
await m.uploadAttachment(UID, DRAFT, 'a.txt', Buffer.from('x'));
- const r = m.adoptDraftAttachments(UID, DRAFT, DRAFT);
+ const r = await m.adoptDraftAttachments(UID, DRAFT, DRAFT);
expect(r.ok).toBe(false);
});
@@ -843,7 +950,7 @@ describe('chat_attachments › adoptDraftAttachments', () => {
const m = await loadMod();
await m.uploadAttachment(UID, CID, 'kept.txt', Buffer.from('kept'));
await m.uploadAttachment(UID, DRAFT, 'new.txt', Buffer.from('fresh'));
- const r = m.adoptDraftAttachments(UID, DRAFT, CID);
+ const r = await m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(fs.existsSync(path.join(cloudAttDir(CID), 'kept.txt'))).toBe(true);
@@ -863,12 +970,13 @@ describe('chat_attachments › adoptDraftAttachments', () => {
String(from).startsWith(draftAttDir(DRAFT) + path.sep)
&& String(to).startsWith(cloudAttDir(CID) + path.sep)
);
- const renameSync = vi.fn((from: fs.PathLike, to: fs.PathLike) => {
+ const actualPromises = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const rename = vi.fn(async (from: fs.PathLike, to: fs.PathLike) => {
if (isForwardMove(from, to)) {
forwardMove += 1;
- if (forwardMove === 2) throw new Error('forced rename failure');
+ if (forwardMove === 2) throw Object.assign(new Error('forced cross-device move'), { code: 'EXDEV' });
}
- return actualFs.renameSync(from, to);
+ return actualPromises.rename(from, to);
});
const copyFileSync = vi.fn((from: fs.PathLike, to: fs.PathLike, mode?: number) => {
if (isForwardMove(from, to) && forwardMove === 2) {
@@ -877,17 +985,19 @@ describe('chat_attachments › adoptDraftAttachments', () => {
return actualFs.copyFileSync(from, to, mode);
});
vi.resetModules();
- vi.doMock('node:fs', () => ({ ...actualFs, renameSync, copyFileSync }));
+ vi.doMock('node:fs', () => ({ ...actualFs, copyFileSync }));
+ vi.doMock('node:fs/promises', () => ({ ...actualPromises, rename }));
try {
const moduleWithFailingMove = await loadMod();
- const result = moduleWithFailingMove.adoptDraftAttachments(UID, DRAFT, CID);
+ const result = await moduleWithFailingMove.adoptDraftAttachments(UID, DRAFT, CID);
expect(result.ok).toBe(false);
expect(fs.readdirSync(draftAttDir(DRAFT)).sort()).toEqual(['first.txt', 'second.txt']);
expect(fs.readdirSync(cloudAttDir(CID))).toEqual(['kept.txt']);
} finally {
vi.doUnmock('node:fs');
+ vi.doUnmock('node:fs/promises');
vi.resetModules();
}
});
@@ -897,7 +1007,7 @@ describe('chat_attachments › adoptDraftAttachments', () => {
await m.uploadAttachment(UID, CID, 'same-name.txt', Buffer.from('existing conversation file'));
await m.uploadAttachment(UID, DRAFT, 'same-name.txt', Buffer.from('new draft file'));
- const r = m.adoptDraftAttachments(UID, DRAFT, CID);
+ const r = await m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
@@ -1651,10 +1761,16 @@ describe('chat_attachments › HTML preview assets', () => {
// file viewer. Unlike the media route, nothing is served until the viewer
// grants the page's folder, and hidden or outside files never are.
let prevHome: string | undefined;
- beforeEach(() => { prevHome = process.env.HOME; });
+ let prevUserProfile: string | undefined;
+ beforeEach(() => {
+ prevHome = process.env.HOME;
+ prevUserProfile = process.env.USERPROFILE;
+ });
afterEach(() => {
if (prevHome === undefined) delete process.env.HOME;
else process.env.HOME = prevHome;
+ if (prevUserProfile === undefined) delete process.env.USERPROFILE;
+ else process.env.USERPROFILE = prevUserProfile;
});
async function setup() {
@@ -1718,10 +1834,12 @@ describe('chat_attachments › HTML preview assets', () => {
const { mod, sandbox, page } = await setup();
fs.writeFileSync(path.join(sandbox, 'index.html'), '<!doctype html>');
process.env.HOME = sandbox;
+ if (process.platform === 'win32') process.env.USERPROFILE = sandbox;
+ expect(os.homedir()).toBe(sandbox);
expect(mod.grantLocalHtmlPreviewAssets(path.join(sandbox, 'index.html'))).toMatchObject({ ok: false, code: 'forbidden' });
process.env.HOME = path.join(page, 'assets');
+ if (process.platform === 'win32') process.env.USERPROFILE = process.env.HOME;
expect(mod.grantLocalHtmlPreviewAssets(path.join(page, 'index.html'))).toMatchObject({ ok: false, code: 'forbidden' });
- process.env.HOME = prevHome;
expect(mod.grantLocalHtmlPreviewAssets(path.join(page, 'style.css'))).toMatchObject({ ok: false, code: 'bad_input' });
expect(mod.grantLocalHtmlPreviewAssets(path.join(page, 'gone.html'))).toMatchObject({ ok: false, code: 'not_found' });
expect(mod.resolveLocalHtmlPreviewAssetPath(path.join(page, 'style.css'))).toMatchObject({ ok: false, code: 'forbidden' });
diff --git a/test/main/features/chats-autotitle.test.ts b/test/main/features/chats-autotitle.test.ts
index 8378b261..627c70f9 100644
--- a/test/main/features/chats-autotitle.test.ts
+++ b/test/main/features/chats-autotitle.test.ts
@@ -82,40 +82,40 @@ describe('autoTitle — set A (produces clean title)', () => {
// did not: 25 Chinese characters render twice as wide as 25 Latin ones, so
// rows ended raggedly and Latin titles were cut at half the useful length.
it('ends a Chinese and a Latin title at the same rendered width', () => {
- const zh = autoTitle('一'.repeat(40));
- const en = autoTitle('A'.repeat(80));
+ const zh = autoTitle('一'.repeat(80));
+ const en = autoTitle('A'.repeat(160));
expect(zh.endsWith('…')).toBe(true);
expect(en.endsWith('…')).toBe(true);
expect(renderedWidth(zh)).toBe(renderedWidth(en));
});
- it('keeps a Chinese title exactly as long as the character cap did', () => {
- // 25 full-width characters was the previous cap's output. Nothing may get
- // shorter for users who already have titles at that length.
- expect(autoTitle('一'.repeat(40))).toBe(`${'一'.repeat(25)}…`);
+ it('shows about fifty Chinese characters before cutting a long request', () => {
+ // The project task tab is wide; a 25-character stub left most of each row
+ // empty. Wider titles must also never be shorter than the old 25 cap.
+ expect(autoTitle('一'.repeat(80))).toBe(`${'一'.repeat(50)}…`);
});
it('gives a Latin title the full width instead of half of it', () => {
- expect(autoTitle('A'.repeat(80))).toBe(`${'A'.repeat(50)}…`);
+ expect(autoTitle('A'.repeat(160))).toBe(`${'A'.repeat(100)}…`);
});
it('leaves a title that fits the budget untouched, and marks the one past it', () => {
- expect(autoTitle('A'.repeat(50))).toBe('A'.repeat(50));
- expect(autoTitle('A'.repeat(51))).toBe(`${'A'.repeat(50)}…`);
- expect(autoTitle('一'.repeat(25))).toBe('一'.repeat(25));
- expect(autoTitle('一'.repeat(26))).toBe(`${'一'.repeat(25)}…`);
+ expect(autoTitle('A'.repeat(100))).toBe('A'.repeat(100));
+ expect(autoTitle('A'.repeat(101))).toBe(`${'A'.repeat(100)}…`);
+ expect(autoTitle('一'.repeat(50))).toBe('一'.repeat(50));
+ expect(autoTitle('一'.repeat(51))).toBe(`${'一'.repeat(50)}…`);
});
it('never cuts a grapheme cluster in half', () => {
- const out = autoTitle('🙂'.repeat(40));
- expect(out).toBe(`${'🙂'.repeat(25)}…`);
+ const out = autoTitle('🙂'.repeat(80));
+ expect(out).toBe(`${'🙂'.repeat(50)}…`);
// A lone surrogate would survive a character slice but not a cluster walk.
expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(out)).toBe(false);
});
it('measures a mixed-script title by what it renders, not by character count', () => {
- // 20 full-width (40 units) + 10 half-width (10 units) exactly fills 50.
- const mixed = `${'一'.repeat(20)}${'A'.repeat(10)}`;
+ // 40 full-width (80 units) + 20 half-width (20 units) exactly fills 100.
+ const mixed = `${'一'.repeat(40)}${'A'.repeat(20)}`;
expect(autoTitle(mixed)).toBe(mixed);
expect(autoTitle(`${mixed}B`)).toBe(`${mixed}…`);
});
diff --git a/test/main/features/chats-move-to-project.test.ts b/test/main/features/chats-move-to-project.test.ts
index c3bc5edb..a655f0c3 100644
--- a/test/main/features/chats-move-to-project.test.ts
+++ b/test/main/features/chats-move-to-project.test.ts
@@ -326,6 +326,7 @@ describe('chats › moveConversationToProject', () => {
const other = await chats.createConversation(UID, { title: 'unrelated', projectId: PID });
const cid = conv.conversation_id;
seedConversationBytes(cid);
+ await (await import('../../../src/main/features/search/indexer')).flushAll();
const result = spawnSync(process.execPath, ['-r', 'tsx/cjs', '-e', `
const fs = require('node:fs');
const slash = file => file.split(require('node:path').sep).join('/');
@@ -446,6 +447,39 @@ describe('chats › moveConversationToProject', () => {
});
+// Sync checks every disk, remote and index path against unresolved move
+// records on each pass. The once-built matcher must answer exactly like the
+// plain per-record lists, whether or not every recorded path names the
+// conversation, and must not match a look-alike that merely contains its id.
+describe('conversation relocation › unresolved path matcher', () => {
+ it('matches exactly the paths the per-record lists cover', async () => {
+ const relocation = await import('../../../src/main/util/conversation-relocate');
+ const cid = 'c0a1b2c3d4e5';
+ const unresolved = [
+ { cid, exact: [`cloud/chats/${cid}.jsonl`, `cloud/projects/p1/chats/${cid}.jsonl`],
+ prefixes: [`cloud/chats/${cid}/`, `cloud/sessions/gmember-${cid}-`] },
+ // A record whose paths do not all name its conversation is never gated.
+ { cid: 'c9f8e7d6c5b4', exact: ['cloud/legacy/moved.json'], prefixes: ['cloud/legacy/dir/'] },
+ ];
+ const reference = (relPath: string) => unresolved.some((item) => item.exact.includes(relPath)
+ || item.prefixes.some((prefix) => relPath.startsWith(prefix)));
+ const paths = [
+ `cloud/chats/${cid}.jsonl`, `cloud/chats/${cid}/state.json`, `cloud/projects/p1/chats/${cid}.jsonl`,
+ `cloud/sessions/gmember-${cid}-agent.jsonl`, `cloud/sessions/gmember-other-${cid}.jsonl`,
+ `cloud/chats/${cid}.jsonl.bak`, `cloud/chats/${cid}`, `cloud/projects/p2/chats/${cid}.jsonl`,
+ 'cloud/legacy/moved.json', 'cloud/legacy/dir/a/b.json', 'cloud/legacy/dir', 'cloud/legacy/moved.json2',
+ 'cloud/contexts/notes.md', '',
+ ];
+ const matches = relocation.unresolvedRelocationMatcher(unresolved);
+ for (const relPath of paths) {
+ expect(matches(relPath), relPath).toBe(reference(relPath));
+ expect(relocation.matchesUnresolvedRelocation(unresolved, relPath), relPath).toBe(reference(relPath));
+ }
+ expect(paths.filter(reference)).toHaveLength(6);
+ expect(relocation.unresolvedRelocationMatcher([])('cloud/chats/x.jsonl')).toBe(false);
+ });
+});
+
describe('chats › moveConversationOutOfProject', () => {
it('brings every location back to the root and leaves nothing in the project', async () => {
const chats = await import('../../../src/main/features/chats');
@@ -513,6 +547,9 @@ describe('chats › moveConversationOutOfProject', () => {
seedConversationBytes(cid);
expect((await chats.moveConversationToProject(UID, cid, PID)).ok).toBe(true);
+ // The child represents the sole writer after the original host exits.
+ // Close its search worker before resetting that host's module graph.
+ await (await import('../../../src/main/features/search/indexer')).flushAll();
const result = spawnSync(process.execPath, ['-r', 'tsx/cjs', '-e', `
const fs = require('node:fs');
const slash = file => file.split(require('node:path').sep).join('/');
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 49d2d999..8ca99621 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -77,11 +77,18 @@ describe('chats › createConversation', () => {
it('caps the initial title by display width', async () => {
const chats = await loadChats();
- const english = await chats.createConversation(TEST_UID, { title: 'a'.repeat(70) });
- const chinese = await chats.createConversation(TEST_UID, { title: '长'.repeat(40) });
+ const english = await chats.createConversation(TEST_UID, { title: 'a'.repeat(120) });
+ const chinese = await chats.createConversation(TEST_UID, { title: '长'.repeat(60) });
- expect(english.title).toBe('a'.repeat(60));
- expect(chinese.title).toBe('长'.repeat(30));
+ expect(english.title).toBe('a'.repeat(101));
+ expect(chinese.title).toBe('长'.repeat(50));
+ });
+
+ it('stores a full auto title, ellipsis included, past the shared 60-unit name limit', async () => {
+ const chats = await loadChats();
+ const auto = chats.autoTitle(`请帮我${'设计'.repeat(40)}`);
+ const conv = await chats.createConversation(TEST_UID, { title: auto });
+ expect(conv.title).toBe(`${'设计'.repeat(25)}…`);
});
// Project membership wiring. Project conversations live in the project's
@@ -370,6 +377,28 @@ describe('chats › message history tombstones', () => {
]);
});
+ // A quoted reference knows only its message id. Its page must be the same
+ // page, cursors and source indexes the index-anchored read returns, found
+ // past malformed lines and a tombstoned copy of the same id.
+ it('reads the page around a quoted message id exactly like its index page', async () => {
+ const chats = await loadChats();
+ const conv = await chats.createConversation(TEST_UID, { title: 'quoted target' });
+ const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);
+ const rows = Array.from({ length: 35 }, (_, i) => JSON.stringify(
+ i === 4 ? { id: 'm27', from: 'user', text: 'deleted copy', deleted_at: '2026-07-10T11:00:00' }
+ : { id: `m${i}`, ts: `2026-07-10T10:${String(i).padStart(2, '0')}:00`, from: i % 2 ? 'commander' : 'user', text: `message ${i}` },
+ ));
+ rows.splice(9, 0, '{malformed');
+ fs.writeFileSync(file, rows.join('\n') + '\n');
+
+ const quoted = await chats.getMessagesPageAtMessageId(TEST_UID, conv.conversation_id, 'm27', 10);
+ const indexed = await chats.getMessagesPageAtIndex(TEST_UID, conv.conversation_id, 27, 10);
+
+ expect(quoted).toEqual({ ...indexed, messageIndex: 27 });
+ expect(quoted!.history.map((row) => row.id)).toContain('m27');
+ expect(await chats.getMessagesPageAtMessageId(TEST_UID, conv.conversation_id, 'gone', 10)).toBeNull();
+ });
+
it('keeps an explicit global history read out of a duplicate project root', async () => {
const chats = await loadChats();
const projects = await import('../../../src/main/features/projects');
@@ -444,8 +473,8 @@ describe('chats › conversation turn navigation index', () => {
const chats = await loadChats();
const conv = await chats.createConversation(TEST_UID, { title: 'legacy turn index' });
const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);
- const longUser = `## [Useful link](https://example.com) ${'用'.repeat(60)}`;
- const longReply = `> ${'答'.repeat(110)}`;
+ const longUser = `## [Useful link](https://example.com) ${'用'.repeat(120)}`;
+ const longReply = `> ${'答'.repeat(260)}`;
fs.writeFileSync(file, [
JSON.stringify({ role: 'user', content: longUser }),
'{malformed',
@@ -455,9 +484,9 @@ describe('chats › conversation turn navigation index', () => {
const first = await chats.getConversationTurnPage(TEST_UID, conv.conversation_id);
expect(first.total).toBe(1);
- expect(Array.from(first.turns[0].userPreview)).toHaveLength(40);
+ expect(Array.from(first.turns[0].userPreview)).toHaveLength(100);
expect(first.turns[0].userPreview).toContain('Useful link');
- expect(Array.from(first.turns[0].assistantPreview)).toHaveLength(80);
+ expect(Array.from(first.turns[0].assistantPreview)).toHaveLength(240);
expect(first.turns[0].assistantPreview).not.toContain('hidden dispatch');
expect(first.turns[0].messageIndex).toBe(0);
// Worker-local diagnostic redaction is covered by conversation-turn-index.test.ts.
@@ -469,7 +498,7 @@ describe('chats › conversation turn navigation index', () => {
expect(fs.existsSync(indexFile)).toBe(true);
const persisted = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
expect(persisted).toMatchObject({
- version: 2,
+ version: 3,
recordCount: 3,
tailHash: expect.stringMatching(/^[a-f0-9]{64}$/),
});
@@ -495,9 +524,8 @@ describe('chats › conversation turn navigation index', () => {
assistantPreview: 'second reply · extra detail',
});
expect(JSON.parse(fs.readFileSync(indexFile, 'utf8')).recordCount).toBe(6);
- await expect(chats.findMessageIndexById(
- TEST_UID, conv.conversation_id, 'u2',
- )).resolves.toBe(3);
+ expect((await chats.getMessagesPageAtMessageId(TEST_UID, conv.conversation_id, 'u2'))?.messageIndex)
+ .toBe(3);
});
it('falls back to a full rebuild when a same-inode source prefix is rewritten', async () => {
@@ -785,7 +813,7 @@ describe('chats › renameConversation', () => {
const renamed = await chats.renameConversation(TEST_UID, conv.conversation_id, raw);
- expect(renamed?.title).toBe('长'.repeat(30));
+ expect(renamed?.title).toBe('长'.repeat(50));
expect(renamed?.title_manually_set).toBe(true);
});
@@ -898,7 +926,7 @@ describe('chats › index repair', () => {
.map((c) => c.conversation_id)).toEqual([collapsedConv.conversation_id]);
});
- it('always includes tasks active since the renderer day start, even under collapsed projects', async () => {
+ it.each([1, 47, 49])('includes collapsed-project tasks across a %s-hour recent calendar window', async (lookbackHours) => {
const chats = await loadChats();
const projects = await import('../../../src/main/features/projects');
const collapsed = await projects.createProject(TEST_UID, 'Collapsed');
@@ -923,7 +951,9 @@ describe('chats › index repair', () => {
collapsedOld.conversation_id,
);
chats.invalidateConversationCaches(TEST_UID);
- const activeSinceMs = Date.now() - 60 * 60 * 1000;
+ // Late yesterday/today windows approach 48h; a one-hour DST fallback
+ // can extend the two local days to 49h.
+ const activeSinceMs = Date.now() - lookbackHours * 60 * 60 * 1000;
// Negative control: without the day-start filter the collapsed project
// contributes nothing, so the Today aggregate would miss a live task.
@@ -949,7 +979,7 @@ describe('chats › index repair', () => {
expect(startup.unprojected_pagination).toEqual({ total: 2, next_offset: null });
});
- it('rejects renderer active-since values outside a plausible local day', async () => {
+ it('rejects renderer active-since values outside a plausible recent calendar window', async () => {
const chats = await loadChats();
const projects = await import('../../../src/main/features/projects');
const collapsed = await projects.createProject(TEST_UID, 'Collapsed');
@@ -959,7 +989,7 @@ describe('chats › index repair', () => {
projectId: collapsed.project.project_id,
});
- for (const activeSinceMs of [0, Date.now() + 60 * 60 * 1000]) {
+ for (const activeSinceMs of [0, Date.now() - 51 * 60 * 60 * 1000, Date.now() + 60 * 60 * 1000]) {
const startup = await chats.listStartupConversations(TEST_UID, {
expandedProjectIds: [],
activeSinceMs,
@@ -1496,6 +1526,23 @@ describe('chats › index repair', () => {
});
describe('chats › deleteConversation', () => {
+ it('keeps history and the live index when the maintenance guard rejects current metadata', async () => {
+ const chats = await loadChats();
+ const conv = await chats.createConversation(TEST_UID, { title: 'Protected during preview' });
+ await chats.setConversationPinned(TEST_UID, conv.conversation_id, true);
+ const history = path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);
+ fs.writeFileSync(history, '{"content":"keep"}\n');
+ const guard = vi.fn(async (current: any) => !current.pinned_at);
+ expect(await chats.deleteConversation(TEST_UID, conv.conversation_id, null, guard)).toBe(false);
+ expect(guard).toHaveBeenCalledWith(expect.objectContaining({ pinned_at: expect.any(String) }));
+ expect(fs.readFileSync(history, 'utf8')).toContain('keep');
+ expect(await chats.getConversationMetadata(TEST_UID, conv.conversation_id)).not.toBeNull();
+ expect((await chats.listCleanupConversationRows(TEST_UID)).map(row => row.conversation_id)).toContain(conv.conversation_id);
+ await chats.setConversationPinned(TEST_UID, conv.conversation_id, false);
+ expect(await chats.deleteConversation(TEST_UID, conv.conversation_id, null, guard)).toBe(true);
+ expect(fs.existsSync(history)).toBe(false);
+ expect(await chats.listCleanupConversationRows(TEST_UID)).toEqual([]);
+ });
it('purges retained member outputs after a model-state reset removed the session JSONL', async () => {
const chats = await loadChats();
const conv = await chats.createConversation(TEST_UID);
diff --git a/test/main/features/conversation-assistance-context.test.ts b/test/main/features/conversation-assistance-context.test.ts
index e3d0a56c..8a9f40f8 100644
--- a/test/main/features/conversation-assistance-context.test.ts
+++ b/test/main/features/conversation-assistance-context.test.ts
@@ -84,6 +84,76 @@ describe('conversation entry assistance', () => {
expect((await context.resolveConversationAssistanceForTurn('u1', cid)).guidance).toBe('');
});
+ it('tells the Commander only the count and ids of open to-dos saved from this conversation', async () => {
+ const chats = await import('../../../src/main/features/chats');
+ const projectTasks = await import('../../../src/main/features/project_tasks');
+ const context = await import('../../../src/main/features/conversation_assistance_context');
+ const conv = await chats.createConversation('u1', { title: 'launch prep' });
+ const other = await chats.createConversation('u1', { title: 'elsewhere' });
+ const cid = conv.conversation_id;
+ // A long to-do must not grow the per-turn context.
+ const body = `Draft the pricing page\n${'SECRET_DETAIL '.repeat(250)}`;
+ const save = async (content: string, linkTo: string) => {
+ const created = await projectTasks.createTask('u1', '', { content });
+ if (!created.ok) throw new Error(created.error);
+ await projectTasks.recordTaskExecution('u1', '', created.task.id, linkTo);
+ return created.task.id;
+ };
+ const first = await save(body, cid);
+ const done = await save('Ship it', cid);
+ expect((await projectTasks.updateTask('u1', '', done, { status: 'done' })).ok).toBe(true);
+ await save('Unrelated', other.conversation_id);
+
+ const { guidance } = await context.resolveConversationAssistanceForTurn('u1', cid);
+ expect(guidance).toContain('## Keeping work going');
+ expect(guidance).toContain('## Open to-dos from this conversation');
+ expect(guidance).toContain(`Host facts: 1 open to-do(s) were saved from this conversation: ${first}.`);
+ expect(guidance).not.toContain(done);
+ expect(guidance).not.toContain('Draft the pricing page');
+ expect(guidance).not.toContain('SECRET_DETAIL');
+ expect(guidance).not.toContain('Unrelated');
+ expect(guidance).not.toMatch(/\$(count|ids)\b/);
+ // The other conversation's turn sees only its own to-do.
+ expect((await context.resolveConversationAssistanceForTurn('u1', other.conversation_id)).guidance)
+ .toContain('Host facts: 1 open to-do(s)');
+
+ // Beyond three, the count stays exact and the listing is marked as cut.
+ for (const n of [1, 2, 3]) await save(`Next step ${n}`, cid);
+ const many = (await context.resolveConversationAssistanceForTurn('u1', cid)).guidance;
+ expect(many).toContain('Host facts: 4 open to-do(s)');
+ expect(many.match(/t_[a-f0-9]{12}/g)).toHaveLength(3);
+ expect(many).toContain(', ….');
+
+ // Finishing them removes the block; the follow-up guidance is unchanged.
+ for (const task of await projectTasks.listTasks('u1', '')) {
+ if (task.origin_cid === cid && task.status !== 'done') {
+ expect((await projectTasks.updateTask('u1', '', task.id, { status: 'done' })).ok).toBe(true);
+ }
+ }
+ expect((await context.resolveConversationAssistanceForTurn('u1', cid)).guidance).toBe(
+ fs.readFileSync(path.join(__dirname, '../../../src/main/prompts/followup_offer_guidance.md'), 'utf8').trim(),
+ );
+ });
+
+ it('reads open to-dos from the project scope once the conversation is filed', async () => {
+ const chats = await import('../../../src/main/features/chats');
+ const projects = await import('../../../src/main/features/projects');
+ const projectTasks = await import('../../../src/main/features/project_tasks');
+ const context = await import('../../../src/main/features/conversation_assistance_context');
+ const pid = ((await projects.createProject('u1', 'Backlog')) as { project: any }).project.project_id;
+ const conv = await chats.createConversation('u1', { title: 'run' });
+ expect((await chats.moveConversationToProject('u1', conv.conversation_id, pid)).ok).toBe(true);
+ const created = await projectTasks.createTask('u1', pid, { content: 'Write the migration' });
+ if (!created.ok) throw new Error(created.error);
+ // Project to-dos link on their first run, not at creation.
+ expect((await context.resolveConversationAssistanceForTurn('u1', conv.conversation_id)).guidance).toBe('');
+ await projectTasks.recordTaskExecution('u1', pid, created.task.id, conv.conversation_id);
+ const { guidance } = await context.resolveConversationAssistanceForTurn('u1', conv.conversation_id);
+ expect(guidance).not.toContain('## Keeping work going');
+ expect(guidance).toContain(`saved from this conversation: ${created.task.id}.`);
+ expect(guidance).not.toContain('Write the migration');
+ });
+
it('stops offering a project once the conversation has one or is on its way', async () => {
const chats = await import('../../../src/main/features/chats');
const projects = await import('../../../src/main/features/projects');
diff --git a/test/main/features/conversation-history-cache.test.ts b/test/main/features/conversation-history-cache.test.ts
index 14b9d870..1d998a15 100644
--- a/test/main/features/conversation-history-cache.test.ts
+++ b/test/main/features/conversation-history-cache.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
+import { createHash } from 'node:crypto';
const TEST_UID = 'history-cache-user';
@@ -74,6 +75,247 @@ afterEach(async () => {
});
describe('conversation history projection cache', () => {
+ it.each([0, 1001])('caches legacy native classification with %s process items across page boundaries without rewriting raw history', async count => {
+ const earlier = { ...message('native-0'), from: 'claude', text: 'Checking the files.',
+ turn_id: 'turn-native', source_message_id: 'user-1', seg: 0,
+ process: Array.from({ length: count }, (_, n) => ({ type: 'progress', text: `Operation ${n}` })) };
+ const final = { ...earlier, id: 'native-1', text: 'Final answer.', seg: 1,
+ process: [{ type: 'event', event: { stream: 'runtime', data: { phase: 'end', duration_ms: 12 } } }] };
+ writeRows([earlier, final]);
+ const original = fs.readFileSync(sourceFile, 'utf8');
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const first = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1);
+ expect(first.records[0]).toMatchObject({ display_phase: 'final_answer', text: 'Final answer.' });
+ const previous = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1, first.nextCursor!);
+ expect(previous.records[0]).toMatchObject({ display_phase: 'commentary', text: earlier.text });
+ const part = previous.records[0].process_parts?.[0];
+ const items = part && 'ref' in part
+ ? (await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 0, earlier.id)).items
+ : previous.records[0].process!;
+ expect(items[0]).toEqual({ type: 'progress', text: earlier.text,
+ event: { stream: 'assistant', data: { phase: 'commentary', native_segment: 0 } } });
+ expect(items.filter(item => item.type === 'progress' && item.text === earlier.text)).toHaveLength(1);
+ await (await import('../../../src/main/features/conversation-history-client')).closeConversationHistoryWorker();
+ expect((await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1)).records).toEqual(first.records);
+ expect(fs.readFileSync(sourceFile, 'utf8')).toBe(original);
+ });
+
+ it('does not classify unknown, live or Commander records from their prose', async () => {
+ const { projectConversationHistoryRecord } = await import('../../../src/main/features/conversation_history_cache');
+ for (const record of [message('ordinary'), { ...message(''), from: 'claude', seg: 0, turn_id: 't', source_message_id: 'u', process: [] },
+ { ...message('commander'), seg: 0, turn_id: 't', source_message_id: 'u', process: [] },
+ { ...message('unknown'), from: 'claude', seg: 0, turn_id: 't' }]) {
+ expect(projectConversationHistoryRecord(record as any, tmpDir)).toEqual(record);
+ }
+ });
+
+ it('bounds raw process-page bytes independently of event count and keeps the legacy content address', async () => {
+ const items = Array.from({ length: 401 }, (_, n) => ({ type: 'event', event: { stream: 'tool',
+ data: { phase: 'end', name: 'bash', id: `call-${n}`, output: `${n}:` + '界🌟'.repeat(9400) } } }));
+ const { storeProcessPages, readProcessPage, processCacheDirectory } = await import('../../../src/main/features/conversation-process-cache');
+ const expected = createHash('sha256');
+ for (let n = 0; n < items.length; n += 200) expected.update(JSON.stringify(items.slice(n, n + 200)) + '\n');
+ const part = storeProcessPages(tmpDir, items as any);
+ if (!('ref' in part)) throw new Error('Missing process reference');
+ expect(part.ref).toBe(expected.digest('hex'));
+ const directory = processCacheDirectory(tmpDir);
+ const indexFile = fs.readdirSync(directory).find(name => name.endsWith('.json'))!;
+ const index = JSON.parse(fs.readFileSync(path.join(directory, indexFile), 'utf8'));
+ for (let n = 0; n < index.offsets.length; n++) {
+ expect((index.offsets[n + 1] ?? index.bytes) - index.offsets[n]).toBeLessThanOrEqual(1024 * 1024);
+ }
+ const received: unknown[] = [];
+ let cursor: number | null = 0;
+ do {
+ const page = await readProcessPage(tmpDir, part.ref, cursor!);
+ expect(Buffer.byteLength(JSON.stringify(page.items))).toBeLessThanOrEqual(1024 * 1024);
+ received.push(...page.items); cursor = page.nextCursor;
+ } while (cursor !== null);
+ expect(received).toEqual(items);
+ });
+
+ it('externalizes an oversized real tool result before storing a bounded page and retains its full Unicode body', async () => {
+ const output = 'HEAD🌟\n' + '工具输出'.repeat(400_000) + '\nTAIL🌟';
+ const process = [
+ { type: 'event', event: { stream: 'tool', data: { phase: 'end', name: 'bash', id: 'huge-call', output } } },
+ ...Array.from({ length: 1000 }, (_, n) => ({ type: 'progress', text: `Event ${n}` })),
+ { type: 'event', event: { stream: 'runtime', data: { phase: 'end', duration_ms: 1200 } } },
+ ];
+ writeRows([message('huge', process)]);
+ const canonical = fs.readFileSync(sourceFile);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const history = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const part = history.records[0].process_parts![0];
+ if (!('ref' in part)) throw new Error('Missing process reference');
+ const first = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 0, 'huge');
+ expect(Buffer.byteLength(JSON.stringify(first))).toBeLessThanOrEqual(1024 * 1024);
+ const tool = (first.items[0] as any).event.data;
+ expect(tool.output).toBeUndefined();
+ expect(tool.id).toBe('huge-call');
+ expect(fs.readFileSync(tool.result_path, 'utf8')).toBe(output);
+ const directory = path.join(onlyCacheEntry(), 'process-records');
+ const indexFile = fs.readdirSync(directory).find(name => name.endsWith('.json'))!;
+ const index = JSON.parse(fs.readFileSync(path.join(directory, indexFile), 'utf8'));
+ expect(index.offsets.every((start: number, n: number) => (index.offsets[n + 1] ?? index.bytes) - start <= 1024 * 1024)).toBe(true);
+ expect(fs.readFileSync(sourceFile).equals(canonical)).toBe(true);
+ expect(history.records[0].process).toContainEqual(process.at(-1));
+ });
+
+ it('keeps native JSON content addresses across Unicode boundaries and cleans up rejected cyclic records', async () => {
+ const { storeProcessPages, processPageReference, readProcessPage, processCacheDirectory } = await import('../../../src/main/features/conversation-process-cache');
+ const items: any[] = Array.from({ length: 201 }, (_, n) => ({ type: 'progress', text: `${n}` }));
+ items[0] = { type: 'progress', text: 'x'.repeat(16 * 1024 - 1) + '🌟界\n\t"\\' + String.fromCharCode(0xd800),
+ nested: [undefined, NaN, Infinity, -0, { omit: undefined, escaped: '\b', boxed: new Number(7) }] };
+ items[200] = { toJSON(key: string) { return { type: 'progress', text: `JSON key ${key}` }; } };
+ const expected = createHash('sha256');
+ for (let n = 0; n < items.length; n += 200) expected.update(JSON.stringify(items.slice(n, n + 200)) + '\n');
+ const ref = expected.digest('hex');
+ expect(processPageReference(items)).toBe(ref);
+ expect(storeProcessPages(tmpDir, items)).toMatchObject({ ref, count: 201 });
+ expect((await readProcessPage(tmpDir, ref)).items).toEqual(JSON.parse(JSON.stringify(items.slice(0, 200))));
+ const cycle: any = {}; cycle.self = cycle;
+ expect(() => storeProcessPages(tmpDir, [cycle])).toThrow();
+ expect(fs.readdirSync(processCacheDirectory(tmpDir)).some(file => file.endsWith('.tmp'))).toBe(false);
+ });
+
+ it('rebuilds oversized legacy pages without changing legacy cursor meaning and resumes after cache clearing', async () => {
+ const items = Array.from({ length: 1001 }, (_, n) => ({ type: 'event', event: { stream: 'tool',
+ data: { phase: 'end', name: 'bash', id: `legacy-${n}`, output: `${n}:` + '界🌟'.repeat(1200) } } }));
+ writeRows([message('legacy', items)]);
+ const original = fs.readFileSync(sourceFile);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const history = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const part = history.records[0].process_parts![0];
+ if (!('ref' in part)) throw new Error('Missing process reference');
+ const entry = onlyCacheEntry();
+ const directory = path.join(entry, 'process-records');
+ fs.rmSync(directory, { recursive: true }); fs.mkdirSync(directory);
+ const lines = Array.from({ length: Math.ceil(items.length / 200) }, (_, n) => JSON.stringify(items.slice(n * 200, n * 200 + 200)) + '\n');
+ const offsets: number[] = []; let bytes = 0;
+ for (const line of lines) { offsets.push(bytes); bytes += Buffer.byteLength(line); }
+ fs.writeFileSync(path.join(directory, part.ref + '.jsonl'), lines.join(''));
+ fs.writeFileSync(path.join(directory, part.ref + '.json'), JSON.stringify({ offsets, bytes, count: items.length }));
+ const direct = await import('../../../src/main/features/conversation-process-cache');
+ await expect(direct.readProcessPage(entry, part.ref, 1)).rejects.toMatchObject({ code: 'E_PROCESS_PAGE_REBUILD' });
+ const second = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 1, 'legacy');
+ expect((second.items[0] as any).event.data.id).toBe('legacy-200');
+ expect(second.nextCursor).not.toBeNull();
+ const following = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, second.nextCursor!, 'legacy');
+ fs.rmSync(directory, { recursive: true });
+ expect(await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, second.nextCursor!, 'legacy')).toEqual(following);
+ const tail = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 5, 'legacy');
+ expect(tail.items).toHaveLength(1);
+ expect((tail.items[0] as any).event.data.id).toBe('legacy-1000');
+ expect(tail.nextCursor).toBeNull();
+ expect(fs.readFileSync(sourceFile).equals(original)).toBe(true);
+ });
+
+ it('keeps hidden oversized diagnostic groups navigable without disclosing their contents', async () => {
+ const hidden = { type: 'event', event: { stream: 'command_output', data: { output: 'secret'.repeat(180_000) } } };
+ const direct = await import('../../../src/main/features/conversation-process-cache');
+ const empty = direct.storeProcessPages(tmpDir, [hidden] as any, () => []);
+ if (!('ref' in empty)) throw new Error('Missing empty process reference');
+ expect(await direct.readProcessPage(tmpDir, empty.ref)).toEqual({ items: [], nextCursor: null });
+ writeRows([message('hidden', [hidden, ...Array.from({ length: 199 }, () => ({ type: 'event', event: { stream: 'usage', data: {} } })),
+ ...Array.from({ length: 801 }, (_, n) => ({ type: 'progress', text: `Visible ${n}` }))])]);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const history = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const part = history.records[0].process_parts![0];
+ if (!('ref' in part)) throw new Error('Missing process reference');
+ const first = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 0, 'hidden');
+ expect(first.items).toEqual([]);
+ expect(first.nextCursor).not.toBeNull();
+ const next = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, first.nextCursor!, 'hidden');
+ expect(next.items[0]).toEqual({ type: 'progress', text: 'Visible 0' });
+ }, 30_000);
+
+ it('opens a large process history with bounded first-paint data and pages every event in order', async () => {
+ const process = Array.from({ length: 1503 }, (_, index) => ({ type: 'event', event: { stream: 'tool',
+ data: { phase: 'end', name: 'bash', id: `call-${index}`, output: `Complete output ${index}` } } }));
+ const rows = [message('question'), message('large', process)];
+ writeRows(rows);
+ const original = fs.readFileSync(sourceFile, 'utf8');
+ const { readConversationHistoryPage, readConversationProcessPage } = await import('../../../src/main/features/conversation_history_cache');
+ const page = await readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ expect(page.records.map(record => record.text)).toEqual(['message question', 'message large']);
+ expect(Buffer.byteLength(JSON.stringify(page))).toBeLessThan(4096);
+ const part = page.records[1].process_parts![0];
+ expect(part).toMatchObject({ count: 1503, message_id: 'large' });
+ expect('ref' in part).toBe(true);
+ if (!('ref' in part)) throw new Error('Missing deferred process');
+ const received: unknown[] = [];
+ let cursor: number | null = 0;
+ do {
+ const details = await readConversationProcessPage(TEST_UID, sourceFile, part.ref, cursor!, 'large');
+ expect(details.items.length).toBeLessThanOrEqual(200);
+ received.push(...details.items);
+ cursor = details.nextCursor;
+ } while (cursor !== null);
+ expect(received).toEqual(process);
+ expect(fs.readFileSync(sourceFile, 'utf8')).toBe(original);
+ });
+
+ it('rebuilds a cleared process cache and refuses another source or malformed reference', async () => {
+ writeRows([message('large', Array.from({ length: 1001 }, (_, n) => ({ type: 'progress', text: `Event ${n}` })))]);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const first = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const part = first.records[0].process_parts![0];
+ if (!('ref' in part)) throw new Error('Missing deferred process');
+ await cache.purgeConversationHistoryCache(TEST_UID, sourceFile);
+ expect((await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 5, 'large')).items)
+ .toEqual([{ type: 'progress', text: 'Event 1000' }]);
+ const otherSource = path.join(tmpDir, 'other.jsonl');
+ fs.writeFileSync(otherSource, JSON.stringify(message('large')) + '\n');
+ await expect(cache.readConversationProcessPage(TEST_UID, otherSource, part.ref, 0, 'large')).rejects.toThrow();
+ await expect(cache.readConversationProcessPage(TEST_UID, sourceFile, '../outside', 0, 'large')).rejects.toThrow();
+ await expect(cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 99, 'large')).rejects.toThrow();
+ });
+
+ it('invalidates the legacy projection without reading it into first paint', async () => {
+ writeRows([message('latest')]);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const entry = onlyCacheEntry();
+ fs.rmSync(path.join(entry, 'latest-page-v6.json'));
+ fs.writeFileSync(path.join(entry, 'latest-page.json'), JSON.stringify({ version: 4, unrelated: 'x'.repeat(1024 * 1024) }));
+ fs.writeFileSync(path.join(entry, 'latest-page-v5.json'), JSON.stringify({ version: 5, unrelated: 'x'.repeat(1024 * 1024) }));
+ const next = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ expect(next.records.map(record => record.id)).toEqual(['latest']);
+ expect(fs.existsSync(path.join(entry, 'latest-page.json'))).toBe(false);
+ expect(fs.existsSync(path.join(entry, 'latest-page-v5.json'))).toBe(false);
+ expect(fs.statSync(path.join(entry, 'latest-page-v6.json')).size).toBeLessThan(4096);
+ });
+
+ it('keeps the answer available during a process-cache write failure and recovers its details', async () => {
+ writeRows([message('large', Array.from({ length: 1001 }, (_, n) => ({ type: 'progress', text: `Event ${n}` })))]);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ const entry = onlyCacheEntry();
+ await cache.purgeConversationHistoryCache(TEST_UID, sourceFile);
+ fs.mkdirSync(entry, { recursive: true });
+ fs.writeFileSync(path.join(entry, 'process-records'), 'Blocked cache fixture');
+ const page = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ expect(page.records[0].text).toBe('message large');
+ expect(Buffer.byteLength(JSON.stringify(page))).toBeLessThan(4096);
+ const part = page.records[0].process_parts![0];
+ if (!('ref' in part)) throw new Error('Missing deferred process');
+ fs.rmSync(path.join(entry, 'process-records'));
+ expect((await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, 5, 'large')).items)
+ .toEqual([{ type: 'progress', text: 'Event 1000' }]);
+ });
+
+ it('retains terminal and elapsed-time receipts when later bookkeeping has no duration', async () => {
+ const end = { type: 'event', event: { stream: 'runtime', data: { phase: 'end', duration_ms: 2000 } } };
+ const later = { type: 'event', event: { stream: 'runtime', data: { phase: 'bookkeeping' } } };
+ writeRows([message('large', [
+ ...Array.from({ length: 1001 }, (_, n) => ({ type: 'progress', text: `Event ${n}` })), end, later,
+ ])]);
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const page = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
+ expect(page.records[0].process).toEqual([end, later]);
+ expect(page.records[0].process_parts).toHaveLength(1);
+ });
+
it('caches only the requested tail page and moves large output behind lazy files', async () => {
const rows = Array.from({ length: 30 }, (_, index) => toolMessage(
`m${index + 1}`,
@@ -92,7 +334,7 @@ describe('conversation history projection cache', () => {
);
expect(page.nextCursor).not.toBeNull();
const cacheEntry = onlyCacheEntry();
- const latestPageFile = path.join(cacheEntry, 'latest-page.json');
+ const latestPageFile = path.join(cacheEntry, 'latest-page-v6.json');
const cached = JSON.parse(fs.readFileSync(latestPageFile, 'utf8'));
expect(cached.records).toHaveLength(10);
expect(fs.statSync(latestPageFile).size).toBeLessThan(canonicalBytes / 20);
@@ -125,7 +367,7 @@ describe('conversation history projection cache', () => {
const result = (page.records[0].process as any[])[0].event.data;
expect(result.output).toBeUndefined();
expect(result.outputPath).toBeUndefined();
- expect(fs.statSync(path.join(onlyCacheEntry(), 'latest-page.json')).size).toBeLessThan(4_000);
+ expect(fs.statSync(path.join(onlyCacheEntry(), 'latest-page-v6.json')).size).toBeLessThan(4_000);
const canonical = JSON.parse(fs.readFileSync(sourceFile, 'utf8').trim());
expect(canonical.process[0].event.data.output).toEqual(structuredOutput);
@@ -160,7 +402,7 @@ describe('conversation history projection cache', () => {
const extended = await readConversationHistoryPage(TEST_UID, sourceFile, 2);
expect(extended.records.map((record) => record.id)).toEqual(['m3', 'm4']);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v6.json'), 'utf8'));
expect(cached.records.map((entry: any) => entry.record.id)).toEqual(['m3', 'm4']);
});
@@ -193,7 +435,7 @@ describe('conversation history projection cache', () => {
expect(expanded.records.map((record) => record.id)).toEqual(
Array.from({ length: 8 }, (_, index) => `m${index + 5}`),
);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v6.json'), 'utf8'));
expect(cached.records).toHaveLength(8);
});
@@ -211,7 +453,7 @@ describe('conversation history projection cache', () => {
expect(whole.records.map((record) => record.id)).toEqual(
Array.from({ length: 30 }, (_, index) => `m${index + 1}`),
);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v6.json'), 'utf8'));
expect(cached.records).toHaveLength(10);
});
@@ -226,7 +468,7 @@ describe('conversation history projection cache', () => {
);
expect(pages.every((page) => page.records.length === 10)).toBe(true);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v6.json'), 'utf8'));
expect(cached.records).toHaveLength(10);
});
diff --git a/test/main/features/conversation-turn-index.test.ts b/test/main/features/conversation-turn-index.test.ts
index 31449307..0ec93cb3 100644
--- a/test/main/features/conversation-turn-index.test.ts
+++ b/test/main/features/conversation-turn-index.test.ts
@@ -62,7 +62,7 @@ it('preserves exact preview text across Unicode, math, Markdown and truncation b
const texts = ['', 'plain', '中文🌟e\u0301👨‍👩‍👧‍👦', '\\(x^2+y^2=z^2\\)\n$$\\frac{a}{b}$$',
'## [Useful link](https://example.com) ![image](image.png) <b>bold</b>',
'> quoted\n1. numbered\n- list\n```js\nconst n = 1;\n```', '[unclosed](\n<unfinished',
- ' \r\n\t ', ...[39, 40, 41, 79, 80, 81].flatMap(n => ['中', '🌟'].map(c => c.repeat(n))),
+ ' \r\n\t ', ...[99, 100, 101, 239, 240, 241].flatMap(n => ['中', '🌟'].map(c => c.repeat(n))),
'word '.repeat(400_000)];
const file = write('previews', texts.flatMap((text, i) => [user(`u${i}`, text), reply(text)]));
const turns: any[] = [];
@@ -74,8 +74,8 @@ it('preserves exact preview text across Unicode, math, Markdown and truncation b
} while (before !== undefined);
expect(turns.map(t => t.messageId)).toEqual(texts.map((_, i) => `u${i}`));
turns.forEach((turn, i) => {
- expect(turn.userPreview).toBe(legacyPreview(texts[i], 40));
- expect(turn.assistantPreview).toBe(legacyPreview(texts[i], 80));
+ expect(turn.userPreview).toBe(legacyPreview(texts[i], 100));
+ expect(turn.assistantPreview).toBe(legacyPreview(texts[i], 240));
expect(turn.messageIndex).toBe(i * 2);
});
});
@@ -137,7 +137,7 @@ it.each(['replace', 'truncate', 'unterminated', 'corrupt-index', 'old-version']
const page = await read(file);
expect(page.turns.map(t => t.messageId)).toEqual(mode === 'unterminated' ? ['old', 'new']
: mode === 'replace' || mode === 'truncate' ? ['new'] : ['old']);
- expect(JSON.parse(fs.readFileSync(indexPath('user', 'chat'), 'utf8')).version).toBe(2);
+ expect(JSON.parse(fs.readFileSync(indexPath('user', 'chat'), 'utf8')).version).toBe(3);
});
it('retries a moving source once and never publishes a repeatedly unstable scan', async () => {
diff --git a/test/main/features/project_files.test.ts b/test/main/features/project_files.test.ts
index 3cc0bb97..b9333063 100644
--- a/test/main/features/project_files.test.ts
+++ b/test/main/features/project_files.test.ts
@@ -8,6 +8,7 @@ import { makeMinimalPptx, makeMinimalXlsx } from '../../fixtures/make-minimal-of
let tmpDir: string;
let prevWs: string | undefined;
+
const enqueueCalls: Array<{ userId: string; projectId: string; name: string; op: string }> = [];
vi.mock('../../../src/main/features/projects', () => ({
diff --git a/test/main/features/projects.test.ts b/test/main/features/projects.test.ts
index ae0a47f9..e8d43a34 100644
--- a/test/main/features/projects.test.ts
+++ b/test/main/features/projects.test.ts
@@ -137,6 +137,7 @@ describe('projects › createProject', () => {
});
describe('projects › listProjects', () => {
+
it('sorts project display names alphabetically with natural number order', async () => {
const projects = await loadProjects();
for (const name of ['Zulu', 'Beta 10', 'alpha', 'Beta 2']) {
diff --git a/test/main/features/recycle-display.test.ts b/test/main/features/recycle-display.test.ts
index 2c57f12c..c741cd9f 100644
--- a/test/main/features/recycle-display.test.ts
+++ b/test/main/features/recycle-display.test.ts
@@ -21,6 +21,98 @@ afterEach(() => {
});
describe('recycle display preview', () => {
+ it('shows project automation names from their own configs and keeps attachments grouped', async () => {
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(UID);
+ const paths = await import('../../../src/main/paths');
+ const root = paths.userCloudRoot(UID);
+ const write = (rel: string, data: unknown) => {
+ const file = path.join(root, rel);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(data));
+ };
+ write('projects/p_launch/project.json', { project_id: 'p_launch', name: 'Client Launch' });
+ write('projects/p_launch/auto_tasks/at_report/config.json', { title: 'Weekly report', content: 'Prepare report' });
+ write('auto_tasks/at_report/config.json', { title: 'Unrelated global task' });
+ write('auto_tasks/at_personal/config.json', { content: 'Personal digest\nDetails' });
+ const { buildRecycleDisplayPreview } = await import('../../../src/main/features/recycle_bin');
+ const items = await buildRecycleDisplayPreview(UID, [
+ 'cloud/projects/p_launch/auto_tasks/at_report/config.json',
+ 'cloud/projects/p_launch/auto_tasks/at_report/attachments/input.txt',
+ 'cloud/auto_tasks/at_personal/config.json',
+ ]);
+ expect(items).toEqual([
+ { category: 'auto_task', id: 'at_report', title: 'Weekly report', detail: 'Client Launch',
+ path: 'cloud/projects/p_launch/auto_tasks/at_report/config.json' },
+ { category: 'auto_task', id: 'at_personal', title: 'Personal digest',
+ path: 'cloud/auto_tasks/at_personal/config.json' },
+ ]);
+ });
+
+ it('repairs legacy automation labels from archived configs without changing recovery data', async () => {
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(UID);
+ const paths = await import('../../../src/main/paths');
+ const batchId = 'legacy-automations';
+ const batchDir = path.join(paths.userRecycleDir(UID), batchId);
+ const configs = [
+ { path: 'cloud/projects/p_launch/auto_tasks/at_report/config.json', title: 'Archived report', project: 'p_launch' },
+ { path: 'cloud/auto_tasks/at_digest/config.json', title: 'Archived digest', project: 'p_launch' },
+ ];
+ for (const config of configs) {
+ const file = path.join(batchDir, 'files', config.path.slice('cloud/'.length));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify({ title: config.title, project_id: config.project }));
+ }
+ const raw = {
+ id: batchId, source: 'cloud_sync', reason: 'remote_tombstone', created_at_ms: 1,
+ items: configs.map(config => ({ path: config.path, size: 30 })),
+ metadata: { project_rows: [{ project_id: 'p_launch', name: 'Client Launch' }] },
+ display_items: ['at_report', 'at_digest'].map(id => ({
+ category: 'auto_task', id, title: id, path: `cloud/auto_tasks/${id}/config.json`,
+ })),
+ };
+ const metaFile = path.join(batchDir, 'batch.json');
+ fs.writeFileSync(metaFile, JSON.stringify(raw));
+ const original = fs.readFileSync(metaFile, 'utf8');
+ const { listRecycleBatches } = await import('../../../src/main/features/recycle_bin');
+ const [batch] = await listRecycleBatches(UID);
+ expect(batch.display_items).toEqual([
+ { category: 'auto_task', id: 'at_report', title: 'Archived report', detail: 'Client Launch', path: configs[0].path },
+ { category: 'auto_task', id: 'at_digest', title: 'Archived digest', detail: 'Client Launch', path: configs[1].path },
+ ]);
+ expect(batch.items).toEqual(raw.items);
+ expect(batch.metadata).toEqual(raw.metadata);
+ expect(fs.readFileSync(metaFile, 'utf8')).toBe(original);
+ });
+
+ it.each([null, '{}', '{broken'])('keeps a cached automation name when its archived config has no readable title (%s)', async (archivedConfig) => {
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(UID);
+ const paths = await import('../../../src/main/paths');
+ const batchDir = path.join(paths.userRecycleDir(UID), 'missing-automation');
+ fs.mkdirSync(batchDir, { recursive: true });
+ fs.writeFileSync(path.join(batchDir, 'batch.json'), JSON.stringify({
+ id: 'missing-automation', source: 'app', reason: 'app_delete', created_at_ms: 1,
+ items: [{ path: 'cloud/projects/p_launch/auto_tasks/at_report/config.json', size: 10 }],
+ display_items: [{ category: 'auto_task', id: 'at_report', title: 'Saved task name',
+ path: 'cloud/auto_tasks/at_report/config.json' }],
+ }));
+ const live = path.join(paths.userCloudRoot(UID), 'projects/p_launch/auto_tasks/at_report/config.json');
+ fs.mkdirSync(path.dirname(live), { recursive: true });
+ fs.writeFileSync(live, JSON.stringify({ title: 'Different task created later' }));
+ if (archivedConfig !== null) {
+ const archived = path.join(batchDir, 'files/projects/p_launch/auto_tasks/at_report/config.json');
+ fs.mkdirSync(path.dirname(archived), { recursive: true });
+ fs.writeFileSync(archived, archivedConfig);
+ }
+ const { listRecycleBatches } = await import('../../../src/main/features/recycle_bin');
+ const [batch] = await listRecycleBatches(UID);
+ expect(batch.display_items?.[0]).toEqual(expect.objectContaining({
+ title: 'Saved task name', path: 'cloud/projects/p_launch/auto_tasks/at_report/config.json',
+ }));
+ });
+
it('shows skill edit chats as edit conversations and skills as skills', async () => {
const users = await import('../../../src/main/features/users');
users.activateUser(UID);
diff --git a/test/main/features/recycle_bin.test.ts b/test/main/features/recycle_bin.test.ts
index 57b62b4b..2775d53f 100644
--- a/test/main/features/recycle_bin.test.ts
+++ b/test/main/features/recycle_bin.test.ts
@@ -80,6 +80,31 @@ afterEach(async () => {
});
describe('global recycle bin', () => {
+ it('permanently deletes only the selected archive while preserving live data and other accounts', async () => {
+ const paths = await import('../../../src/main/paths');
+ const recycle = await import('../../../src/main/features/recycle_bin');
+ const relPath = 'cloud/contexts/note.txt';
+ const seed = async (uid: string, text: string) => {
+ const source = path.join(paths.userCloudRoot(uid), 'contexts', 'note.txt');
+ await fsp.mkdir(path.dirname(source), { recursive: true });
+ await fsp.writeFile(source, text);
+ const batch = await recycle.createAppRecycleBatchForCloudEntry(uid, relPath, 'context');
+ if (!batch) throw new Error('archive creation failed');
+ return { source, batch };
+ };
+ const selected = await seed(UID, 'selected original');
+ const retained = await seed(UID, 'current live content');
+ const other = await seed('other-account', 'other account content');
+
+ expect(await recycle.deleteRecycleBatch(UID, selected.batch.id)).toEqual({ deleted: true });
+ expect(fs.existsSync(path.join(paths.userRecycleDir(UID), selected.batch.id))).toBe(false);
+ expect((await recycle.listRecycleBatches(UID)).map(batch => batch.id)).toEqual([retained.batch.id]);
+ expect(await fsp.readFile(selected.source, 'utf8')).toBe('current live content');
+ expect((await recycle.listRecycleBatches('other-account')).map(batch => batch.id)).toEqual([other.batch.id]);
+ expect(await fsp.readFile(other.source, 'utf8')).toBe('other account content');
+ expect(await recycle.deleteRecycleBatch(UID, selected.batch.id)).toEqual({ deleted: false });
+ });
+
it.each(['app-file', 'app-directory', 'sync-file'] as const)(
'rejects an ancestor symlink before a %s archive can import outside data',
async (entry) => {
diff --git a/test/main/features/task-cleanup.test.ts b/test/main/features/task-cleanup.test.ts
new file mode 100644
index 00000000..417e4546
--- /dev/null
+++ b/test/main/features/task-cleanup.test.ts
@@ -0,0 +1,245 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+const mocks = vi.hoisted(() => ({ rows: [] as any[], quiet: true,
+ archive: vi.fn(), remove: vi.fn(), discard: vi.fn() }));
+vi.mock('../../../src/main/features/chats', () => ({
+ listCleanupConversationRows: async () => mocks.rows,
+ getConversationMetadata: async (_uid: string, cid: string) => mocks.rows.find(r => r.conversation_id === cid) || null,
+ deleteConversation: (...args: any[]) => mocks.remove(...args),
+}));
+vi.mock('../../../src/main/features/group_chat/bus', () => ({ isQuiescent: () => mocks.quiet }));
+vi.mock('../../../src/main/features/recycle_bin', () => ({
+ createAppRecycleBatchForConversation: (...args: any[]) => mocks.archive(...args),
+ deleteRecycleBatch: (...args: any[]) => mocks.discard(...args),
+}));
+let root: string;
+let previous: string | undefined;
+const uid = 'cleanup-user';
+const old = '2020-01-01T00:00:00Z';
+async function seed(cid = 'old-done', updates: any = {}, status = 'done') {
+ const { conversationLayout } = await import('../../../src/main/util/project-layout');
+ if (updates.project_id) {
+ const { projectMetaFile } = await import('../../../src/main/paths');
+ const file = projectMetaFile(uid, updates.project_id);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify({ project_id: updates.project_id, name: 'Fixture project' }));
+ }
+ const layout = conversationLayout(uid, cid, updates.project_id || null);
+ fs.mkdirSync(path.dirname(layout.stateFile), { recursive: true });
+ fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'idle', in_flight: [], last_active_at: old }));
+ fs.writeFileSync(path.join(path.dirname(layout.stateFile), 'tasks.json'), JSON.stringify([
+ { task_id: 't1', created_by: 'user', source_msg_id: 'm1', created_at: old, ended_at: old, status },
+ ]));
+ const row = { conversation_id: cid, title: cid, kind: 'normal', created_at: old, updated_at: old, ...updates };
+ mocks.rows.push(row);
+ return { row, layout };
+}
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-cleanup-'));
+ previous = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = root;
+ vi.resetModules(); vi.clearAllMocks(); mocks.rows = []; mocks.quiet = true;
+ mocks.archive.mockResolvedValue({ id: 'backup', items: [{ path: 'history' }] });
+ mocks.discard.mockResolvedValue(undefined);
+ mocks.remove.mockImplementation(async (_uid, cid, _hint, guard) => {
+ const row = mocks.rows.find(r => r.conversation_id === cid);
+ if (!await guard(row)) return false;
+ mocks.rows = mocks.rows.filter(r => r !== row);
+ return true;
+ });
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ try {
+ // Let pending file-handle callbacks run between Windows cleanup retries.
+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ } finally {
+ if (previous === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previous;
+ }
+});
+
+describe('safe historical task cleanup', () => {
+ it('keeps corrupt state and a recent completion even when its index is stale', async () => {
+ const corrupt = await seed('corrupt');
+ fs.writeFileSync(corrupt.layout.stateFile, '{');
+ const recent = await seed('recent-result');
+ fs.writeFileSync(path.join(path.dirname(recent.layout.stateFile), 'tasks.json'), JSON.stringify([
+ { created_by: 'user', created_at: old, status: 'done', ended_at: new Date().toISOString() },
+ ]));
+ const api = await import('../../../src/main/features/task_cleanup');
+ expect((await api.preview(uid, { days: 90, protectedIds: [] })).total).toBe(0);
+ });
+ it('keeps a failed sibling of the latest user request while allowing an older recovered failure', async () => {
+ const first = await seed('mixed');
+ const second = await seed('recovered');
+ const prior = { created_by: 'user', source_msg_id: 'prior', created_at: '2019-01-01', ended_at: old, status: 'failed' };
+ const done = { created_by: 'user', source_msg_id: 'latest', created_at: old, ended_at: old, status: 'done' };
+ fs.writeFileSync(path.join(path.dirname(first.layout.stateFile), 'tasks.json'), JSON.stringify([done, { ...done, status: 'failed' }]));
+ fs.writeFileSync(path.join(path.dirname(second.layout.stateFile), 'tasks.json'), JSON.stringify([prior, done]));
+ const api = await import('../../../src/main/features/task_cleanup');
+ expect((await api.preview(uid, { days: 90, protectedIds: [] })).rows.map(r => r.cid)).toEqual(['recovered']);
+ });
+ it('expires previews and never uses an old receipt after restart or expiry', async () => {
+ await seed(); const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ const now = Date.now(); vi.spyOn(Date, 'now').mockReturnValue(now + 31 * 60 * 1000);
+ expect(() => api.page(uid, p.token, 0)).toThrow('cleanup_preview_expired');
+ await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow('cleanup_preview_expired');
+ expect(mocks.archive).not.toHaveBeenCalled();
+ });
+ it('selects old completed tasks inside and outside projects, retaining protected and uncertain work', async () => {
+ await seed();
+ await seed('pinned', { pinned_at: old }); await seed('project', { project_id: 'p1' });
+ await seed('auto', { origin_auto_task_id: 'a1' }); await seed('edit', { kind: 'edit' });
+ await seed('recent', { updated_at: new Date().toISOString() });
+ await seed('unread'); await seed('draft');
+ for (const status of ['failed', 'stopped', 'waiting_input', 'queued', 'running', 'blocked', 'cancelled']) await seed(status, {}, status);
+ const unknown = await seed('unknown'); fs.unlinkSync(path.join(path.dirname(unknown.layout.stateFile), 'tasks.json'));
+ const api = await import('../../../src/main/features/task_cleanup');
+ const preview = await api.preview(uid, { days: 90, protectedIds: ['unread', 'draft'] });
+ expect(preview.total).toBe(2); expect(preview.rows.map(r => r.cid)).toEqual(['old-done', 'project']);
+ expect(mocks.archive).not.toHaveBeenCalled(); expect(mocks.remove).not.toHaveBeenCalled();
+ });
+ it('deletes a completed project task using its frozen project membership', async () => {
+ await seed('project-done', { project_id: 'p1' });
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ expect(p.rows[0]).toMatchObject({ cid: 'project-done', projectId: 'p1' });
+ expect(await api.remove(uid, p.token, 'project-done')).toEqual({ status: 'deleted' });
+ expect(mocks.remove).toHaveBeenCalledWith(uid, 'project-done', 'p1', expect.any(Function));
+ });
+ it('protects project task drafts, unread, pinned, automated and unfinished work', async () => {
+ for (const status of ['failed', 'stopped', 'running', 'queued', 'waiting_input']) await seed(status, { project_id: 'p1' }, status);
+ await seed('pinned-project', { project_id: 'p1', pinned_at: old });
+ await seed('auto-project', { project_id: 'p1', origin_auto_task_id: 'a1' });
+ await seed('unread-project', { project_id: 'p1' }); await seed('draft-project', { project_id: 'p1' });
+ const api = await import('../../../src/main/features/task_cleanup');
+ expect((await api.preview(uid, { days: 90, protectedIds: ['unread-project', 'draft-project'] })).total).toBe(0);
+ });
+ it.each([null, 'p2'])('skips a project task relocated to %s after preview', async projectId => {
+ const { row } = await seed('moved-project', { project_id: 'p1' });
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ row.project_id = projectId;
+ expect(await api.remove(uid, p.token, 'moved-project')).toEqual({ status: 'skipped' });
+ expect(mocks.archive).not.toHaveBeenCalled();
+ });
+ it.each([30, 90, 180])('uses the exact %i-day cutoff for every activity source, independent of timezone and file mtime', async days => {
+ const now = Date.parse('2026-10-16T14:10:00Z');
+ vi.spyOn(Date, 'now').mockReturnValue(now);
+ const expected: string[] = [];
+ // A recent index, runtime activity, or completion must independently
+ // protect the task, even if all its other timestamps are stale.
+ for (const field of ['created_at', 'updated_at', 'last_active_at', 'ended_at']) {
+ for (const delta of [-1, 0, 1]) {
+ const cid = `${field}-${delta + 1}`;
+ const { row, layout } = await seed(cid);
+ const timestamp = new Date(now - days * 86400000 + delta + 8 * 3600000)
+ .toISOString().replace('Z', '+08:00');
+ if (field === 'created_at' || field === 'updated_at') row[field] = timestamp;
+ else if (field === 'last_active_at') {
+ const state = JSON.parse(fs.readFileSync(layout.stateFile, 'utf8'));
+ fs.writeFileSync(layout.stateFile, JSON.stringify({ ...state, last_active_at: timestamp }));
+ } else {
+ const file = path.join(path.dirname(layout.stateFile), 'tasks.json');
+ const tasks = JSON.parse(fs.readFileSync(file, 'utf8'));
+ tasks[0].ended_at = timestamp;
+ fs.writeFileSync(file, JSON.stringify(tasks));
+ }
+ if (delta < 0) expected.push(cid);
+ }
+ }
+ const api = await import('../../../src/main/features/task_cleanup');
+ const preview = await api.preview(uid, { days, protectedIds: [] });
+ expect(preview.rows.map(r => r.cid).sort()).toEqual(expected.sort());
+ expect(preview.total).toBe(4);
+ expect(mocks.archive).not.toHaveBeenCalled();
+ expect(mocks.remove).not.toHaveBeenCalled();
+ });
+ it('paginates a fixed preview and never adds later arrivals to its deletion scope', async () => {
+ for (let i = 0; i < 25; i++) await seed(`task-${String(i).padStart(2, '0')}`);
+ const api = await import('../../../src/main/features/task_cleanup');
+ const preview = await api.preview(uid, { days: 30, protectedIds: [] });
+ await seed('new-arrival');
+ expect(preview.rows).toHaveLength(20); expect(preview.total).toBe(25);
+ expect(api.page(uid, preview.token, 20).rows).toHaveLength(5);
+ await expect(api.remove(uid, preview.token, 'new-arrival')).rejects.toThrow();
+ expect(mocks.archive).not.toHaveBeenCalled();
+ });
+ it.each(['pinned', 'recent', 'project', 'running', 'waiting'])('skips a task changed to %s during its backup', async change => {
+ const { row, layout } = await seed();
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ mocks.archive.mockImplementationOnce(async () => {
+ if (change === 'pinned') row.pinned_at = old;
+ if (change === 'recent') row.updated_at = new Date().toISOString();
+ if (change === 'project') row.project_id = 'p1';
+ if (change === 'running') mocks.quiet = false;
+ if (change === 'waiting') fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'idle', in_flight: [], orchestration_ledger: {} }));
+ return { id: 'backup', items: [{}] };
+ });
+ expect(await api.remove(uid, p.token, 'old-done')).toEqual({ status: 'skipped' });
+ expect(mocks.rows).toHaveLength(1);
+ });
+ it('keeps the source when backup fails, then permits retry', async () => {
+ await seed(); const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ mocks.archive.mockRejectedValueOnce(new Error('backup unavailable'));
+ await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow();
+ expect(mocks.remove).not.toHaveBeenCalled(); expect(mocks.rows).toHaveLength(1);
+ expect(await api.remove(uid, p.token, 'old-done')).toEqual({ status: 'deleted' });
+ expect(await api.remove(uid, p.token, 'old-done')).toEqual({ status: 'skipped' });
+ expect(mocks.archive).toHaveBeenCalledTimes(2);
+ });
+ it.each([null, 'p1'])('keeps a newly attached unsent file during backup in project %s', async projectId => {
+ const { row } = await seed('new-attachment', projectId ? { project_id: projectId } : {});
+ const api = await import('../../../src/main/features/task_cleanup');
+ const { chatAttachmentDirForConversation } = await import('../../../src/main/util/project-layout');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ const dir = chatAttachmentDirForConversation(uid, row.conversation_id);
+ mocks.archive.mockImplementationOnce(async () => {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'draft.txt'), 'New unsent work');
+ return { id: 'backup', items: [{}] };
+ });
+ expect(await api.remove(uid, p.token, row.conversation_id)).toEqual({ status: 'skipped' });
+ expect(mocks.rows).toHaveLength(1);
+ expect(fs.readFileSync(path.join(dir, 'draft.txt'), 'utf8')).toBe('New unsent work');
+ expect(mocks.discard).toHaveBeenCalledWith(uid, 'backup');
+ // The rejected receipt cannot delete the task on a duplicate delivery.
+ expect(await api.remove(uid, p.token, row.conversation_id)).toEqual({ status: 'skipped' });
+ expect(mocks.archive).toHaveBeenCalledTimes(1);
+ });
+ it('retains the backup after a deletion failure', async () => {
+ await seed(); const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ mocks.remove.mockRejectedValueOnce(new Error('delete unavailable'));
+ await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow();
+ expect(mocks.discard).not.toHaveBeenCalled();
+ });
+ it('rejects cross-account, stale and invalid requests without mutation', async () => {
+ await seed(); const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ await expect(api.remove('other', p.token, 'old-done')).rejects.toThrow();
+ await expect(api.preview(uid, { days: -1, protectedIds: [] })).rejects.toThrow();
+ await expect(api.preview(uid, { days: 90, protectedIds: ['../escape'] })).rejects.toThrow();
+ await api.preview(uid, { days: 180, protectedIds: [] });
+ expect(() => api.page(uid, p.token, 0)).toThrow();
+ expect(mocks.archive).not.toHaveBeenCalled();
+ });
+ it('rejects concurrent duplicate deletion while a backup is in progress', async () => {
+ await seed(); const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 90, protectedIds: [] });
+ let finish!: (v: any) => void;
+ mocks.archive.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const first = api.remove(uid, p.token, 'old-done');
+ for (let i = 0; i < 20 && !finish; i++) await new Promise(resolve => setTimeout(resolve, 5));
+ await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow();
+ finish({ id: 'backup', items: [{}] }); await first;
+ expect(mocks.archive).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/test/main/ipc/conversation-delete-recycle.test.ts b/test/main/ipc/conversation-delete-recycle.test.ts
index aae227dd..8e6bc6be 100644
--- a/test/main/ipc/conversation-delete-recycle.test.ts
+++ b/test/main/ipc/conversation-delete-recycle.test.ts
@@ -64,6 +64,16 @@ describe('conversations.delete recycle transaction', () => {
const recycleBin = await import('../../../src/main/features/recycle_bin');
const conv = await chats.createConversation(TEST_UID, { title: 'Delete during stop' });
const cid = conv.conversation_id;
+ // A stale Settings page cannot preview or mutate the newly active account.
+ for (const action of ['preview', 'page', 'remove']) {
+ const result = await invoke(`conversations.cleanup.${action}`, {
+ expectedUserId: 'previous-account', days: 90, protectedIds: [], token: 'stale', offset: 0, cid,
+ });
+ expect(result).toMatchObject({ ok: false, error: 'cleanup_account_changed' });
+ }
+ expect(await chats.getConversationMetadata(TEST_UID, cid)).not.toBeNull();
+ expect(await recycleBin.listRecycleBatches(TEST_UID)).toEqual([]);
+
const chatFile = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
const groupDir = paths.groupChatDir(TEST_UID, cid);
const stateFile = path.join(groupDir, 'state.json');
diff --git a/test/main/ipc/conversations-history-timing.test.ts b/test/main/ipc/conversations-history-timing.test.ts
index 60a804f1..4b69a0bd 100644
--- a/test/main/ipc/conversations-history-timing.test.ts
+++ b/test/main/ipc/conversations-history-timing.test.ts
@@ -26,6 +26,8 @@ function setup() {
chats: {
getConversationMetadata: vi.fn(async () => { clock = 100; return { project_id: null }; }),
getMessagesPage: vi.fn(() => history),
+ getMessagesPageAtIndex: vi.fn(() => history),
+ getMessagesPageAtMessageId: vi.fn(async () => null),
},
groupChat: { runtimeStatus: vi.fn(() => runtime), displaySnapshot: vi.fn(async () => ({ sequence: 7, turns: [] })) },
};
@@ -86,3 +88,81 @@ describe('conversation history latency diagnostics', () => {
expect(s.context.groupChat.displaySnapshot).not.toHaveBeenCalled();
});
});
+
+// A quoted reference knows only the stable id of its original message. The
+// renderer asks for the page around that id, which the history worker finds
+// and reads in one pass (never a scan on main); the index-based anchor remains
+// the search/turn-navigation contract and must not pay for an id scan.
+function anchorSetup(found: boolean, indexedId = 'm23') {
+ const latest = { history: [{ id: 'latest' }], nextCursor: 40, followingCursor: null };
+ const indexed = {
+ history: [{ id: indexedId }], historyIndexes: [23], nextCursor: 10, followingCursor: 30, pageStart: 20,
+ };
+ const quoted = {
+ history: [{ id: 'm23' }], historyIndexes: [41], nextCursor: 35, followingCursor: 50, pageStart: 40, messageIndex: 41,
+ };
+ const context = {
+ performance: { now: () => 0 },
+ safeId: () => true,
+ conversationProjectHint: () => null,
+ isAgentEnabled: () => true,
+ log: { info: vi.fn() },
+ chats: {
+ getConversationMetadata: vi.fn(async () => ({ project_id: null })),
+ getMessagesPage: vi.fn(async () => latest),
+ getMessagesPageAtIndex: vi.fn(async () => indexed),
+ getMessagesPageAtMessageId: vi.fn(async () => (found ? quoted : null)),
+ },
+ groupChat: { runtimeStatus: vi.fn(async () => ({ processing: false })), displaySnapshot: vi.fn() },
+ };
+ const handler = vm.runInNewContext(`(${handlerSource})`, context);
+ return { context, handler, latest, indexed, quoted };
+}
+
+describe('conversation history anchored on a quoted message id', () => {
+ it('positions the page on the quoted message with one id read when only its id is known', async () => {
+ const s = anchorSetup(true);
+ const result = await s.handler({ cid: 'c1', around_message_id: 'm23' }, { userId: 'u1' });
+ expect(s.context.chats.getMessagesPageAtMessageId).toHaveBeenCalledExactlyOnceWith('u1', 'c1', 'm23', 10, null);
+ expect(s.context.chats.getMessagesPageAtIndex).not.toHaveBeenCalled();
+ expect(s.context.chats.getMessagesPage).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ history: s.quoted.history,
+ page_start: 40,
+ history_indexes: [41],
+ next_cursor: 35,
+ following_cursor: 50,
+ });
+ });
+
+ it('falls back to the latest page when the quoted message no longer exists', async () => {
+ const s = anchorSetup(false);
+ const result = await s.handler({ cid: 'c1', around_message_id: 'gone' }, { userId: 'u1' });
+ expect(s.context.chats.getMessagesPageAtIndex).not.toHaveBeenCalled();
+ expect(s.context.chats.getMessagesPage).toHaveBeenCalledOnce();
+ expect(result.history).toEqual(s.latest.history);
+ expect(result).not.toHaveProperty('page_start');
+ expect(result).not.toHaveProperty('history_indexes');
+ });
+
+ it('keeps an indexed anchor on its direct page read without scanning for the id', async () => {
+ const s = anchorSetup(true);
+ const result = await s.handler(
+ { cid: 'c1', around_index: 23, around_message_id: 'm23' }, { userId: 'u1' },
+ );
+ expect(s.context.chats.getMessagesPageAtMessageId).not.toHaveBeenCalled();
+ expect(s.context.chats.getMessagesPageAtIndex).toHaveBeenCalledExactlyOnceWith('u1', 'c1', 23, 10, null);
+ expect(result).toMatchObject({ page_start: 20, history_indexes: [23] });
+ });
+
+ // Sync can rewrite or reorder the source after a search index was taken.
+ it('repairs a stale indexed anchor with one id read', async () => {
+ const s = anchorSetup(true, 'someone-else');
+ const result = await s.handler(
+ { cid: 'c1', around_index: 23, around_message_id: 'm23' }, { userId: 'u1' },
+ );
+ expect(s.context.chats.getMessagesPageAtIndex).toHaveBeenCalledExactlyOnceWith('u1', 'c1', 23, 10, null);
+ expect(s.context.chats.getMessagesPageAtMessageId).toHaveBeenCalledExactlyOnceWith('u1', 'c1', 'm23', 10, null);
+ expect(result).toMatchObject({ history: s.quoted.history, page_start: 40, history_indexes: [41] });
+ });
+});
diff --git a/test/main/ipc/conversations-process-page.test.ts b/test/main/ipc/conversations-process-page.test.ts
new file mode 100644
index 00000000..2e597d2f
--- /dev/null
+++ b/test/main/ipc/conversations-process-page.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+
+const source = fs.readFileSync(path.join(__dirname, '../../../src/main/ipc/index.ts'), 'utf8');
+const marker = "'conversations.processPage': ";
+const handlerSource = source.slice(source.indexOf(marker) + marker.length, source.indexOf("'conversations.history':"))
+ .trim().replace(/,$/, '');
+function harness(exists = true) {
+ const chats = {
+ getConversationMetadata: vi.fn(async () => exists ? { project_id: 'actual-owner' } : null),
+ getConversationProcessPage: vi.fn(async () => ({ items: [{ type: 'progress', text: 'Visible event' }], nextCursor: 2 })),
+ };
+ const handler = vm.runInNewContext(`(${handlerSource})`, {
+ chats, safeId: (v: unknown) => typeof v === 'string' && /^[a-zA-Z0-9_-]+$/.test(v),
+ conversationProjectHint: (v: any) => v.project_id,
+ });
+ return { handler, chats };
+}
+const input = { cid: 'conversation', message_id: 'message', ref: 'a'.repeat(64), cursor: 1, project_id: 'stale-owner' };
+
+describe('conversation process disclosure authority', () => {
+ it('resolves the active account and actual conversation owner before reading a page', async () => {
+ const { handler, chats } = harness();
+ expect(await handler(input, { userId: 'current-account' })).toMatchObject({ next_cursor: 2 });
+ expect(chats.getConversationProcessPage).toHaveBeenCalledExactlyOnceWith(
+ 'current-account', 'conversation', input.ref, 1, 'message', 'actual-owner');
+ });
+ it.each([{ cid: '../another' }, { ref: '../outside' }, { message_id: '' }, { cursor: -1 }, { cursor: 0.5 }, { cursor: 'bad' }])(
+ 'rejects an invalid disclosure without reading state (%j)', async invalid => {
+ const { handler, chats } = harness();
+ await expect(handler({ ...input, ...invalid }, { userId: 'account' })).rejects.toThrow();
+ expect(chats.getConversationMetadata).not.toHaveBeenCalled();
+ expect(chats.getConversationProcessPage).not.toHaveBeenCalled();
+ });
+ it('does not serve cached details for an unavailable or deleted conversation', async () => {
+ const { handler, chats } = harness(false);
+ await expect(handler(input, { userId: 'other-account' })).rejects.toThrow('conversation not found');
+ expect(chats.getConversationProcessPage).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/main/ipc/home-continuation.test.ts b/test/main/ipc/home-continuation.test.ts
new file mode 100644
index 00000000..eb7817ec
--- /dev/null
+++ b/test/main/ipc/home-continuation.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+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(),
+ dropChatConversation: vi.fn(),
+ invalidateChatDisplayCatalog: vi.fn(),
+}));
+
+let tmpDir: string;
+let previousWorkspace: string | undefined;
+const TEST_UID = 'uHomeContinuation';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-home-continuation-'));
+ previousWorkspace = 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(() => {
+ vi.useRealTimers();
+ if (previousWorkspace === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspace;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function invoke(channel: string, payload: Record<string, unknown>): 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();
+ return call[1]({ sender: trustedIpcSender() }, { channel, payload });
+}
+
+/** Each write gets its own clock so "most recently updated" is deterministic. */
+async function at<T>(iso: string, write: () => Promise<T>): Promise<T> {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date(iso));
+ try {
+ return await write();
+ } finally {
+ vi.useRealTimers();
+ }
+}
+
+describe('projects.tasks.listOpen', () => {
+ it('lists unfinished to-dos across the global scope and every project, newest first', async () => {
+ const projects = await import('../../../src/main/features/projects');
+ const tasks = await import('../../../src/main/features/project_tasks');
+ const created = await projects.createProject(TEST_UID, 'Growth');
+ if (!created.ok) throw new Error('createProject failed');
+ const pid = created.project.project_id;
+
+ const globalTodo = await at('2026-10-01T08:00:00.000Z', () => tasks.createTask(TEST_UID, '', { content: 'Global follow-up' }));
+ const projectTodo = await at('2026-10-02T08:00:00.000Z', () => tasks.createTask(TEST_UID, pid, { content: 'Project review', status: 'review' }));
+ const finished = await at('2026-10-03T08:00:00.000Z', () => tasks.createTask(TEST_UID, pid, { content: 'Already shipped', status: 'done' }));
+ const older = await at('2026-09-30T08:00:00.000Z', () => tasks.createTask(TEST_UID, pid, { content: 'Older project to-do' }));
+ for (const result of [globalTodo, projectTodo, finished, older]) expect(result.ok).toBe(true);
+
+ const res = await invoke('projects.tasks.listOpen', { limit: 3 });
+ expect(res.ok).toBe(true);
+ expect(res.total).toBe(3);
+ expect(res.tasks.map((task: any) => [task.project_id, task.project_name, task.status])).toEqual([
+ [pid, 'Growth', 'review'],
+ ['', '', 'todo'],
+ [pid, 'Growth', 'todo'],
+ ]);
+ });
+
+ it('caps the rows but still reports how many unfinished to-dos exist', async () => {
+ const tasks = await import('../../../src/main/features/project_tasks');
+ for (let i = 0; i < 5; i += 1) {
+ const result = await at(`2026-10-0${i + 1}T08:00:00.000Z`, () => tasks.createTask(TEST_UID, '', { content: `Item ${i}` }));
+ expect(result.ok).toBe(true);
+ }
+ const res = await invoke('projects.tasks.listOpen', { limit: 3 });
+ expect(res.tasks).toHaveLength(3);
+ expect(res.total).toBe(5);
+ expect(res.tasks[0].updated_at > res.tasks[1].updated_at).toBe(true);
+ });
+
+ // The home page repeats this listing on every visit and, while visible, on
+ // task events; to-dos only accumulate. Unchanged to-do files must not be
+ // re-read, and every way a to-do file changes must show on the next call.
+ it('re-reads only changed to-do files and still sees edits, synced copies, rewrites and deletions', async () => {
+ const tasks = await import('../../../src/main/features/project_tasks');
+ const paths = await import('../../../src/main/paths');
+ const ids: string[] = [];
+ for (let i = 0; i < 4; i += 1) {
+ const result = await at(`2026-10-0${i + 1}T08:00:00.000Z`, () => tasks.createTask(TEST_UID, '', {
+ content: `Item ${i}`, ...(i === 3 ? { status: 'done' } : {}),
+ }));
+ if (!result.ok) throw new Error('createTask failed');
+ ids.push(result.task.id);
+ }
+ const file = (i: number) => paths.userTaskFile(TEST_UID, ids[i]);
+ const list = async () => invoke('projects.tasks.listOpen', { limit: 20 });
+ const open = (res: any) => res.tasks.map((task: any) => task.content).sort();
+ const first = await list();
+ expect(open(first)).toEqual(['Item 0', 'Item 1', 'Item 2']);
+
+ const realRead = fs.promises.readFile;
+ const reads: string[] = [];
+ const spy = vi.spyOn(fs.promises, 'readFile').mockImplementation(async (...args: any[]) => {
+ if (/[\\/]t_[^\\/]+\.json$/.test(String(args[0]))) reads.push(String(args[0]));
+ return (realRead as any).apply(fs.promises, args);
+ });
+ syncBuiltinESMExports();
+ try {
+ expect(await list()).toEqual(first);
+ expect(reads).toEqual([]);
+
+ await at('2026-10-05T08:00:00.000Z', () => tasks.updateTask(TEST_UID, '', ids[0], { status: 'done' }));
+ reads.length = 0;
+ expect(open(await list())).toEqual(['Item 1', 'Item 2']);
+ expect(reads).toEqual([file(0)]);
+
+ // A synced copy arrives by rename.
+ const synced = { ...JSON.parse(fs.readFileSync(file(1), 'utf8')), status: 'done' };
+ fs.writeFileSync(`${file(1)}.sync`, JSON.stringify(synced));
+ fs.renameSync(`${file(1)}.sync`, file(1));
+ // Conflict resolution rewrites in place, here keeping the same size.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ fs.writeFileSync(file(2), fs.readFileSync(file(2), 'utf8').replace('Item 2', 'Item Z'));
+ reads.length = 0;
+ expect(open(await list())).toEqual(['Item Z']);
+ expect(reads.sort()).toEqual([file(1), file(2)].sort());
+
+ fs.rmSync(file(2));
+ reads.length = 0;
+ expect(await list()).toMatchObject({ tasks: [], total: 0 });
+ expect(reads).toEqual([]);
+ } finally {
+ spy.mockRestore();
+ syncBuiltinESMExports();
+ }
+ });
+
+ it('returns an empty list when there is nothing left to do', async () => {
+ const res = await invoke('projects.tasks.listOpen', {});
+ expect(res).toMatchObject({ ok: true, tasks: [], total: 0 });
+ });
+});
+
+describe('conversations.getMany', () => {
+ it('returns index rows for known conversations and reports the rest as missing', async () => {
+ const chats = await import('../../../src/main/features/chats');
+ const projects = await import('../../../src/main/features/projects');
+ const created = await projects.createProject(TEST_UID, 'Growth');
+ if (!created.ok) throw new Error('createProject failed');
+ const plain = await chats.createConversation(TEST_UID, { title: 'Weekly summary' });
+ const filed = await chats.createConversation(TEST_UID, { title: 'Pricing check', projectId: created.project.project_id });
+
+ const res = await invoke('conversations.getMany', {
+ cids: [plain.conversation_id, filed.conversation_id, 'c_missing0001', plain.conversation_id, '../escape', 42],
+ });
+ expect(res.ok).toBe(true);
+ expect(res.conversations).toEqual([
+ { conversation_id: plain.conversation_id, title: 'Weekly summary', project_id: '', origin_auto_task_id: '' },
+ { conversation_id: filed.conversation_id, title: 'Pricing check', project_id: created.project.project_id, origin_auto_task_id: '' },
+ ]);
+ expect(res.missing).toEqual(['c_missing0001']);
+ });
+
+ it('reads at most 25 ids per call', async () => {
+ const ids = Array.from({ length: 30 }, (_, i) => `c_unknown${String(i).padStart(4, '0')}`);
+ const res = await invoke('conversations.getMany', { cids: ids });
+ expect(res.missing).toHaveLength(25);
+ expect(res.conversations).toEqual([]);
+ });
+});
diff --git a/test/main/ipc/saved-app-delete-recycle.test.ts b/test/main/ipc/saved-app-delete-recycle.test.ts
new file mode 100644
index 00000000..973e607d
--- /dev/null
+++ b/test/main/ipc/saved-app-delete-recycle.test.ts
@@ -0,0 +1,77 @@
+/** A saved-app delete that fails must leave the app and the recycle bin as they were. */
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import * as crypto from 'node:crypto';
+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';
+import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';
+
+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/model/client', () => ({
+ async *streamChatWithModel() { yield { type: 'done' }; },
+ async chatWithModel() { return { ok: true, text: '' }; },
+}));
+vi.mock('node:fs/promises', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>();
+ return { ...actual, rm: vi.fn(actual.rm) };
+});
+
+const UID = 'uSavedAppDeleteRecycle';
+let tmpDir: string, previousWorkspace: string | undefined;
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-saved-app-delete-'));
+ previousWorkspace = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+});
+afterEach(async () => {
+ await drainMainRuntimeForTest();
+ if (previousWorkspace === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspace;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function invoke(channel: string, payload: Record<string, unknown>): 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');
+ return call[1]({ sender: trustedIpcSender() }, { channel, payload });
+}
+
+it('drops the recycle copy and reports a stable code when deletion fails, then recycles a successful retry once', async () => {
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const saved = await import('../../../src/main/features/saved_apps');
+ const recycleBin = await import('../../../src/main/features/recycle_bin');
+ const created = await artifacts.createArtifact(UID, 'c1', 'helper', { files: [{ path: 'index.html', content: '<h1>Keep</h1>' }] });
+ if (!created.ok) throw new Error(created.error);
+ const app = await saved.saveFromArtifact(UID, 'c1', created.artifactId);
+ if (!app.ok) throw new Error(app.error);
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved', app.id])).digest('hex');
+ const local = path.join(tmpDir, UID, 'local/web_apps', key);
+ fs.mkdirSync(local, { recursive: true }); fs.writeFileSync(path.join(local, 'data.sqlite'), 'records');
+ const fsp = await import('node:fs/promises');
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const fault = vi.spyOn(fsp, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === local) throw Object.assign(new Error(`EBUSY: resource busy '${local}'`), { code: 'EBUSY' });
+ return rm(target, options);
+ });
+ let failed: any;
+ try { failed = await invoke('savedApps.delete', { appId: app.id }); } finally { fault.mockRestore(); }
+ expect(failed).toMatchObject({ ok: false, code: 'app_delete_failed', error: 'app_delete_failed' });
+ expect(JSON.stringify(failed)).not.toContain(tmpDir);
+ expect(await recycleBin.listRecycleBatches(UID)).toEqual([]);
+ expect(saved.listSavedApps(UID).map(item => item.id)).toEqual([app.id]);
+ expect(await invoke('savedApps.delete', { appId: app.id })).toEqual({ ok: true });
+ expect(saved.listSavedApps(UID)).toEqual([]);
+ expect(await recycleBin.listRecycleBatches(UID)).toHaveLength(1);
+});
diff --git a/test/renderer/artifact-security.test.ts b/test/renderer/artifact-security.test.ts
index cbc600da..66dbb923 100644
--- a/test/renderer/artifact-security.test.ts
+++ b/test/renderer/artifact-security.test.ts
@@ -18,6 +18,15 @@ function loadSecurity() {
}
describe('artifact iframe security boundary', () => {
+ it('round trips result JSON without allowing payload text to close its structural tag', () => {
+ const context:any={window:{OrkasArtifactSecurity:loadSecurity()}};
+ vm.runInNewContext(chatSource,context);
+ const payload={text:'</artifact-result> unexpected <artifact-result> & "quoted"',nested:['<div>']};
+ const result=context.window.encodeArtifactResult('artifact','commander','Fixture',payload);
+ expect(result.match(/<\/artifact-result>/g)).toHaveLength(1);
+ const body=result.match(/<artifact-result[^>]*>\n([\s\S]*)\n<\/artifact-result>/)[1];
+ expect(JSON.parse(body)).toEqual(payload);
+ });
it('loads the shared boundary before eager and lazy artifact renderers use it', () => {
expect(indexSource.indexOf('./modules/artifact-security.js')).toBeGreaterThanOrEqual(0);
expect(indexSource.indexOf('./modules/artifact-security.js')).toBeLessThan(
@@ -53,14 +62,18 @@ describe('artifact iframe security boundary', () => {
}
});
- it('requires both the marker and the live iframe contentWindow identity', () => {
+ it('requires the marker, live iframe identity and its exact registered origin', () => {
const security = loadSecurity();
const liveWindow = {};
- const frame = { contentWindow: liveWindow };
+ const frame = { contentWindow: liveWindow, src:'chat-app://local/chat/app/index.html' };
+ const origin = 'chat-app://local';
const data = { __orkasArtifact: true, type: 'submit' };
- expect(security.trustedArtifactMessage({ source: liveWindow, data }, frame)).toBe(true);
+ expect(security.trustedArtifactMessage({ source: liveWindow, origin, data }, frame)).toBe(true);
expect(security.trustedArtifactMessage({ source: {}, data }, frame)).toBe(false);
expect(security.trustedArtifactMessage({ source: liveWindow, data: { type: 'submit' } }, frame)).toBe(false);
expect(security.trustedArtifactMessage({ source: liveWindow, data: null }, frame)).toBe(false);
+ for(const foreign of ['https://example.com','chat-app://saved','chat-app://local.evil','null','',undefined])
+ expect(security.trustedArtifactMessage({source:liveWindow,origin:foreign,data},frame)).toBe(false);
+ expect(security.trustedArtifactMessage({source:liveWindow,origin:'https://example.com',data},{...frame,src:'https://example.com'})).toBe(false);
});
});
diff --git a/test/renderer/auto-project-groups.test.ts b/test/renderer/auto-project-groups.test.ts
index 26f7885b..4024558f 100644
--- a/test/renderer/auto-project-groups.test.ts
+++ b/test/renderer/auto-project-groups.test.ts
@@ -26,8 +26,13 @@ function loadAutoTab(options: { projects: Project[] | null; view: string }) {
};
Object.defineProperty(list, 'innerHTML', { set() { list.clears += 1; scopes = []; selectedGroup = null; }, get() { return ''; } });
const elements: Record<string, any> = {
+ 'auto-add-btn': {
+ dataset: {}, click() {},
+ addEventListener(name: string, fn: () => void) { if (name === 'click') this.click = fn; },
+ },
'auto-list': list,
'auto-empty': { style: {} },
+ 'auto-row-project': { hidden: false },
'auto-header-count': { textContent: '' },
};
const sidebarLoads: unknown[] = [];
@@ -64,6 +69,7 @@ function loadAutoTab(options: { projects: Project[] | null; view: string }) {
};
context.window.window = context.window;
vm.createContext(context);
+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/icons.js'), 'utf8'), context);
vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/auto.js'), 'utf8'), context, { filename: 'auto.js' });
// Device, sync notice, per-task counts and row markup are owned by other cases.
vm.runInContext(`
@@ -75,8 +81,10 @@ function loadAutoTab(options: { projects: Project[] | null; view: string }) {
`, context);
return {
context,
+ create: () => elements['auto-add-btn'].click(),
sidebarLoads,
scopeNames: () => scopes.map((scope) => /todo-scope-chip-name">([^<]*)</.exec(scope.innerHTML)?.[1] || ''),
+ scopeIcons: () => scopes.map((scope) => /\bis-(folder|globe)\b/.exec(scope.innerHTML)?.[1]),
activeScope: () => selectedGroup?.dataset.projectId,
selectScope: (id: string) => scopes.find((scope) => scope.dataset.projectId === id)?.click(),
clears: () => list.clears,
@@ -84,6 +92,85 @@ function loadAutoTab(options: { projects: Project[] | null; view: string }) {
}
describe('automation tab and the sidebar project cache', () => {
+ it('initializes each new draft from the currently selected scope without locking its project', async () => {
+ const tab = loadAutoTab({ projects: [{ project_id: 'a', name: 'Alpha' }], view: 'auto' });
+ const opened: any[] = [];
+ tab.context.recordEditor = (opts: any) => opened.push(JSON.parse(JSON.stringify(opts)));
+ vm.runInContext('openAutoTaskDialog = opts => recordEditor(opts)', tab.context);
+ await tab.context.loadAutoList(true);
+ tab.selectScope('a');
+ tab.create();
+ tab.selectScope('');
+ tab.create();
+ tab.selectScope('a');
+ await tab.context.loadAutoList(true);
+ tab.create();
+ expect(opened).toEqual([
+ { initialProjectId: 'a' }, { initialProjectId: '' }, { initialProjectId: 'a' },
+ ]);
+ });
+
+ it('defaults creation to global when the selected automation project is unavailable', async () => {
+ const tab = loadAutoTab({ projects: [{ project_id: 'a', name: 'Alpha' }], view: 'auto' });
+ tab.context.window.orkas.invoke = async () => ({ ok: true, tasks: [{ id: 'orphan', project_id: 'removed' }] });
+ let selected: string | null = null;
+ tab.context.projectPicker = { setOptions() {}, setValue(value: string) { selected = value; }, getValue() { return selected; } };
+ // Keep the real create entry, dialog initialization and scope validation;
+ // unrelated composer, localization and modal painting are covered by E2E.
+ vm.runInContext(`
+ _autoFormMounted = true;
+ _autoProjectSel = projectPicker;
+ _autoResetForm = () => {};
+ _autoRepaintLabels = () => {};
+ _showAutoDialog = () => {};
+ `, tab.context);
+ await tab.context.loadAutoList(true);
+ tab.selectScope('removed');
+ expect(tab.activeScope()).toBe('removed');
+ tab.create();
+ expect(selected).toBe('');
+ expect(vm.runInContext('_autoSelectedProjectId()', tab.context)).toBe('');
+ });
+
+ it.each([
+ ['first visit', null, 't1', 'a'],
+ ['another project selected', [{ project_id: 'a', name: 'Alpha' }], 't2', ''],
+ ['global scope selected', [{ project_id: 'a', name: 'Alpha' }], 't1', 'a'],
+ ] as const)('selects the saved automation scope on %s before opening its editor', async (_name, projects, taskId, scope) => {
+ const tab = loadAutoTab({ projects: projects ? [...projects] : null, view: 'auto' });
+ const opened: any[] = [];
+ tab.context.recordEditor = (task: Task) => opened.push({ task, scope: tab.activeScope() });
+ vm.runInContext('openAutoTaskDialog = ({ task }) => recordEditor(task)', tab.context);
+ if (projects) {
+ await tab.context.loadAutoList(true);
+ tab.selectScope(scope ? '' : 'a');
+ }
+
+ expect(await tab.context.window.openAutoTaskById(taskId)).toBe(true);
+
+ expect(tab.activeScope()).toBe(scope);
+ expect(opened).toEqual([{ task: taskId === 't1' ? { id: 't1', project_id: 'a' } : { id: 't2' }, scope }]);
+ await tab.context.loadAutoList(true);
+ expect(tab.activeScope()).toBe(scope);
+ });
+
+ it('uses the current project assignment and leaves the selection intact for a deleted automation', async () => {
+ const tab = loadAutoTab({ projects: [{ project_id: 'a', name: 'Alpha' }, { project_id: 'b', name: 'Beta' }], view: 'auto' });
+ const opened: Task[] = [];
+ tab.context.recordEditor = (task: Task) => opened.push(task);
+ vm.runInContext('openAutoTaskDialog = ({ task }) => recordEditor(task)', tab.context);
+ await tab.context.loadAutoList(true);
+ tab.selectScope('a');
+ tab.context.window.orkas.invoke = async () => ({ ok: true, tasks: [{ id: 't1', project_id: 'b' }, { id: 't2' }] });
+
+ expect(await tab.context.window.openAutoTaskById('t1')).toBe(true);
+ expect(tab.activeScope()).toBe('b');
+ expect(opened).toEqual([{ id: 't1', project_id: 'b' }]);
+ expect(await tab.context.window.openAutoTaskById('missing')).toBe(false);
+ expect(tab.activeScope()).toBe('b');
+ expect(opened).toHaveLength(1);
+ });
+
it('groups from the warm project cache without asking the sidebar to repaint', async () => {
const tab = loadAutoTab({ projects: [{ project_id: 'a', name: 'Alpha' }], view: 'auto' });
diff --git a/test/renderer/auto-task-conversation-pagination.test.ts b/test/renderer/auto-task-conversation-pagination.test.ts
index bd681870..9f526896 100644
--- a/test/renderer/auto-task-conversation-pagination.test.ts
+++ b/test/renderer/auto-task-conversation-pagination.test.ts
@@ -48,7 +48,8 @@ describe('automation execution-history pagination', () => {
expect(ipcSource).toContain("'conversations.autoTaskCounts'");
});
- it('aligns the project sync note and create action in one toolbar', () => {
- expect(html).toMatch(/class="project-auto-tab-head"[\s\S]*?id="project-auto-sync-note"[\s\S]*?id="project-auto-add-btn"/);
+ it('puts the project create action on the tab row and the sync note above the cards', () => {
+ expect(html).toMatch(/<div class="project-tab-tools" data-project-tools="auto" hidden>\s*<button[^>]*id="project-auto-add-btn"/);
+ expect(html).toMatch(/data-project-panel="auto" hidden>\s*<div class="auto-sync-note" id="project-auto-sync-note" hidden><\/div>\s*<div class="auto-list" id="project-auto-list">/);
});
});
diff --git a/test/renderer/auto-title-parity.test.ts b/test/renderer/auto-title-parity.test.ts
index 400105fc..dae58f37 100644
--- a/test/renderer/auto-title-parity.test.ts
+++ b/test/renderer/auto-title-parity.test.ts
@@ -27,6 +27,7 @@
import { describe, it, expect } from 'vitest';
import * as mainAutoTitle from '../../src/main/util/auto-title';
+import { limitNameDisplayText } from '../../src/main/util/name-limit';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const rendererAutoTitle = require('../../src/renderer/modules/auto-title.js');
import { autoTitle as backendAutoTitle } from '../../src/main/features/chats';
@@ -36,6 +37,7 @@ const renderer: {
_AUTO_TITLE_ZH_FILLER: RegExp;
_AUTO_TITLE_EN_FILLER: RegExp;
_AUTO_TITLE_MAX_UNITS: number;
+ _CONVERSATION_TITLE_MAX_UNITS: number;
_truncateTitleToWidth: (text: string) => string;
} = rendererAutoTitle;
@@ -59,6 +61,13 @@ describe('auto-title parity › regex source / flags match across main + rendere
it('the display-width budget matches', () => {
expect(renderer._AUTO_TITLE_MAX_UNITS).toBe(mainAutoTitle.TITLE_MAX_UNITS);
});
+
+ it('the stored conversation-title cap matches and keeps a full auto title intact', () => {
+ expect(renderer._CONVERSATION_TITLE_MAX_UNITS).toBe(mainAutoTitle.CONVERSATION_TITLE_MAX_UNITS);
+ const full = mainAutoTitle.truncateTitleToWidth('一'.repeat(80));
+ expect(full.endsWith('…')).toBe(true);
+ expect(limitNameDisplayText(full, mainAutoTitle.CONVERSATION_TITLE_MAX_UNITS)).toBe(full);
+ });
});
/**
@@ -70,16 +79,16 @@ describe('auto-title parity › regex source / flags match across main + rendere
*/
describe('auto-title parity › width table agrees on every script class', () => {
const widthCases: Array<[string, string]> = [
- ['Han', '一'.repeat(40)],
- ['Hangul', '가'.repeat(40)],
- ['Hiragana', 'あ'.repeat(40)],
- ['fullwidth Latin', 'A'.repeat(40)],
- ['halfwidth Latin', 'A'.repeat(80)],
- ['emoji', '🙂'.repeat(40)],
- ['emoji with a variation selector', '☘️'.repeat(40)],
- ['combining marks', 'e\u0301'.repeat(60)],
- ['mixed scripts at the boundary', `${'一'.repeat(20)}${'A'.repeat(12)}`],
- ['CJK punctuation', ','.repeat(40)],
+ ['Han', '一'.repeat(80)],
+ ['Hangul', '가'.repeat(80)],
+ ['Hiragana', 'あ'.repeat(80)],
+ ['fullwidth Latin', 'A'.repeat(80)],
+ ['halfwidth Latin', 'A'.repeat(160)],
+ ['emoji', '🙂'.repeat(80)],
+ ['emoji with a variation selector', '☘️'.repeat(80)],
+ ['combining marks', 'e\u0301'.repeat(120)],
+ ['mixed scripts at the boundary', `${'一'.repeat(40)}${'A'.repeat(24)}`],
+ ['CJK punctuation', ','.repeat(80)],
];
for (const [label, input] of widthCases) {
diff --git a/test/renderer/bash-permission.test.ts b/test/renderer/bash-permission.test.ts
index af19a616..6cec5f60 100644
--- a/test/renderer/bash-permission.test.ts
+++ b/test/renderer/bash-permission.test.ts
@@ -187,12 +187,16 @@ interface DialogView {
showModeControl: boolean;
allowRun: boolean;
choices: string[];
+ /** The highlighted choice, which also receives initial focus. */
+ primary: string;
+ choiceLabels: Record<string, string>;
}
function dialogView(overlay: FakeElement): DialogView {
const text = (selector: string) => overlay.querySelector(selector)?.textContent ?? '';
const options = overlay.querySelectorAll('.bash-permission-mode-option');
- const choices = overlay.querySelectorAll('[data-act="choice"]').map((button) => button.dataset.id);
+ const choiceButtons = overlay.querySelectorAll('[data-act="choice"]');
+ const choices = choiceButtons.map((button) => button.dataset.id);
return {
title: text('.ui-dialog-title'),
context: text('.ui-dialog-context'),
@@ -211,6 +215,8 @@ function dialogView(overlay: FakeElement): DialogView {
showModeControl: overlay.querySelector('.bash-permission-mode-control') !== null,
allowRun: choices.includes('allow_run'),
choices,
+ primary: choiceButtons.find((button) => button.classes.has('btn-primary'))?.dataset.id ?? '',
+ choiceLabels: Object.fromEntries(choiceButtons.map((button) => [button.dataset.id, button.textContent])),
};
}
@@ -1273,67 +1279,6 @@ describe('renderer bash permission prompt', () => {
});
});
-describe('web assist page actions reuse the same permission dialog', () => {
- const handback = {
- request_id: 'web-assist-request',
- cid: 'task-1',
- tab_id: '0123456789ab',
- page_title: 'ChatGPT',
- page_origin: 'https://chatgpt.com',
- control_label: 'Send prompt',
- control_kind: 'button',
- reason: 'high_impact_action',
- };
-
- it('offers a task grant and answers with the run decision', async () => {
- const h = loadHarness('allow_run');
- h.emitPush('web-assist:action-confirm', handback);
- await flush();
- expect(h.dialogs[0]).toMatchObject({
- title: 'Allow this action on the page?',
- currentMode: 'all_files_approval',
- // The repeat is the case this gate exists for, so the grant is offered.
- allowRun: true,
- showModeControl: true,
- });
- for (const detail of ['ChatGPT', 'https://chatgpt.com', 'Send prompt']) {
- expect(h.dialogs[0].message).toContain(detail);
- }
- expect(h.invokeCalls.at(-1)).toEqual({
- channel: 'webAssist.actionConfirmResponse',
- payload: { request_id: handback.request_id, decision: 'run' },
- });
- });
-
- it('answers once without a grant', async () => {
- const h = loadHarness('allow_once');
- h.emitPush('web-assist:action-confirm', handback);
- await flush();
- expect(h.invokeCalls.at(-1)).toEqual({
- channel: 'webAssist.actionConfirmResponse',
- payload: { request_id: handback.request_id, decision: 'once' },
- });
- });
-
- it('declines with a deny decision the host can distinguish from an approval', async () => {
- const h = loadHarness('deny');
- h.emitPush('web-assist:action-confirm', handback);
- await flush();
- expect(h.invokeCalls.at(-1)).toEqual({
- channel: 'webAssist.actionConfirmResponse',
- payload: { request_id: handback.request_id, decision: 'deny' },
- });
- });
-
- it('drops a withdrawn request without answering it', async () => {
- const h = loadHarness('pending');
- h.emitPush('web-assist:action-confirm', handback);
- h.emitPush('web-assist:action-confirm-cancelled', { request_ids: [handback.request_id], cid: 'task-1' });
- await flush();
- expect(h.invokeCalls.some(call => call.channel === 'webAssist.actionConfirmResponse')).toBe(false);
- });
-});
-
describe('Web application sensitive approval', () => {
it.each(['zh', 'en', 'ja', 'pt'] as const)('uses the shared dialog with a usage button and no additional explanation in %s', async locale => {
const table = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/renderer/locales', `${locale}.json`), 'utf8'));
@@ -1368,7 +1313,7 @@ it('application windows ignore task prompts and cancellations while showing thei
describe('global request attribution', () => {
- it.each(['bash:permission', 'connectors:action-confirm', 'web-assist:action-confirm', 'local-agent:permission'])(
+ it.each(['bash:permission', 'connectors:action-confirm', 'local-agent:permission'])(
'identifies the source of %s even while a different task is open', async channel => {
const h = loadHarness('pending', undefined, { locale: 'zh' });
h.context.currentConvId = 'unrelated';
diff --git a/test/renderer/chat-rich-composer-newline.test.ts b/test/renderer/chat-rich-composer-newline.test.ts
index dc12f44d..9f44fd4c 100644
--- a/test/renderer/chat-rich-composer-newline.test.ts
+++ b/test/renderer/chat-rich-composer-newline.test.ts
@@ -85,3 +85,76 @@ describe('composer document preserves the authored text', () => {
expect(m.offset(doc, m.position(doc, Number.MAX_SAFE_INTEGER))).toBe(text.length);
});
});
+
+// Run the production ownership boundary with real editor documents/history.
+// Only the view mount is replaced; no browser layout is needed for this state.
+function projectComposer() {
+ const context = vm.createContext({ currentUserId: 'first',
+ Event: class { constructor(public type: string) {} },
+ _findChatComposerTokens: () => [],
+ });
+ vm.runInContext(readFileSync(path.join(__dirname, '../../src/renderer/vendor/prosemirror/prosemirror.min.js'), 'utf8'), context);
+ vm.runInContext(readFileSync(path.join(__dirname, '../../src/renderer/modules/composer-input.js'), 'utf8'), context);
+ const api = vm.runInContext(`(() => {
+ const input = { id: 'project-chat-input', matches: () => true, dispatchEvent() {} };
+ const api = { editor: input, owner: null, revision: 0, epoch: 0, stamp: {}, anchors: new Set(),
+ plugins: [OrkasEditor.history()], autoGrow() {}, view: {
+ composing: false, state: OrkasEditor.EditorState.create({schema: _composerSchema}),
+ updateState(state) { this.state = state; },
+ } };
+ _composerInputs.set(input.id, api);
+ return {
+ bind: owner => composerBindOwner(input, owner),
+ text: () => composerText(input),
+ edit: text => { api.view.state = api.view.state.apply(api.view.state.tr
+ .replaceWith(0, api.view.state.doc.content.size, _composerDocument(text, input.id).content));
+ api.revision++; api.stamp = {}; },
+ snapshot: () => composerSnapshot(input),
+ discard: (owner, snapshot) => composerDiscardStoredDraft(input, owner, snapshot),
+ undo: () => OrkasEditor.undo(api.view.state, tr => { api.view.state = api.view.state.apply(tr); }),
+ };
+ })()`, context);
+ return { ...api, account: (id: string) => { context.currentUserId = id; } };
+}
+
+describe('project composer draft isolation', () => {
+ it('restores each project’s unsent text, preserves refreshes and fences undo after navigation', () => {
+ const p = projectComposer();
+ p.bind('A'); p.edit('中文 A\nunsent');
+ const submitted = p.snapshot();
+ p.bind('B');
+ expect(p.text()).toBe('');
+ expect(p.undo()).toBe(false);
+ expect(submitted.matches()).toBe(false);
+ p.edit('B draft'); p.bind('B');
+ expect(p.text()).toBe('B draft');
+ p.bind(null); p.bind('A');
+ expect(p.text()).toBe('中文 A\nunsent');
+ expect(p.undo()).toBe(false);
+ p.bind('B');
+ expect(p.text()).toBe('B draft');
+ p.edit(''); p.bind('A'); p.bind('B');
+ expect(p.text()).toBe('');
+ });
+
+ it('does not expose a previous account’s drafts even when the project id is the same', () => {
+ const p = projectComposer();
+ p.bind('A'); p.edit('first account'); p.bind('B'); p.edit('other first draft');
+ p.account('second'); p.bind('B');
+ expect(p.text()).toBe('');
+ p.bind('A');
+ expect(p.text()).toBe('');
+ });
+
+ it.each([false, true])('a delayed successful send consumes only its saved revision (edited=%s)', edited => {
+ const p = projectComposer();
+ p.bind('A'); p.edit('submitted');
+ const submitted = p.snapshot();
+ if (edited) { p.edit('different'); p.edit('submitted'); }
+ p.bind('B'); p.edit('B survives');
+ p.discard('A', submitted);
+ expect(p.text()).toBe('B survives');
+ p.bind('A');
+ expect(p.text()).toBe(edited ? 'submitted' : '');
+ });
+});
diff --git a/test/renderer/chat-use-inline-chips.test.ts b/test/renderer/chat-use-inline-chips.test.ts
index cb90decc..90343b18 100644
--- a/test/renderer/chat-use-inline-chips.test.ts
+++ b/test/renderer/chat-use-inline-chips.test.ts
@@ -8,7 +8,7 @@ const skillsSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/mo
const conversationSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation.js'), 'utf8');
const composerHelpers = [
['const _MENTION_FALLBACK_CLASS', 'function _highlightMentionsIn'],
- ['function _quotedLineRanges', 'function _composerDispatchShape'],
+ ['function _quotedLineRanges', 'function _resolvedMentionSpans'],
['function _resolvedMentionSpans', 'function _explicitMentionRecipients'],
['function _findChatComposerTokens', 'function _chatRichAutoGrowMax'],
].map(([start, end]) => {
diff --git a/test/renderer/cli-account-usage.test.ts b/test/renderer/cli-account-usage.test.ts
new file mode 100644
index 00000000..b3d436b2
--- /dev/null
+++ b/test/renderer/cli-account-usage.test.ts
@@ -0,0 +1,83 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+import { LOCALES } from '../../src/main/i18n';
+
+const root = path.resolve(__dirname, '../../src/renderer');
+function harness() {
+ const section = { hidden: true };
+ const slot = { innerHTML: '', querySelector: () => null };
+ const pending: Array<(v: any) => void> = [];
+ const failures: Array<(error: Error) => void> = [];
+ const warn = vi.fn();
+ const calls: any[] = [];
+ const context = vm.createContext({
+ document: { getElementById: (id: string) => id.endsWith('-section') ? section : slot },
+ window: { orkas: { invoke: (...args: any[]) => { calls.push(args); return new Promise((r, reject) => { pending.push(r); failures.push(reject); }); } } },
+ createLogger: () => ({ warn }),
+ escapeHtml: (v: any) => String(v).replaceAll('<', '&lt;'),
+ getLang: () => 'en',
+ t: (key: string, vars: any = {}) => key + JSON.stringify(vars),
+ Date, Intl,
+ });
+ vm.runInContext(fs.readFileSync(path.join(root, 'modules/cli-account-usage.js'), 'utf8'), context);
+ return { section, slot, pending, failures, warn, calls, render: (agent: any) => context.renderCliAccountUsage(agent) };
+}
+const agent = (id: string, cli = 'codex') => ({ agent_id: id, runtime: { kind: 'cli', cli } });
+const reply = (remaining: number) => ({ usage: { status: 'ready', checked_at: 1900000000000, windows: [
+ { label: '<img>', minutes: 300, remaining_percent: remaining, resets_at: 1900000000000 },
+] } });
+
+describe('CLI account allowance detail', () => {
+ it('shows only quota and reset details and rechecks when details are rendered again', async () => {
+ const h = harness(); const render = h.render(agent('one'));
+ expect(h.slot.innerHTML).toContain('common.loading');
+ h.pending.shift()!(reply(83)); await render;
+ expect(h.slot.innerHTML).toContain('83%');
+ expect(h.slot.innerHTML).toContain('agents.cli_usage_resets');
+ expect(h.slot.innerHTML).toContain('&lt;img>');
+ expect(h.slot.innerHTML).not.toContain('<img>');
+ expect(h.slot.innerHTML).not.toContain('agents.cli_usage_shared');
+ expect(h.slot.innerHTML).not.toContain('agents.cli_usage_checked');
+ expect(h.slot.innerHTML).not.toContain('<button');
+ const reopened = h.render(agent('one'));
+ expect(h.calls[1]).toEqual(['localAgents.accountUsage', { agent_id: 'one', force: false }]);
+ h.pending.shift()!({ usage: { status: 'unavailable', windows: [] } }); await reopened;
+ expect(h.slot.innerHTML).toContain('agents.cli_usage_unavailable');
+ expect(h.slot.innerHTML).not.toContain('83%');
+ });
+
+ it('ignores a late response after switching agents or leaving CLI details', async () => {
+ const h = harness(); const first = h.render(agent('one')); const second = h.render(agent('two', 'claude'));
+ h.pending[1](reply(20)); await second;
+ h.pending[0](reply(99)); await first;
+ expect(h.slot.innerHTML).toContain('20%'); expect(h.slot.innerHTML).not.toContain('99%');
+ const third = h.render(agent('three'));
+ await h.render({ agent_id: 'ordinary', runtime: { kind: 'in_process' } });
+ h.pending[2](reply(50)); await third;
+ expect(h.section.hidden).toBe(true); expect(h.slot.innerHTML).toBe('');
+ });
+
+ it('localizes all visible quota states in every registered locale', () => {
+ for (const { code } of LOCALES) {
+ const table = JSON.parse(fs.readFileSync(path.join(root, 'locales', code + '.json'), 'utf8'));
+ for (const key of ['title', 'unavailable', 'unsupported', 'resets', 'hours', 'days', 'window']) {
+ expect(table['agents.cli_usage_' + key], code + ':' + key).toBeTruthy();
+ }
+ expect(table['agents.cli_usage_shared']).toBeUndefined();
+ expect(table['agents.cli_usage_checked']).toBeUndefined();
+ if (code === 'zh') expect(table['agents.cli_usage_title']).toBe('剩余额度');
+ }
+ });
+
+ it('logs a rejected IPC safely while keeping the unavailable recovery state', async () => {
+ const h = harness();
+ const render = h.render(agent('one'));
+ h.failures[0](new Error('private-account /private/fixture/token.txt'));
+ await render;
+ expect(h.slot.innerHTML).toContain('agents.cli_usage_unavailable');
+ expect(h.warn).toHaveBeenCalledOnce();
+ expect(JSON.stringify(h.warn.mock.calls)).not.toContain('private');
+ });
+});
diff --git a/test/renderer/composer-abort-restore.test.ts b/test/renderer/composer-abort-restore.test.ts
index 1e86a91d..0991ee90 100644
--- a/test/renderer/composer-abort-restore.test.ts
+++ b/test/renderer/composer-abort-restore.test.ts
@@ -302,6 +302,8 @@ describe('stop and settlement wiring', () => {
expect(clear).toHaveBeenCalledWith('conv-a');
expect([...watermarks]).toEqual([['conv-other', 20]]);
- expect([...offViewDirty]).toEqual(['conv-other']);
+ // Composer state is retired, but a background transcript must still fetch
+ // its saved terminal reply when the user returns to it.
+ expect([...offViewDirty]).toEqual(['conv-a', 'conv-other']);
});
});
diff --git a/test/renderer/composer-floor-reconciliation.test.ts b/test/renderer/composer-floor-reconciliation.test.ts
index f27e5993..54300765 100644
--- a/test/renderer/composer-floor-reconciliation.test.ts
+++ b/test/renderer/composer-floor-reconciliation.test.ts
@@ -103,6 +103,9 @@ function boot() {
setFloor: (agentId: string) => vm.runInContext(
`_serverFloorByCid.set('${CID}', '${agentId}')`, context,
),
+ snapshot: (state: Record<string, unknown>) => vm.runInContext(
+ `_rememberServerFloor('${CID}', ${JSON.stringify(state)})`, context,
+ ),
stickyPick: () => vm.runInContext(`_recipientByCid['${CID}'] || null`, context),
hasPendingWrite: () => vm.runInContext(`_floorSyncByCid.has('${CID}')`, context),
pickOnChip: (agent: { id: string; name: string }) => vm.runInContext(
@@ -181,4 +184,19 @@ describe('composer chip / server floor reconciliation', () => {
expect(app.chipEl.textContent).toBe(AGENT_B.name);
expect(app.activeRecipient()).toMatchObject({ kind: 'agent', id: AGENT_B.id });
});
+ it('restores a waiting form owner from backend state and ignores an older reset', async () => {
+ const app = boot();
+ app.snapshot({ active_recipient: AGENT_A.id, active_recipient_revision: 2 });
+ await app.reconcile();
+ expect(app.chipEl.textContent).toBe(AGENT_A.name);
+ expect(app.activeRecipient()).toMatchObject({ kind: 'agent', id: AGENT_A.id });
+ app.snapshot({ active_recipient_revision: 1 });
+ await app.reconcile();
+ expect(app.chipEl.textContent).toBe(AGENT_A.name);
+ app.snapshot({ active_recipient_revision: 3 });
+ await app.reconcile();
+ expect(app.chipEl.textContent).toBe('chat.recipient_commander');
+ expect(app.activeRecipient()).toMatchObject({ kind: 'commander' });
+ });
+
});
diff --git a/test/renderer/contexts-external-drop.test.ts b/test/renderer/contexts-external-drop.test.ts
index 2a958c96..59ac2439 100644
--- a/test/renderer/contexts-external-drop.test.ts
+++ b/test/renderer/contexts-external-drop.test.ts
@@ -597,6 +597,30 @@ describe('Library external file drag-and-drop', () => {
describe('Library project switching', () => {
+ it('keeps global first and the natural project order when mounting and refreshing the switcher', async () => {
+ const context = loadContextsScript();
+ const host = { addEventListener: vi.fn() };
+ context.document.getElementById = (id: string) => id === 'contexts-project-select' ? host : null;
+ const selector = { setOptions: vi.fn(), setAriaLabel: vi.fn() };
+ context._aiSelectMount = vi.fn(() => selector);
+ const projects = Object.freeze([
+ { project_id: 's2', name: 'Zulu 2' },
+ { project_id: 's10', name: 'Zulu 10' },
+ { project_id: 'p2', name: 'Alpha 2' },
+ { project_id: 'p10', name: 'Alpha 10' },
+ ]);
+ context.loadProjects = vi.fn(async () => projects);
+
+ context._renderCtxScopeSelector(projects);
+ const mounted = context._aiSelectMount.mock.calls[0][1];
+ expect(mounted.options.map((option: any) => option.value)).toEqual(['', 'p2', 'p10', 's2', 's10']);
+ vm.runInContext('_ctxProjectId = "s10"', context);
+ await context._refreshCtxProjects();
+ const [options, selection] = selector.setOptions.mock.calls[0];
+ expect(options.map((option: any) => option.value)).toEqual(['', 'p2', 'p10', 's2', 's10']);
+ expect(selection.value).toBe('s10');
+ });
+
it('keeps the latest selection when an earlier Library load finishes late', async () => {
const context = loadContextsScript();
let finishGlobal: (value: any) => void = () => {};
diff --git a/test/renderer/conversation-bucket.test.ts b/test/renderer/conversation-bucket.test.ts
index 6f8e522e..b8578113 100644
--- a/test/renderer/conversation-bucket.test.ts
+++ b/test/renderer/conversation-bucket.test.ts
@@ -7,9 +7,10 @@
import { describe, it, expect } from 'vitest';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const convBucket = require('../../src/renderer/modules/conv-bucket.js');
-const { timeBucket, selectTodayConversations } = convBucket as {
+const { timeBucket, selectRecentConversations, recentConversationsSince } = convBucket as {
timeBucket: (iso: string, now?: Date) => 'today' | 'yesterday' | 'last7' | 'last30' | 'older';
- selectTodayConversations: (rows: unknown, now?: Date) => Array<Record<string, unknown>>;
+ selectRecentConversations: (rows: unknown, now?: Date) => Array<Record<string, unknown>>;
+ recentConversationsSince: (now?: Date) => Date;
};
// 2026-05-15T14:30:00 local — anchor every fixture against this; today
@@ -92,21 +93,24 @@ describe('timeBucket — older + degenerate inputs', () => {
});
});
-// The sidebar "Today's Tasks" aggregate must agree with the "Today" bucket
-// header of every list it mirrors: same activity field precedence, same local
-// midnight boundary, projected and unprojected rows alike.
-describe('selectTodayConversations — Today aggregate membership', () => {
- it('keeps today rows from any project and drops yesterday rows at the exact boundary', () => {
+// The sidebar "Recent Tasks" aggregate must agree with the "Today" and
+// "Yesterday" bucket headers of every list it mirrors: same activity field
+// precedence, same local midnight boundaries, projected and unprojected rows
+// alike.
+describe('selectRecentConversations — Recent Tasks membership', () => {
+ it('keeps today and yesterday rows from any project and drops older rows at the exact boundary', () => {
const rows = [
{ conversation_id: 'unprojected-today', last_active_at: offsetFromTodayStart(10 * 60 * 60 * 1000) },
{ conversation_id: 'projected-today', project_id: 'p1', last_active_at: offsetFromTodayStart(0) },
{ conversation_id: 'yesterday-late', project_id: 'p2', last_active_at: offsetFromTodayStart(-1) },
+ { conversation_id: 'yesterday-start', last_active_at: offsetFromTodayStart(-DAY) },
+ { conversation_id: 'day-before-late', project_id: 'p3', last_active_at: offsetFromTodayStart(-DAY - 1) },
{ conversation_id: 'no-timestamps' },
{ title: 'no id', last_active_at: NOW.toISOString() },
null,
];
- expect(selectTodayConversations(rows, NOW).map((c) => c.conversation_id))
- .toEqual(['unprojected-today', 'projected-today']);
+ expect(selectRecentConversations(rows, NOW).map((c) => c.conversation_id))
+ .toEqual(['unprojected-today', 'projected-today', 'yesterday-late', 'yesterday-start']);
});
it('reads last_active_at before updated_at and created_at, exactly like the bucket headers', () => {
@@ -117,12 +121,26 @@ describe('selectTodayConversations — Today aggregate membership', () => {
{ conversation_id: 'created', created_at: offsetFromTodayStart(60_000) },
{ conversation_id: 'stale', updated_at: offsetFromTodayStart(-2 * DAY), created_at: offsetFromTodayStart(-3 * DAY) },
];
- expect(selectTodayConversations(rows, NOW).map((c) => c.conversation_id))
+ expect(selectRecentConversations(rows, NOW).map((c) => c.conversation_id))
.toEqual(['bumped', 'created']);
});
+ it('drops yesterday rows once the local date rolls over', () => {
+ const rows = [{ conversation_id: 'yesterday', last_active_at: offsetFromTodayStart(-60_000) }];
+ expect(selectRecentConversations(rows, NOW).map((c) => c.conversation_id)).toEqual(['yesterday']);
+ const tomorrow = new Date(NOW.getTime() + DAY);
+ expect(selectRecentConversations(rows, tomorrow)).toEqual([]);
+ });
+
it('tolerates a missing or non-array cache', () => {
- expect(selectTodayConversations(undefined, NOW)).toEqual([]);
- expect(selectTodayConversations({} as unknown, NOW)).toEqual([]);
+ expect(selectRecentConversations(undefined, NOW)).toEqual([]);
+ expect(selectRecentConversations({} as unknown, NOW)).toEqual([]);
+ });
+
+ it('loads the startup slice from the local start of yesterday', () => {
+ const since = recentConversationsSince(NOW);
+ expect(since.getTime()).toBe(new Date(offsetFromTodayStart(-DAY)).getTime());
+ expect(since.getHours()).toBe(0);
+ expect(since.getMinutes()).toBe(0);
});
});
diff --git a/test/renderer/conversation-cache-test-source.ts b/test/renderer/conversation-cache-test-source.ts
new file mode 100644
index 00000000..796def1d
--- /dev/null
+++ b/test/renderer/conversation-cache-test-source.ts
@@ -0,0 +1,11 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import ts from 'typescript';
+
+// Narrow renderer fixtures load the actual cache boundary without importing
+// conversation.js's unrelated DOM/IPC initialization or reimplementing merges.
+const source = readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation.js'), 'utf8');
+const parsed = ts.createSourceFile('conversation.js', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+const names = new Set(['_replaceConversationSlice', '_appendConversationSlice', '_cacheCreatedConversation']);
+export const conversationCacheSource = parsed.statements.filter(node =>
+ ts.isFunctionDeclaration(node) && names.has(node.name?.text || '')).map(node => node.getText(parsed)).join('\n');
diff --git a/test/renderer/conversation-cross-task-reference.test.ts b/test/renderer/conversation-cross-task-reference.test.ts
index 823afd8d..e4aecc7d 100644
--- a/test/renderer/conversation-cross-task-reference.test.ts
+++ b/test/renderer/conversation-cross-task-reference.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import { conversationCacheSource } from './conversation-cache-test-source';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
@@ -19,6 +20,30 @@ const projectDetailSource = fs.readFileSync(
const indexSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
describe('conversation cross-task message reference UI', () => {
+ it('keeps one target task and its newer metadata when creation is already visible during a quote handoff', async () => {
+ const current = { conversation_id: 'target', title: 'Renamed target', project_id: 'p-new',
+ created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:01:00Z', processing: true };
+ const payload = { msgId: 'source-message', text: 'Quoted message' };
+ const context = vm.createContext({
+ conversations: [current],
+ _addQuote: vi.fn(), _closeReferenceTargetPicker: vi.fn(), _exitMessageSelection: vi.fn(),
+ setView: vi.fn(), renderConversationList: vi.fn(), _renderQuotePreview: vi.fn(),
+ document: { getElementById: () => null },
+ });
+ vm.runInContext(conversationCacheSource + '\n' + conversationSource.slice(
+ conversationSource.indexOf('async function _transferSelectedReferences('),
+ conversationSource.indexOf('function _referenceTargetProject('),
+ ), context);
+ await context._transferSelectedReferences('target', [payload], { fresh: true,
+ conversation: { conversation_id: 'target', title: 'Creation title', project_id: 'p-old',
+ created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:00:00Z' },
+ });
+ expect(context.conversations).toEqual([current]);
+ expect(context._addQuote).toHaveBeenCalledExactlyOnceWith('target', payload);
+ expect(context.setView).toHaveBeenCalledExactlyOnceWith('conversation', 'target', { skipLoad: true });
+ expect(context._exitMessageSelection).toHaveBeenCalledOnce();
+ });
+
it('exposes secondary actions after the quote without an overflow menu', () => {
expect(conversationSource).toContain('<span class="chat-bubble-direct-actions">${quoteButton}</span>');
expect(conversationSource).toContain('${secondaryActions}');
@@ -79,29 +104,41 @@ describe('conversation cross-task message reference UI', () => {
expect(conversationSource).toContain("setView('conversation', targetCid");
expect(conversationSource).toContain("setView('new-chat')");
expect(conversationSource).toContain("setView('project', projectId)");
- expect(conversationSource).toContain('_stageReferencesForNewTask(payloads, sourceProjectId)');
+ expect(conversationSource).toContain('_stageReferencesForNewTask(payloads, picker.projectId)');
+ expect(conversationSource).toContain("_stageReferencesForNewTask(payloads, '')");
+ expect(conversationSource).toContain('_stageReferencesForNewTask(payloads, target.dataset.createProjectId)');
expect(conversationSource).not.toContain('function _createReferenceTargetTask');
expect(conversationSource).not.toContain('_transferSelectedReferences(targetCid, payloads);\n sendInCurrentConversation');
});
- it('inherits project scope for new tasks and shows only the five most recent tasks by default', () => {
- expect(conversationSource).toContain("const sourceProjectId = _projectIdForConversation(currentCid)");
+ it('lets the user pick the new-task owner and browse every task of a scope in batches', () => {
+ expect(conversationSource).not.toContain('const sourceProjectId = _projectIdForConversation(currentCid)');
expect(conversationSource).toContain('return projectId ? `projchat-${projectId}` : DRAFT_CID');
expect(conversationSource).toContain("const res = await apiFetch('/api/conversations/list')");
expect(conversationSource).toContain('const [targetConversations] = await Promise.all(loads)');
expect(conversationSource).toContain('Array.isArray(targetConversations) ? targetConversations : []');
- expect(conversationSource).toContain('const tasks = needle ? matches.slice(0, 80) : matches.slice(0, 5)');
+ expect(conversationSource).not.toContain('matches.slice(0, 80)');
+ expect(conversationSource).not.toContain('matches.slice(0, 5)');
+ expect(conversationSource).toContain('const shown = matches.slice(0, picker.limit)');
+ expect(conversationSource).toContain('picker.limit += _REFERENCE_TARGET_PAGE_SIZE');
+ expect(conversationSource).toContain("if (picker.scope === 'global') return !conv.project_id");
+ expect(conversationSource).toContain("if (picker.scope === 'project') return conv.project_id === picker.projectId");
expect(conversationSource).toContain('_referenceTargetActivity(b).localeCompare(_referenceTargetActivity(a))');
expect(conversationSource).toContain("String(conv.title || '').toLowerCase().includes(needle)");
expect(conversationSource).not.toContain('_referenceTargetAreaLabel(conv).toLowerCase().includes(needle)');
});
- it('keeps search inside the existing-task section and uses compact picker typography', () => {
- const existingStart = conversationSource.indexOf('class="chat-reference-existing"');
+ it('places new-task above search in the browse pane and uses compact picker typography', () => {
+ const browseStart = conversationSource.indexOf('class="chat-reference-browse"');
+ const newTaskStart = conversationSource.indexOf('class="chat-reference-new-task"');
const searchStart = conversationSource.indexOf('class="chat-reference-target-search-wrap"');
- expect(existingStart).toBeGreaterThanOrEqual(0);
- expect(searchStart).toBeGreaterThan(existingStart);
- expect(styleSource).toContain('width: min(468px, calc(100vw - 40px));');
+ expect(browseStart).toBeGreaterThanOrEqual(0);
+ expect(newTaskStart).toBeGreaterThan(browseStart);
+ expect(searchStart).toBeGreaterThan(newTaskStart);
+ expect(conversationSource.indexOf('class="chat-reference-scopes"')).toBeLessThan(browseStart);
+ expect(styleSource).toContain('width: min(744px, calc(100vw - 40px));');
+ expect(styleSource).toContain('grid-template-columns: 184px minmax(0, 1fr);');
+ expect(styleSource).toContain('.chat-reference-create[hidden] { display: none; }');
expect(styleSource).toContain('.chat-reference-target-header h2');
expect(styleSource).toContain('font-size: 13px;');
expect(styleSource).toContain('height: 38px;');
diff --git a/test/renderer/conversation-detail-performance.test.ts b/test/renderer/conversation-detail-performance.test.ts
index 3d65726b..8a0d8e3c 100644
--- a/test/renderer/conversation-detail-performance.test.ts
+++ b/test/renderer/conversation-detail-performance.test.ts
@@ -69,7 +69,8 @@ describe('conversation detail first-paint boundary', () => {
expect(handler).toContain('const [runtime, initialPage] = await Promise.all([');
expect(handler).not.toContain('? await chats.getMessagesPageAtIndex(');
expect(handler).toContain('chats.getMessagesPageAtIndex(');
- expect(handler).toContain('requestedAroundIndex, requestedLimit, resolvedProjectId');
+ expect(handler).toContain('anchorIndex, requestedLimit, resolvedProjectId');
+ expect(handler).toContain('ctx.userId, cid, requestedAroundMessageId, requestedLimit, resolvedProjectId');
expect(handler).toContain('resolvedProjectId,\n );');
});
diff --git a/test/renderer/conversation-failed-retry.test.ts b/test/renderer/conversation-failed-retry.test.ts
index 86cc1ca5..0965ed92 100644
--- a/test/renderer/conversation-failed-retry.test.ts
+++ b/test/renderer/conversation-failed-retry.test.ts
@@ -262,7 +262,6 @@ describe('conversation busy-path send with a deduped retry', () => {
_convLog: { warn: (text: string) => { warnings.push(text); }, info: noop, error: noop, debug: noop },
_renderOrClaimPersistedUserMessage: (cid: string, msg: unknown) => { rendered.push(msg); return true; },
_chatModelTelemetryContext: () => ({}),
- _normalizeCommanderTemplateAttribution: () => ({}),
window: { TaskBoard: { resync: noop } },
};
const context = new Proxy(target, {
diff --git a/test/renderer/conversation-handoff-process.test.ts b/test/renderer/conversation-handoff-process.test.ts
index 6cc579dc..df5b6d00 100644
--- a/test/renderer/conversation-handoff-process.test.ts
+++ b/test/renderer/conversation-handoff-process.test.ts
@@ -88,6 +88,7 @@ function loadRedundantCommanderRecord(): (record: unknown) => boolean {
extractFunction('_isRoutingOnlyEventNames'),
extractFunction('_isRoutingOnlyProcessItems'),
extractFunction('_processItemsContainSuccessfulTerminalHandoff'),
+ extractFunction('_processItemsHavePublicCommentary'),
`(${extractFunction('_isRedundantRoutingOnlyCommanderRecord')})`,
].join('\n');
return vm.runInNewContext(combined, {});
@@ -290,6 +291,17 @@ describe('routing-only Commander history visibility', () => {
})).toBe(false);
});
+ it('preserves a commentary-only segment even when its tools only route', () => {
+ const isRedundant = loadRedundantCommanderRecord();
+ expect(isRedundant({ from: 'commander', text: '', process: [
+ { type: 'progress', text: 'I will delegate the requested work.',
+ event: { stream: 'assistant', data: { phase: 'commentary' } } }, dispatchItem,
+ ] })).toBe(false);
+ expect(isRedundant({ from: 'commander', text: '', process: [
+ { type: 'progress', text: ' ', event: { stream: 'assistant', data: { phase: 'commentary' } } }, dispatchItem,
+ ] })).toBe(true);
+ });
+
it('still drops empty and abort-only routing tails', () => {
const isRedundant = loadRedundantCommanderRecord();
expect(isRedundant({ from: 'commander', text: '', process: [dispatchItem] })).toBe(true);
diff --git a/test/renderer/conversation-history-auto-load.test.ts b/test/renderer/conversation-history-auto-load.test.ts
index dfaee588..7c9d7f58 100644
--- a/test/renderer/conversation-history-auto-load.test.ts
+++ b/test/renderer/conversation-history-auto-load.test.ts
@@ -126,7 +126,8 @@ describe('conversation history auto-load', () => {
const row = { dataset: { state: 'idle', cursor: '120', cid: 'c1' } };
const container = {
scrollTop: 32,
- querySelector: () => row,
+ _historyEarlierRow: row,
+ contains: (node: unknown) => node === row,
};
const context: any = {
Number,
@@ -143,6 +144,7 @@ describe('conversation history auto-load', () => {
vm.createContext(context);
vm.runInContext([
extractFunction('_historyNextCursor'),
+ extractFunction('_historyLoaderRow'),
extractFunction('_maybeAutoLoadEarlierHistory'),
].join('\n'), context);
@@ -166,12 +168,14 @@ describe('conversation history auto-load', () => {
vm.createContext(context);
vm.runInContext([
extractFunction('_historyNextCursor'),
+ extractFunction('_historyLoaderRow'),
extractFunction('_maybeAutoLoadEarlierHistory'),
].join('\n'), context);
- context._maybeAutoLoadEarlierHistory({ scrollTop: 12, querySelector: () => row });
+ const holding = (scrollTop: number) => ({ scrollTop, _historyEarlierRow: row, contains: (node: unknown) => node === row });
+ context._maybeAutoLoadEarlierHistory(holding(12));
context._isProgrammaticStickyScroll = () => false;
- context._maybeAutoLoadEarlierHistory({ scrollTop: 80, querySelector: () => row });
+ context._maybeAutoLoadEarlierHistory(holding(80));
expect(calls).toBe(0);
});
@@ -184,7 +188,8 @@ describe('conversation history auto-load', () => {
getBoundingClientRect: () => ({ top: 100, bottom: 140 }),
};
const container = {
- querySelector: (selector: string) => selector === '.chat-history-load-newer' ? row : null,
+ _historyNewerRow: row,
+ contains: (node: unknown) => node === row,
getBoundingClientRect: () => ({ top: 0, bottom: 500 }),
addEventListener: (name: string, listener: (event?: any) => void) => { listeners[name] = listener; },
};
@@ -197,6 +202,7 @@ describe('conversation history auto-load', () => {
};
vm.createContext(context);
vm.runInContext([
+ extractFunction('_historyLoaderRow'),
extractFunction('_maybeAutoLoadNewerHistory'),
extractFunction('_bindAutoLoadEarlierHistory'),
].join('\n'), context);
@@ -208,6 +214,68 @@ describe('conversation history auto-load', () => {
expect(calls).toEqual(['c1']);
});
+ // Scroll and wheel events fire at 60-120 Hz on a transcript that grows with
+ // every page the reader visits; finding the two loader rows must not search
+ // it, and on the latest page (no newer row) that search used to visit every
+ // node on every event.
+ it('handles scroll and wheel without searching the transcript for loader rows', () => {
+ const listeners: Record<string, (event?: any) => void> = {};
+ const calls: string[] = [];
+ let searches = 0;
+ const container: any = {
+ scrollTop: 400,
+ querySelector: () => { searches += 1; return null; },
+ contains: (node: any) => node?.parentElement === container,
+ getBoundingClientRect: () => ({ top: 0, bottom: 500 }),
+ addEventListener: (name: string, listener: (event?: any) => void) => { listeners[name] = listener; },
+ };
+ const context: any = {
+ Number, String, currentCid: 'c1', HISTORY_AUTO_LOAD_THRESHOLD: 48,
+ _isProgrammaticStickyScroll: () => false,
+ _loadOlderConversationHistory: (cid: string, cursor: number) => { calls.push(`older:${cid}:${cursor}`); },
+ _loadNewerConversationHistory: (cid: string) => { calls.push(`newer:${cid}`); },
+ _setEarlierHistoryLoaderState: (row: any, state: string) => { row.dataset.state = state; },
+ };
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction('_historyNextCursor'),
+ rendererSource.includes('function _historyLoaderRow') ? extractFunction('_historyLoaderRow') : '',
+ extractFunction('_maybeAutoLoadEarlierHistory'),
+ extractFunction('_maybeAutoLoadNewerHistory'),
+ extractFunction('_bindAutoLoadEarlierHistory'),
+ ].join('\n'), context);
+ context._bindAutoLoadEarlierHistory(container);
+
+ // Latest page and start of history: no loader rows at all.
+ for (let i = 0; i < 3; i += 1) listeners.scroll();
+ listeners.wheel({ deltaY: 100 });
+ listeners.wheel({ deltaY: -100 });
+ expect(calls).toEqual([]);
+
+ const newer = { parentElement: container, dataset: { cid: 'c1', state: 'idle' },
+ getBoundingClientRect: () => ({ top: 480, bottom: 520 }) };
+ container._historyNewerRow = newer;
+ listeners.wheel({ deltaY: 100 });
+ expect(calls).toEqual(['newer:c1']);
+
+ const earlier = { parentElement: container, dataset: { cid: 'c1', cursor: '120', state: 'error' } };
+ container._historyEarlierRow = earlier;
+ listeners.scroll();
+ expect(earlier.dataset.state).toBe('idle');
+ container.scrollTop = 10;
+ listeners.scroll();
+ expect(calls).toEqual(['newer:c1', 'newer:c1', 'older:c1:120', 'newer:c1']);
+
+ // A rebuilt transcript detaches the rows; their stale references are ignored.
+ newer.parentElement = null;
+ earlier.parentElement = null;
+ calls.length = 0;
+ listeners.scroll();
+ listeners.wheel({ deltaY: 100 });
+ expect(calls).toEqual([]);
+ expect(searches).toBe(0);
+ });
+
it('keeps the previous reading anchor after prepending older content', () => {
const context: any = { Number, Math };
vm.createContext(context);
diff --git a/test/renderer/conversation-info-library-import.test.ts b/test/renderer/conversation-info-library-import.test.ts
index 2db32668..2aabd8fd 100644
--- a/test/renderer/conversation-info-library-import.test.ts
+++ b/test/renderer/conversation-info-library-import.test.ts
@@ -103,7 +103,7 @@ function createHarness(options: {
const monitorEvent = vi.fn();
const labels: Record<string, string> = {
'conversation_info.file_reveal_action': 'Show in folder',
- 'conversation_info.file_reveal_failed': 'Could not open folder: {reason}',
+ 'conversation_info.file_reveal_failed': 'Could not open the folder. The file may have been moved or deleted.',
'conversation_info.file_add_to_chat_action': 'Add to chat',
'conversation_info.file_add_to_library_action': 'Add to Library',
'conversation_info.file_add_to_library_done': 'Added to {library}',
@@ -319,13 +319,16 @@ describe('shared file actions for inline audio', () => {
expect(onDeleted).not.toHaveBeenCalled();
});
- it.each(['response', 'rejection'])('reports a reveal %s failure and allows another attempt', async failure => {
- const harness = createHarness({ importResult: {} });
+ it.each(['response', 'rejection'])('reports a reveal %s failure with only localized copy and allows another attempt', async failure => {
+ const en = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/renderer/locales/en.json'), 'utf8')) as Record<string, string>;
+ const harness = createHarness({ importResult: {}, labels: en });
const menu = await harness.openFileMenu(filePath);
- if (failure === 'response') harness.invoke.mockResolvedValueOnce({ ok: false, error: 'unavailable' });
- else harness.invoke.mockRejectedValueOnce(new Error('unavailable'));
+ // Raw host reasons can carry local paths and internal error text.
+ const reason = 'ENOENT: /Users/test/private/voice.mp3';
+ if (failure === 'response') harness.invoke.mockResolvedValueOnce({ ok: false, error: reason });
+ else harness.invoke.mockRejectedValueOnce(new Error(reason));
await menu.click('reveal');
- expect(harness.uiAlert).toHaveBeenCalledExactlyOnceWith('Could not open folder: unavailable');
+ expect(harness.uiAlert).toHaveBeenCalledExactlyOnceWith('Could not open the folder. The file may have been moved or deleted.');
await (await harness.openFileMenu(filePath)).click('reveal');
expect(harness.invoke.mock.calls.filter(([channel]) => channel === 'workspace.revealPath')).toHaveLength(2);
});
diff --git a/test/renderer/conversation-info.test.ts b/test/renderer/conversation-info.test.ts
index c4f9eec7..52709038 100644
--- a/test/renderer/conversation-info.test.ts
+++ b/test/renderer/conversation-info.test.ts
@@ -179,6 +179,39 @@ describe('ConversationInfo files tab', () => {
});
});
+ it('dismisses only the owning browser and remembers background dismissal without changing Files or Attachments', async () => {
+ await renderFilesResult({ history: [], files: { items: [] } }, context => {
+ const info = context.window.ConversationInfo;
+ const panel = context.document.getElementById('conversation-info-panel');
+ const body = context.document.getElementById('conversation-info-body');
+ info.openAndSetTab('browser');
+ info.closeBrowserForTask('c1');
+ expect(panel.hidden).toBe(true);
+ // Returning to the task must retain the automatic dismissal.
+ info.bind('c2');
+ info.bind('c1');
+ expect(panel.hidden).toBe(true);
+ info.openAndSetTab('browser');
+ info.bind('c2');
+ info.openAndSetTab('browser');
+ info.closeBrowserForTask('c1');
+ expect(panel.hidden).toBe(false);
+ info.bind('c1');
+ expect(panel.hidden).toBe(true);
+ for (const tab of ['files', 'attachments']) {
+ info.openAndSetTab(tab);
+ info.closeBrowserForTask('c1');
+ expect(panel.hidden).toBe(false);
+ expect(body.hidden).toBe(false);
+ info.bind('c2');
+ info.closeBrowserForTask('c1');
+ info.bind('c1');
+ expect(panel.hidden).toBe(false);
+ expect(body.hidden).toBe(false);
+ }
+ });
+ });
+
// Membership now arrives already merged from
// `features/conversation_outputs.ts`; what the panel still owns is where each
// entry lands. A file written outside the workspace has no tree position, and
diff --git a/test/renderer/conversation-keyed-rendering.test.ts b/test/renderer/conversation-keyed-rendering.test.ts
index 0d964ca6..671bc480 100644
--- a/test/renderer/conversation-keyed-rendering.test.ts
+++ b/test/renderer/conversation-keyed-rendering.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
@@ -38,10 +38,13 @@ class FakeNode {
final: { children: [], textContent: '', replaceChildren() { this.children = []; this.textContent = ''; } },
};
+ processDisclosure: any = null;
querySelector(selector: string) {
+ if (selector === '.stream-process') return this.processDisclosure;
if (selector === '[data-role="process"]') return this.bodies.process;
if (selector === '[data-role="final"]') return this.bodies.final;
- if (selector === '.chat-bubble') return { querySelector: () => null, appendChild() {} };
+ if (selector === '.chat-bubble') return { querySelector: () => null, appendChild() {},
+ insertBefore: (child: any) => { this.processDisclosure = child; } };
return null;
}
@@ -63,6 +66,7 @@ class FakeContainer {
}
appendChild(node: FakeNode) {
+ node.parentElement?.removeChild(node);
node.parentElement = this as any;
this.rows.push(node);
return node;
@@ -81,7 +85,9 @@ class FakeContainer {
node.parentElement = null;
}
+ processDisclosure: any = null;
querySelector(selector: string) {
+ if (selector === '.stream-process') return this.processDisclosure;
return this.matchRows(selector)[0] || null;
}
@@ -114,6 +120,7 @@ function loadRenderer(cid: string) {
const appended: any[] = [];
const pendingConvs = new Map<string, any>();
const groupBusyConvs = new Map<string, boolean>();
+ const documentListeners = new Map<string, Function[]>();
const context: any = {
console, setTimeout, clearTimeout, setInterval, clearInterval,
@@ -138,7 +145,9 @@ function loadRenderer(cid: string) {
// 'loading' keeps module-level boot wiring from running during eval —
// these tests drive the event handler directly.
readyState: 'loading',
- addEventListener() {},
+ addEventListener(name: string, callback: Function) {
+ documentListeners.set(name, [...(documentListeners.get(name) || []), callback]);
+ },
querySelector: () => null,
querySelectorAll: () => [],
getElementById: (id: string) => (id === 'chat-history' ? container : null),
@@ -187,9 +196,8 @@ function loadRenderer(cid: string) {
// branch) so a merged record's earlier segments reach the row.
if (legacy._narration && legacy._narration.length) {
for (var i = 0; i < legacy._narration.length; i++) {
- _appendNarrationBlock(node, legacy._narration[i].seg, legacy._narration[i].text, { deferFold: true });
+ _appendNarrationBlock(node, legacy._narration[i].seg, legacy._narration[i].text, { paint: false });
}
- _applyNarrationFold(node);
}
(opts.container || __container).appendChild(node);
return node;
@@ -203,7 +211,10 @@ function loadRenderer(cid: string) {
_startPlaceholderActivity = function() {};
_stampPlaceholderTriggerMsg = function() {};
_streamingAppendFinalDelta = function(node, text) {
- node.bodies.final.textContent += text;
+ // Production replaces the painted body from its buffer; it never
+ // appends to the DOM's existing text during snapshot recovery.
+ node.dataset.streamBuf = (node.dataset.streamBuf || '') + text;
+ node.bodies.final.textContent = node.dataset.streamBuf;
};
_streamingAppendProgress = function(node) { node.bodies.process.children.push(1); };
_streamingUpdateActivity = function() {};
@@ -230,12 +241,189 @@ function loadRenderer(cid: string) {
context.__appended = appended;
context.__makeNode = () => new FakeNode();
- return { context, container, finalized, appended };
+ return { context, container, finalized, appended, documentListeners };
+}
+
+function configureDisplayRecovery(context: any) {
+ context.performance = performance;
+ context.convAgentEnabledByCid = new Map();
+ context.pollMsgCounts = new Map();
+ context._agentsCache = [];
+ for (const name of ['_setChatScrollOffset', '_ensureCreateAgentInlineObserver',
+ '_ensureConvCreateAgentInline', '_syncFailedFromHistory',
+ '_setLoadEarlierHistory', '_setLoadNewerHistory', '_setHistoryLatestAction',
+ '_bindAutoLoadEarlierHistory', '_scheduleConversationTurnNavigation', '_renderConvDisabledBanner',
+ '_scrollToBottomNoAnim', '_observeConversationRunFromPlanAction', '_startRuntimeActorRecovery',
+ '_captureHistoryReloadScroll', '_restoreHistoryReloadScroll', '_stickBottomIfPinned']) {
+ context[name] = () => {};
+ }
}
const CID = 'c1';
const TURN = 'turn-1';
+describe('keyed rendering › durable terminal recovery', () => {
+ it('keeps a saved-task shortcut when an otherwise empty Commander reply hands off the work', () => {
+ const h = loadRenderer(CID);
+ const record = { from: 'commander', text: '', process: [{ type: 'event', event: {
+ stream: 'tool', data: { name: 'hand_off_to', phase: 'end', isError: false },
+ } }] };
+ expect(h.context._isVisibleGroupHistoryRecord(record)).toBe(false);
+ expect(h.context._isVisibleGroupHistoryRecord({ ...record, saved_tasks: [{
+ kind: 'todo', task_id: 'saved-todo', project_id: '', title: 'Review release',
+ }] })).toBe(true);
+ });
+
+ const actor = 'codex-agent';
+ const terminalRecord = (status = 'success', seg = 0): any => ({
+ id: 'saved-terminal', from: actor, to: ['user'], turn_id: TURN, seg,
+ text: 'Canonical result', ts: '2026-10-08T09:13:19Z', source_message_id: 'user-trigger',
+ process: [{ type: 'event', event: { stream: 'runtime', data: {
+ phase: 'end', duration_ms: 239_326, status,
+ aborted: status === 'cancelled', errored: status === 'error',
+ } } }],
+ });
+ function setup(seg = 0) {
+ const h = loadRenderer(CID);
+ configureDisplayRecovery(h.context);
+ const row = h.context._ensureActorPlaceholder(CID, actor, null, TURN, null, undefined, seg);
+ row.dataset.placeholder = '1';
+ row.dataset.streamBuf = 'Partial result';
+ row.bodies.final.textContent = 'Partial result';
+ return { ...h, row };
+ }
+
+ it('recovers a missing terminal record before stream cleanup removes the reply', async () => {
+ const h = setup();
+ let release!: () => void;
+ h.context.apiFetch = async () => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return { ok: true, json: async () => ({ ok: true, history: [terminalRecord()] }) };
+ };
+ h.context.stopPolling = () => {};
+ h.context.pendingConvs.set(CID, { loadingEl: h.row });
+ const settling = h.context._finishStreamingMsg(CID);
+ expect(h.container.rows).toEqual([h.row]);
+ release();
+ await settling;
+ expect(h.container.rows).toEqual([h.row]);
+ expect(h.row.dataset.msgId).toBe('saved-terminal');
+ expect(h.finalized[0].gm.text).toBe('Canonical result');
+ });
+
+ it('preserves an unconfirmed reply when history recovery fails', async () => {
+ const h = setup();
+ h.context.apiFetch = async () => ({ ok: false, json: async () => ({ ok: false }) });
+ await h.context._settleFinishedConversationDisplay(CID, false);
+ expect(h.container.rows).toEqual([h.row]);
+ expect(h.row.dataset.msgId).toBeUndefined();
+ });
+
+ it('does not purge a newer turn that starts during terminal recovery', async () => {
+ const h = setup();
+ let release!: () => void;
+ h.context.apiFetch = async () => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return { ok: true, json: async () => ({ ok: true, history: [terminalRecord()] }) };
+ };
+ const settling = h.context._settleFinishedConversationDisplay(CID, false);
+ const next = h.context._ensureActorPlaceholder(CID, actor, null, 'next-turn', null, undefined, 0);
+ h.context.pendingConvs.set(CID, { loadingEl: next });
+ release();
+ await settling;
+ expect(h.container.rows).toEqual([h.row, next]);
+ expect(next.dataset.msgId).toBeUndefined();
+ });
+
+ // A dropped terminal IPC event must be recoverable from durable history,
+ // regardless of how execution ended. No reply text is used as a status signal.
+ it.each(['success', 'error', 'cancelled', 'waiting_input'])(
+ 'settles the existing reply when polling recovers a %s terminal', async (status) => {
+ const h = setup();
+ await h.context._recoverPolledVisibleMessages(CID, [terminalRecord(status)]);
+ expect(h.container.rows).toEqual([h.row]);
+ expect(h.row.dataset.msgId).toBe('saved-terminal');
+ expect(h.row.dataset.turnEnd).toBe('1');
+ expect(h.finalized).toHaveLength(1);
+ expect(h.finalized[0].gm.text).toBe('Canonical result');
+ expect(h.appended).toHaveLength(0);
+ },
+ );
+
+ it('settles a row advanced beyond the terminal segment without losing earlier narration', async () => {
+ const h = setup(2);
+ const earlier = { ...terminalRecord(), id: 'segment-0', text: 'Earlier explanation', process: [] };
+ await h.context._recoverPolledVisibleMessages(CID, [earlier, terminalRecord('success', 1)]);
+ expect(h.container.rows).toEqual([h.row]);
+ expect(h.row.dataset.msgId).toBe('saved-terminal');
+ expect(h.finalized).toHaveLength(1);
+ expect(h.finalized[0].gm._narration.map((item: any) => item.text)).toEqual(['Earlier explanation']);
+ expect(h.row.dataset.turnEnd).toBe('1');
+ });
+
+ it('keeps recovered completion absorbing while another turn of the same actor runs', async () => {
+ const h = setup();
+ const record = terminalRecord();
+ await h.context._recoverPolledVisibleMessages(CID, [record]);
+ const next = h.context._ensureActorPlaceholder(CID, actor, null, 'next-turn', null, undefined, 0);
+ next.bodies.final.textContent = 'New live text';
+ await h.context._recoverPolledVisibleMessages(CID, [record]);
+ h.context._handleGroupBusEvent(CID, null, { type: 'message', msg: record, turn_end: true });
+ h.context._handleGroupBusEvent(CID, null, { type: 'process', actor, turn_id: TURN, seg: 0,
+ data: { type: 'delta', text: 'Late old delta' } });
+ h.context._restoreLiveDisplaySnapshot(CID, { sequence: 10, turns: [{ actor, turn_id: TURN,
+ records: [{ ...record, id: '', text: 'Stale old snapshot' }] }] });
+ expect(h.container.rows).toEqual([h.row, next]);
+ expect(h.finalized).toHaveLength(1);
+ expect(next.bodies.final.textContent).toBe('New live text');
+ expect(next.dataset.msgId).toBeUndefined();
+ expect(next.dataset.turnEnd).toBeUndefined();
+ });
+
+ it.each(['segment_end', 'retrying', 'duration-only', 'tool-end', 'unpersisted'])(
+ 'preserves live work when recovery contains only %s evidence', async (shape) => {
+ const h = setup();
+ const record = terminalRecord();
+ if (shape === 'unpersisted') record.id = '';
+ else if (shape === 'tool-end') record.process[0].event.stream = 'tool';
+ else if (shape === 'duration-only') delete record.process[0].event.data.phase;
+ else record.process[0].event.data.phase = shape;
+ await h.context._recoverPolledVisibleMessages(CID, [record]);
+ expect(h.container.rows).toEqual([h.row]);
+ expect(h.finalized).toHaveLength(0);
+ expect(h.row.dataset.turnEnd).toBeUndefined();
+ expect(h.row.dataset.msgId).toBeUndefined();
+ },
+ );
+
+ it('retains a durable terminal through a cold load with stale active-turn and display snapshots', async () => {
+ const h = loadRenderer(CID);
+ configureDisplayRecovery(h.context);
+ h.context.document.createDocumentFragment = () => new FakeContainer();
+ const append = h.container.appendChild.bind(h.container);
+ h.container.appendChild = (node: any) => {
+ if (node instanceof FakeContainer) {
+ for (const row of [...node.rows]) append(row);
+ return node;
+ }
+ return append(node);
+ };
+ const record = terminalRecord();
+ const active = [{ actor, turn_id: TURN, started_at_ms: Date.now() }];
+ h.context.apiFetch = async () => ({ json: async () => ({ ok: true, history: [record],
+ conversation: { processing: true, processing_since: new Date().toISOString(),
+ active_turns: active, in_flight: [actor] },
+ live_display: { sequence: 1, active_turns: active, turns: [{ actor, turn_id: TURN,
+ records: [{ ...record, id: '', text: 'Stale partial result', process: [] }] }] },
+ }) });
+ await h.context.loadConversationHistory(CID);
+ expect(h.container.rows).toHaveLength(1);
+ expect(h.container.rows[0].dataset.msgId).toBe(record.id);
+ expect(h.container.rows[0].dataset.turnEnd).toBe('1');
+ expect(h.container.rows[0].bodies.final.textContent).toBe(record.text);
+ });
+});
+
describe('keyed rendering › reconnect history', () => {
it('recovers missing replies once without merging same-text replies from different turns', async () => {
const { context, container, appended, finalized } = loadRenderer(CID);
@@ -444,11 +632,11 @@ describe('keyed rendering › a turn that settles before its records arrive', ()
const row = container.rows[0];
// The DOM fold suite covers the default presentation of six blocks.
// A passive record delivery must not switch that presentation to open.
- row.dataset.narrationExpanded = '0';
+ row.processDisclosure = { open: false, remove() {} };
context._handleGroupBusEvent(CID, null, seg(0, 'part 0', 'rec-0'));
expect(container.rows).toHaveLength(1);
expect(row._narration).toHaveLength(6);
- expect(row.dataset.narrationExpanded).toBe('0');
+ expect(row.processDisclosure.open).toBe(false);
expect(row.dataset.msgId).toBe('rec-6');
});
@@ -499,31 +687,23 @@ describe('keyed rendering › a turn split across history pages', () => {
.toEqual([[0, 'first']]);
});
- it('expands the bubble it absorbed into, so auto-load cannot fire back to back', () => {
- // A folded narration block adds no height. If absorbing left the bubble
- // folded, `scrollHeight` would not move, `scrollTop` would stay under
- // HISTORY_AUTO_LOAD_THRESHOLD, and the next scroll event would load
- // another page immediately — pages firing back to back to the start of the
- // conversation. That is what "scrolling stutters" was (2026-09-18).
+ it.each([false, true])('preserves settled process open=%s when older history is absorbed', (open) => {
const { context, container } = loadRenderer(CID);
settle(context, 'T1', 9);
- container.rows[0].dataset.narrationExpanded = '0';
+ container.rows[0].processDisclosure = { open, remove() {} };
context._mergeNativeSegmentRecords([record('T1', 5, 'fifth')], CID);
- expect(container.rows[0].dataset.narrationExpanded,
- 'older segments are what the reader scrolled up for').toBe('1');
+ expect(container.rows[0].processDisclosure.open === true,
+ 'loading data must not change the reader\'s disclosure state').toBe(open);
});
- it('does not override a fold the reader chose', () => {
- // Absorbing expands so auto-load cannot fire back to back, but that must
- // not undo an explicit collapse (2026-09-18: switching conversations and
- // back re-opened it).
+ it('keeps the shared process disclosure collapsed for passive history reconciliation', () => {
const { context, container } = loadRenderer(CID);
settle(context, 'T-chosen', 9);
- context._rememberNarrationFoldChoice('T-chosen', false);
- container.rows[0].dataset.narrationExpanded = '0';
- context._mergeNativeSegmentRecords([record('T-chosen', 5, 'fifth')], CID);
- expect(container.rows[0].dataset.narrationExpanded,
- 'the reader decided this one').toBe('0');
+ container.rows[0].processDisclosure = { open: false, remove() {} };
+ context._absorbEarlierTurnPage(CID, 'agent-1', 'T-chosen',
+ [record('T-chosen', 5, 'fifth')]);
+ expect(container.rows[0].processDisclosure.open === true).toBe(false);
+ expect((container.rows[0] as any)._persistedProcessItems[0].text).toBe('fifth');
});
it('leaves a record alone when no rendered bubble owns its turn', () => {
@@ -738,6 +918,24 @@ describe('keyed rendering › silent turns', () => {
expect(container.rows[0].dataset.msgId).toBe('msg-0');
});
+ it('retains a persisted commentary-only Commander bubble at the dispatch boundary', () => {
+ const { context, container } = loadRenderer(CID);
+ context._handleGroupBusEvent(CID, null, {
+ ...delta(0, 'I will delegate the requested work.'),
+ data: { type: 'delta', phase: 'commentary', text: 'I will delegate the requested work.' },
+ });
+ const message: any = segMessage(0, '', 'commentary-segment');
+ message.msg.process = [
+ { type: 'progress', text: 'I will delegate the requested work.',
+ event: { stream: 'assistant', data: { phase: 'commentary' } } },
+ { type: 'event', event: { stream: 'tool', data: { name: 'dispatch_to', phase: 'start' } } },
+ ];
+ context._handleGroupBusEvent(CID, null, message);
+ context._handleGroupBusEvent(CID, null, { type: 'segment_boundary', cid: CID, actor: 'commander', turn_id: TURN });
+ expect(commanderRows(container)).toHaveLength(1);
+ expect(container.rows[0].dataset.msgId).toBe('commentary-segment');
+ });
+
it('never drops a persisted segment when its turn goes silent', () => {
const { context, container } = loadRenderer(CID);
@@ -1255,8 +1453,8 @@ describe('keyed rendering › one bubble per external-CLI turn', () => {
expect(finalized).toHaveLength(1);
expect(finalized[0].gm.text).toBe('改完了。');
expect(finalized[0].gm._narration.map((item: any) => item.seg)).toEqual([0, 1]);
- expect(finalized[0].gm.process.map((item: any) => item.event.data.name + ':' + item.event.data.phase))
- .toEqual(['read_file:start', 'bash:start', 'bash:end']);
+ expect(finalized[0].gm.process.map((item: any) => item.text || item.event.data.name + ':' + item.event.data.phase))
+ .toEqual(['开始改。', 'read_file:start', '我在核对。', 'bash:start', 'bash:end']);
expect(appended).toHaveLength(0);
});
@@ -1294,7 +1492,7 @@ describe('keyed rendering › one bubble per external-CLI turn', () => {
expect(appended).toHaveLength(1);
expect(row.dataset.msgId).toBe('native-3');
expect((row as any)._narration.map((item: any) => item.seg).sort()).toEqual([0, 1, 2]);
- expect((row as any)._persistedProcessItems.map((item: any) => item.event.data.duration_ms)).toEqual([0, 1, 2, 30]);
+ expect((row as any)._persistedProcessItems.map((item: any) => item.text ?? item.event.data.duration_ms)).toEqual(['过程 0', 0, '过程 1', 1, '过程 2', 2, 30]);
const otherActor = nativeMessage(0, '另一位成员', 'other-actor', false).msg;
otherActor.from = 'agent-other';
expect(context._mergeNativeSegmentRecords([otherActor], CID)).toHaveLength(1);
@@ -1413,7 +1611,7 @@ describe('keyed rendering › one bubble per external-CLI turn', () => {
expect(container.rows.map(row => row.dataset.msgId)).toEqual(['native-2']);
expect(finalized).toHaveLength(1);
expect(finalized[0].gm._narration.map((item: any) => item.seg)).toEqual([0, 1]);
- expect(finalized[0].gm.process.map((item: any) => item.text)).toEqual(['读取文件', '运行测试', '收尾']);
+ expect(finalized[0].gm.process.map((item: any) => item.text)).toEqual(['开始改。', '读取文件', '我在核对。', '运行测试', '收尾']);
expect(appended).toHaveLength(0);
});
@@ -1438,6 +1636,198 @@ describe('keyed rendering › one bubble per external-CLI turn', () => {
describe('active transcript recovery after task switching', () => {
+ it('defers an in-flight foreground snapshot after the window hides, then restores it when visible', async () => {
+ const { context, container } = loadRenderer(CID);
+ configureDisplayRecovery(context);
+ const actor = 'codex-agent';
+ context._handleGroupBusEvent(CID, null, delta(0, 'Visible prefix', actor));
+ const row = container.rows[0];
+ row.dataset.placeholder = '1';
+ context.pendingConvs.set(CID, { loadingEl: row, controller: {}, needsIndicator: false });
+ const snapshot = { ok: true, history: [],
+ conversation: { processing: true, processing_since: new Date().toISOString(),
+ active_turns: [{ actor, turn_id: TURN }] },
+ live_display: { sequence: 2, turns: [{ actor, turn_id: TURN,
+ records: [{ id: '', from: actor, turn_id: TURN, seg: 0, text: 'Latest hidden text', process: [] }] }] },
+ };
+ let resolve!: (response: any) => void;
+ context.apiFetch = () => new Promise(release => { resolve = release; });
+ const refreshing = context.loadConversationHistory(CID, { preserveScroll: true, refreshDisplay: true });
+ context._onConversationWindowVisibility({ active: false });
+ resolve({ json: async () => snapshot });
+ await refreshing;
+ expect(row.bodies.final.textContent).toBe('Visible prefix');
+ context.apiFetch = async () => ({ json: async () => snapshot });
+ context._onConversationWindowVisibility({ active: true });
+ await vi.waitFor(() => expect(row.bodies.final.textContent).toBe('Latest hidden text'));
+ expect(container.rows).toEqual([row]);
+ });
+
+ // Typical trigger: the app restores the last task at startup while the user
+ // has switched to another window. The completed cold or anchored load must
+ // still end with its paging rows and its target once the window is active.
+ it.each(['native-hidden', 'other-panel'])('replays a full history load that finished while not visible: %s', async (surface) => {
+ const { context } = loadRenderer(CID);
+ configureDisplayRecovery(context);
+ // A cold load stages its rows off-DOM before mounting them.
+ context.document.createDocumentFragment = () => new FakeContainer();
+ const rows: any[] = [];
+ const revealed: string[] = [];
+ context._setLoadEarlierHistory = (_el: any, cid: string, cursor: any) => rows.push(['earlier', cid, cursor]);
+ context._setLoadNewerHistory = (_el: any, cid: string, cursor: any) => rows.push(['newer', cid, cursor]);
+ context._revealConversationHistorySearchTarget = (_cid: string, target: any) => { revealed.push(target.msgId); return true; };
+ const page = { ok: true, next_cursor: 40, following_cursor: 41,
+ history: [{ id: 'm-40', from: 'commander', text: 'Quoted original', ts: '2026-10-01T00:00:00Z', _history_index: 40 }],
+ conversation: { processing: false, active_turns: [] },
+ live_display: { sequence: 1, active_turns: [], turns: [] } };
+ let requests = 0;
+ let resolve!: (response: any) => void;
+ context.apiFetch = () => { requests++; return new Promise(release => { resolve = release; }); };
+ const loading = context.loadConversationHistory(CID, { searchTarget: { msgId: 'm-40' } });
+ if (surface === 'native-hidden') context._onConversationWindowVisibility({ active: false });
+ else context.currentView = 'agents';
+ resolve({ json: async () => page });
+ await loading;
+ expect(rows).toEqual([]);
+ expect(revealed).toEqual([]);
+
+ context.apiFetch = async () => { requests++; return { json: async () => page }; };
+ if (surface === 'native-hidden') context._onConversationWindowVisibility({ active: true });
+ else { context.currentView = 'conversation'; context._refreshVisibleConversationDisplay(CID); }
+ await vi.waitFor(() => expect(revealed).toEqual(['m-40']));
+ expect(rows).toEqual([['earlier', CID, 40], ['newer', CID, 41]]);
+ expect(requests).toBe(2);
+ });
+
+ it('refreshes once on foreground, preserves older mounted history, and continues from the latest snapshot', async () => {
+ const { context, container, documentListeners } = loadRenderer(CID);
+ configureDisplayRecovery(context);
+ const actor = 'codex-agent';
+ context._handleGroupBusEvent(CID, null, {
+ type: 'message', msg: { id: 'older', from: 'commander', text: 'Older history stays mounted', ts: '2026-01-01T00:00:00Z' },
+ });
+ const older = container.rows[0];
+ context._handleGroupBusEvent(CID, null, delta(0, 'Before hiding', actor));
+ context.document.visibilityState = 'hidden';
+ for (const handler of documentListeners.get('visibilitychange') || []) handler();
+ context._handleGroupBusEvent(CID, null, { ...delta(0, ' unseen text', actor), display_seq: 1 });
+ expect(container.rows[1].bodies.final.textContent).toBe('Before hiding');
+ let requests = 0;
+ let resolveHistory!: (response: any) => void;
+ context.apiFetch = () => { requests++; return new Promise(resolve => { resolveHistory = resolve; }); };
+ context.document.visibilityState = 'visible';
+ for (const handler of documentListeners.get('visibilitychange') || []) handler();
+ context._refreshVisibleConversationDisplay(CID);
+ expect(requests).toBe(1);
+ context._handleGroupBusEvent(CID, null, { ...delta(0, ' latest', actor), display_seq: 2 });
+ const active = [{ actor, turn_id: TURN }];
+ resolveHistory({ json: async () => ({ ok: true, history: [],
+ conversation: { processing: true, processing_since: new Date().toISOString(), active_turns: active },
+ live_display: { sequence: 2, active_turns: active, turns: [{ actor, turn_id: TURN, records: [{
+ id: '', from: actor, turn_id: TURN, seg: 0, text: 'Before hiding unseen text latest', process: [],
+ }] }] },
+ }) });
+ await vi.waitFor(() => expect(container.rows.find(row => row.dataset.turnId === TURN)?.bodies.final.textContent)
+ .toBe('Before hiding unseen text latest'));
+ expect(container.rows[0]).toBe(older);
+ context._handleGroupBusEvent(CID, null, { ...delta(0, ' next', actor), display_seq: 3 });
+ expect(container.rows.find(row => row.dataset.turnId === TURN)?.bodies.final.textContent)
+ .toBe('Before hiding unseen text latest next');
+ expect(requests).toBe(1);
+ });
+
+ it('recovers the saved terminal reply when the task finishes while hidden', async () => {
+ const { context, container } = loadRenderer(CID);
+ configureDisplayRecovery(context);
+ context.document.visibilityState = 'hidden';
+ const reply = { id: 'terminal', from: 'codex-agent', turn_id: TURN, seg: 0, text: 'Saved final result' };
+ context._handleGroupBusEvent(CID, null, { type: 'message', turn_end: true, msg: reply });
+ expect(container.rows).toHaveLength(0);
+ context.document.visibilityState = 'visible';
+ context.apiFetch = async () => ({ json: async () => ({ ok: true, history: [reply],
+ conversation: { processing: false, active_turns: [] },
+ live_display: { sequence: 4, active_turns: [], turns: [] },
+ }) });
+ await context.loadConversationHistory(CID, { preserveScroll: true, refreshDisplay: true });
+ context._handleGroupBusEvent(CID, null, { ...delta(0, 'Late old text', reply.from), display_seq: 4 });
+ expect(container.rows).toHaveLength(1);
+ expect(container.rows[0].dataset.msgId).toBe('terminal');
+ expect(container.rows[0].bodies.final.textContent).toBe(reply.text);
+ });
+
+ it('keeps a terminal arriving during post-paint recovery ahead of the older live snapshot', async () => {
+ const { context, container } = loadRenderer(CID);
+ configureDisplayRecovery(context);
+ const actor = 'codex-agent';
+ context.document.visibilityState = 'hidden';
+ context._handleGroupBusEvent(CID, null, { ...delta(0, 'Partial', actor), display_seq: 1 });
+ context.document.visibilityState = 'visible';
+ const active = [{ actor, turn_id: TURN }];
+ context.apiFetch = async () => ({ json: async () => ({ ok: true, history: [],
+ conversation: { processing: true, processing_since: new Date().toISOString(), active_turns: active },
+ live_display: { sequence: 1, active_turns: active, turns: [{ actor, turn_id: TURN, records: [{
+ id: '', from: actor, turn_id: TURN, seg: 0, text: 'Partial', process: [],
+ }] }] },
+ }) });
+ let release!: () => void;
+ let waiting = false;
+ context._evaluateAutoRecipient = () => {
+ if (waiting) return Promise.resolve();
+ waiting = true;
+ return new Promise<void>(resolve => { release = resolve; });
+ };
+ const refreshing = context.loadConversationHistory(CID, { preserveScroll: true, refreshDisplay: true });
+ await vi.waitFor(() => expect(waiting).toBe(true));
+ context._handleGroupBusEvent(CID, null, { type: 'message', turn_end: true,
+ msg: { id: 'terminal', from: actor, turn_id: TURN, seg: 0, text: 'Saved complete result' },
+ });
+ release();
+ await refreshing;
+ expect(container.rows).toHaveLength(1);
+ expect(container.rows[0].dataset.msgId).toBe('terminal');
+ expect(container.rows[0].bodies.final.textContent).toBe('Saved complete result');
+ });
+
+ it.each(['hidden-window', 'native-hidden', 'other-panel', 'other-task'])('consumes background process events without painting or waiting for frames: %s', (surface) => {
+ const { context, container } = loadRenderer(CID);
+ if (surface === 'hidden-window') context.document.visibilityState = 'hidden';
+ if (surface === 'native-hidden') {
+ context.document.visibilityState = 'visible';
+ context._onConversationWindowVisibility({ active: false });
+ }
+ if (surface === 'other-panel') context.currentView = 'agents';
+ if (surface === 'other-task') context.currentCid = 'other';
+ const yieldToPaint = context._makeStreamPaintYield(() => context._isConversationDisplayVisible(CID));
+ for (let i = 1; i <= 600; i++) {
+ context._handleGroupBusEvent(CID, null, { ...delta(0, 'chunk', 'codex-agent'), display_seq: i });
+ expect(yieldToPaint()).toBeNull();
+ }
+ expect(container.rows).toHaveLength(0);
+ expect(vm.runInContext('_offViewLiveDisplayDirty.has(currentCid === "other" ? "c1" : currentCid)', context)).toBe(true);
+ // Task state still reaches its consumer while no transcript can be painted.
+ const tasks: any[] = [];
+ context.window.TaskBoard = { onEvent: (_cid: string, event: any) => tasks.push(event.task) };
+ context._handleGroupBusEvent(CID, null, { type: 'task_state', task: { task_id: 'task-1', status: 'done' } });
+ expect(tasks).toEqual([{ task_id: 'task-1', status: 'done' }]);
+ });
+
+ it('shows the complete latest display once and ignores the delayed IPC prefix from every turn', () => {
+ const { context, container } = loadRenderer(CID);
+ const actor = 'codex-agent';
+ context.document.visibilityState = 'hidden';
+ for (let i = 1; i <= 600; i++) context._handleGroupBusEvent(CID, null, { ...delta(0, 'chunk', actor), display_seq: i });
+ expect(container.rows).toHaveLength(0);
+ context.document.visibilityState = 'visible';
+ context._restoreLiveDisplaySnapshot(CID, { sequence: 600, turns: [{ actor, turn_id: TURN, records: [{
+ id: '', from: actor, turn_id: TURN, seg: 0, text: 'Latest complete text', process: [],
+ }] }] });
+ context._handleGroupBusEvent(CID, null, { ...delta(0, 'Old turn'), turn_id: 'finished-turn', display_seq: 590 });
+ for (let i = 1; i <= 600; i++) context._handleGroupBusEvent(CID, null, { ...delta(0, 'chunk', actor), display_seq: i });
+ context._handleGroupBusEvent(CID, null, { ...delta(0, ' plus live text', actor), display_seq: 601 });
+ expect(container.rows).toHaveLength(1);
+ expect(container.rows[0].bodies.final.textContent).toBe('Latest complete text plus live text');
+ });
+
it('joins events received during the history request without replaying the snapshot prefix', () => {
const { context, container } = loadRenderer(CID);
const actor = 'codex-agent';
@@ -1456,6 +1846,20 @@ describe('active transcript recovery after task switching', () => {
expect(context.__load.processEvents).toEqual([]);
});
+ it.each([0, 1])('retires the previous body when recovery reports an empty segment %s', (seg) => {
+ const { context, container } = loadRenderer(CID);
+ const actor = 'codex-agent';
+ context._handleGroupBusEvent(CID, null, delta(0, 'Earlier body', actor));
+ const row = container.rows[0];
+ context._restoreLiveDisplaySnapshot(CID, { sequence: 2, turns: [{ actor, turn_id: TURN, records: [{
+ id: '', from: actor, turn_id: TURN, seg, text: '', process: [],
+ }] }] });
+ expect(container.rows).toEqual([row]);
+ expect(row.bodies.final.textContent).toBe('');
+ context._handleGroupBusEvent(CID, null, { ...delta(seg, 'Current body', actor), display_seq: 3 });
+ expect(row.bodies.final.textContent).toBe('Current body');
+ });
+
it('keeps a terminal reply that arrives before the active snapshot can be restored', () => {
const { context, container, finalized } = loadRenderer(CID);
const actor = 'codex-agent';
@@ -1496,7 +1900,7 @@ describe('active transcript recovery after task switching', () => {
});
expect(container.rows).toHaveLength(1);
expect(finalized[0].gm._narration.map((item: any) => item.text)).toEqual(['First message']);
- expect(finalized[0].gm.process.map((item: any) => item.text)).toEqual(['Read', 'Check']);
+ expect(finalized[0].gm.process.map((item: any) => item.text)).toEqual(['First message', 'Read', 'Check']);
});
it('restores more than 300 operations and continues a partial reply once', () => {
diff --git a/test/renderer/conversation-load-more.test.ts b/test/renderer/conversation-load-more.test.ts
index 6f7be064..8a058e43 100644
--- a/test/renderer/conversation-load-more.test.ts
+++ b/test/renderer/conversation-load-more.test.ts
@@ -1,19 +1,36 @@
import { describe, expect, it } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
+import { LOCALES } from '../../src/main/i18n';
const root = path.join(__dirname, '../..');
const read = (relativePath: string) => fs.readFileSync(path.join(root, relativePath), 'utf8');
describe('conversation load-more control', () => {
- it('uses quantity-free copy in every supported locale', () => {
+ it('offers to show more conversations in every supported locale', () => {
const expected = {
- zh: '加载更多',
- en: 'Load more',
- ja: 'さらに読み込む',
- pt: 'Carregar mais',
+ zh: '显示更多',
+ 'zh-tw': '顯示更多',
+ en: 'Show more',
+ fr: 'Afficher plus',
+ de: 'Mehr anzeigen',
+ hi: 'और दिखाएँ',
+ id: 'Tampilkan lebih banyak',
+ it: 'Mostra altro',
+ ja: 'さらに表示',
+ ko: '더 보기',
+ pt: 'Mostrar mais',
+ 'pt-pt': 'Mostrar mais',
+ ru: 'Показать ещё',
+ es: 'Mostrar más',
+ 'es-419': 'Mostrar más',
+ th: 'แสดงเพิ่มเติม',
+ tr: 'Daha fazla göster',
+ vi: 'Hiển thị thêm',
+ ar: 'عرض المزيد',
};
+ expect(Object.keys(expected).sort()).toEqual(LOCALES.map(locale => locale.code).sort());
for (const [locale, label] of Object.entries(expected)) {
const messages = JSON.parse(read(`src/renderer/locales/${locale}.json`));
expect(messages['sidebar.load_more_conversations']).toBe(label);
@@ -23,8 +40,12 @@ describe('conversation load-more control', () => {
it('provides responsive, focus, disabled, and loading styles', () => {
const styles = read('src/renderer/style.css');
- expect(styles).toMatch(/\.conversation-list-load-more\s*\{[\s\S]*?width:\s*calc\(100% - 16px\)/);
- expect(styles).toMatch(/\.conversation-list-load-more\s*\{[\s\S]*?border:\s*0;/);
+ // Accept shared selector lists while keeping each property in its owning rule.
+ const rule = Array.from(styles.replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/([^{}]+)\{([^{}]*)\}/g))
+ .find(match => match[1].split(',').some(selector => selector.trim() === '.conversation-list-load-more'));
+ expect(rule, 'the load-more selector must own its base declarations').toBeDefined();
+ expect(rule![2]).toMatch(/width:\s*calc\(100% - 16px\)/);
+ expect(rule![2]).toMatch(/border:\s*0;/);
expect(styles).toContain('.conversation-list-load-more:focus-visible');
expect(styles).toContain('.conversation-list-load-more:disabled');
expect(styles).toContain('.conversation-list-load-more[aria-busy="true"]::before');
diff --git a/test/renderer/conversation-narration-fold.test.ts b/test/renderer/conversation-narration-fold.test.ts
index 1a3752e5..686fdda4 100644
--- a/test/renderer/conversation-narration-fold.test.ts
+++ b/test/renderer/conversation-narration-fold.test.ts
@@ -3,18 +3,9 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
-/**
- * Narration folding (2026-09-18).
- *
- * An external-CLI turn narrates every tool loop, so one turn can carry dozens
- * of segments — a 16-minute task produced 62, and the 61 narration blocks
- * filled 95% of the bubble. All but the last couple fold behind one line.
- * Folding is presentation only: every block stays in the DOM and in
- * `row._narration`, so quoting, copying and search keep working.
- *
- * The keyed-rendering harness deliberately stubs `.chat-bubble`, so the fold
- * path is inert there. This file mounts a DOM complete enough to execute it.
- */
+/** Native message boundaries place earlier text in the shared process disclosure.
+ * These cases protect the single final body, live/canonical reconciliation,
+ * chronological recovery and bounded deferred history loading. */
const SOURCE = fs.readFileSync(
path.join(__dirname, '../../src/renderer/modules/conversation.js'),
@@ -27,6 +18,7 @@ const VIEW_MODEL_SOURCE = fs.readFileSync(
class El {
className = '';
+ hidden = false;
dataset: Record<string, string> = {};
children: El[] = [];
parentElement: El | null = null;
@@ -69,6 +61,11 @@ class El {
}
get firstChild() { return this.children[0] || null; }
+ get lastElementChild() { return this.children.at(-1) || null; }
+ get nextElementSibling() {
+ const siblings = this.parentElement?.children || [];
+ return siblings[siblings.indexOf(this) + 1] || null;
+ }
setAttribute(name: string, value: string) { this.attrs[name] = value; }
getAttribute(name: string) { return this.attrs[name] ?? null; }
@@ -87,17 +84,18 @@ class El {
querySelectorAll(selector: string): El[] {
const cls = selector.replace(/^\./, '').replace(/\[.*$/, '');
- const segMatch = selector.match(/data-narration-seg="([^"]+)"/);
+ const segMatch = selector.match(/data-native-seg="([^"]+)"/);
return this.descendants().filter((el) => {
if (cls && !el.classList.contains(cls)) return false;
- if (segMatch && el.dataset.narrationSeg !== segMatch[1]) return false;
+ if (segMatch && el.dataset.nativeSeg !== segMatch[1]) return false;
return true;
});
}
querySelector(selector: string): El | null {
- if (selector === '[data-role="final"]') {
- return this.descendants().find((el) => el.getAttribute('data-role') === 'final') || null;
+ if (selector.startsWith('[data-role=')) {
+ const role = selector.match(/data-role="([^"]+)"/)?.[1];
+ return this.descendants().find((el) => el.getAttribute('data-role') === role) || null;
}
if (selector === '.chat-bubble') {
return this.descendants().find((el) => el.classList.contains('chat-bubble')) || null;
@@ -115,6 +113,7 @@ function loadFoldContext() {
requestAnimationFrame: (fn: Function) => { fn(); return 1; },
createLogger: () => ({ warn() {}, info() {}, error() {}, debug() {} }),
escapeHtml: (s: string) => String(s),
+ renderMarkdownFull: (s: string) => String(s),
t: (key: string) => key,
localStorage: { getItem: () => null, setItem() {}, removeItem() {} },
document: {
@@ -131,129 +130,107 @@ function loadFoldContext() {
vm.createContext(context);
vm.runInContext(VIEW_MODEL_SOURCE, context);
vm.runInContext(SOURCE, context);
- vm.runInContext('globalThis.__fold = _applyNarrationFold;', context);
+
return context;
}
-function rowWithBlocks(count: number, turnId = 'T-fold') {
+function rowWithProcess() {
const row = new El();
- row.dataset.turnId = turnId;
+ row.dataset.turnId = 'T-process';
const bubble = new El();
bubble.className = 'chat-bubble';
row.appendChild(bubble);
- for (let i = 0; i < count; i++) {
- const block = new El();
- block.className = 'chat-turn-narration';
- block.dataset.narrationSeg = String(i);
- bubble.appendChild(block);
- }
- const body = new El();
- body.setAttribute('data-role', 'final');
- bubble.appendChild(body);
- return { row, bubble };
+ const details = new El();
+ details.className = 'stream-process';
+ const process = new El();
+ process.className = 'stream-process-body';
+ process.setAttribute('data-role', 'process');
+ details.appendChild(process);
+ bubble.appendChild(details);
+ const final = new El();
+ final.setAttribute('data-role', 'final');
+ final.textContent = 'Final answer';
+ bubble.appendChild(final);
+ return { row, bubble, process, final };
}
-function foldedCount(bubble: El) {
- return bubble.querySelectorAll('.chat-turn-narration')
- .filter((b) => b.classList.contains('chat-turn-narration--folded')).length;
-}
-
-describe('narration folding', () => {
- it('leaves a short turn alone', () => {
- const ctx = loadFoldContext();
- const { row, bubble } = rowWithBlocks(3);
- ctx.__fold(row);
- expect(foldedCount(bubble), 'three blocks stay readable').toBe(0);
- expect(bubble.querySelectorAll('.chat-turn-narration-toggle')).toHaveLength(0);
- });
-
- it('folds all but the tail of a long turn and counts what it hid', () => {
- const ctx = loadFoldContext();
- const { row, bubble } = rowWithBlocks(61);
- ctx.__fold(row);
- expect(foldedCount(bubble)).toBe(59);
- const toggle = bubble.querySelectorAll('.chat-turn-narration-toggle')[0];
- expect(toggle, 'a fold needs a way back').toBeTruthy();
- expect(toggle.dataset.hiddenCount).toBe('59');
- expect(toggle.getAttribute('aria-expanded')).toBe('false');
- // The blocks are hidden, never dropped: quoting and search still see them.
- expect(bubble.querySelectorAll('.chat-turn-narration')).toHaveLength(61);
- });
+const commentary = (text: string) => ({
+ type: 'progress', text, event: { stream: 'assistant', data: { phase: 'commentary' } },
+});
- it('keeps the newest segments visible, not the oldest', () => {
+describe('native narration in the shared process disclosure', () => {
+ it('uses stored commentary without classifying or duplicating raw source text', () => {
const ctx = loadFoldContext();
- const { row, bubble } = rowWithBlocks(61);
- ctx.__fold(row);
- const visible = bubble.querySelectorAll('.chat-turn-narration')
- .filter((b) => !b.classList.contains('chat-turn-narration--folded'))
- .map((b) => Number(b.dataset.narrationSeg));
- expect(visible).toEqual([59, 60]);
+ ctx._groupActorLabel = () => 'Claude';
+ const process = [commentary('Stored process text')];
+ const record = { id: 'classified', from: 'claude', seg: 0, text: 'Raw source text',
+ display_phase: 'commentary', process };
+ const merged = ctx._mergeSegmentGroup([record,
+ { id: 'answer', seg: 1, text: 'Answer', display_phase: 'final_answer', process: [] }]).merged;
+ expect(merged.process).toEqual(process);
+ expect(ctx._groupMsgToLegacy(record).content).toBe('');
+ expect(ctx._groupMsgToLegacy(record).display_phase).toBe('commentary');
+ const part = { ref: 'stored-process', message_id: record.id };
+ expect(ctx._processPartsForRecord({ ...record, process_parts: [part] }, true)).toEqual([part]);
});
- it('opens and closes on click', () => {
+ it.each([1, 3, 19, 61])('keeps all %s earlier messages inside process information with no exposed tail', count => {
const ctx = loadFoldContext();
- const { row, bubble } = rowWithBlocks(61);
- ctx.__fold(row);
- const toggle = bubble.querySelectorAll('.chat-turn-narration-toggle')[0];
- toggle.click();
- expect(foldedCount(bubble), 'expanded shows every segment').toBe(0);
- expect(toggle.getAttribute('aria-expanded')).toBe('true');
- toggle.click();
- expect(foldedCount(bubble), 'collapsing again re-hides them').toBe(59);
+ const { row, bubble, process, final } = rowWithProcess();
+ for (let i = 0; i < count; i++) ctx._appendNarrationBlock(row, i, `Progress ${i}`);
+ expect(process.children.map(child => child.dataset.processText))
+ .toEqual(Array.from({ length: count }, (_, i) => `Progress ${i}`));
+ expect(bubble.children.map(child => child.className)).toEqual(['stream-process', '']);
+ expect(bubble.querySelectorAll('.chat-turn-narration-toggle')).toHaveLength(0);
+ expect(final.textContent).toBe('Final answer');
});
- it('remembers a collapse across a transcript rebuild', () => {
- // Switching conversations rebuilds the transcript, so the row carrying
- // `narrationExpanded` is gone. A fold the reader chose must survive it
- // (2026-09-18: it came back open).
+ it('replaces a provisional segment with its canonical text without duplicating the process entry', () => {
const ctx = loadFoldContext();
- const first = rowWithBlocks(61, 'T-keep');
- ctx.__fold(first.row);
- const toggle = first.bubble.querySelectorAll('.chat-turn-narration-toggle')[0];
- toggle.click(); // open
- toggle.click(); // and fold again — an explicit choice
- expect(foldedCount(first.bubble)).toBe(59);
-
- // Same turn, brand new DOM: what a conversation switch produces.
- const rebuilt = rowWithBlocks(61, 'T-keep');
- ctx.__fold(rebuilt.row);
- expect(foldedCount(rebuilt.bubble), 'the choice outlives the row').toBe(59);
- expect(rebuilt.row.dataset.narrationExpanded).toBe('0');
+ const { row, process } = rowWithProcess();
+ ctx._appendNarrationBlock(row, 0, 'Partial');
+ ctx._appendNarrationBlock(row, 0, 'Complete', { canonical: true });
+ ctx._appendNarrationBlock(row, 0, 'Complete', { canonical: true });
+ expect(process.children.map(child => child.dataset.processText)).toEqual(['Complete']);
+ ctx._appendNarrationBlock(row, 0, '', { canonical: true });
+ expect(process.children).toHaveLength(0);
});
- it('carries an explicit open across a rebuild too', () => {
+ it('moves each previous body before its tool activity while the next body remains independent', () => {
const ctx = loadFoldContext();
- const first = rowWithBlocks(61, 'T-open');
- ctx.__fold(first.row);
- first.bubble.querySelectorAll('.chat-turn-narration-toggle')[0].click();
- const rebuilt = rowWithBlocks(61, 'T-open');
- ctx.__fold(rebuilt.row);
- expect(foldedCount(rebuilt.bubble)).toBe(0);
+ const { row, process } = rowWithProcess();
+ const tool = new El(); tool.textContent = 'Read files'; process.appendChild(tool);
+ row.dataset.streamBuf = 'Inspecting';
+ ctx._demoteBodyToNarration(row, 0);
+ const nextTool = new El(); nextTool.textContent = 'Run tests'; process.appendChild(nextTool);
+ row.dataset.streamBuf = 'Verifying';
+ ctx._demoteBodyToNarration(row, 1);
+ expect(process.children.filter(child => !child.hidden).map(child => child.dataset.processText || child.textContent))
+ .toEqual(['Inspecting', 'Read files', 'Verifying', 'Run tests']);
});
- it('keeps turns independent', () => {
+ it('projects recovered segments into chronological process items and keeps only the last body', () => {
const ctx = loadFoldContext();
- const a = rowWithBlocks(61, 'T-a');
- ctx.__fold(a.row);
- a.bubble.querySelectorAll('.chat-turn-narration-toggle')[0].click();
- const b = rowWithBlocks(61, 'T-b');
- ctx.__fold(b.row);
- expect(foldedCount(a.bubble), 'opened turn stays open').toBe(0);
- expect(foldedCount(b.bubble), 'untouched turn keeps the default').toBe(59);
+ const tool = { type: 'progress', text: 'Read files' };
+ const records = [
+ { id: 'one', seg: 0, text: 'Inspecting', process: [tool] },
+ { id: 'two', seg: 1, text: 'Verifying', process: [] },
+ { id: 'three', seg: 2, text: 'Final answer', process: [] },
+ ];
+ const merged = ctx._mergeSegmentGroup(records).merged;
+ expect(merged.text).toBe('Final answer');
+ expect(merged.process).toEqual([commentary('Inspecting'), tool, commentary('Verifying')]);
+ expect(records[0].process).toEqual([tool]);
});
- it('re-folds newly absorbed older segments without losing the open state', () => {
+ it('keeps earlier commentary with its deferred process part without fetching that history', () => {
const ctx = loadFoldContext();
- const { row, bubble } = rowWithBlocks(61);
- ctx.__fold(row);
- bubble.querySelectorAll('.chat-turn-narration-toggle')[0].click();
- // An older history page lands in this bubble (cross-page absorb).
- const older = new El();
- older.className = 'chat-turn-narration';
- older.dataset.narrationSeg = '-1';
- bubble.insertBefore(older, bubble.children[0]);
- ctx.__fold(row);
- expect(foldedCount(bubble), 'still expanded after absorbing').toBe(0);
- expect(bubble.querySelectorAll('.chat-turn-narration-toggle')[0].dataset.hiddenCount).toBe('60');
+ const part = { ref: 'fixture-ref', message_id: 'one' };
+ const merged = ctx._mergeSegmentGroup([
+ { id: 'one', seg: 0, text: 'Inspecting', process_parts: [part] },
+ { id: 'two', seg: 1, text: 'Final answer', process: [] },
+ ]).merged;
+ expect(merged.process_parts[0]).toEqual({ ...part, leading_items: [commentary('Inspecting')] });
+ expect(part).not.toHaveProperty('leading_items');
});
});
diff --git a/test/renderer/conversation-placeholder-consume.test.ts b/test/renderer/conversation-placeholder-consume.test.ts
index e9cde0a4..a8719e6d 100644
--- a/test/renderer/conversation-placeholder-consume.test.ts
+++ b/test/renderer/conversation-placeholder-consume.test.ts
@@ -125,6 +125,11 @@ function loadClaimHelpers(nodes: FakePlaceholder[] = []): {
if (!renderKey) return null;
return nodes.find((node) => node.dataset.renderKey === renderKey) || null;
},
+ // `_liveTurnRow` looks up a turn's rows by render-key prefix.
+ querySelectorAll(selector: string) {
+ const prefix = selector.match(/data-render-key\^="([^"]+)"/)?.[1];
+ return prefix ? nodes.filter((node) => (node.dataset.renderKey || '').startsWith(prefix)) : [];
+ },
};
const sandbox: any = {
document: { getElementById: () => container },
@@ -139,6 +144,11 @@ function loadClaimHelpers(nodes: FakePlaceholder[] = []): {
extractFunction('_messageRenderKey'),
extractFunction('_phKey'),
extractFunction('_findRenderNode'),
+ // A terminal record without its segment row adopts its turn's live row
+ // and re-keys it (79f70212d); the claim calls all three helpers.
+ extractFunction('_isTerminalGroupHistoryRecord'),
+ extractFunction('_liveTurnRow'),
+ extractFunction('_stampRenderKey'),
extractFunction('_claimRenderNodeForMessage'),
'({ placeholders: _groupPlaceholders, claim: _claimRenderNodeForMessage, key: _phKey });',
].join('\n');
@@ -248,6 +258,12 @@ describe('conversation record claim by render key', () => {
expect(claim('cid-1', { id: 'm1', from: 'commander', turn_id: 'turn-1', seg: 1 })).toBeNull();
expect(otherSegment.dataset.finalized).toBeUndefined();
expect(otherTurn.dataset.finalized).toBeUndefined();
+
+ // A terminal record may adopt only its own turn's live row, never one
+ // from another turn.
+ expect(claim('cid-1', { id: 'm2', from: 'commander', turn_id: 'turn-3', seg: 0, turn_end: true })).toBeNull();
+ expect(otherSegment.dataset.finalized).toBeUndefined();
+ expect(otherTurn.dataset.finalized).toBeUndefined();
});
// Re-delivery of a record must not re-claim a row that already settled;
diff --git a/test/renderer/conversation-process-pages.test.ts b/test/renderer/conversation-process-pages.test.ts
new file mode 100644
index 00000000..c24cb187
--- /dev/null
+++ b/test/renderer/conversation-process-pages.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+
+const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation.js'), 'utf8');
+const start = source.indexOf('function _bindPersistedProcessPages(');
+const end = source.indexOf('// ─── Quote-reply', start);
+const binder = source.slice(start, end);
+function harness(parts: unknown[]) {
+ const rendered: string[] = [];
+ const more: any = { attributes: {}, setAttribute(name: string, value: string) { this.attributes[name] = value; },
+ classList: { add: vi.fn(), remove: vi.fn() }, addEventListener: vi.fn() };
+ const context: any = { currentCid: 'task', document: { createElement: () => more },
+ t: (key: string) => key, _createProcessDisplayContext: () => ({}), _projectIdForConversation: () => 'owner',
+ _processItemsForDisplay: (items: unknown[]) => items,
+ _projectProcessRow: (_event: unknown, _context: unknown, text: string) => text,
+ _appendProjectedProcessRowToBody: (_body: unknown, text: string) => rendered.push(text),
+ _convLog: { warn: vi.fn() }, encodeURIComponent };
+ vm.createContext(context);
+ vm.runInContext(binder, context);
+ const details = { isConnected: true, appendChild() {} };
+ const next = context._bindPersistedProcessPages({}, details, {}, parts);
+ return { next, more, context, rendered, details };
+}
+const part = { ref: 'a'.repeat(64), message_id: 'message', count: 400 };
+const response = (text: string, next_cursor: number | null) => ({ json: async () => ({ ok: true, items: [{ type: 'progress', text }], next_cursor }) });
+
+describe('paged execution disclosure', () => {
+ it('retries a failed page at the same cursor and preserves order across inline and deferred segments', async () => {
+ const h = harness([{ ...part, leading_items: [{ type: 'progress', text: 'Earlier commentary' }] }, { items: [{ type: 'progress', text: 'Later segment' }] }]);
+ const urls: string[] = [];
+ h.context.apiFetch = async (url: string) => { urls.push(url); throw new Error('Unavailable'); };
+ await h.next();
+ expect(h.rendered).toEqual([]);
+ expect(h.more.textContent).toBe('chat.history_retry_newer');
+ h.context.apiFetch = async (url: string) => { urls.push(url); return response(url.includes('cursor=0') ? 'First page' : 'Second page', url.includes('cursor=0') ? 1 : null); };
+ await h.next();
+ await h.next();
+ await h.next();
+ expect(h.rendered).toEqual(['Earlier commentary', 'First page', 'Second page', 'Later segment']);
+ expect(urls[0]).toBe(urls[1]);
+ expect(h.more.hidden).toBe(true);
+ });
+ it('admits only one page at a time and retires a response when its task closes', async () => {
+ const h = harness([part]);
+ let resolve!: (value: unknown) => void;
+ h.context.apiFetch = vi.fn(() => new Promise(r => { resolve = r; }));
+ const loading = h.next();
+ expect(h.more.attributes['aria-busy']).toBe('true');
+ await h.next();
+ expect(h.context.apiFetch).toHaveBeenCalledOnce();
+ h.context.currentCid = 'another-task';
+ resolve(response('Old task detail', null));
+ await loading;
+ expect(h.more.attributes['aria-busy']).toBe('false');
+ expect(h.rendered).toEqual([]);
+ });
+ it('rejects a non-advancing cursor instead of duplicating the page', async () => {
+ const h = harness([part]);
+ h.context.apiFetch = async () => response('Duplicate detail', 0);
+ await h.next();
+ expect(h.rendered).toEqual([]);
+ expect(h.more.textContent).toBe('chat.history_retry_newer');
+ expect(h.more.disabled).toBe(false);
+ });
+});
+
+const toggleStart = source.indexOf('async function _toggleToolResultRow(');
+const toggle = source.slice(toggleStart, source.indexOf('async function _onToolResultRowClick', toggleStart));
+function resultHarness() {
+ function element() {
+ const node: any = { className: '', isConnected: true, textContent: '', children: [], attributes: {}, listeners: {},
+ appendChild(child: any) { this.children.push(child); },
+ insertBefore(child: any, before: any) { this.children.splice(this.children.indexOf(before), 0, child); },
+ addEventListener(name: string, listener: Function) { this.listeners[name] = listener; },
+ setAttribute(name: string, value: string) { this.attributes[name] = value; },
+ remove() { this.isConnected = false; row.nextElementSibling = null; } };
+ node.classList = { contains: (name: string) => node.className.split(' ').includes(name),
+ add(name: string) { node.className += ` ${name}`; }, remove(name: string) { node.className = node.className.replace(` ${name}`, ''); } };
+ return node;
+ }
+ const row: any = { dataset: { toolResultRef: 'bash.0123456789abcdef' }, isConnected: true,
+ insertAdjacentElement(_position: string, pre: any) { this.nextElementSibling = pre; } };
+ const context: any = { currentCid: 'task', document: { createElement: element }, window: { orkas: { invoke: vi.fn() } },
+ t: (key: string) => key, _setExpandableProcessRowSemantics: vi.fn(), _compactAdjacentProcessRows: vi.fn() };
+ vm.createContext(context); vm.runInContext(toggle, context);
+ return { row, context, expand: () => context._toggleToolResultRow(row), invoke: context.window.orkas.invoke };
+}
+
+describe('paged complete tool output', () => {
+ it('retains literal body chunks, retries at the same byte cursor and never admits duplicate concurrent reads', async () => {
+ const h = resultHarness();
+ const head = '🌟<script>window.leaked=true</script>';
+ h.invoke.mockResolvedValueOnce({ ok: true, content: head, truncated: true, next_cursor: 256 });
+ await h.expand();
+ const pre = h.row.nextElementSibling;
+ const more = pre.children[0];
+ expect(pre.textContent).toBe(head);
+ h.invoke.mockRejectedValueOnce(new Error('storage unavailable'));
+ await more.listeners.click();
+ expect(more.textContent).toBe('chat.history_retry_newer');
+ expect(pre.textContent).toBe(head);
+ expect(pre.children).toHaveLength(1);
+ let release!: (res: unknown) => void;
+ h.invoke.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
+ const pending = more.listeners.click();
+ await more.listeners.click();
+ expect(h.invoke).toHaveBeenCalledTimes(3);
+ expect(more.attributes['aria-busy']).toBe('true');
+ release({ ok: true, content: '工具尾部🌟', truncated: false, next_cursor: null }); await pending;
+ expect(h.invoke.mock.calls.slice(1).map((call: any[]) => call[1])).toEqual([
+ { ref: 'bash.0123456789abcdef', cursor: 256 }, { ref: 'bash.0123456789abcdef', cursor: 256 }]);
+ expect(pre.children[0].textContent).toBe('工具尾部🌟');
+ expect(pre.children[0].innerHTML).toBeUndefined();
+ expect(more.hidden).toBe(true);
+ expect(more.attributes['aria-busy']).toBe('false');
+ });
+ it.each(['collapse', 'navigate'])('retires delayed output when the disclosure changes: %s', async change => {
+ const h = resultHarness(); let release!: (res: unknown) => void;
+ h.invoke.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
+ const pending = h.expand(); const pre = h.row.nextElementSibling;
+ if (change === 'collapse') await h.expand(); else h.context.currentCid = 'another-task';
+ release({ ok: true, content: 'stale output', next_cursor: 200, truncated: true }); await pending;
+ expect(pre.textContent).toBe(''); expect(pre.children).toEqual([]);
+ });
+ it('rejects a non-advancing continuation before displaying duplicate content', async () => {
+ const h = resultHarness();
+ h.invoke.mockResolvedValueOnce({ ok: true, content: 'duplicate', next_cursor: 0 });
+ await h.expand();
+ expect(h.row.nextElementSibling.textContent).toBe('');
+ expect(h.row.nextElementSibling.children[0].textContent).toBe('chat.history_retry_newer');
+ });
+});
diff --git a/test/renderer/conversation-reference-locate.test.ts b/test/renderer/conversation-reference-locate.test.ts
new file mode 100644
index 00000000..c18ad07b
--- /dev/null
+++ b/test/renderer/conversation-reference-locate.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+// Scenario: a sent message quotes an earlier message ("Quoted from @Agent:").
+// Clicking that quote must take the user to the original message: revealed in
+// place when it is still mounted, loaded around its id when it scrolled out of
+// the paged transcript, opened in its source task for a cross-task quote, and
+// reported as missing (never silently landing at the bottom) when the original
+// is gone. Legacy quotes without a stored identity remain static text.
+
+const conversationSource = fs.readFileSync(
+ path.join(__dirname, '../../src/renderer/modules/conversation.js'),
+ 'utf8',
+);
+const styleSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/style.css'), 'utf8');
+
+function extractFunction(source: string, name: string): string {
+ const asyncMarker = `async function ${name}(`;
+ const syncMarker = `function ${name}(`;
+ const start = source.indexOf(asyncMarker) >= 0
+ ? source.indexOf(asyncMarker)
+ : source.indexOf(syncMarker);
+ if (start < 0) throw new Error(`missing ${name}`);
+ const signatureEnd = source.indexOf(') {', start);
+ const braceStart = signatureEnd >= 0 ? signatureEnd + 2 : -1;
+ if (braceStart < 0) throw new Error(`missing body for ${name}`);
+ let depth = 0;
+ for (let i = braceStart; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(start, i + 1);
+ }
+ }
+ throw new Error(`unterminated ${name}`);
+}
+
+const t = (key: string, values: Record<string, string> = {}) => {
+ if (key === 'chat.quote_from') return `Quoted from @${values.name}:`;
+ if (key === 'chat.reference_locate_title') return 'Go to the original message';
+ if (key === 'chat.reference_locate_missing') return 'The original message no longer exists.';
+ return key;
+};
+
+function renderHarness() {
+ const context: any = {
+ String,
+ Array,
+ Math,
+ escapeHtml: (value: unknown) => String(value),
+ _chatFileIconHtml: () => '',
+ _referenceDisplayName: (ref: any) => ref.from_name || 'Unknown',
+ _conversationTitleForCid: (cid: string) => `Title for ${cid}`,
+ t,
+ };
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction(conversationSource, '_quotePreviewAttribution'),
+ extractFunction(conversationSource, '_renderMessageReferencesHtml'),
+ ].join('\n'), context);
+ return context;
+}
+
+type FakeMessage = {
+ dataset: Record<string, string>;
+ classList: { add: (n: string) => void; remove: (n: string) => void; contains: () => boolean };
+ closest: () => any;
+ getBoundingClientRect: () => { top: number; height: number };
+};
+
+function locateHarness(opts: { currentCid?: string; mounted?: string[] } = {}) {
+ const flashes: string[] = [];
+ const messages: FakeMessage[] = [];
+ const container: any = {
+ scrollTop: 0,
+ clientHeight: 400,
+ style: { scrollBehavior: '' },
+ getBoundingClientRect: () => ({ top: 0, height: 400 }),
+ querySelectorAll: () => messages,
+ };
+ const mount = (msgId: string) => {
+ messages.push({
+ dataset: { msgId },
+ classList: {
+ contains: () => true,
+ add: (name: string) => flashes.push(`${msgId}:${name}`),
+ remove: () => {},
+ },
+ closest: () => container,
+ getBoundingClientRect: () => ({ top: 100, height: 50 }),
+ });
+ };
+ for (const id of opts.mounted || []) mount(id);
+ const context: any = {
+ String,
+ Number,
+ Math,
+ Array,
+ currentCid: opts.currentCid || 'task-a',
+ document: { getElementById: (id: string) => (id === 'chat-history' ? container : null) },
+ t,
+ uiToast: vi.fn(),
+ setView: vi.fn(),
+ loadConversationHistory: vi.fn(async () => {}),
+ _msTs: () => 0,
+ _markProgrammaticStickyScroll: () => {},
+ requestAnimationFrame: (fn: () => void) => { fn(); return 1; },
+ setTimeout: () => 1,
+ };
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction(conversationSource, '_findConversationHistorySearchTarget'),
+ extractFunction(conversationSource, '_flashConversationHistorySearchTarget'),
+ extractFunction(conversationSource, '_revealConversationHistorySearchTarget'),
+ extractFunction(conversationSource, '_showReferenceMissingToast'),
+ extractFunction(conversationSource, '_locateReferencedMessage'),
+ ].join('\n'), context);
+ return { context, container, flashes, mount };
+}
+
+describe('locating the original message behind a quoted reference', () => {
+ it('renders a quote as a locatable row only when its source identity survived', () => {
+ const context = renderHarness();
+ const html = context._renderMessageReferencesHtml([
+ { source_cid: 'task-a', source_msg_id: 'm1', from_name: 'Writer', text: 'Keep this' },
+ { from_name: 'Legacy', text: 'Old quote without identity' },
+ ], 'task-a');
+ expect(html).toContain('<button type="button" class="chat-reference-message is-locatable" data-source-cid="task-a" data-source-msg-id="m1" title="Go to the original message">');
+ expect(html).toContain('<div class="chat-reference-message"><span class="chat-reference-author">Quoted from @Legacy:</span>');
+ expect(html.match(/<button /g)).toHaveLength(1);
+ expect(html).toContain('Keep this');
+ expect(html).toContain('Old quote without identity');
+ expect(styleSource).toContain('.chat-reference-message.is-locatable {');
+ });
+
+ it('reveals a mounted same-task original in place without reloading history', async () => {
+ const h = locateHarness({ mounted: ['m0', 'm1'] });
+ await expect(h.context._locateReferencedMessage({ source_cid: 'task-a', source_msg_id: 'm1' }))
+ .resolves.toBe(true);
+ expect(h.flashes).toEqual(['m1:search-flash']);
+ expect(h.context.loadConversationHistory).not.toHaveBeenCalled();
+ expect(h.context.setView).not.toHaveBeenCalled();
+ expect(h.context.uiToast).not.toHaveBeenCalled();
+ });
+
+ it('loads the page around an original that scrolled out of the transcript and flashes it', async () => {
+ const h = locateHarness({ mounted: ['m40'] });
+ h.context.loadConversationHistory = vi.fn(async (cid: string, opts: any) => {
+ expect(cid).toBe('task-a');
+ expect(opts.searchTarget.msgId).toBe('m1');
+ expect(opts.searchTarget).not.toHaveProperty('msgIndex');
+ h.mount('m1');
+ // The real loader reveals the target after the anchored page paints.
+ h.context._revealConversationHistorySearchTarget(cid, opts.searchTarget);
+ });
+ await expect(h.context._locateReferencedMessage({ source_cid: 'task-a', source_msg_id: 'm1' }))
+ .resolves.toBe(true);
+ expect(h.context.loadConversationHistory).toHaveBeenCalledOnce();
+ expect(h.flashes).toEqual(['m1:search-flash']);
+ expect(h.context.uiToast).not.toHaveBeenCalled();
+ expect(h.context.setView).not.toHaveBeenCalled();
+ });
+
+ it('tells the user when the original no longer exists instead of silently landing at the bottom', async () => {
+ const h = locateHarness({ mounted: ['m40'] });
+ h.context.loadConversationHistory = vi.fn(async (cid: string, opts: any) => {
+ // Main fell back to the latest page: the id is not in the transcript.
+ h.context._revealConversationHistorySearchTarget(cid, opts.searchTarget);
+ });
+ await expect(h.context._locateReferencedMessage({ source_cid: 'task-a', source_msg_id: 'gone' }))
+ .resolves.toBe(false);
+ expect(h.flashes).toEqual([]);
+ expect(h.context.uiToast).toHaveBeenCalledExactlyOnceWith(
+ 'The original message no longer exists.', { variant: 'warning' },
+ );
+ expect(h.context.setView).not.toHaveBeenCalled();
+ });
+
+ it('opens the source task positioned on the original for a cross-task quote', async () => {
+ const h = locateHarness({ mounted: ['m1'] });
+ await expect(h.context._locateReferencedMessage({ source_cid: 'task-b', source_msg_id: 'm9' }))
+ .resolves.toBe(true);
+ expect(h.context.setView).toHaveBeenCalledOnce();
+ const [view, cid, opts] = h.context.setView.mock.calls[0];
+ expect(view).toBe('conversation');
+ expect(cid).toBe('task-b');
+ expect(opts.historyTarget.msgId).toBe('m9');
+ expect(typeof opts.historyTarget.onMiss).toBe('function');
+ expect(h.context.loadConversationHistory).not.toHaveBeenCalled();
+ expect(h.flashes).toEqual([]);
+ expect(h.context.uiToast).not.toHaveBeenCalled();
+ });
+
+ it('reports a legacy quote that carries no source identity without navigating', async () => {
+ const h = locateHarness({ mounted: ['m1'] });
+ await expect(h.context._locateReferencedMessage({ text: 'legacy' })).resolves.toBe(false);
+ expect(h.context.uiToast).toHaveBeenCalledOnce();
+ expect(h.context.setView).not.toHaveBeenCalled();
+ expect(h.context.loadConversationHistory).not.toHaveBeenCalled();
+ });
+
+ it('reports a miss only after the mounted transcript was actually searched', () => {
+ const h = locateHarness({ mounted: ['m1'] });
+ const onMiss = vi.fn();
+ expect(h.context._revealConversationHistorySearchTarget('task-other', { msgId: 'm1', onMiss })).toBe(false);
+ expect(onMiss).not.toHaveBeenCalled();
+ expect(h.context._revealConversationHistorySearchTarget('task-a', { msgId: 'm1', onMiss })).toBe(true);
+ expect(onMiss).not.toHaveBeenCalled();
+ expect(h.context._revealConversationHistorySearchTarget('task-a', { msgId: 'm2', onMiss })).toBe(false);
+ expect(onMiss).toHaveBeenCalledOnce();
+ });
+
+ it('binds each locatable row once and keeps the click off bubble selection', () => {
+ const rows: any[] = [
+ { dataset: { sourceCid: 'task-a', sourceMsgId: 'm1' }, handlers: [] as any[], addEventListener(_: string, fn: any) { this.handlers.push(fn); } },
+ ];
+ const msgDiv = {
+ querySelectorAll: (selector: string) => {
+ expect(selector).toBe('.chat-reference-message.is-locatable[data-source-cid][data-source-msg-id]');
+ return rows;
+ },
+ };
+ const context: any = { _locateReferencedMessage: vi.fn(async () => true) };
+ vm.createContext(context);
+ vm.runInContext(extractFunction(conversationSource, '_hydrateMessageReferenceLocators'), context);
+ context._hydrateMessageReferenceLocators(msgDiv);
+ context._hydrateMessageReferenceLocators(msgDiv);
+ expect(rows[0].handlers).toHaveLength(1);
+ const event = { stopPropagation: vi.fn() };
+ rows[0].handlers[0](event);
+ expect(event.stopPropagation).toHaveBeenCalledOnce();
+ expect(context._locateReferencedMessage).toHaveBeenCalledExactlyOnceWith({
+ source_cid: 'task-a', source_msg_id: 'm1',
+ });
+ expect(conversationSource).toContain('_hydrateMessageReferenceLocators(msgDiv);');
+ });
+
+ it('requests the page around a message id without inventing a source index', () => {
+ const context: any = {
+ Math,
+ Number,
+ encodeURIComponent,
+ HISTORY_PAGE_SIZE: 10,
+ _projectIdForConversation: () => 'p1',
+ };
+ vm.createContext(context);
+ vm.runInContext(extractFunction(conversationSource, '_historyRequestUrl'), context);
+ expect(context._historyRequestUrl('c1', null, 10, Number(undefined), 'm1')).toBe(
+ '/api/conversations/c1/history?limit=10&around_message_id=m1&project_id=p1',
+ );
+ });
+});
diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.ts
index ae9fd8ba..582893e2 100644
--- a/test/renderer/conversation-sidebar.test.ts
+++ b/test/renderer/conversation-sidebar.test.ts
@@ -3460,9 +3460,6 @@ describe('conversation history reconcile', () => {
const finalizeEnd = source.indexOf('\nfunction ', finalizeStart + 1);
const finalizeBody = source.slice(finalizeStart, finalizeEnd);
expect(finalizeBody).toContain('_syncRenderedGroupMessageIdentity(ph, gm);');
- expect(finalizeBody).toMatch(
- /ph\.querySelector\('\.stream-process'\)\?\.remove\(\);[\s\S]*_renderPersistedProcess\(ph, gm\.process\);/,
- );
});
it('moves a live AI bubble once after newer send-now user activity', () => {
@@ -8451,7 +8448,8 @@ describe('conversation auto recipient', () => {
input.value += '\n> @Writing Helper original quote\nemail@Reviewer';
context._toggleComposerRecipient(target, a);
expect(input.value).toBe('review this @Reviewer check sources\n> @Writing Helper original quote\nemail@Reviewer');
- expect(context._composerSelectedRecipients(target).map((r: any) => r.id)).toEqual(['', 'b']);
+ // D29: prose around a mention gets no default owner; the planner splits it.
+ expect(context._composerSelectedRecipients(target).map((r: any) => r.id)).toEqual(['b']);
context._toggleComposerRecipient(target, b);
expect(input.value).toBe('review this check sources\n> @Writing Helper original quote\nemail@Reviewer');
expect(context.getChatRecipient(target).kind).toBe('commander');
@@ -8475,16 +8473,17 @@ describe('conversation auto recipient', () => {
expect(context._composerSelectedRecipients('new-chat').map((r: any) => r.id)).toEqual(['a']);
const snapshot = context._recipientSnapshotForSend('new-chat');
expect(context._applyRecipientPrefixWithSnapshot(input.value, snapshot)).toBe('@Writer ' + input.value);
- expect(context._composerDispatchShape(input.value, context._agentsCache)).toEqual({ segments: 0, groups: 0 });
+ expect(context._composerSendIsPlanned(input.value)).toBe(false);
});
- it('keeps editable selections but excludes empty trailing recipients from the send snapshot', () => {
+ it('keeps every mentioned actor, including a trailing one, in the send snapshot (D29)', () => {
const context = loadConversationRenderer();
context._agentsCache = [{ agent_id: 'a', name: 'Writer' }, { agent_id: 'b', name: 'Reviewer' }];
const input = { value: '@Writer @Writer inspect @Reviewer' };
context.document.getElementById = (id: string) => id === 'new-chat-input' ? input : null;
expect(context._composerSelectedRecipients('new-chat').map((r: any) => r.id)).toEqual(['a', 'b']);
- expect(context._recipientSnapshotForSend('new-chat')).toMatchObject({ kind: 'agent', id: 'a' });
+ expect(context._recipientSnapshotForSend('new-chat').recipients.map((r: any) => r.id)).toEqual(['a', 'b']);
+ expect(context._composerSendIsPlanned(input.value)).toBe(true);
expect(context._applyRecipientPrefixWithSnapshot(input.value, context._recipientSnapshotForSend('new-chat'))).toBe(input.value);
});
@@ -8497,7 +8496,7 @@ describe('conversation auto recipient', () => {
context.setChatRecipient('new-chat', { kind: 'agent', id: 'a', name: 'Writer' });
context._toggleComposerRecipient('new-chat', { kind: 'agent', id: 'a', name: 'Writer' });
expect(input.value).toBe('draft @Reviewer inspect');
- expect(context._composerSelectedRecipients('new-chat').map((r: any) => r.id)).toEqual(['', 'b']);
+ expect(context._composerSelectedRecipients('new-chat').map((r: any) => r.id)).toEqual(['b']);
});
it('ignores a replayed old floor after a newer user choice was confirmed', async () => {
@@ -8531,7 +8530,7 @@ describe('conversation auto recipient', () => {
it.each([
['new-chat', 'new-chat-input'], ['conversation', 'chat-input'], ['project', 'project-chat-input'],
- ])('inserts panel recipients at the selection and shows the inherited first owner in %s', (target, inputId) => {
+ ])('inserts panel recipients at the selection and previews only the mentioned actors in %s', (target, inputId) => {
const context = loadConversationRenderer();
context.Event = class { constructor(public type: string) {} };
context._agentsCache = [
@@ -8550,29 +8549,30 @@ describe('conversation auto recipient', () => {
expect(input.value).toBe('你好, @Writing Helper 继续');
context._toggleComposerRecipient(target, b);
expect(input.value).toBe('你好, @Writing Helper @Reviewer 继续');
- expect(context._mentionPreviewLabels(target)).toEqual(['chat.recipient_commander', 'Writing Helper', 'Reviewer']);
+ expect(context._mentionPreviewLabels(target)).toEqual(['Writing Helper', 'Reviewer']);
expect(input.selectionStart).toBe(input.value.indexOf('继续'));
// Removing an earlier chip keeps the insertion point beside the remaining chip.
context._toggleComposerRecipient(target, a);
expect(input.value).toBe('你好, @Reviewer 继续');
expect(input.selectionStart).toBe(input.value.indexOf('继续'));
- expect(context._mentionPreviewLabels(target)).toEqual(['chat.recipient_commander', 'Reviewer']);
+ expect(context._mentionPreviewLabels(target)).toEqual(['Reviewer']);
// A new cursor selection replaces text there, preserving the rest of the draft.
input.setSelectionRange(input.value.indexOf('继续'), input.value.length);
context._toggleComposerRecipient(target, a);
expect(input.value).toBe('你好, @Reviewer @Writing Helper ');
- // Commander remains the fallback owner; cancellation must not move chips.
+ // D29: picking Commander while other actors are named involves it
+ // explicitly, inserted at the caret like any other actor.
context._toggleComposerRecipient(target, { kind: 'commander', id: '' });
- expect(input.value).toBe('你好, @Reviewer @Writing Helper ');
- expect(context._mentionPreviewLabels(target)).toEqual(['chat.recipient_commander', 'Reviewer', 'Writing Helper']);
+ expect(input.value).toBe('你好, @Reviewer @Writing Helper @commander ');
+ expect(context._mentionPreviewLabels(target)).toEqual(['Reviewer', 'Writing Helper', 'chat.recipient_commander']);
input.value = '@commander first @Reviewer second';
context._toggleComposerRecipient(target, { kind: 'commander', id: '' });
expect(input.value).toBe('first @Reviewer second');
- expect(context._mentionPreviewLabels(target)).toEqual(['chat.recipient_commander', 'Reviewer']);
+ expect(context._mentionPreviewLabels(target)).toEqual(['Reviewer']);
input.value = 'before after';
input.setSelectionRange(0, 0);
@@ -8613,8 +8613,9 @@ describe('conversation auto recipient', () => {
render('@Orkas Codex check this');
expect(modelChip).toMatchObject({ hidden: false, disabled: true });
+ // D29: two actors make a planned send, and planning runs on the model.
render('@Orkas Codex @Orkas Claude check this');
- expect(modelChip).toMatchObject({ hidden: false, disabled: true });
+ expect(modelChip).toMatchObject({ hidden: false, disabled: false });
render('plan this @Orkas Codex implement');
expect(modelChip).toMatchObject({ hidden: false, disabled: false });
@@ -8642,7 +8643,7 @@ describe('conversation auto recipient', () => {
expect(modelChip).toMatchObject({ hidden: false, disabled: false });
});
- it('freezes the first instruction owner and lets leading mentions override it', () => {
+ it('never injects a default owner into text that already routes by mention (D29)', () => {
// Scenario value: on the new-chat / project composers the picked
// recipient is synthesized into the outgoing text. When the user has
// already named their assignees inline, adding that prefix silently turns
@@ -8663,8 +8664,8 @@ describe('conversation auto recipient', () => {
// prefix is suppressed by real routing rather than by position.
const twoTargets = '先出个提纲 @PptMaker 做成ppt,素材找 @FamilyTutor 要';
expect(context.applyRecipientPrefix(twoTargets, 'new-chat', { recipientSnapshot: context.__snap }))
- .toBe('@FamilyTutor ' + twoTargets);
- expect(context.applyRecipientPrefix(twoTargets, 'project')).toBe('@FamilyTutor ' + twoTargets);
+ .toBe(twoTargets);
+ expect(context.applyRecipientPrefix(twoTargets, 'project')).toBe(twoTargets);
// Negative control: tokens that do NOT route must not swallow the prefix,
// or the message lands on the commander while the chip says FamilyTutor.
@@ -8677,67 +8678,40 @@ describe('conversation auto recipient', () => {
.toBe('@FamilyTutor 接着写');
});
- it('surfaces the order choice for every multi-segment send with the shape default (D23)', () => {
- // Scenario value: the user asked for the serial/parallel choice to be
- // visible on EVERY multi-agent send. An adjacent group used to run
- // parallel with no way to chain it; a wrong default here silently
- // changes execution order.
- const context = loadConversationRenderer();
- context._agentsCache = [
- { agent_id: 'a1', name: 'FamilyTutor' },
- { agent_id: 'a2', name: 'OtherTutor' },
- ];
- const shape = (text: string) => context._composerDispatchShape(text, context._agentsCache);
- const mode = (text: string) => context._composerDispatchDefaultMode(shape(text));
-
- // Adjacent mentions: ONE group but TWO segments → toggle shows, default
- // stays today's all-parallel semantics.
- expect(shape('@FamilyTutor @OtherTutor check this')).toEqual({ segments: 2, groups: 1 });
- expect(mode('@FamilyTutor @OtherTutor check this')).toBe('parallel');
- // Multi-group: written order chains by default.
- expect(shape('@FamilyTutor write it @OtherTutor make a ppt')).toEqual({ segments: 2, groups: 2 });
- expect(mode('@FamilyTutor write it @OtherTutor make a ppt')).toBe('serial');
- // The unaddressed first instruction is its own ordered segment.
- expect(shape('写一个登录页 @FamilyTutor 出视觉稿')).toEqual({ segments: 2, groups: 2 });
- // Same agent twice = two segments (no dedup), one target each span.
- expect(shape('@FamilyTutor a @FamilyTutor b')).toEqual({ segments: 2, groups: 2 });
- expect(shape('@FamilyTutor @FamilyTutor check @OtherTutor')).toEqual({ segments: 1, groups: 1 });
- expect(shape('@FamilyTutor @OtherTutor')).toEqual({ segments: 0, groups: 0 });
- // Single mention / plain text → no choice to offer.
- expect(shape('@FamilyTutor 单独做')).toEqual({ segments: 1, groups: 1 });
- expect(shape('no mentions at all')).toEqual({ segments: 0, groups: 0 });
- });
-
- it('keeps a flipped order override for the send and drops it when the text stops qualifying', () => {
+ it('mirrors the main-process route: only a message that starts with its sole mentioned actor is direct (D29)', () => {
const context = loadConversationRenderer();
context._agentsCache = [
{ agent_id: 'a1', name: 'FamilyTutor' },
{ agent_id: 'a2', name: 'OtherTutor' },
];
- let text = '@FamilyTutor @OtherTutor check this';
- const btn = { hidden: true, textContent: '', title: '' };
- context.document.getElementById = (id: string) => (
- id === 'chat-input' ? { value: text }
- : id === 'chat-seq-toggle' ? btn
- : null
- );
-
- context._updateComposerSeqToggle('conversation');
- expect(btn.hidden).toBe(false);
- expect(context._composerEffectiveDispatchMode('conversation')).toBe('parallel');
-
- // Flip: adjacent group can now chain serially for this one send.
- // (script-scope const — reach it from inside the vm context)
- vm.runInContext("_composerDispatchOverride.set('conversation', 'serial')", context);
- context._updateComposerSeqToggle('conversation');
- expect(context._composerEffectiveDispatchMode('conversation')).toBe('serial');
- expect(btn.textContent).toBe('chat.multi_dispatch_serial');
-
- // Text stops qualifying → toggle hides and the override is forgotten.
- text = '@FamilyTutor 单独做';
- context._updateComposerSeqToggle('conversation');
- expect(btn.hidden).toBe(true);
- expect(vm.runInContext("_composerDispatchOverride.has('conversation')", context)).toBe(false);
+ const planned = (text: string) => context._composerSendIsPlanned(text);
+ expect(planned('@FamilyTutor 单独做')).toBe(false);
+ expect(planned('@FamilyTutor a @FamilyTutor b')).toBe(false);
+ expect(planned('> 引用的上下文\n@FamilyTutor 处理')).toBe(false);
+ expect(planned('no mentions at all')).toBe(false);
+ expect(planned('@FamilyTutor @OtherTutor')).toBe(false);
+ expect(planned('@FamilyTutor @OtherTutor check this')).toBe(true);
+ expect(planned('@FamilyTutor write it @OtherTutor make a ppt')).toBe(true);
+ expect(planned('写一个登录页 @FamilyTutor 出视觉稿')).toBe(true);
+ expect(planned('帮我翻译 @FamilyTutor')).toBe(true);
+ // Commander alone has one possible owner wherever it is named.
+ expect(planned('先看一下现状 @指挥官 再定计划')).toBe(false);
+ expect(planned('check first @commander review')).toBe(false);
+ expect(planned('先看一下现状 @指挥官 再让 @FamilyTutor 出稿')).toBe(true);
+ });
+
+ it('keeps a quoted single-recipient forward direct and enables planning for multiple recipients without prose', () => {
+ const context = loadConversationRenderer();
+ context._agentsCache = [{ agent_id: 'a1', name: 'QuoteWriter' }, { agent_id: 'a2', name: 'QuoteReviewer' }];
+ vm.runInContext('currentCid = "c1";', context);
+ expect(context._composerSendIsEmpty('@QuoteWriter', 'conversation')).toBe(true);
+ context._addQuote('c1', { sourceCid: 'source-cid', msgId: 'source-msg', text: 'Quoted user question.' });
+ expect(context._composerSendIsEmpty('@QuoteWriter', 'conversation', context._getQuotes('c1'))).toBe(false);
+ expect(context._composerSendIsPlanned('@QuoteWriter')).toBe(false);
+ expect(context._composerSendIsPlanned('@QuoteWriter @QuoteReviewer')).toBe(true);
+ context._clearQuotes('c1');
+ expect(context._composerSendIsEmpty('@QuoteWriter @QuoteReviewer', 'conversation')).toBe(true);
+ expect(context._composerSendIsPlanned('@QuoteWriter @QuoteReviewer')).toBe(false);
});
it('normalizes commander routing markers on replay without hiding agent mentions', () => {
@@ -8758,8 +8732,10 @@ describe('conversation auto recipient', () => {
const commander = { kind: 'commander' };
expect(context._commanderMentionDisplayForSend('@指挥官 check this', commander))
.toEqual({ commander_mention_display: 'preserve' });
+ // D29: no owner prefix is generated for mention-carrying text, so an
+ // authored mid-text Commander mention is preserved as written.
expect(context._commanderMentionDisplayForSend('first instruction @commander second', commander))
- .toEqual({ commander_mention_display: 'hide_generated_prefix' });
+ .toEqual({ commander_mention_display: 'preserve' });
expect(context._commanderMentionDisplayForSend('just a follow-up', { ...commander, resetFloor: true }))
.toEqual({});
expect(context._commanderMentionDisplayForSend('Explain `@commander` and email@commander', commander))
@@ -8797,7 +8773,6 @@ describe('conversation auto recipient', () => {
context._clearQuotes = () => {};
context._rememberSentComposerSnapshot = () => {};
context.autoGrow = () => {};
- context._updateComposerSeqToggle = () => {};
context.isConvPending = (cid: string) => busy && cid === 'conversation-a';
context.apiFetch = async (url: string, options: any) => {
sends.push({ cid: url.split('/')[3], content: JSON.parse(options.body).content });
@@ -9134,7 +9109,11 @@ describe('conversation controller settlement', () => {
context.ensureModelConfigured = () => true;
context.nowIsoLocal = () => '2026-08-24T15:59:31';
context._createStreamingAssistantMessage = () => ({ dataset: {}, querySelector: () => null });
- context._handleStreamEvent = (_cid: string, _msg: any, event: any) => rendered.push(event);
+ context.currentCid = 'c2';
+ context.currentView = 'conversation';
+ // Routing must still consume global state; observe actual process paints
+ // rather than treating every call into the router as a DOM mutation.
+ context._renderAgentEvent = (_msg: any, event: any) => rendered.push(event);
context._bufferOffViewGroupProcessEvent = (_cid: string, event: any) => {
buffered.push(event);
return true;
@@ -10352,8 +10331,11 @@ describe('new chat quick-start scenarios', () => {
expect(button.disabled).toBe(false);
});
- it('keeps the full composer retryable when attachment adoption is incomplete', async () => {
+ it.each(['incomplete', 'permission_denied'])('keeps the full composer retryable and hides adoption failure details (%s)', async (failure) => {
const context = loadConversationRenderer();
+ const messages = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
+ context.t = (key: string, params: Record<string, unknown> = {}) => String(messages[key] || key)
+ .replace(/\{(\w+)\}/g, (_: string, name: string) => String(params[name] ?? `{${name}}`));
const events: any[] = [];
const invocations: any[] = [];
const alerts: string[] = [];
@@ -10412,6 +10394,9 @@ describe('new chat quick-start scenarios', () => {
if (url.endsWith('/create')) {
return { ok: true, conversation: { conversation_id: 'c_failed_adopt', title: 'New task' } };
}
+ if (failure === 'permission_denied') return {
+ ok: false, error: 'EPERM: rename C:\\PRIVATE_ATTACHMENT_PATH\\draft to conversation',
+ };
return {
ok: true,
items: [{ sourceName: 'brief.pdf', targetName: 'brief.pdf' }],
@@ -10437,14 +10422,13 @@ describe('new chat quick-start scenarios', () => {
expect(consumedSelections).toBe(0);
expect(renderedConversations).toBe(0);
expect(sends).toBe(0);
- expect(alerts).toEqual(['chat.attach_adopt_failed']);
+ expect(alerts).toEqual(['Could not confirm the attachments. Your message and files are still here; try again.']);
+ expect(alerts.join(' ')).not.toContain('PRIVATE_ATTACHMENT_PATH');
});
it('falls back to commander without toast when the scenario agent is missing', async () => {
const context = loadConversationRenderer();
const toasts: any[] = [];
- const clicks: any[] = [];
- const events: any[] = [];
const classChanges: string[] = [];
let clickHandler: Function | null = null;
const input = {
@@ -10472,11 +10456,6 @@ describe('new chat quick-start scenarios', () => {
};
context._agentsCache = [];
- context.Monitor = {
- click: (name: string, payload: any) => clicks.push({ name, payload }),
- event: (name: string, payload: any) => events.push({ name, payload }),
- };
- context.window.Monitor = true;
context.loadAgents = async () => [];
context._setQuickStartItems([{ id: 'ui_design', agent_id: 'missing-ui-agent' }]);
context.uiToast = (...args: any[]) => toasts.push(args);
@@ -10501,11 +10480,7 @@ describe('new chat quick-start scenarios', () => {
expect(input.value.slice(input.selection[0], input.selection[1])).toBe('a personal finance app');
expect(classChanges).toEqual([]);
expect(toasts).toHaveLength(0);
- expect(input.dataset).toMatchObject({
- commanderEntryPoint: 'quick_start',
- commanderResourceId: 'ui_design',
- commanderRecipientType: 'commander',
- });
+ expect(input.dataset).not.toHaveProperty('commanderEntryPoint');
expect(input.dataset.commanderQuickStartPlaceholder).toBeUndefined();
});
diff --git a/test/renderer/conversation-submit-attach-guards.test.ts b/test/renderer/conversation-submit-attach-guards.test.ts
index 86baa986..444e4419 100644
--- a/test/renderer/conversation-submit-attach-guards.test.ts
+++ b/test/renderer/conversation-submit-attach-guards.test.ts
@@ -85,10 +85,42 @@ function loadConversation(overrides: Record<string, any> = {}) {
const proxied = withNoopFallback(context);
vm.createContext(proxied);
vm.runInContext(composerAccessorSource, proxied);
+ vm.runInContext(fs.readFileSync(path.join(rendererRoot, 'modules/strip-structural-blocks.js'), 'utf8'), proxied);
vm.runInContext(conversationSource, proxied);
return { context: proxied, revoked, elements };
}
+describe('empty addressed composer requests', () => {
+ it.each(['new-chat', 'conversation', 'project'].flatMap((entry) =>
+ ['@commander', '@Orkas Codex', '@Orkas Codex @QuoteReviewer'].map((text) => ({ entry, text }))))(
+ 'keeps $text in the $entry draft without starting a send', async ({ entry, text }) => {
+ let modelChecks = 0;
+ let requests = 0;
+ const { context, elements } = loadConversation({
+ ensureModelConfigured: () => { modelChecks += 1; return false; },
+ apiFetch: async () => { requests += 1; throw new Error('An empty request must not reach transport'); },
+ });
+ if (entry === 'project') {
+ vm.runInContext(fs.readFileSync(path.join(rendererRoot, 'modules/project-detail.js'), 'utf8'), context);
+ vm.runInContext("_projectDetailPid = 'p_empty'", context);
+ }
+ vm.runInContext("currentCid = 'c_empty'", context);
+ context._agentsCache = [{ agent_id: 'codex', name: 'Orkas Codex' }, { agent_id: 'reviewer', name: 'QuoteReviewer' }];
+ if (entry === 'project') {
+ vm.runInContext("_composerAgentScopes.set('project', { pid: 'p_empty', ids: new Set(['codex', 'reviewer']) })", context);
+ }
+ const id = entry === 'conversation' ? 'chat-input' : `${entry}-chat-input`;
+ const inputId = entry === 'new-chat' ? 'new-chat-input' : id;
+ elements[inputId] = stubEl({ value: text });
+ Object.assign(context, { _getQuotes: () => [], _chatAttachList: () => [], getChatUseSelections: () => [] });
+ await (entry === 'project' ? context._submitProjectChat()
+ : entry === 'conversation' ? context.handleChatSubmit() : context.handleNewChatSubmit());
+ expect(modelChecks).toBe(0);
+ expect(requests).toBe(0);
+ expect(elements[inputId].value).toBe(text);
+ });
+});
+
describe('chat attachment blob URL lifecycle', () => {
it('revokes blob preview URLs on the plain after-send clear (no deleteFiles)', async () => {
const { context, revoked } = loadConversation();
@@ -107,6 +139,72 @@ describe('chat attachment blob URL lifecycle', () => {
});
describe('new-chat submit re-entrancy gate', () => {
+ it.each(['new-chat', 'project'])('keeps one %s task when a list refresh runs during attachment adoption', async (entry) => {
+ let releaseAdoption!: (value: any) => void;
+ let reachedAdoption!: () => void;
+ const adoptionStarted = new Promise<void>((resolve) => { reachedAdoption = resolve; });
+ const original = { conversation_id: 'c_adopt_race', title: 'Initial title',
+ created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:00:00Z',
+ ...(entry === 'project' ? { project_id: 'p_race' } : {}) };
+ const current = { ...original, title: 'Title changed while waiting', title_manually_set: true,
+ updated_at: '2026-05-15T09:01:00Z', last_active_at: '2026-05-15T09:01:00Z', processing: true };
+ const sends: any[] = [];
+ let creates = 0;
+ const { context, elements } = loadConversation({
+ ensureModelConfigured: () => true,
+ apiFetch: async (url: string) => {
+ if (url.endsWith('/create')) {
+ creates += 1;
+ return { json: async () => ({ ok: true, conversation: { ...original } }) };
+ }
+ if (url.endsWith('/adopt')) {
+ reachedAdoption();
+ return new Promise((resolve) => { releaseAdoption = resolve; });
+ }
+ if (url.startsWith('/api/conversations/list')) return { json: async () => ({
+ ok: true, conversations: [current], unprojected_pagination: { total: 1, next_offset: null },
+ total: 1, next_offset: null,
+ }) };
+ throw new Error(`Unexpected fixture request: ${url}`);
+ },
+ });
+ if (entry === 'project') {
+ vm.runInContext(fs.readFileSync(path.join(rendererRoot, 'modules/project-detail.js'), 'utf8'), context);
+ vm.runInContext("_projectDetailPid = 'p_race'", context);
+ }
+ Object.assign(context, {
+ currentView: entry === 'project' ? 'project' : 'new-chat',
+ _chatAttachTryBeginSend: () => () => {},
+ _chatAttachSnapshotForSend: async () => ({ ok: true, items: [{ name: 'brief.pdf', status: 'ready' }] }),
+ _recipientSnapshotForSend: () => ({ kind: 'commander' }),
+ _getQuotes: () => [], _referenceSnapshotsForQuotes: () => [],
+ transformWithChatUse: (text: string) => text, transformChatUseTokens: (text: string) => text,
+ applyRecipientPrefix: (text: string) => text,
+ _titleSeedWithoutRoutingMentions: (text: string) => text,
+ _commanderMentionDisplayForSend: () => ({}),
+ _autoTitle: (text: string) => text,
+ getChatUseSelections: () => [], consumeChatUseSelections: () => [],
+ renderConversationList() {}, loadProjects() {}, setView() {}, setChatRecipient() {},
+ _renderRecipientChip() {}, _saveRecipientMap() {},
+ unresolvedOssTemplatePlaceholder: () => false,
+ sendInConversation: async (...args: any[]) => { sends.push(args); },
+ });
+ elements[entry === 'project' ? 'project-chat-input' : 'new-chat-input'] = stubEl({ value: 'Review the brief' });
+ const submit = entry === 'project' ? context._submitProjectChat() : context.handleNewChatSubmit();
+ await adoptionStarted;
+ await context.loadConversations();
+ releaseAdoption({ json: async () => ({ ok: true,
+ items: [{ sourceName: 'brief.pdf', targetName: 'brief (1).pdf' }],
+ }) });
+ await submit;
+ expect(creates).toBe(1);
+ expect(context.conversations).toEqual([current]);
+ expect(sends).toHaveLength(1);
+ expect(sends[0].slice(0, 3)).toEqual(['c_adopt_race', 'Review the brief', {
+ title_text: 'Review the brief', attachments: ['brief (1).pdf'],
+ }]);
+ });
+
it('a second submit during the create round trip does not create a second conversation', async () => {
const createCalls: string[] = [];
let resolveCreate: (v: any) => void = () => {};
@@ -179,13 +277,11 @@ describe('conversation send ownership across navigation', () => {
context._recipientSnapshotForSend = () => ({ kind: 'agent', id: context.currentCid, name: context.currentCid });
context._commanderMentionDisplayForSend = () => ({});
context._applyRecipientPrefixWithSnapshot = (text: string, recipient: any) => `@${recipient.id} ${text}`;
- context._composerEffectiveDispatchMode = () => undefined;
context.transformWithChatUse = (text: string) => text;
context.isConvPending = () => phase === 'busy-response';
context._clearDraft = (cid: string) => { clearedDrafts.push(cid); };
context._clearQuotes = () => {};
context.autoGrow = () => {};
- context._updateComposerSeqToggle = () => {};
context._rememberSentComposerSnapshot = () => {};
context.sendInConversation = async (cid: string, content: string, extra: any) => {
sends.push({ cid, content, extra });
diff --git a/test/renderer/conversation-turn-navigation.test.ts b/test/renderer/conversation-turn-navigation.test.ts
index d17efd92..9695f448 100644
--- a/test/renderer/conversation-turn-navigation.test.ts
+++ b/test/renderer/conversation-turn-navigation.test.ts
@@ -236,14 +236,14 @@ describe('conversation turn navigation', () => {
expect(sentBeforeInitialPage[0].turnNo).toBe(22);
});
- it('stores at most one user line and two compact assistant lines', () => {
+ it('stores at most two user lines and five compact assistant lines', () => {
const turn = turnNav.normalizeTurnDescriptor({
turn_no: 1,
- user_preview: '用'.repeat(50),
- assistant_preview: '答'.repeat(100),
+ user_preview: '用'.repeat(150),
+ assistant_preview: '答'.repeat(300),
});
- expect(Array.from(turn.userPreview)).toHaveLength(40);
- expect(Array.from(turn.assistantPreview)).toHaveLength(80);
+ expect(Array.from(turn.userPreview)).toHaveLength(100);
+ expect(Array.from(turn.assistantPreview)).toHaveLength(240);
expect(turn.userPreview.endsWith('…')).toBe(true);
expect(turn.assistantPreview.endsWith('…')).toBe(true);
});
@@ -435,8 +435,8 @@ describe('conversation turn navigation', () => {
expect(styleSource).toContain('left: 6.5px');
expect(styleSource).toContain('border-radius: 99px');
expect(styleSource).toMatch(/\.chat-turn-nav-marker::before\s*\{[^}]*height: 2px;/s);
- expect(styleSource).toContain('width: clamp(200px, 26cqw, 260px)');
- expect(styleSource).toContain('-webkit-line-clamp: 1');
- expect(styleSource).toContain('-webkit-line-clamp: 2');
+ expect(styleSource).toContain('width: clamp(260px, 38cqw, 420px)');
+ expect(styleSource).toMatch(/\.chat-turn-nav-preview-title\s*\{[^}]*-webkit-line-clamp: 2;/s);
+ expect(styleSource).toMatch(/\.chat-turn-nav-preview-body\s*\{[^}]*-webkit-line-clamp: 5;/s);
});
});
diff --git a/test/renderer/design-token-integrity.test.ts b/test/renderer/design-token-integrity.test.ts
index 63f5c035..0f412af0 100644
--- a/test/renderer/design-token-integrity.test.ts
+++ b/test/renderer/design-token-integrity.test.ts
@@ -22,6 +22,7 @@ const RUNTIME_INJECTED = new Set([
'--composer-model-marquee-distance', // modules/composer-model-picker.js
'--composer-model-marquee-duration', // modules/composer-model-picker.js
'--turn-nav-preview-y', // modules/conversation-turn-nav.js
+ '--activity-group-height', // modules/web-assist.js, set before `.is-contained` applies it
]);
function readRendererCss() {
diff --git a/test/renderer/dialogs.test.ts b/test/renderer/dialogs.test.ts
index 708539bf..7ef7e4b8 100644
--- a/test/renderer/dialogs.test.ts
+++ b/test/renderer/dialogs.test.ts
@@ -253,6 +253,31 @@ function overlays(ctx: any): FakeElement[] {
}
describe('shared renderer dialogs', () => {
+ it('restores an action revealed by its focusable parent without focusing disabled or detached actions', () => {
+ const ctx = loadDialogs();
+ const parent = ctx._document.createElement('div');
+ parent.tabIndex = 0;
+ const action = ctx._document.createElement('button');
+ ctx._document.body.appendChild(parent);
+ parent.appendChild(action);
+ Object.defineProperty(action, 'parentElement', { value: { closest: () => parent } });
+ action.focus = () => {
+ if (ctx._document.activeElement === parent && !action.disabled) ctx._document.activeElement = action;
+ };
+ ctx._uiRestoreDialogFocus(action);
+ expect(ctx._document.activeElement).toBe(action);
+ const unrelated = ctx._document.createElement('button');
+ ctx._document.body.appendChild(unrelated);
+ unrelated.focus();
+ action.disabled = true;
+ ctx._uiRestoreDialogFocus(action);
+ expect(ctx._document.activeElement).toBe(unrelated);
+ action.disabled = false;
+ action.remove();
+ ctx._uiRestoreDialogFocus(action);
+ expect(ctx._document.activeElement).toBe(unrelated);
+ });
+
it('keeps an async danger action visible and prevents duplicate confirmation or dismissal until it succeeds', async () => {
const ctx = loadDialogs();
let complete!: () => void;
diff --git a/test/renderer/global-search-navigation.test.ts b/test/renderer/global-search-navigation.test.ts
index 4a3f36e7..8a1bb724 100644
--- a/test/renderer/global-search-navigation.test.ts
+++ b/test/renderer/global-search-navigation.test.ts
@@ -58,6 +58,30 @@ function loadingHarness() {
}
describe('global search conversation navigation', () => {
+ it('loads the Agent detail dependencies before opening a search hit and preserves its return target', async () => {
+ const callbacks: Array<() => Promise<void>> = [];
+ const target = { view: 'conversation', id: 'previous-conversation' };
+ let release!: () => void;
+ const loader = vi.fn(() => new Promise<void>(resolve => { release = resolve; }));
+ const open = vi.fn();
+ const context: any = {
+ _searchActiveIdx: 0, _SEARCH_KIND_META: { agent: {} }, window: {},
+ _captureAgentDetailReturnTarget: () => target,
+ closeGlobalSearch: vi.fn(), loadRendererFeature: loader, openAgentDetail: open,
+ setTimeout: (callback: () => Promise<void>) => { callbacks.push(callback); return 1; },
+ };
+ vm.createContext(context);
+ vm.runInContext(extractFunction(searchSource, '_gotoSearchResult'), context);
+ await context._gotoSearchResult({ kind: 'agent', id: 'matching-agent' });
+ const navigation = callbacks[0]();
+ expect(loader).toHaveBeenCalledWith('agents');
+ expect(open).not.toHaveBeenCalled();
+ release();
+ await navigation;
+ expect(open).toHaveBeenCalledOnce();
+ expect(open).toHaveBeenCalledWith('matching-agent', { returnTarget: target });
+ });
+
// Visible wait feedback must survive reordering; no stale hit may become
// actionable while the next input is still waiting for its debounce.
it('keeps loading for the latest input through stale replies, tabs, clearing and reopening', async () => {
@@ -122,7 +146,7 @@ describe('global search conversation navigation', () => {
let resolveResults!: (value: any) => void;
const context: any = {
_searchResults: [], _searchVisibleResults: [], _searchActiveIdx: -1,
- _searchLoading: false, _searchTab: 'all', _searchChatIndexComplete: true, _searchSeq: 0, _searchLastQuery: '',
+ _searchLoading: false, _searchTab: 'all', _searchChatIndexBuilding: false, _searchSeq: 0, _searchLastQuery: '',
_searchTimer: null,
_SEARCH_FETCH_LIMIT: 200,
document: { getElementById: () => body }, escapeHtml: (s: string) => s,
@@ -143,13 +167,13 @@ describe('global search conversation navigation', () => {
const pending = context._runSearchNow('marker');
expect(body.innerHTML).toContain('search-loading');
expect(body.innerHTML).toContain(locale['common.loading']);
- resolveStatus({ ok: true, chat_index_complete: false });
+ resolveStatus({ ok: true, chat_index_complete: false, chat_index_building: true });
await new Promise(resolve => setImmediate(resolve));
const copy = '正在准备中,结果暂不完整,请稍后重试。';
expect(body.innerHTML).toContain(copy);
expect(body.innerHTML).toContain('search-loading');
expect(body.innerHTML).not.toContain(locale['search.no_results']);
- resolveResults({ ok: true, chat_index_complete: false, results: [{ kind: 'chat' }] });
+ resolveResults({ ok: true, chat_index_complete: false, chat_index_building: true, results: [{ kind: 'chat' }] });
await pending;
expect(body.innerHTML).toContain(copy);
expect(body.innerHTML).toContain('existing hit');
@@ -158,7 +182,7 @@ describe('global search conversation navigation', () => {
const ready = context._runSearchNow('marker');
resolveResults({ ok: true, chat_index_complete: true, results: [{ kind: 'chat' }] });
await ready;
- resolveStatus({ ok: true, chat_index_complete: false });
+ resolveStatus({ ok: true, chat_index_complete: false, chat_index_building: true });
await new Promise(resolve => setImmediate(resolve));
expect(body.innerHTML).not.toContain(copy);
expect(body.innerHTML).toContain('existing hit');
@@ -168,7 +192,7 @@ describe('global search conversation navigation', () => {
it('ignores preparation status from a closed or superseded search session', async () => {
let reply!: (value: any) => void;
const context: any = {
- _searchSeq: 1, _searchChatIndexComplete: true,
+ _searchSeq: 1, _searchChatIndexBuilding: false,
apiFetch: () => new Promise(resolve => { reply = data => resolve({ json: async () => data }); }),
_renderSearchEmptyState: vi.fn(), _renderSearchResults: vi.fn(),
};
@@ -176,9 +200,9 @@ describe('global search conversation navigation', () => {
vm.runInContext(extractFunction(searchSource, '_refreshSearchIndexStatus'), context);
const pending = context._refreshSearchIndexStatus(1, '', { active: true });
context._searchSeq++;
- reply({ ok: true, chat_index_complete: false });
+ reply({ ok: true, chat_index_complete: false, chat_index_building: true });
await pending;
- expect(context._searchChatIndexComplete).toBe(true);
+ expect(context._searchChatIndexBuilding).toBe(false);
expect(context._renderSearchEmptyState).not.toHaveBeenCalled();
expect(context._renderSearchResults).not.toHaveBeenCalled();
});
@@ -187,7 +211,7 @@ describe('global search conversation navigation', () => {
const body = { innerHTML: '', classList: { remove: vi.fn() }, querySelectorAll: () => [] };
const context: any = {
_searchResults: [], _searchVisibleResults: [], _searchActiveIdx: -1,
- _searchLoading: false, _searchTab: 'all', _searchChatIndexComplete: false,
+ _searchLoading: false, _searchTab: 'all', _searchChatIndexBuilding: true,
document: { getElementById: () => body },
escapeHtml: (s: string) => s, t: (key: string) => key,
_partitionSearchResults: (rows: any[]) => ({ chats: rows, agents: [], skills: [], contexts: [] }),
@@ -214,12 +238,56 @@ describe('global search conversation navigation', () => {
expect(body.innerHTML).toContain('search.no_results');
context._searchTab = 'chat';
- context._searchChatIndexComplete = true;
+ context._searchChatIndexBuilding = false;
context._renderSearchResults('query');
expect(body.innerHTML).not.toContain('search.history_indexing');
expect(body.innerHTML).toContain('search-result');
});
+ // An index that was built once and only waits for its catch-up repair
+ // (after a restart, a crash or a sync) is not announced: it lacks at most
+ // the newest history, and the notice read as broken search.
+ it('stays quiet while an index that was built once only waits for catch-up', async () => {
+ const body = { innerHTML: '', classList: { add: vi.fn(), remove: vi.fn() },
+ querySelectorAll: () => [], querySelector: () => null };
+ const locale = JSON.parse(fs.readFileSync(path.join(root, 'src/renderer/locales/zh.json'), 'utf8'));
+ let resolveResults!: (value: any) => void;
+ const context: any = {
+ _searchResults: [], _searchVisibleResults: [], _searchActiveIdx: -1,
+ _searchLoading: false, _searchTab: 'all', _searchChatIndexBuilding: false, _searchSeq: 0, _searchLastQuery: '',
+ _searchTimer: null, _SEARCH_FETCH_LIMIT: 200,
+ document: { getElementById: () => body }, escapeHtml: (s: string) => s,
+ t: (key: string) => locale[key], _activeProjectIdForSearch: () => '',
+ _setSearchTabsVisible: vi.fn(), _trackGlobalSearchResult: vi.fn(),
+ _renderSearchError: vi.fn(), _reportGlobalSearchFailure: vi.fn(),
+ _loadSearchHistory: () => ['earlier query'],
+ _partitionSearchResults: (rows: any[]) => ({ chats: rows, agents: [], skills: [], contexts: [] }),
+ _sectionRows: (s: any) => s.bucket, _renderSearchRow: () => '',
+ apiFetch: (url: string) => url.endsWith('/status')
+ ? Promise.resolve({ json: async () => ({ ok: true, chat_index_complete: false, chat_index_building: false }) })
+ : new Promise(resolve => { resolveResults = data => resolve({ json: async () => data }); }),
+ };
+ vm.createContext(context);
+ for (const name of ['_refreshSearchIndexStatus', '_showSearchLoading', '_runSearchNow',
+ '_renderSearchResults', '_renderSearchEmptyState']) {
+ vm.runInContext(extractFunction(searchSource, name), context);
+ }
+ const copy = locale['search.history_indexing'];
+ await context._runSearchNow('');
+ await new Promise(resolve => setImmediate(resolve));
+ expect(body.innerHTML).toContain('earlier query');
+ expect(body.innerHTML).not.toContain(copy);
+
+ const pending = context._runSearchNow('absent');
+ await new Promise(resolve => setImmediate(resolve));
+ expect(body.innerHTML).not.toContain(copy);
+ resolveResults({ ok: true, chat_index_complete: false, chat_index_building: false, results: [] });
+ await pending;
+ expect(body.innerHTML).not.toContain(copy);
+ expect(body.innerHTML).toContain(locale['search.no_results']);
+ expect(context._searchChatIndexBuilding).toBe(false);
+ });
+
it('tracks the bounded entry that opened global search', () => {
const events: Array<{ action: string; data: Record<string, unknown> }> = [];
const input: any = { value: 'old query', focus: vi.fn() };
diff --git a/test/renderer/helpers/mini-dom.ts b/test/renderer/helpers/mini-dom.ts
new file mode 100644
index 00000000..a538a564
--- /dev/null
+++ b/test/renderer/helpers/mini-dom.ts
@@ -0,0 +1,307 @@
+// Minimal DOM double for classic renderer modules run in `node:vm`. jsdom and
+// happy-dom are not project dependencies, so journey tests that need real
+// template markup, selector lookup and event bubbling across several shipped
+// modules (dialogs.js, saved-apps.js, app-publishing.js) share this one double
+// instead of each re-implementing a partial element class. It supports the
+// subset those modules use: element/text nodes, innerHTML parsing of
+// well-formed templates, compound/descendant selectors with `:not()` and
+// `:disabled`, capture/bubble dispatch with `on<type>` handlers, and focus.
+// Layout, CSS and real focus events are out of scope.
+
+type Listener = { fn: (event: any) => void; capture: boolean };
+const VOID_TAGS = new Set(['br', 'hr', 'img', 'input', 'meta', 'link', 'source', 'wbr']);
+const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", apos: "'", nbsp: ' ' };
+const decode = (text: string) => text.replace(/&(#?\w+);/g, (m, name) => ENTITIES[name] ?? m);
+const encode = (text: string) => text.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' } as any)[c]);
+
+export class MiniEvent {
+ defaultPrevented = false;
+ propagationStopped = false;
+ target: any = null;
+ currentTarget: any = null;
+ isComposing = false;
+ keyCode = 0;
+ shiftKey = false;
+ key?: string;
+ constructor(readonly type: string, init: Record<string, any> = {}) { Object.assign(this, init); }
+ preventDefault() { this.defaultPrevented = true; }
+ stopPropagation() { this.propagationStopped = true; }
+}
+
+abstract class MiniNode {
+ parentNode: MiniElement | null = null;
+ readonly listeners = new Map<string, Listener[]>();
+ constructor(readonly ownerDocument: MiniDocument) {}
+ abstract get textContent(): string;
+ get isConnected(): boolean {
+ let node: MiniNode | null = this;
+ while (node) { if (node === this.ownerDocument.documentElement) return true; node = node.parentNode; }
+ return false;
+ }
+ get parentElement(): MiniElement | null { return this.parentNode; }
+ remove(): void {
+ if (!this.parentNode) return;
+ const siblings = this.parentNode.childNodes;
+ siblings.splice(siblings.indexOf(this), 1);
+ this.parentNode = null;
+ }
+ addEventListener(type: string, fn: (event: any) => void, options?: boolean | { capture?: boolean }): void {
+ const capture = typeof options === 'boolean' ? options : !!options?.capture;
+ this.listeners.set(type, [...(this.listeners.get(type) || []), { fn, capture }]);
+ }
+ removeEventListener(type: string, fn: (event: any) => void, options?: boolean | { capture?: boolean }): void {
+ const capture = typeof options === 'boolean' ? options : !!options?.capture;
+ this.listeners.set(type, (this.listeners.get(type) || []).filter(item => item.fn !== fn || item.capture !== capture));
+ }
+ dispatchEvent(event: MiniEvent): boolean {
+ event.target = this;
+ const path: any[] = [];
+ for (let node: any = this; node; node = node.parentNode) path.push(node);
+ if (this.isConnected) path.push(this.ownerDocument);
+ const fire = (node: any, phase: 'capture' | 'target' | 'bubble') => {
+ event.currentTarget = node;
+ for (const item of [...(node.listeners.get(event.type) || [])]) {
+ if (phase === 'capture' && !item.capture) continue;
+ if (phase === 'bubble' && item.capture) continue;
+ item.fn.call(node, event);
+ }
+ if (phase !== 'capture' && typeof node['on' + event.type] === 'function') node['on' + event.type](event);
+ };
+ for (const node of [...path].reverse().slice(0, -1)) { fire(node, 'capture'); if (event.propagationStopped) return !event.defaultPrevented; }
+ fire(this, 'target');
+ for (const node of path.slice(1)) { if (event.propagationStopped) break; fire(node, 'bubble'); }
+ return !event.defaultPrevented;
+ }
+}
+
+export class MiniText extends MiniNode {
+ constructor(doc: MiniDocument, public data: string) { super(doc); }
+ get textContent(): string { return this.data; }
+ set textContent(value: string) { this.data = String(value); }
+}
+
+class MiniClassList {
+ constructor(private readonly element: MiniElement) {}
+ private get values(): string[] { return (this.element.getAttribute('class') || '').split(/\s+/).filter(Boolean); }
+ private set values(next: string[]) { this.element.setAttribute('class', [...new Set(next)].join(' ')); }
+ add(...names: string[]) { this.values = [...this.values, ...names]; }
+ remove(...names: string[]) { this.values = this.values.filter(name => !names.includes(name)); }
+ contains(name: string) { return this.values.includes(name); }
+ toggle(name: string, force?: boolean) {
+ const on = force === undefined ? !this.contains(name) : !!force;
+ if (on) this.add(name); else this.remove(name);
+ return on;
+ }
+}
+
+export class MiniElement extends MiniNode {
+ readonly childNodes: MiniNode[] = [];
+ readonly attributes = new Map<string, string>();
+ readonly classList = new MiniClassList(this);
+ readonly style: Record<string, string> = {};
+ readonly localName: string;
+ value = '';
+ checked = false;
+ scrollTop = 0;
+ [handler: `on${string}`]: any;
+ readonly dataset: Record<string, string>;
+ constructor(doc: MiniDocument, tag: string) {
+ super(doc);
+ this.localName = tag.toLowerCase();
+ const attr = (key: string) => 'data-' + key.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
+ this.dataset = new Proxy({} as Record<string, string>, {
+ get: (_t, key: string) => this.attributes.get(attr(key)),
+ set: (_t, key: string, value) => { this.setAttribute(attr(key), String(value)); return true; },
+ has: (_t, key: string) => this.attributes.has(attr(key)),
+ });
+ }
+ get tagName(): string { return this.localName.toUpperCase(); }
+ get id(): string { return this.getAttribute('id') || ''; }
+ set id(value: string) { this.setAttribute('id', value); }
+ get className(): string { return this.getAttribute('class') || ''; }
+ set className(value: string) { this.setAttribute('class', value); }
+ get type(): string { return this.getAttribute('type') || ''; }
+ set type(value: string) { this.setAttribute('type', value); }
+ get disabled(): boolean { return this.attributes.has('disabled'); }
+ set disabled(value: boolean) { this.toggleAttribute('disabled', !!value); }
+ get hidden(): boolean { return this.attributes.has('hidden'); }
+ set hidden(value: boolean) { this.toggleAttribute('hidden', !!value); }
+ get tabIndex(): number {
+ const raw = this.getAttribute('tabindex');
+ if (raw != null) return Number(raw);
+ return ['button', 'input', 'textarea', 'select', 'a'].includes(this.localName) ? 0 : -1;
+ }
+ set tabIndex(value: number) { this.setAttribute('tabindex', String(value)); }
+ get title(): string { return this.getAttribute('title') || ''; }
+ set title(value: string) { this.setAttribute('title', value); }
+ get children(): MiniElement[] { return this.childNodes.filter((node): node is MiniElement => node instanceof MiniElement); }
+ get childElementCount(): number { return this.children.length; }
+ get offsetParent(): MiniElement | null {
+ if (!this.isConnected) return null;
+ for (let node: MiniElement | null = this; node; node = node.parentNode) if (node.hidden || node.style.display === 'none') return null;
+ return this.parentNode;
+ }
+ get textContent(): string { return this.childNodes.map(node => node.textContent).join(''); }
+ set textContent(value: string) {
+ for (const node of [...this.childNodes]) node.remove();
+ if (value != null && String(value) !== '') this.appendChild(new MiniText(this.ownerDocument, String(value)));
+ }
+ get innerHTML(): string { return this.childNodes.map(serialize).join(''); }
+ set innerHTML(html: string) {
+ for (const node of [...this.childNodes]) node.remove();
+ parseInto(this, String(html));
+ }
+ getAttribute(name: string): string | null { return this.attributes.has(name) ? this.attributes.get(name)! : null; }
+ hasAttribute(name: string): boolean { return this.attributes.has(name); }
+ setAttribute(name: string, value: string): void { this.attributes.set(name, String(value)); }
+ removeAttribute(name: string): void { this.attributes.delete(name); }
+ toggleAttribute(name: string, force: boolean): void { if (force) this.attributes.set(name, ''); else this.attributes.delete(name); }
+ appendChild<T extends MiniNode>(node: T): T {
+ node.remove();
+ node.parentNode = this;
+ this.childNodes.push(node);
+ return node;
+ }
+ append(...nodes: Array<MiniNode | string>): void {
+ for (const node of nodes) this.appendChild(typeof node === 'string' ? new MiniText(this.ownerDocument, node) : node);
+ }
+ replaceChildren(...nodes: Array<MiniNode | string>): void {
+ for (const node of [...this.childNodes]) node.remove();
+ this.append(...nodes);
+ }
+ contains(node: MiniNode | null): boolean {
+ for (let current = node; current; current = current.parentNode) if (current === this) return true;
+ return false;
+ }
+ descendants(): MiniElement[] { return this.children.flatMap(child => [child, ...child.descendants()]); }
+ matches(selector: string): boolean { return splitList(selector).some(item => matchComplex(this, item)); }
+ closest(selector: string): MiniElement | null {
+ for (let node: MiniElement | null = this; node; node = node.parentNode) if (node.matches(selector)) return node;
+ return null;
+ }
+ querySelectorAll(selector: string): MiniElement[] { return this.descendants().filter(node => node.matches(selector)); }
+ querySelector(selector: string): MiniElement | null { return this.querySelectorAll(selector)[0] || null; }
+ focus(): void { if (this.isConnected) this.ownerDocument.activeElement = this; }
+ blur(): void { if (this.ownerDocument.activeElement === this) this.ownerDocument.activeElement = this.ownerDocument.body; }
+ click(): void { if (!this.disabled) this.dispatchEvent(new MiniEvent('click', { bubbles: true })); }
+ getBoundingClientRect() { return { top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }; }
+}
+
+export class MiniDocument {
+ readonly listeners = new Map<string, Listener[]>();
+ readonly documentElement: MiniElement;
+ readonly body: MiniElement;
+ activeElement: MiniElement | null;
+ constructor() {
+ this.documentElement = new MiniElement(this, 'html');
+ this.body = this.documentElement.appendChild(new MiniElement(this, 'body'));
+ this.activeElement = this.body;
+ }
+ get parentNode() { return null; }
+ createElement(tag: string): MiniElement { return new MiniElement(this, tag); }
+ createElementNS(_ns: string, tag: string): MiniElement { return new MiniElement(this, tag); }
+ createTextNode(text: string): MiniText { return new MiniText(this, text); }
+ getElementById(id: string): MiniElement | null { return this.documentElement.descendants().find(node => node.id === id) || null; }
+ querySelectorAll(selector: string): MiniElement[] { return this.documentElement.querySelectorAll(selector); }
+ querySelector(selector: string): MiniElement | null { return this.documentElement.querySelector(selector); }
+ contains(node: MiniNode | null): boolean { return this.documentElement.contains(node); }
+ addEventListener = MiniElement.prototype.addEventListener;
+ removeEventListener = MiniElement.prototype.removeEventListener;
+ /** Dispatch a keydown from the focused element, as a real key press would. */
+ press(key: string, init: Record<string, any> = {}): MiniEvent {
+ const event = new MiniEvent('keydown', { key, ...init });
+ (init.target || this.activeElement || this.body).dispatchEvent(event);
+ return event;
+ }
+}
+
+/** Visible text with `<br>` as a line break, the way a user reads a dialog message. */
+export function visibleText(node: MiniNode): string {
+ if (node instanceof MiniText) return node.data;
+ const element = node as MiniElement;
+ if (element.localName === 'br') return '\n';
+ return element.childNodes.map(visibleText).join('');
+}
+
+function serialize(node: MiniNode): string {
+ if (node instanceof MiniText) return encode(node.data);
+ const element = node as MiniElement;
+ const attrs = [...element.attributes].map(([key, value]) => value === '' ? ` ${key}` : ` ${key}="${encode(value)}"`).join('');
+ if (VOID_TAGS.has(element.localName)) return `<${element.localName}${attrs} />`;
+ return `<${element.localName}${attrs}>${element.innerHTML}</${element.localName}>`;
+}
+
+function parseInto(root: MiniElement, html: string): void {
+ const doc = root.ownerDocument;
+ const stack: MiniElement[] = [root];
+ const token = /<!--[\s\S]*?-->|<\/([a-zA-Z][\w-]*)\s*>|<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>|([^<]+)/g;
+ let match: RegExpExecArray | null;
+ while ((match = token.exec(html))) {
+ const top = stack[stack.length - 1];
+ if (match[5] != null) {
+ if (match[5].trim() || top.localName === 'textarea') top.appendChild(new MiniText(doc, decode(match[5])));
+ } else if (match[1]) {
+ const tag = match[1].toLowerCase();
+ const index = stack.map(item => item.localName).lastIndexOf(tag);
+ if (index > 0) stack.length = index;
+ } else if (match[2]) {
+ const element = new MiniElement(doc, match[2]);
+ for (const attr of (match[3] || '').matchAll(/([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) {
+ element.setAttribute(attr[1].toLowerCase(), decode(attr[2] ?? attr[3] ?? attr[4] ?? ''));
+ }
+ if (element.hasAttribute('value')) element.value = element.getAttribute('value')!;
+ top.appendChild(element);
+ if (!VOID_TAGS.has(element.localName) && !match[4]) stack.push(element);
+ }
+ }
+ for (const textarea of [root, ...root.descendants()].filter(node => node.localName === 'textarea')) textarea.value = textarea.textContent;
+}
+
+function splitTop(text: string, separator: RegExp): string[] {
+ const parts: string[] = [];
+ let depth = 0, quote = '', current = '';
+ for (const char of text) {
+ if (quote) { if (char === quote) quote = ''; current += char; continue; }
+ if (char === '"' || char === "'") quote = char;
+ if (char === '(' || char === '[') depth += 1;
+ if (char === ')' || char === ']') depth -= 1;
+ if (depth === 0 && separator.test(char)) { if (current.trim()) parts.push(current.trim()); current = ''; continue; }
+ current += char;
+ }
+ if (current.trim()) parts.push(current.trim());
+ return parts;
+}
+const splitList = (selector: string) => splitTop(selector, /,/);
+
+function matchComplex(element: MiniElement, selector: string): boolean {
+ const parts = splitTop(selector, /\s/);
+ if (!matchCompound(element, parts[parts.length - 1])) return false;
+ let node = element.parentNode;
+ for (let index = parts.length - 2; index >= 0; index -= 1) {
+ while (node && !matchCompound(node, parts[index])) node = node.parentNode;
+ if (!node) return false;
+ node = node.parentNode;
+ }
+ return true;
+}
+
+function matchCompound(element: MiniElement, compound: string): boolean {
+ const pattern = /^(?:([a-zA-Z][\w-]*|\*)|#([\w-]+)|\.([\w-]+)|\[([\w-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\]]*)))?\]|:not\(((?:[^()]|\([^()]*\))*)\)|:(disabled))/;
+ let rest = compound;
+ while (rest) {
+ const match = pattern.exec(rest);
+ if (!match) throw new Error(`mini-dom: unsupported selector "${compound}"`);
+ rest = rest.slice(match[0].length);
+ if (match[1] && match[1] !== '*' && element.localName !== match[1].toLowerCase()) return false;
+ if (match[2] && element.id !== match[2]) return false;
+ if (match[3] && !element.classList.contains(match[3])) return false;
+ if (match[4]) {
+ const expected = match[5] ?? match[6] ?? match[7];
+ if (!element.hasAttribute(match[4])) return false;
+ if (expected !== undefined && element.getAttribute(match[4]) !== expected) return false;
+ }
+ if (match[8] !== undefined && element.matches(match[8])) return false;
+ if (match[9] && !element.disabled) return false;
+ }
+ return true;
+}
diff --git a/test/renderer/home.test.ts b/test/renderer/home.test.ts
new file mode 100644
index 00000000..465e4a49
--- /dev/null
+++ b/test/renderer/home.test.ts
@@ -0,0 +1,396 @@
+// Commander home (modules/home.js): which state the New task view shows, how
+// open to-dos and unopened finished runs are grouped, folded and opened, and
+// the shortcuts and connect chooser. jsdom isn't installed, so — like the other
+// renderer tests — the classic script runs in a vm sandbox with a minimal DOM
+// shim and the real zh copy, and assertions read the generated HTML.
+
+import { describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+const R = path.join(__dirname, '../../src/renderer');
+const homeSource = fs.readFileSync(path.join(R, 'modules/home.js'), 'utf8');
+const iconsContext: any = { window: {}, document: undefined };
+vm.createContext(iconsContext);
+vm.runInContext(fs.readFileSync(path.join(R, 'modules/icons.js'), 'utf8'), iconsContext);
+const uiIconHtml = iconsContext.window.uiIconHtml;
+const zh = JSON.parse(fs.readFileSync(path.join(R, 'locales/zh.json'), 'utf8')) as Record<string, string>;
+
+function t(key: string, vars?: Record<string, unknown>): string {
+ let s = Object.prototype.hasOwnProperty.call(zh, key) ? zh[key] : key;
+ if (vars) for (const k of Object.keys(vars)) s = s.split(`{${k}}`).join(String(vars[k]));
+ return s;
+}
+
+function escapeHtml(s: unknown) {
+ return String(s ?? '').replace(/[&<>"]/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;',
+ }[c] || c));
+}
+
+function element(extra: Record<string, any> = {}) {
+ const listeners: Record<string, Array<(event: any) => unknown>> = {};
+ const attrs: Record<string, string> = {};
+ return {
+ dataset: {} as Record<string, string>,
+ hidden: false,
+ innerHTML: '',
+ textContent: '',
+ focusCount: 0,
+ addEventListener(type: string, fn: (event: any) => unknown) { (listeners[type] ||= []).push(fn); },
+ setAttribute(name: string, value: unknown) { attrs[name] = String(value); },
+ getAttribute(name: string) { return name in attrs ? attrs[name] : null; },
+ focus() { this.focusCount += 1; },
+ getBoundingClientRect: () => ({ left: 100, top: 600, bottom: 628 }),
+ fire(type: string, event: any) { return (listeners[type] || []).map((fn) => fn(event)); },
+ ...extra,
+ };
+}
+
+/** An event whose target answers `closest()` for the given selectors. */
+function click(matches: Record<string, any>) {
+ return { target: { closest: (selector: string) => matches[selector] || null } };
+}
+
+const MINUTE = 60 * 1000;
+
+function loadHome(options: {
+ todos?: { tasks: any[]; total: number };
+ todosError?: boolean;
+ unread?: any[];
+ conversations?: any[];
+ lookup?: (cids: string[]) => any;
+ connectors?: any[];
+} = {}) {
+ const els: Record<string, any> = {
+ 'panel-new-chat': element({ dataset: { homeState: 'pending' } }),
+ 'home-groups': element(),
+ 'home-explore-context': element(),
+ };
+ const clicks: Array<[string, any]> = [];
+ const events: Array<[string, any]> = [];
+ const views: any[][] = [];
+ const invokes: Array<[string, any]> = [];
+ const forgotten: string[] = [];
+ const menus: any[][] = [];
+ const timers: Array<{ fn: () => void; ms: number }> = [];
+ const context: any = {
+ console,
+ Promise,
+ Date,
+ Intl,
+ currentView: 'new-chat',
+ conversations: options.conversations || [],
+ _projectsCache: [{ project_id: 'p1', name: '增长' }],
+ setTimeout: (fn: () => void, ms: number) => { timers.push({ fn, ms }); return timers.length; },
+ clearTimeout: () => {},
+ createLogger: () => ({ warn() {}, info() {}, error() {}, debug() {} }),
+ escapeHtml,
+ t,
+ getLang: () => 'zh',
+ getLocaleMeta: () => ({ intlLocale: 'zh-CN' }),
+ performance: { now: () => 0 },
+ setView: (...args: any[]) => { views.push(args); },
+ _forgetUnreadConversation: (cid: string) => { forgotten.push(cid); },
+ loadRendererFeature: vi.fn(async () => {}),
+ focusTodo: vi.fn(),
+ showContextMenu: (_anchor: any, items: any[]) => { menus.push(items); },
+ Monitor: {
+ click: (action: string, data: any) => { clicks.push([action, data]); },
+ event: (action: string, data: any) => { events.push([action, data]); },
+ },
+ document: { getElementById: (id: string) => els[id] || null },
+ };
+ context.window = {
+ uiIconHtml,
+ innerHeight: 720,
+ Monitor: true,
+ addEventListener() {},
+ TaskUnread: { list: () => options.unread || [] },
+ loadConnectorNavTarget: async (id: string) => ({ name: { feishu: '飞书', dingtalk: '钉钉', gmail: 'Gmail', 'm365-mail': 'Microsoft 365 邮箱' }[id] || id }),
+ openConnectorSetupById: vi.fn(async () => true),
+ orkas: {
+ invoke: async (channel: string, payload: any) => {
+ invokes.push([channel, payload]);
+ if (channel === 'projects.tasks.listOpen') {
+ if (options.todosError) throw new Error('read failed');
+ return { ok: true, ...(options.todos || { tasks: [], total: 0 }) };
+ }
+ if (channel === 'conversations.getMany') {
+ return options.lookup ? options.lookup(payload.cids) : { conversations: [], missing: [] };
+ }
+ if (channel === 'connectors.list') return { ok: true, instances: options.connectors || [] };
+ throw new Error(`unexpected channel ${channel}`);
+ },
+ },
+ };
+ vm.createContext(context);
+ vm.runInContext(homeSource, context);
+ const settle = async () => {
+ for (let i = 0; i < 4; i += 1) await new Promise((resolve) => setImmediate(resolve));
+ };
+ return {
+ context, els, clicks, events, views, invokes, forgotten, menus, timers, settle,
+ state: () => els['panel-new-chat'].dataset.homeState,
+ html: () => els['home-groups'].innerHTML as string,
+ data: () => JSON.parse(vm.runInContext('JSON.stringify(_homeData)', context)),
+ };
+}
+
+function run(cid: string, status: string, minutesAgo: number, entryPoint?: string) {
+ return {
+ cid, projectId: '', finishedAt: Date.now() - minutesAgo * MINUTE, status,
+ ...(entryPoint ? { entryPoint } : {}),
+ };
+}
+
+describe('Commander home states', () => {
+ it('shows the empty state when nothing is open or unopened', async () => {
+ const h = loadHome();
+ h.context.homeOnEnter();
+ await h.settle();
+
+ expect(h.state()).toBe('empty');
+ expect(h.html()).toBe('');
+ // The context line carries the connect chooser inside the translated sentence.
+ expect(h.els['home-explore-context'].innerHTML).toBe(
+ '用 + 分享资料,或<button type="button" class="home-connect-link" data-home-connect="1">连接飞书 / 钉钉 / 邮箱</button>,补充背景,让 Orkas 更了解你。从你愿意分享的内容开始。',
+ );
+ });
+
+ it('groups open to-dos, automation runs and other finished tasks in that order', async () => {
+ const h = loadHome({
+ todos: {
+ total: 5,
+ tasks: [
+ { id: 't1', project_id: 'p1', project_name: '增长', status: 'review', content: '确认定价方案\n附件见对话', updated_at: new Date(Date.now() - 5 * MINUTE).toISOString() },
+ { id: 't2', project_id: '', project_name: '', status: 'todo', content: '整理客户访谈', updated_at: new Date(Date.now() - 3 * 60 * MINUTE).toISOString() },
+ { id: 't3', project_id: '', project_name: '', status: 'progress', content: '周报', updated_at: '' },
+ ],
+ },
+ unread: [
+ run('auto-new', 'failed', 2, 'automation'),
+ // A reply the user wrote inside an automation run is still that run.
+ run('auto-reply', 'completed', 10, 'conversation'),
+ run('project-task', 'waiting_input', 20, 'chat_send'),
+ run('legacy', '', 30),
+ run('deleted-elsewhere', 'completed', 40, 'chat_send'),
+ ],
+ conversations: [
+ { conversation_id: 'auto-new', title: '每周竞品简报', project_id: '', origin_auto_task_id: 'a1' },
+ { conversation_id: 'auto-reply', title: '每日销售摘要', project_id: '', origin_auto_task_id: 'a2' },
+ { conversation_id: 'project-task', title: '竞品对比', project_id: 'p1' },
+ ],
+ lookup: (cids) => ({
+ conversations: cids.includes('legacy')
+ ? [{ conversation_id: 'legacy', title: '', project_id: '', origin_auto_task_id: '' }]
+ : [],
+ missing: cids.filter((cid) => cid === 'deleted-elsewhere'),
+ }),
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+
+ expect(h.state()).toBe('populated');
+ // Only conversations missing from the sidebar cache are looked up.
+ expect(h.invokes.filter(([channel]) => channel === 'conversations.getMany'))
+ .toEqual([['conversations.getMany', { cids: ['legacy', 'deleted-elsewhere'] }]]);
+ expect(h.forgotten).toEqual(['deleted-elsewhere']);
+
+ const html = h.html();
+ const order = [...html.matchAll(/data-section="(\w+)"/g)].map((match) => match[1]);
+ expect(order).toEqual(['todos', 'automations', 'tasks']);
+ expect(html).toContain('重要待办<span class="home-group-count">5</span>');
+ expect(html).toContain('自动化待处理<span class="home-group-count">2</span>');
+ expect(html).toContain('任务待你处理<span class="home-group-count">2</span>');
+ // To-do rows share the sidebar's To-do icon, with status still shown in words.
+ const sidebarTodoIcon = fs.readFileSync(path.join(R, 'index.html'), 'utf8')
+ .match(/id="todos-btn"[^>]*><span data-ui-icon="([^"]+)"/)?.[1];
+ expect(sidebarTodoIcon).toBe('clipboard-list');
+ const todoIcon = uiIconHtml(sidebarTodoIcon, 'home-row-status-icon');
+ expect(html).toContain(`<span class="home-row-status is-review" aria-hidden="true">${todoIcon}</span><span class="home-row-main"><span class="home-row-title">确认定价方案</span>`);
+ expect(html).toContain('<span class="home-row-source">增长 · 待办</span>待确认 · 5分钟前更新');
+ expect(html).toContain(`<span class="home-row-status is-todo" aria-hidden="true">${todoIcon}</span><span class="home-row-main"><span class="home-row-title">整理客户访谈</span>`);
+ expect(html).toContain('<span class="home-row-source">全局待办</span>待处理 · 3小时前更新');
+ expect(html).toContain('<span class="home-row-source">全局待办</span>处理中</span>');
+ expect(html).toContain(`<span class="home-row-status is-progress" aria-hidden="true">${todoIcon}</span>`);
+ // More to-dos than rows: the link to the full To-dos page sits in the group header, not below the list.
+ expect(html).toContain('重要待办<span class="home-group-count">5</span></h2><button type="button" class="home-text-btn" data-home-action="more_todos" aria-describedby="home-group-todos-title">查看全部 →</button></div>');
+ expect(html).not.toContain('home-group-more" data-home-action="more_todos"');
+ expect(html).not.toContain('data-home-toggle="todos"');
+ // Run rows: result-specific glyph and action, automation source, fallbacks for old records.
+ expect(html).toMatch(/data-home-cid="auto-new"[^>]*data-home-status="failed"[^>]*><span class="home-row-status is-failed"/);
+ expect(html).toMatch(/data-home-cid="auto-reply"[^>]*><span class="home-row-status is-completed"/);
+ expect(html).toMatch(/data-home-cid="project-task"[^>]*><span class="home-row-status is-waiting_input"/);
+ expect(html).toMatch(/data-home-cid="legacy"[^>]*><span class="home-row-status is-unknown"/);
+ expect(html).toContain(`<span class="home-row-status is-failed" aria-hidden="true">${uiIconHtml('x-circle', 'home-row-status-icon')}</span>`);
+ expect(html).toContain('<span class="home-row-title">每周竞品简报</span><span class="home-row-meta"><span class="home-row-source">自动化</span>失败 · 2分钟前</span></span><span class="home-row-action">查看原因');
+ expect(html).toContain('<span class="home-row-source">增长 · 项目任务</span>等你输入 · 20分钟前</span></span><span class="home-row-action">去回复');
+ expect(html).toContain('<span class="home-row-title">未命名任务</span><span class="home-row-meta"><span class="home-row-source">全局任务</span>有新结果 · 30分钟前');
+ expect(html).not.toContain('deleted-elsewhere');
+ expect(html).toContain('全部自动化 →');
+ });
+
+ it('shows three runs per group and folds up to twenty more', async () => {
+ const unread = Array.from({ length: 25 }, (_, i) => run(`task-${i}`, 'completed', i + 1, 'chat_send'));
+ const h = loadHome({
+ unread,
+ conversations: unread.map((record) => ({ conversation_id: record.cid, title: record.cid, project_id: '' })),
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+
+ const html = h.html();
+ const visible = html.split('<div class="home-list-fold"')[0];
+ const fold = html.match(/<div class="home-list-fold" id="home-fold-tasks" hidden>(.*?)<\/div>/)?.[1] || '';
+ expect([...visible.matchAll(/data-home-cid="([^"]+)"/g)].map((m) => m[1])).toEqual(['task-0', 'task-1', 'task-2']);
+ expect([...fold.matchAll(/data-home-position="(\d+)"/g)].map((m) => Number(m[1])))
+ .toEqual(Array.from({ length: 20 }, (_, i) => i + 4));
+ expect(html).toContain('aria-expanded="false">展开其余 20 条</button>');
+ expect(html).toContain('任务待你处理<span class="home-group-count">25</span>');
+
+ const foldEl = element({ hidden: true });
+ h.els['home-fold-tasks'] = foldEl;
+ const toggle = element({ dataset: { homeToggle: 'tasks', homeFolded: '20' } });
+ h.els['home-groups'].fire('click', click({ '[data-home-toggle]': toggle }));
+ expect(foldEl.hidden).toBe(false);
+ expect(toggle.getAttribute('aria-expanded')).toBe('true');
+ expect(toggle.textContent).toBe('收起');
+ // A refresh during the visit keeps the group unfolded.
+ expect(vm.runInContext('_homeSectionHtml("tasks")', h.context)).toContain('id="home-fold-tasks">');
+
+ h.els['home-groups'].fire('click', click({ '[data-home-toggle]': toggle }));
+ expect(foldEl.hidden).toBe(true);
+ expect(toggle.textContent).toBe('展开其余 20 条');
+ });
+
+ it('opens a run in its conversation and a to-do on the To-dos page', async () => {
+ const h = loadHome({
+ todos: { total: 1, tasks: [{ id: 't1', project_id: 'p1', project_name: '增长', status: 'todo', content: 'A' }] },
+ unread: [run('auto-new', 'failed', 2, 'automation')],
+ conversations: [{ conversation_id: 'auto-new', title: '简报', project_id: '', origin_auto_task_id: 'a1' }],
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+ // Every open to-do is already listed, so there is no link to more of them.
+ expect(h.html()).not.toContain('data-home-action="more_todos"');
+
+ h.els['home-groups'].fire('click', click({
+ '.home-row': { dataset: { homeCid: 'auto-new', homeSection: 'automations', homeStatus: 'failed', homePosition: '1' } },
+ }));
+ expect(h.views).toEqual([['conversation', 'auto-new', { entryPoint: 'home' }]]);
+ // Gone right away, so coming back never shows the run just opened.
+ expect(h.data().automations).toEqual([]);
+
+ h.els['home-groups'].fire('click', click({
+ '.home-row': { dataset: { homeTodo: 't1', homePid: 'p1', homeStatus: 'todo', homePosition: '1' } },
+ }));
+ await h.settle();
+ expect(h.context.loadRendererFeature).toHaveBeenCalledWith('project');
+ expect(h.context.focusTodo).toHaveBeenCalledWith('p1', 't1', { entryPoint: 'home' });
+
+ h.els['home-groups'].fire('click', click({ '[data-home-action]': { dataset: { homeAction: 'all_automations' } } }));
+ h.els['home-groups'].fire('click', click({ '[data-home-action]': { dataset: { homeAction: 'more_todos' } } }));
+ expect(h.views.slice(1)).toEqual([['auto', null, { entryPoint: 'home' }], ['todos', null, { entryPoint: 'home' }]]);
+ });
+
+ it('returns to the conversation a to-do belongs to, and falls back to the To-dos page when it is gone', async () => {
+ const h = loadHome({
+ todos: { total: 2, tasks: [
+ { id: 't-saved', project_id: '', status: 'todo', content: 'Write chapter 3', origin_cid: 'conv-origin' },
+ { id: 't-gone', project_id: 'p1', status: 'progress', content: 'Deleted thread', origin_cid: 'conv-deleted' },
+ ] },
+ conversations: [{ conversation_id: 'conv-origin', title: 'Novel', project_id: '' }],
+ lookup: (cids: string[]) => ({ conversations: [], missing: cids }),
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+ expect(h.html()).toContain('data-home-origin-cid="conv-origin"');
+
+ h.els['home-groups'].fire('click', click({
+ '.home-row': { dataset: { homeTodo: 't-saved', homePid: '', homeStatus: 'todo', homePosition: '1', homeOriginCid: 'conv-origin' } },
+ }));
+ await h.settle();
+ // Back to the original conversation, with nothing prefilled.
+ expect(h.views).toEqual([['conversation', 'conv-origin', { entryPoint: 'home' }]]);
+ expect(h.context.focusTodo).not.toHaveBeenCalled();
+
+ h.els['home-groups'].fire('click', click({
+ '.home-row': { dataset: { homeTodo: 't-gone', homePid: 'p1', homeStatus: 'progress', homePosition: '2', homeOriginCid: 'conv-deleted' } },
+ }));
+ await h.settle();
+ expect(h.context.focusTodo).toHaveBeenCalledWith('p1', 't-gone', { entryPoint: 'home' });
+ expect(h.invokes.some(([channel, payload]) => channel === 'conversations.getMany'
+ && JSON.stringify(payload.cids) === JSON.stringify(['conv-deleted']))).toBe(true);
+ });
+
+ it('hides only the group whose lookup failed', async () => {
+ const h = loadHome({
+ todosError: true,
+ unread: [run('task-a', 'completed', 1, 'chat_send')],
+ conversations: [{ conversation_id: 'task-a', title: '报告', project_id: '' }],
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+
+ expect(h.state()).toBe('populated');
+ expect(h.html()).not.toContain('data-section="todos"');
+ expect(h.html()).toContain('data-section="tasks"');
+ });
+
+ it('falls back to the empty layout when the first lookup is slow, then paints what arrives', async () => {
+ let release: (value: any) => void = () => {};
+ const h = loadHome();
+ h.context.window.orkas.invoke = () => new Promise((resolve) => { release = resolve; });
+ h.context.homeOnEnter();
+ expect(h.state()).toBe('pending');
+ const fallback = h.timers.find((timer) => timer.ms === 1500);
+ fallback!.fn();
+ expect(h.state()).toBe('empty');
+
+ release({ ok: true, tasks: [{ id: 't1', project_id: '', status: 'todo', content: '迟到的待办' }], total: 1 });
+ await h.settle();
+ expect(h.state()).toBe('populated');
+ expect(h.html()).toContain('迟到的待办');
+ });
+
+ it('refreshes while the home is showing and leaves it to the next visit otherwise', async () => {
+ const h = loadHome();
+ h.context.homeOnEnter();
+ await h.settle();
+ const lookups = () => h.invokes.filter(([channel]) => channel === 'projects.tasks.listOpen').length;
+ expect(lookups()).toBe(1);
+
+ h.context.homeRefresh();
+ const debounce = h.timers.filter((timer) => timer.ms === 500);
+ expect(debounce).toHaveLength(1);
+ debounce[0].fn();
+ await h.settle();
+ expect(lookups()).toBe(2);
+
+ h.context.currentView = 'conversation';
+ h.context.homeRefresh();
+ expect(h.timers.filter((timer) => timer.ms === 500)).toHaveLength(1);
+ });
+});
+
+describe('Commander home connect chooser', () => {
+ it('marks connected services and opens the picked one in Connectors', async () => {
+ const h = loadHome({ connectors: [
+ { id: 'lark', status: { kind: 'connected' } },
+ { id: 'gmail', status: { kind: 'error' } },
+ ] });
+ h.context.homeOnEnter();
+ await h.settle();
+
+ h.els['home-explore-context'].fire('click', click({ '[data-home-connect]': element() }));
+ await h.settle();
+ expect(h.menus).toHaveLength(1);
+ expect(h.menus[0].map((item: any) => item.label)).toEqual(['飞书 · 已连接', '钉钉', 'Gmail', 'Microsoft 365 邮箱']);
+
+ h.menus[0][2].onClick();
+ expect(h.views).toEqual([['connectors', null, { entryPoint: 'home' }]]);
+ expect(h.context.window.openConnectorSetupById).toHaveBeenCalledWith('gmail', 'form');
+ });
+});
diff --git a/test/renderer/i18n.test.ts b/test/renderer/i18n.test.ts
index b52d8b8d..1bde65ee 100644
--- a/test/renderer/i18n.test.ts
+++ b/test/renderer/i18n.test.ts
@@ -11,7 +11,7 @@ const i18nSource = fs.readFileSync(
path.join(rendererRoot, 'modules', 'i18n.js'),
'utf8',
);
-const LANGS = ['en', 'zh', 'ja', 'pt', 'es', 'fr', 'ko', 'de', 'ru', 'it', 'ar', 'hi', 'id', 'th', 'tr', 'vi', 'zh-tw', 'pt-pt', 'es-419'] as const;
+const LANGS = MAIN_LOCALES.map((locale) => locale.code);
type Deferred<T> = {
promise: Promise<T>;
diff --git a/test/renderer/lazy-features.test.ts b/test/renderer/lazy-features.test.ts
index fbd06b11..66160ca8 100644
--- a/test/renderer/lazy-features.test.ts
+++ b/test/renderer/lazy-features.test.ts
@@ -56,6 +56,7 @@ describe('renderer lazy feature loader', () => {
expect(appended.map((script) => script.src)).toEqual([
'./modules/settings.js',
'./modules/memory.js',
+ './modules/task-cleanup.js',
]);
expect(appended.every((script) => script.async === false)).toBe(true);
expect(telemetry.events).toEqual([]);
@@ -311,3 +312,10 @@ describe('renderer lazy feature loader', () => {
});
});
+
+
+it('loads public apps without requesting an unavailable publication module', async () => {
+ const { context, appended } = loadFeatureLoader();
+ await context.loadRendererFeature('apps');
+ expect(appended.map(script => script.src)).toEqual(['./modules/saved-apps.js']);
+});
diff --git a/test/renderer/local-agent-user-input.test.ts b/test/renderer/local-agent-user-input.test.ts
index b74ed7f2..29c43497 100644
--- a/test/renderer/local-agent-user-input.test.ts
+++ b/test/renderer/local-agent-user-input.test.ts
@@ -184,6 +184,16 @@ describe('renderer local Agent structured user input', () => {
});
});
+ it('retains the card when IPC rejects an expired answer or a failed history write', async () => {
+ const h = loadHarness();
+ h.push('local-agent:user-input', { request_id: 'save-answer', cid: 'chat-1', questions: [choiceQuestion] });
+ h.invoke.mockResolvedValueOnce({ handled: false, save_failed: true } as any);
+ expect(await h.requests[0].submit(['Staging'], [['Staging']])).toBe(false);
+ h.invoke.mockResolvedValueOnce({ handled: false } as any);
+ expect(await h.requests[0].submit(['Staging'], [['Staging']])).toBe(false);
+ expect(await h.requests[0].submit(['Staging'], [['Staging']])).toBe(true);
+ });
+
it('reports a failed reply so the card can keep the answer for a retry', async () => {
const harness = loadHarness();
harness.invoke.mockRejectedValueOnce(new Error('ipc down'));
@@ -195,6 +205,23 @@ describe('renderer local Agent structured user input', () => {
expect(await harness.requests[0].submit(['Staging'], [['Staging']])).toBe(true);
});
+ it.each(['retry', null])('retains collected dialog answers across a failed save, then handles %s', async decision => {
+ const h = loadHarness({ dock: false });
+ h.uiPrompt.mockResolvedValue('Retained answer');
+ h.uiChoice.mockResolvedValue(decision);
+ h.invoke.mockResolvedValueOnce({ handled: false, save_failed: true } as any);
+ h.push('local-agent:user-input', { request_id: 'dialog-save', cid: 'chat-1', questions: [textQuestion] });
+ await flush();
+ expect(h.uiPrompt).toHaveBeenCalledOnce();
+ expect(h.uiChoice).toHaveBeenCalledWith(expect.objectContaining({ message: 'chat.cli_question.send_failed' }));
+ expect(h.invoke.mock.calls.map(([, payload]) => payload)).toEqual([
+ { request_id: 'dialog-save', answers: { note: ['Retained answer'] }, cancelled: false },
+ decision === 'retry'
+ ? { request_id: 'dialog-save', answers: { note: ['Retained answer'] }, cancelled: false }
+ : { request_id: 'dialog-save', answers: {}, cancelled: true },
+ ]);
+ });
+
it('accepts only confirmed cancellation or native closure, never IPC receipt alone', async () => {
const harness = loadHarness();
harness.push('local-agent:user-input', {
diff --git a/test/renderer/math-lazy.test.ts b/test/renderer/math-lazy.test.ts
index d50f0cb3..d664021f 100644
--- a/test/renderer/math-lazy.test.ts
+++ b/test/renderer/math-lazy.test.ts
@@ -48,7 +48,7 @@ function loadMathBridge({ failLoads = 0 } = {}) {
describe('renderer MathJax lazy loading', () => {
it('does not retain intermediate stream versions in the session HTML cache', async () => {
const { context, warn } = loadMathBridge();
- context.document.createElement = () => ({ style: {}, innerHTML: '', parentElement: null });
+ context.document.createElement = () => ({ dataset: {}, style: {}, innerHTML: '', parentElement: null });
context.window.MathJax.typesetPromise = async () => {};
await context.typesetMathHtml('$stable$');
for (let i = 0; i < 180; i++) await context.typesetMathHtml(`$x+${i}$`, { cache: false });
@@ -60,7 +60,7 @@ describe('renderer MathJax lazy loading', () => {
const { context, warn } = loadMathBridge();
const retained = new Set();
const mounted = new Set();
- context.document.createElement = () => ({ style: {}, innerHTML: '', parentElement: null });
+ context.document.createElement = () => ({ dataset: {}, style: {}, innerHTML: '', parentElement: null });
context.document.body = {
appendChild(host: any) { mounted.add(host); host.parentElement = this; },
removeChild(host: any) { mounted.delete(host); host.parentElement = null; },
diff --git a/test/renderer/oss.test.ts b/test/renderer/oss.test.ts
index d820cd4c..a3fabd50 100644
--- a/test/renderer/oss.test.ts
+++ b/test/renderer/oss.test.ts
@@ -154,31 +154,10 @@ describe('oss.js', () => {
expect(calls.setView).toEqual([]);
});
- it('prefillCommander keeps only structured Commander attribution', () => {
- const { context, el } = loadOss();
- const applied = context.prefillCommander('Use X for [task].', {
- entry_point: 'oss_tool',
- resource_id: 'project-x',
- position: 4,
- source: 'commander_home',
- recipient_type: 'commander',
- });
-
- expect(applied).toBe(true);
- expect(el('new-chat-input').dataset).toMatchObject({
- commanderEntryPoint: 'oss_tool',
- commanderResourceId: 'project-x',
- commanderPosition: '4',
- commanderSource: 'commander_home',
- commanderRecipientType: 'commander',
- });
- });
-
it('does not treat bracketed content in an existing task as an OSS placeholder', () => {
const { context, el } = loadOss();
const applied = context.prefillCommander(
'Use Project X for this task: keep [sample] in the copy.',
- { entry_point: 'oss_tool', resource_id: 'project-x' },
{ trackPlaceholder: false },
);
@@ -195,7 +174,7 @@ describe('oss.js', () => {
};
const quickStartInput = {
value: 'Build a landing page with $& in the example copy.',
- dataset: { commanderEntryPoint: 'quick_start' },
+ dataset: {},
};
const enhanced = context._ossPromptForComposer(project, quickStartInput);
expect(enhanced).toContain('Build a landing page with $& in the example copy.');
@@ -203,7 +182,7 @@ describe('oss.js', () => {
const existingOssInput = {
value: enhanced,
- dataset: { commanderEntryPoint: 'oss_tool' },
+ dataset: { ossTemplateDraft: '1' },
};
expect(context._ossPromptForComposer(project, existingOssInput))
.toContain('[describe your task here]');
@@ -594,3 +573,21 @@ describe('oss.js', () => {
}
});
});
+
+it('keeps application logging free of retired statistics wrappers and their success-only payloads', () => {
+ const retired = /\b(?:_logManageResult|_logOpenResult|_logCreateAction|_logSavedAppSaveResult|_logLibraryImportResult|_artifactSaveSourceView|_logArtifactSaveResult|_savedAppSourceKind|_fileKindForLog|_trackRendererFeatureLoad|_autoCreateActionLogger|_autoAttachmentPayload|_logWorkspaceOpenFolderResult)\b/;
+ for (const module of ['saved-apps.js', 'chat-artifact.js', 'conversation-info.js', 'lazy-features.js', 'auto.js', 'user-workspace.js']) {
+ const source = fs.readFileSync(path.resolve(process.cwd(), 'src/renderer/modules', module), 'utf8');
+ expect(source, module).not.toMatch(retired);
+ }
+});
+
+it('keeps private creation and execution analytics out of the local executors', () => {
+ for (const file of ['src/main/features/agent_creation_telemetry.ts', 'bin/execution-error-diagnostics.cjs', 'bin/execution-error-diagnostics.d.cts']) {
+ expect(fs.existsSync(path.resolve(process.cwd(), file)), file).toBe(false);
+ }
+ for (const file of ['src/main/features/project_setup_tool.ts', 'src/main/features/auto_tasks_tool.ts', 'src/core-agent/src/agent/runner.ts']) {
+ expect(fs.readFileSync(path.resolve(process.cwd(), file), 'utf8'), file)
+ .not.toMatch(/\b(?:reportAgentCreation|onAgentCreationTelemetry|onInternalToolError|reportInternalToolError|captureErrorDiagnostic|priorErrorDiagnostic)\b/);
+ }
+});
diff --git a/test/renderer/overlay-manager.test.ts b/test/renderer/overlay-manager.test.ts
new file mode 100644
index 00000000..d9b5da2e
--- /dev/null
+++ b/test/renderer/overlay-manager.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+const source = fs.readFileSync(path.resolve(__dirname, '../../src/renderer/modules/overlay-manager.js'), 'utf8');
+
+function fixture() {
+ const roots: any[] = [];
+ let notify!: (records: any[]) => void;
+ const queue: Array<() => void> = [];
+ const invoke = vi.fn(async (_channel: string, payload: any) => ({ ok: true, ...payload }));
+ const warn = vi.fn();
+ const events = new Map<string, Array<() => void>>();
+ const body: any = { nodeType: 1, matches: () => false, contains: (element: any) => roots.includes(element),
+ querySelectorAll: () => roots, querySelector: () => null };
+ const window: any = { orkas: { invoke }, getComputedStyle: (element: any) => ({
+ display: element.hidden || element.parentHidden ? 'none' : 'block', visibility: element.visibility, position: element.position,
+ getPropertyValue: () => element.layer,
+ }), addEventListener: () => {} };
+ const document: any = { body, documentElement: body, styleSheets: [{ cssRules: [{
+ selectorText: '.fresh-surface', style: { getPropertyValue: () => 'overlay' },
+ }] }], addEventListener: (event: string, callback: () => void) => {
+ events.set(event, [...(events.get(event) || []), callback]);
+ } };
+ vm.runInNewContext(source, { window, document, createLogger: () => ({ warn }),
+ MutationObserver: class { constructor(callback: any) { notify = callback; } observe() {} },
+ queueMicrotask: (callback: () => void) => queue.push(callback),
+ });
+ const manager = window.OverlayManager;
+ const drain = async () => { while (queue.length) queue.shift()!(); await manager.settled(); };
+ const add = (name = 'fresh-surface', hidden = false) => {
+ const classes = new Set([name]);
+ const element: any = { nodeType: 1, isConnected: true, hidden, parentHidden: false,
+ visibility: 'visible', position: 'fixed', role: '', layer: 'overlay', rect: { width: 300, height: 200 },
+ matches: (selectors: string) => selectors.split(',').some(selector => classes.has(selector.trim().slice(1)) || selector.trim() === `[role="${element.role}"]`),
+ contains: (node: any) => node === element, querySelectorAll: () => [], querySelector: () => null,
+ getClientRects: () => element.hidden || element.parentHidden ? [] : [element.rect],
+ classList: { contains: (name: string) => classes.has(name), toggle: (name: string, wanted: boolean) => wanted ? classes.add(name) : classes.delete(name) },
+ };
+ roots.push(element);
+ notify([{ type: 'childList', target: body, addedNodes: [element], removedNodes: [] }]);
+ return element;
+ };
+ const change = (element: any) => notify([{ type: 'attributes', target: element }]);
+ const remove = (element: any) => {
+ element.isConnected = false; roots.splice(roots.indexOf(element), 1);
+ notify([{ type: 'childList', target: body, addedNodes: [], removedNodes: [element] }]);
+ };
+ return { manager, invoke, warn, add, change, remove, drain, body, notify, document,
+ dispatch: (event: string) => events.get(event)?.forEach(callback => callback()) };
+}
+
+describe('application floating layer presentation', () => {
+ it('automatically suppresses an unnamed shared-style surface and gates paint until native acknowledgement', async () => {
+ const f = fixture();
+ f.manager.setBrowserOpen(true); await f.drain();
+ let acknowledge!: (value: unknown) => void;
+ f.invoke.mockImplementationOnce(() => new Promise(resolve => { acknowledge = resolve; }));
+ const surface = f.add();
+ f.manager.refresh();
+ expect(f.manager.hasOpenLayers()).toBe(true);
+ expect(surface.classList.contains('ui-overlay-waiting')).toBe(true);
+ expect(f.invoke).toHaveBeenLastCalledWith('webAssist.overlayState', expect.objectContaining({ blocked: true }));
+ acknowledge({ ok: true, blocked: true }); await f.drain();
+ expect(surface.classList.contains('ui-overlay-waiting')).toBe(false);
+ f.remove(surface); await f.drain();
+ expect(f.manager.count()).toBe(0);
+ expect(f.invoke).toHaveBeenLastCalledWith('webAssist.overlayState', expect.objectContaining({ blocked: false }));
+ });
+
+ it('keeps suppression until the last nested surface is removed and does not duplicate IPC for unrelated content', async () => {
+ const f = fixture(); f.manager.setBrowserOpen(true); await f.drain();
+ const a = f.add(), b = f.add(); await f.drain();
+ expect(f.manager.count()).toBe(2);
+ f.invoke.mockClear();
+ f.remove(a); await f.drain();
+ expect(f.manager.count()).toBe(1);
+ expect(f.invoke).not.toHaveBeenCalled();
+ f.notify([{ type: 'childList', target: { nodeType: 1, matches: () => false, contains: () => false }, addedNodes: [], removedNodes: [] }]);
+ await f.drain(); expect(f.invoke).not.toHaveBeenCalled();
+ f.remove(b); await f.drain();
+ expect(f.invoke).toHaveBeenCalledExactlyOnceWith('webAssist.overlayState', expect.objectContaining({ blocked: false }));
+ });
+
+ it('handles hidden ancestors, empty roots, visibility-only closing and browser close without a dangling blocker', async () => {
+ const f = fixture(); const a = f.add(); a.parentHidden = true; await f.drain();
+ f.manager.setBrowserOpen(true); await f.drain(); expect(f.manager.count()).toBe(0);
+ a.parentHidden = false; f.change(a); await f.drain(); expect(f.manager.count()).toBe(1);
+ a.rect.height = 0; f.change(a); await f.drain(); expect(f.manager.count()).toBe(0);
+ a.rect.height = 100; a.visibility = 'hidden'; f.change(a); await f.drain(); expect(f.manager.count()).toBe(0);
+ a.visibility = 'visible'; f.change(a); await f.drain();
+ f.manager.setBrowserOpen(false); await f.drain();
+ expect(a.classList.contains('ui-overlay-waiting')).toBe(false);
+ f.invoke.mockClear(); f.remove(a); await f.drain(); expect(f.invoke).not.toHaveBeenCalled();
+ });
+
+ it('ignores stale release acknowledgements during rapid close/reopen', async () => {
+ const f = fixture(); f.manager.setBrowserOpen(true); await f.drain();
+ const a = f.add(); await f.drain();
+ let release!: (value: unknown) => void;
+ f.invoke.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
+ f.remove(a); f.manager.refresh();
+ const b = f.add(); f.manager.refresh(); await f.drain();
+ release({ ok: true, blocked: false }); await Promise.resolve();
+ expect(f.manager.count()).toBe(1);
+ expect(b.classList.contains('ui-overlay-waiting')).toBe(false);
+ expect(f.invoke).toHaveBeenLastCalledWith('webAssist.overlayState', expect.objectContaining({ blocked: true }));
+ });
+
+ it('keeps a surface unpainted after IPC failure and recovers on explicit refresh without uncontrolled retries', async () => {
+ const f = fixture(); f.manager.setBrowserOpen(true); await f.drain();
+ f.invoke.mockRejectedValueOnce(new Error('fixture disconnected'));
+ const a = f.add(); f.manager.refresh();
+ expect(await f.manager.settled()).toBe(false);
+ expect(a.classList.contains('ui-overlay-waiting')).toBe(true);
+ expect(f.warn).toHaveBeenCalledExactlyOnceWith('overlay presentation update failed');
+ f.manager.refresh(); await f.drain();
+ expect(a.classList.contains('ui-overlay-waiting')).toBe(false);
+ });
+
+ it('honors new stylesheet declarations without changing browser code and retains Escape ownership after removal', async () => {
+ const f = fixture();
+ f.document.styleSheets.push({ cssRules: [{ styleSheet: { cssRules: [{ selectorText: '.new-family', style: { getPropertyValue: () => 'overlay' } }] } }] });
+ const style = { nodeType: 1, matches: (s: string) => s.startsWith('style'), querySelector: () => null, querySelectorAll: () => [] };
+ f.notify([{ type: 'childList', target: f.body, addedNodes: [style], removedNodes: [] }]);
+ const a = f.add('new-family'); await f.drain();
+ expect(f.manager.count()).toBe(1);
+ const event = { composedPath: () => [a, f.body] };
+ f.remove(a); await f.drain();
+ expect(f.manager.layerForEvent(event)).toBe(a);
+ });
+
+ it('keeps transcript streaming independent of whole-document rescans and extra native updates', async () => {
+ const f = fixture(); f.manager.setBrowserOpen(true); f.add(); await f.drain();
+ f.invoke.mockClear();
+ f.body.querySelectorAll = () => { throw new Error('Whole document scanned during transcript streaming'); };
+ const transcript = { nodeType: 1, matches: () => false, contains: () => false };
+ const line = () => ({ nodeType: 1, matches: () => false, querySelector: () => null, querySelectorAll: () => [] });
+ f.notify([{ type: 'childList', target: transcript, addedNodes: Array.from({ length: 2000 }, line), removedNodes: [] }]);
+ await f.drain();
+ expect(f.manager.count()).toBe(1);
+ expect(f.invoke).not.toHaveBeenCalled();
+ });
+
+ it('recognizes a standard third-party floating menu without vendor selectors while ignoring inline menu regions', async () => {
+ const f = fixture(); const menu = f.add('vendor-unknown'); menu.role = 'menu'; menu.layer = '';
+ f.change(menu); await f.drain(); expect(f.manager.count()).toBe(1);
+ menu.position = 'static'; f.change(menu); await f.drain(); expect(f.manager.count()).toBe(0);
+ });
+
+ it('reconciles a CSS-only hover transition without requiring a DOM mutation', async () => {
+ const f = fixture(); const menu = f.add(); menu.visibility = 'hidden'; await f.drain();
+ f.manager.setBrowserOpen(true); await f.drain();
+ menu.visibility = 'visible'; f.dispatch('pointerover'); await f.drain();
+ expect(f.manager.count()).toBe(1);
+ expect(f.invoke).toHaveBeenLastCalledWith('webAssist.overlayState', expect.objectContaining({ blocked: true }));
+ menu.visibility = 'hidden'; f.dispatch('pointerout'); await f.drain(); expect(f.manager.count()).toBe(0);
+ });
+});
diff --git a/test/renderer/project-detail-local-cache.test.ts b/test/renderer/project-detail-local-cache.test.ts
index c11a42c8..b2bc5f62 100644
--- a/test/renderer/project-detail-local-cache.test.ts
+++ b/test/renderer/project-detail-local-cache.test.ts
@@ -24,6 +24,7 @@ function mountWithSlowSecondaryCard({ delayInstructionsFor = '' } = {}) {
};
const context = vm.createContext({
console,
+ performance,
currentUserId: 'member',
_byDisplayName: (a: any, b: any) => a.name.localeCompare(b.name),
createLogger: () => ({ warn() {}, info() {}, error() {} }),
@@ -74,7 +75,32 @@ function mountWithSlowSecondaryCard({ delayInstructionsFor = '' } = {}) {
}
describe('project detail local cache after restart', () => {
-it('preserves automation content while its feature loads without a loading placeholder', async () => {
+ it('does not restore a deleted file from a project load started before deletion', async () => {
+ const { context, nodes, finishAutoTasks } = mountWithSlowSecondaryCard();
+ let finishTree!: (value: unknown) => void;
+ const originalInvoke = context.window.orkas.invoke;
+ context.window.orkas.invoke = (channel: string, args: any) => {
+ if (channel === 'projects.files.tree') return new Promise(resolve => { finishTree = resolve; });
+ if (channel === 'projects.files.delete') return Promise.resolve({ ok: true });
+ return originalInvoke(channel, args);
+ };
+ vm.runInContext(`_projectDetailPid = 'project_a'; _projectDetailMeta = {
+ project: { project_id: 'project_a' }, files: [{ type: 'file', name: 'cached.md', relPath: 'cached.md' }]
+ }`, context);
+ context.uiConfirm = vi.fn(async () => true);
+ const loading = context.loadProjectDetail('project_a');
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await context._deleteProjectFile('cached.md');
+ expect(nodes['project-files-list'].innerHTML).not.toContain('cached.md');
+ finishTree({ ok: true, tree: [{ type: 'file', name: 'cached.md', relPath: 'cached.md' }] });
+ finishAutoTasks({ ok: true, tasks: [] });
+ await loading;
+ expect(vm.runInContext('_projectDetailMeta.files', context)).toEqual([]);
+ expect(nodes['project-files-list'].innerHTML).not.toContain('cached.md');
+ expect(nodes['project-instructions-read'].textContent).toBe('Saved local rules');
+ });
+
+ it('preserves automation content while its feature loads without a loading placeholder', async () => {
const { context, nodes } = mountWithSlowSecondaryCard();
const list = { innerHTML: 'Saved automation' };
nodes['project-auto-list'] = list;
diff --git a/test/renderer/project-icons.test.ts b/test/renderer/project-icons.test.ts
new file mode 100644
index 00000000..0c5e37cd
--- /dev/null
+++ b/test/renderer/project-icons.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+
+// Projects keep the same visual identity while users switch pages or choose
+// a destination. Actual directory entries remain folders, even in a shared Library.
+const projects = [
+ { project_id: 'private', name: 'Private' },
+ { project_id: 'shared', name: 'Shared' },
+ { project_id: 'ended', name: 'Ended' },
+ { project_id: 'pending', name: 'Pending' },
+];
+const expected = ['folder', 'folder', 'folder', 'folder'];
+
+function harness(...modules: string[]) {
+ const overlays: any[] = [];
+ const selections: any[] = [];
+ const element = (): any => {
+ const node: any = { children: [], dataset: {}, style: {}, className: '', innerHTML: '', attributes: {}, handlers: {},
+ appendChild(child: any) { this.children.push(child); return child; },
+ setAttribute(key: string, value: string) { this.attributes[key] = value; },
+ addEventListener(key: string, fn: any) { this.handlers[key] = fn; },
+ querySelector(selector: string) { return this.parts[selector] ||= element(); },
+ querySelectorAll() { return []; }, parts: {}, remove() {}, focus() {},
+ classList: { add() {}, toggle() {}, remove() {}, contains() { return false; } },
+ };
+ return node;
+ };
+ const host = element();
+ const context: any = {
+ currentUserId: 'me', currentView: 'todos', setTimeout: () => 0, clearTimeout() {},
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ t: String, escapeHtml: String, addEventListener() {},
+ localStorage: { getItem: () => null },
+ _uiKeepDialogFocus: () => () => {}, _uiRestoreDialogFocus() {},
+ _uiIsTopDialogOverlay: () => true,
+ document: { readyState: 'loading', addEventListener() {}, removeEventListener() {},
+ createElement: element, querySelectorAll: () => [], querySelector: () => null,
+ getElementById: (id: string) => id === 'contexts-project-select' ? host : null,
+ body: { appendChild: (overlay: any) => overlays.push(overlay), contains: () => true },
+ },
+ _aiSelectMount(_host: any, config: any) {
+ selections.push(config);
+ return { state: {}, setValue() {}, setAriaLabel() {}, setOptions(options: any) { selections.push({ options }); } };
+ },
+ orkas: { invoke: async (channel: string) => channel === 'projects.list' ? { projects } : { tree: [] } },
+ };
+ context.window = context;
+ vm.createContext(context);
+ for (const module of ['icons', ...modules]) {
+ vm.runInContext(fs.readFileSync(path.join(__dirname, `../../src/renderer/modules/${module}.js`), 'utf8'), context);
+ }
+ return { context, overlays, selections };
+}
+
+function icon(html: string) {
+ return /\bis-(folder-open|folder|globe)\b/.exec(html)?.[1];
+}
+
+describe('project identity across PC pages', () => {
+ it('keeps local project icons in todo scope chips, driver buttons and card links', () => {
+ const { context } = harness('project-detail', 'todos');
+ const groups = projects.map(project => ({ project, tasks: [], agents: [] }));
+ expect(context._renderGlobalTodoScopeSwitcher(groups).children.map((node: any) => icon(node.innerHTML))).toEqual(expected);
+ expect(groups.map(group => icon(context._renderGlobalTodoDriverToggle(group, true).innerHTML))).toEqual(expected);
+ const cards = projects.map(project => context._renderTodoCard({ id: 'task', status: 'todo', assignee_uid: 'me' }, {
+ pid: project.project_id, project, showProject: true, agents: [], members: [],
+ }));
+ expect(cards.map(card => icon(card.children.find((node: any) => node.className === 'todo-card-meta')
+ .children.find((node: any) => node.className === 'todo-card-project').innerHTML))).toEqual(expected);
+ });
+
+ it('refreshes the Library scope selector after project refresh and keeps global scope a folder', () => {
+ const { context, selections } = harness('contexts');
+ context._renderCtxScopeSelector(projects);
+ expect(Object.fromEntries(selections.at(-1).options.map((option: any) => [option.value, option.iconName])))
+ .toEqual({ '': 'folder', private: 'folder', shared: 'folder', ended: 'folder', pending: 'folder' });
+ context._renderCtxScopeSelector(projects.map(project => ({ ...project })));
+ expect(selections.at(-1).options.map((option: any) => option.iconName)).toEqual(Array(5).fill('folder'));
+ });
+
+ it('shows shared identity when filing a conversation under a project', async () => {
+ const { context, overlays } = harness('conversation-to-project');
+ const choice = context._openConversationProjectPicker(projects);
+ const overlay = overlays[0];
+ const rows = [...overlay.innerHTML.matchAll(/data-project-id="[^"]+">([\s\S]*?)<\/button>/g)];
+ expect(rows.map(row => icon(row[1]))).toEqual(expected);
+ overlay.querySelector('[data-act="cancel"]').handlers.click();
+ await expect(choice).resolves.toBeNull();
+ });
+
+ it('distinguishes shared transfer destinations while retaining directory folder icons', async () => {
+ const { context, overlays, selections } = harness('library-transfer');
+ const dialog = context.LibraryTransfer.open({ source: { scope: 'project', projectId: 'shared' }, paths: ['brief.md'] });
+ // The picker waits for project metadata before it mounts.
+ await new Promise(resolve => setImmediate(resolve));
+ expect(selections[0].options.map((option: any) => option.iconName)).toEqual(['folder', ...expected]);
+ const folders = overlays[0].querySelector('[data-transfer-folders]').innerHTML;
+ expect(icon(folders)).toBe('folder-open');
+ expect(folders).not.toContain('is-globe');
+ overlays[0].querySelector('[data-transfer-cancel]').handlers.click();
+ await dialog;
+ });
+});
diff --git a/test/renderer/project-library-index-recovery.test.ts b/test/renderer/project-library-index-recovery.test.ts
index f6c93151..a3f920ec 100644
--- a/test/renderer/project-library-index-recovery.test.ts
+++ b/test/renderer/project-library-index-recovery.test.ts
@@ -64,6 +64,19 @@ function loadProjectDetailScript() {
}
describe('Project Library indexing recovery', () => {
+ it('keeps available files usable without per-file background download notices', () => {
+ const { context } = loadProjectDetailScript();
+ const html = context._renderProjectFileNodes([
+ { type: 'file', name: 'available.txt', relPath: 'available.txt', kind: 'text' },
+ { type: 'file', name: 'incoming.txt', relPath: 'incoming.txt', kind: 'text', pending: true },
+ ]);
+ expect(html).toContain('data-project-file="available.txt"');
+ expect(html).toContain('data-action="project-file-menu"');
+ expect(html).toContain('incoming.txt');
+ expect(html).not.toContain('common.loading');
+ expect(html).not.toContain('data-project-file="incoming.txt"');
+ });
+
it('explains oversized saved text after an event and a status refresh without offering a futile retry', () => {
const { context } = loadProjectDetailScript();
const status = {
diff --git a/test/renderer/project-library-popup-copy.test.ts b/test/renderer/project-library-popup-copy.test.ts
index f6703456..6993b540 100644
--- a/test/renderer/project-library-popup-copy.test.ts
+++ b/test/renderer/project-library-popup-copy.test.ts
@@ -38,6 +38,68 @@ function loadProjectDetailScript() {
}
describe('Project Library popup copy', () => {
+ it.each([
+ ['confirmation', 'project'], ['confirmation', 'account'],
+ ['deletion', 'project'], ['deletion', 'account'],
+ ])('ignores %s completion after changing %s', async (phase, scope) => {
+ const context = loadProjectDetailScript();
+ context.currentUserId = 'first';
+ let release!: () => void;
+ let started!: () => void;
+ const waiting = new Promise<void>(resolve => { started = resolve; });
+ const gate = () => new Promise(resolve => { release = () => resolve(phase === 'confirmation' ? true : { ok: true }); started(); });
+ context.uiConfirm = vi.fn(phase === 'confirmation' ? gate : async () => true);
+ context.window.orkas.invoke = vi.fn(phase === 'deletion' ? gate : async () => ({ ok: true }));
+ context._renderProjectFiles = vi.fn();
+ const deleting = context._deleteProjectFile('old.md');
+ await waiting;
+ if (scope === 'account') context.currentUserId = 'second';
+ else vm.runInContext("_projectDetailPid = 'project-2'", context);
+ vm.runInContext("_projectDetailMeta = { files: [{ name: 'old.md', relPath: 'old.md', type: 'file' }] }", context);
+ release();
+ await deleting;
+ expect(context.window.orkas.invoke).toHaveBeenCalledTimes(phase === 'confirmation' ? 0 : 1);
+ expect(context._renderProjectFiles).not.toHaveBeenCalled();
+ expect(vm.runInContext('_projectDetailMeta.files.length', context)).toBe(1);
+ });
+
+ it('removes a deleted subtree and updates the list without waiting for unrelated project reloads', async () => {
+ const context = loadProjectDetailScript();
+ const kept = { type: 'file', name: 'keep.md', relPath: 'keep.md', kind: 'text' };
+ vm.runInContext(`_projectDetailMeta = { files: [
+ { type: 'dir', name: 'Notes', relPath: 'Notes', children: [
+ { type: 'file', name: 'old.md', relPath: 'Notes/old.md', kind: 'text' }
+ ] }, kept
+ ] }; _projectLibraryActiveName = 'Notes/old.md';
+ _projectLibraryDrafts.set('Notes/old.md', 'unsaved draft');`, Object.assign(context, { kept }));
+ context.uiConfirm = vi.fn(async () => true);
+ context.window.orkas.invoke = vi.fn(async () => ({ ok: true }));
+ context.loadProjectDetail = vi.fn(() => new Promise(() => {}));
+ context._renderProjectFiles = vi.fn();
+ context._clearProjectLibraryViewer = vi.fn();
+ await context._deleteProjectFile('Notes');
+ expect(context._renderProjectFiles).toHaveBeenCalledWith([kept]);
+ expect(vm.runInContext('_projectDetailMeta.files', context)).toEqual([kept]);
+ expect(vm.runInContext('_projectLibraryDrafts.size', context)).toBe(0);
+ expect(context._clearProjectLibraryViewer).toHaveBeenCalledOnce();
+ expect(context.loadProjectDetail).not.toHaveBeenCalled();
+ });
+
+ it('keeps files and the viewer when local deletion fails', async () => {
+ const context = loadProjectDetailScript();
+ vm.runInContext("_projectDetailMeta = { files: [{ name: 'old.md', relPath: 'old.md', type: 'file' }] }; _projectLibraryActiveName = 'old.md'", context);
+ context.uiConfirm = vi.fn(async () => true);
+ context.uiAlert = vi.fn(async () => {});
+ context.window.orkas.invoke = vi.fn(async () => ({ ok: false }));
+ context._renderProjectFiles = vi.fn();
+ context._clearProjectLibraryViewer = vi.fn();
+ await context._deleteProjectFile('old.md');
+ expect(vm.runInContext('_projectDetailMeta.files.length', context)).toBe(1);
+ expect(context._clearProjectLibraryViewer).not.toHaveBeenCalled();
+ expect(context._renderProjectFiles).not.toHaveBeenCalled();
+ expect(context.uiAlert).toHaveBeenCalledOnce();
+ });
+
it('requires confirmation before deleting and shows only the basename', async () => {
const context = loadProjectDetailScript();
context.uiConfirm = vi.fn(async () => false);
diff --git a/test/renderer/project-todo-controls.test.ts b/test/renderer/project-todo-controls.test.ts
index f765b5be..3398fcbd 100644
--- a/test/renderer/project-todo-controls.test.ts
+++ b/test/renderer/project-todo-controls.test.ts
@@ -1,18 +1,247 @@
import { composerAccessorSource } from './composer-test-source';
-import { describe, expect, it } from 'vitest';
+import { conversationCacheSource } from './conversation-cache-test-source';
+import { describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
+import ts from 'typescript';
const rendererDir = path.join(__dirname, '../../src/renderer');
-const source = fs.readFileSync(path.join(rendererDir, 'modules/project-detail.js'), 'utf8');
+const conversation = ts.createSourceFile('conversation.js', fs.readFileSync(path.join(rendererDir, 'modules/conversation.js'), 'utf8'),
+ ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+const sendNames = new Set(['_composerSendIsEmpty', '_resolvedMentionSpans', '_quotedLineRanges', '_buildMentionRe', '_escapeForRegex',
+ '_COMMANDER', '_composerAgentScopes', '_MENTION_FALLBACK_CLASS']);
+const sendSource = conversation.statements.filter(node =>
+ ts.isFunctionDeclaration(node) ? sendNames.has(node.name?.text || '') : ts.isVariableStatement(node)
+ && node.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && sendNames.has(declaration.name.text)))
+ .map(node => node.getText(conversation)).join('\n');
+const markdown = ts.createSourceFile('strip-structural-blocks.js', fs.readFileSync(path.join(rendererDir, 'modules/strip-structural-blocks.js'), 'utf8'),
+ ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+const markdownSource = markdown.statements.filter(node => ts.isFunctionDeclaration(node) && node.name?.text === '_splitMarkdownProseCode')
+ .map(node => node.getText(markdown)).join('\n');
+const source = [conversationCacheSource, sendSource, markdownSource, fs.readFileSync(path.join(rendererDir, 'modules/project-detail.js'), 'utf8')].join('\n');
// The editor uploads through the shared renderer base64 helper (utils.js).
// eslint-disable-next-line @typescript-eslint/no-var-requires
const rendererUtils = require('../../src/renderer/modules/utils.js');
+function cardNodes(node: any): any[] {
+ return [node, ...(node.children || []).flatMap(cardNodes)];
+}
+
describe('project to-do controls', () => {
- it.each(['todo', 'progress', 'review'])('opens an immediate run from a %s task menu', async (status) => {
+ it.each(['same board', 'account', 'project', 'grouping'])('keeps reading positions only within the mounted scope: %s', (change) => {
+ const element = (): any => ({
+ children: [], dataset: {}, scrollTop: 0, scrollLeft: 0,
+ appendChild(child: any) { child.parentElement = this; this.children.push(child); },
+ setAttribute() {}, addEventListener() {},
+ querySelectorAll(selector: string) {
+ return this.children.flatMap((child: any) => [
+ ...(child.className?.split(' ').includes(selector.slice(1)) ? [child] : []),
+ ...child.querySelectorAll(selector),
+ ]);
+ },
+ });
+ const context = vm.createContext({
+ currentUserId: 'me', createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, createElement: element },
+ window: { addEventListener() {} }, t: (key: string) => key, escapeHtml: String,
+ });
+ vm.runInContext(source, context);
+ const host = element();
+ const board = context._renderTodoBoard([], {}, 'project:one');
+ host.appendChild(board);
+ host.scrollTop = 120;
+ board.scrollLeft = 60;
+ const bodies = board.querySelectorAll('.todo-column-body');
+ bodies[0].scrollTop = 300;
+ bodies[1].scrollTop = 80;
+ const snapshot = context._captureTodoScroll(host);
+ if (change === 'account') context.currentUserId = 'other';
+ const scope = change === 'project' ? 'project:two' : change === 'grouping' ? 'global:status' : 'project:one';
+ const next = context._renderTodoBoard([], {}, scope);
+ host.children = [];
+ host.scrollTop = 0;
+ host.appendChild(next);
+ // Column order is irrelevant to status-specific reading positions.
+ next.children.reverse();
+ context._restoreTodoScroll(host, snapshot);
+ const retained = change === 'same board';
+ expect(host.scrollTop).toBe(retained ? 120 : 0);
+ expect(next.scrollLeft).toBe(retained ? 60 : 0);
+ const columnTops = Object.fromEntries(next.querySelectorAll('.todo-column-body')
+ .map((body: any) => [body.parentElement.dataset.status, body.scrollTop]));
+ expect(columnTops).toEqual({ todo: retained ? 300 : 0, progress: retained ? 80 : 0, review: 0, done: 0 });
+ });
+
+ it.each(['private', 'global'])('discloses %s card text without editing or writing, retaining state only in its account and scope', (kind) => {
+ const element = (tag: string): any => {
+ const node: any = { tag, children: [], dataset: {}, className: '', attributes: {},
+ appendChild(child: any) { this.children.push(child); return child; },
+ setAttribute(key: string, value: string) { this.attributes[key] = value; },
+ querySelector() { return this.children.find((child: any) => child.className === 'project-todo-title'); },
+ };
+ node.classList = {
+ add(value: string) { node.className += ` ${value}`; },
+ toggle(value: string, enabled: boolean) {
+ const classes = node.className.split(' ').filter((name: string) => name !== value);
+ if (enabled) classes.push(value);
+ node.className = classes.join(' ');
+ },
+ };
+ return node;
+ };
+ let click!: (event: any) => void;
+ const invoke = vi.fn();
+ const editor = vi.fn();
+ const context = vm.createContext({
+ currentUserId: 'me', createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, createElement: element },
+ window: { addEventListener() {}, orkas: { invoke } },
+ t: (key: string) => key, escapeHtml: (value: unknown) => String(value),
+ });
+ vm.runInContext(source, context);
+ context._openProjectTodoEditor = editor;
+ const task = Object.freeze({ id: 'same_id', content: 'Title\n<literal> & Full content',
+ status: 'todo', assignee_uid: 'other' });
+ const scope = { pid: kind === 'global' ? '' : 'p_one', global: kind === 'global', tasks: [task],
+ project: {}, agents: [], members: [] };
+ const row = context._renderTodoCard(task, scope);
+ const title = row.querySelector('.project-todo-title');
+ expect(title.attributes['aria-expanded']).toBe('false');
+ expect(title.textContent).toBe(task.content);
+ context._bindTodoListActions({ dataset: {}, addEventListener(_type: string, handler: any) { click = handler; } }, () => scope);
+ const target = (action?: string, control = false) => ({ closest(selector: string) {
+ if (selector === '.project-todo-item') return row;
+ if (action && selector === `[data-action="${action}"]`) return title;
+ if (control && selector.startsWith('button,')) return title;
+ return null;
+ } });
+ click({ target: target(title.dataset.action, true) });
+ expect(title.attributes['aria-expanded']).toBe('true');
+ expect(row.className).toContain('is-expanded');
+ expect(editor).not.toHaveBeenCalled();
+ expect(invoke).not.toHaveBeenCalled();
+ expect(context._renderTodoCard(task, scope).querySelector().attributes['aria-expanded']).toBe('true');
+ expect(context._renderTodoCard(task, { ...scope, pid: 'p_other' }).querySelector().attributes['aria-expanded']).toBe('false');
+ expect(context._renderTodoCard(task, { ...scope, global: !scope.global }).querySelector().attributes['aria-expanded']).toBe('false');
+ context.currentUserId = 'another_account';
+ expect(context._renderTodoCard(task, scope).querySelector().attributes['aria-expanded']).toBe('false');
+ context.currentUserId = 'me';
+ // An interactive child outside disclosure must not toggle it.
+ click({ target: target(undefined, true) });
+ expect(title.attributes['aria-expanded']).toBe('true');
+ // The next click on plain card padding collapses it.
+ click({ target: target() });
+ expect(title.attributes['aria-expanded']).toBe('false');
+ expect(row.className).not.toContain('is-expanded');
+ expect(context._renderTodoCard(task, scope).querySelector().attributes['aria-expanded']).toBe('false');
+ expect(task).toEqual({ id: 'same_id', content: 'Title\n<literal> & Full content', status: 'todo', assignee_uid: 'other' });
+ expect(editor).not.toHaveBeenCalled();
+ expect(invoke).not.toHaveBeenCalled();
+ });
+
+ it('marks collapsed lanes, so the project board can narrow them, and keeps the choice per board', () => {
+ const element = (tag: string): any => {
+ const node: any = { tag, children: [] as any[], dataset: {}, attributes: {} as Record<string, string>,
+ handlers: {} as Record<string, () => void>, className: '', hidden: false, innerHTML: '', textContent: '',
+ appendChild(child: any) { this.children.push(child); return child; },
+ setAttribute(key: string, value: string) { this.attributes[key] = value; },
+ addEventListener(key: string, handler: () => void) { this.handlers[key] = handler; } };
+ node.classList = { toggle(name: string, enabled: boolean) {
+ const names = node.className.split(' ').filter((value: string) => value && value !== name);
+ if (enabled) names.push(name);
+ node.className = names.join(' ');
+ } };
+ return node;
+ };
+ const context = vm.createContext({
+ currentUserId: 'me', createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, createElement: element },
+ window: { addEventListener() {} }, t: (key: string) => key, escapeHtml: String,
+ });
+ vm.runInContext(source, context);
+ const lanes = (board: any) => Object.fromEntries(board.children.map((column: any) => [column.dataset.status, column]));
+ const collapsed = (board: Record<string, any>) => Object.entries(board)
+ .filter(([, column]) => column.className.split(' ').includes('is-collapsed')).map(([status]) => status);
+ const toggle = (column: any) => column.children[0].children[0];
+ let board = lanes(context._renderTodoBoard([], {}, 'project:one'));
+ expect(collapsed(board)).toEqual(['done']);
+ expect(toggle(board.done).innerHTML).toContain('<span class="todo-collapse-label">project.todo.status_done</span>');
+ toggle(board.done).handlers.click();
+ expect(collapsed(board)).toEqual([]);
+ expect(board.done.children[1].hidden).toBe(false);
+ expect(toggle(board.done).attributes['aria-expanded']).toBe('true');
+ toggle(board.todo).handlers.click();
+ expect(collapsed(board)).toEqual(['todo']);
+ expect(board.todo.children[1].hidden).toBe(true);
+ // A repaint keeps the choice for this board only.
+ board = lanes(context._renderTodoBoard([], {}, 'project:one'));
+ expect(collapsed(board)).toEqual(['todo']);
+ expect(collapsed(lanes(context._renderTodoBoard([], {}, 'project:two')))).toEqual(['done']);
+ });
+
+ it.each(['todo', 'progress', 'review', 'done'])('shows the same %s status and footer controls on project and account cards', (stage) => {
+ const element = (tag: string): any => {
+ const node: any = { tag, children: [] as any[], dataset: {}, className: '', attributes: {},
+ appendChild(child: any) { this.children.push(child); return child; },
+ setAttribute(key: string, value: string) { this.attributes[key] = value; },
+ };
+ node.classList = { add(name: string) { node.className += ` ${name}`; } };
+ return node;
+ };
+ const context = vm.createContext({
+ currentUserId: 'me', createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: { readyState: 'loading', addEventListener() {}, createElement: element },
+ window: { addEventListener() {} }, t: (key: string) => key, escapeHtml: String,
+ setTimeout, clearTimeout,
+ });
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext(source, context);
+ const task = { id: 't_one', content: 'Review', status: stage };
+ const status = (card: any) => cardNodes(card).find((child: any) => child.dataset.action === 'todo-status');
+ const project = status(context._renderTodoCard(task, vm.runInContext('_projectTodoContext()', context)));
+ expect(project.className).toBe('btn btn-sm project-todo-status-select is-' + stage);
+ expect(project.innerHTML).toBe('<span class="project-todo-status-dot"></span>'
+ + '<span class="project-todo-status-label">project.todo.status_' + stage + '</span>');
+ expect(project.title).toBe('project.todo.status_' + stage);
+ expect(project.attributes['aria-haspopup']).toBe('menu');
+ const account = status(context._renderTodoCard(task, { global: true, pid: '', tasks: [task], agents: [] }));
+ expect(account.className).toBe(project.className);
+ expect(account.innerHTML).toBe(project.innerHTML);
+ for (const scope of [vm.runInContext('_projectTodoContext()', context), { global: true, tasks: [task], agents: [] }]) {
+ const footer = context._renderTodoCard(task, scope).children.find((child: any) => child.className === 'todo-card-meta');
+ expect(footer).toBeDefined();
+ expect(cardNodes(footer).filter((child: any) => child.dataset.action).map((child: any) => child.dataset.action))
+ .toEqual(['todo-assign', 'todo-status']);
+ }
+ });
+
+ it('shows only the active tab\'s tools on the project tab row', () => {
+ const node = (dataset: Record<string, string>) => ({ dataset, hidden: false, tabIndex: 0,
+ classList: { toggle() {} }, setAttribute() {} });
+ const tabs = ['tasks', 'auto', 'todo'].map(projectTab => node({ projectTab }));
+ const panels = ['tasks', 'auto', 'todo'].map(projectPanel => node({ projectPanel }));
+ const tools = ['auto', 'todo'].map(projectTools => node({ projectTools }));
+ const context = vm.createContext({
+ currentUserId: 'me', createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, querySelectorAll(selector: string) {
+ return ({ '.project-detail-tab': tabs, '.project-detail-tab-panel': panels, '[data-project-tools]': tools } as
+ Record<string, unknown[]>)[selector] || [];
+ } },
+ window: { addEventListener() {} }, t: (key: string) => key,
+ });
+ vm.runInContext(source, context);
+ for (const [active, shown] of [['tasks', []], ['auto', ['auto']], ['todo', ['todo']]] as const) {
+ context.__active = active;
+ vm.runInContext('_projectDetailActiveTab = __active', context);
+ context._syncProjectDetailTabState();
+ expect(tools.filter(group => !group.hidden).map(group => group.dataset.projectTools)).toEqual(shown);
+ expect(panels.filter(panel => !panel.hidden).map(panel => panel.dataset.projectPanel)).toEqual([active]);
+ }
+ });
+
+ it.each(['todo', 'progress', 'review', 'done'])('offers immediate processing only for unfinished %s tasks', async (status) => {
const calls: any[] = [];
const navigations: any[] = [];
let items: any[] = [];
@@ -34,6 +263,13 @@ describe('project to-do controls', () => {
pid: 'p_test', tasks: [{ id: 't_123456789abc', title: 'Continue work', status }],
});
const run = items.find((item) => item.label === 'project.todo.run');
+ if (status === 'done') {
+ expect(run).toBeUndefined();
+ await context._runTodoTask('t_123456789abc', { pid: 'p_test', tasks: [{ id: 't_123456789abc', status }] });
+ expect(calls).toEqual([]);
+ expect(navigations).toEqual([]);
+ return;
+ }
expect(run).toBeDefined();
await run.onClick();
expect(calls).toEqual([{ channel: 'projects.tasks.run', payload: { projectId: 'p_test', taskId: 't_123456789abc' } }]);
@@ -72,6 +308,7 @@ describe('project to-do controls', () => {
id: 't_123456789abc', title: 'Linked task', status: 'progress', origin_cid: 'c_linked',
};
const context = vm.createContext({
+ currentUserId: 'me',
console,
createLogger: () => ({ warn() {}, info() {}, error() {} }),
document: {
@@ -92,7 +329,7 @@ describe('project to-do controls', () => {
vm.runInContext(source, context, { filename: 'project-detail.js' });
const card = context._renderTodoCard(task, { pid: 'p_test', tasks: [task], agents: [] });
- const conversationEntry = card.children.find((child: any) => child.dataset?.action === 'todo-conversation');
+ const conversationEntry = cardNodes(card).find((child: any) => child.dataset?.action === 'todo-conversation');
expect(conversationEntry).toBeDefined();
expect(conversationEntry.innerHTML).toBe(`<svg></svg><span>${label}</span>`);
expect(conversationEntry.attributes['aria-label']).toBe(translations['project.todo.open_conversation']);
@@ -100,11 +337,11 @@ describe('project to-do controls', () => {
{ id: 't_abcdef123456', title: 'Unlinked task', status: 'todo' },
{ pid: 'p_test', tasks: [], agents: [] },
);
- expect(unlinked.children.some((child: any) => child.dataset?.action === 'todo-conversation')).toBe(false);
+ expect(cardNodes(unlinked).some((child: any) => child.dataset?.action === 'todo-conversation')).toBe(false);
// Host execution facts are available to models, without adding a visible card indicator.
for (const is_running of [true, false, null]) {
const executionCard = context._renderTodoCard({ ...task, is_running }, { pid: 'p_test', tasks: [], agents: [] });
- const badge = executionCard.children.find((child: any) => child.dataset?.role === 'todo-execution');
+ const badge = cardNodes(executionCard).find((child: any) => child.dataset?.role === 'todo-execution');
expect(badge).toBeUndefined();
}
@@ -146,6 +383,7 @@ describe('project to-do controls', () => {
'project-todo-count': { textContent: '' },
};
const context = vm.createContext({
+ currentUserId: 'me',
console,
createLogger: () => ({ warn() {}, info() {}, error() {} }),
document: {
@@ -260,6 +498,7 @@ describe('project to-do controls', () => {
'project-todo-count': { textContent: '' },
};
const context = vm.createContext({
+ currentUserId: 'me',
console,
createLogger: () => ({ warn() {}, info() {}, error() {} }),
document: {
@@ -320,10 +559,10 @@ describe('project to-do controls', () => {
// Unassigned task: the menu offers the bound agent and no "unassign" entry.
await listeners.click({ target: assignTarget });
- expect(menuItems.map((item) => item.label)).toEqual(['Researcher']);
+ expect(menuItems.map((item) => item.label)).toEqual(['chat.recipient_commander', 'Researcher']);
// Picking the agent writes owner_agent + owner_agent_id via projects.tasks.update.
- await menuItems[0].onClick!();
+ await menuItems.find(item => item.label === 'Researcher')!.onClick!();
let updates = invocations.filter((call) => call.channel === 'projects.tasks.update');
expect(updates).toHaveLength(1);
expect(updates[0].payload).toMatchObject({
@@ -336,7 +575,7 @@ describe('project to-do controls', () => {
// The post-assign re-fetch now reports the owner. The menu only switches
// agents; clearing moved to the × revealed directly on the assigned chip.
await listeners.click({ target: assignTarget });
- expect(menuItems.map((item) => item.label)).toEqual(['Researcher']);
+ expect(menuItems.map((item) => item.label)).toEqual(['chat.recipient_commander', 'Researcher']);
// Clicking that × clears both owner fields (empty strings → backend drops
// the owner) without opening the assignment menu.
@@ -385,6 +624,7 @@ describe('project to-do controls', () => {
'project-todo-add-btn': { dataset: {}, addEventListener() {} },
};
const context = vm.createContext({
+ currentUserId: 'me',
console,
createLogger: () => ({ warn() {}, info() {}, error() {} }),
document: {
@@ -425,18 +665,20 @@ describe('project to-do controls', () => {
await context._loadProjectTodos('p_test');
const row = { dataset: { tid: 't_edit123abcd', status: 'todo' } };
- const editButton = { dataset: { action: 'todo-edit' } };
+ const editButton = { dataset: { action: 'todo-menu' } };
const editTarget = {
closest(selector: string) {
if (selector === '.project-todo-item') return row;
- if (selector === '[data-action="todo-edit"]') return editButton;
+ if (selector === '[data-action="todo-menu"]') return editButton;
return null;
},
};
- // Clicking the card content opens the shared editor directly; the restored
- // overflow menu remains a separate explicit target.
+ // Editing remains an explicit overflow-menu action.
+ const menuItems: any[] = [];
+ context.showContextMenu = (_event: any, items: any[]) => menuItems.push(...items);
await listeners.click({ target: editTarget });
+ menuItems.find(item => item.label === 'project.todo.edit').onClick();
expect(editor.hidden).toBe(false);
expect(input.value).toBe('Old content\nFull requirements');
@@ -696,6 +938,87 @@ describe('project to-do controls', () => {
expect(toasts[1].opts).toMatchObject({ variant: 'info' });
});
+ it('shows the executing device name and disables then re-enables on the current device', async () => {
+ let click!: () => Promise<void>;
+ const toggle: any = { dataset: {}, disabled: false, _pressed: 'false',
+ getAttribute() { return this._pressed; },
+ setAttribute(_key: string, value: string) { this._pressed = value; },
+ addEventListener(_type: string, callback: typeof click) { click = callback; } };
+ const suffix = { textContent: '' };
+ const sets: boolean[] = [];
+ const device = { id: 'device-b', name: 'Laptop B' };
+ let config: any = { enabled: true, device_id: 'device-a', device_name: '<Office Mac>' };
+ const context = vm.createContext({
+ createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, getElementById(id: string) {
+ return id === 'project-driver-toggle' ? toggle : id === 'project-driver-device' ? suffix : null;
+ } },
+ window: { addEventListener() {}, orkas: { async invoke(channel: string, payload: any) {
+ if (channel === 'projects.driver.set') {
+ sets.push(payload.enabled);
+ config = { enabled: payload.enabled, ...(payload.enabled ? { device_id: device.id, device_name: device.name } : {}) };
+ }
+ return { config, device };
+ } } }, t: String,
+ });
+ vm.runInContext(source, context);
+ vm.runInContext("_projectDetailPid = 'p_device'; _bindProjectDriver();", context);
+ await context._loadProjectDriver('p_device');
+ expect(toggle._pressed).toBe('true');
+ // Hostnames are user data and remain text, including markup look-alikes.
+ expect(suffix.textContent).toBe(' · <Office Mac>');
+ await click();
+ expect(toggle._pressed).toBe('false');
+ expect(suffix.textContent).toBe('');
+ await click();
+ expect(toggle._pressed).toBe('true');
+ expect(suffix.textContent).toBe(' · auto.device_current');
+ expect(sets).toEqual([false, true]);
+ context._setProjectDriverToggleState({ enabled: true, device_id: device.id }, device);
+ expect(suffix.textContent).toBe(' · auto.device_current');
+ context._setProjectDriverToggleState({ enabled: true, device_id: 'device-a', device_name: device.name }, device);
+ expect(suffix.textContent).toBe(' · Laptop B');
+ context._setProjectDriverToggleState({ enabled: true, device_id: 'device-a' }, device);
+ expect(suffix.textContent).toBe(' · device-a');
+ });
+
+ it('ignores reordered driver reads across project navigation and blocks toggling unknown state', async () => {
+ let click!: () => Promise<void>;
+ const toggle: any = { dataset: {}, disabled: false, _pressed: 'false',
+ getAttribute() { return this._pressed; },
+ setAttribute(_key: string, value: string) { this._pressed = value; },
+ addEventListener(_type: string, callback: typeof click) { click = callback; } };
+ const suffix = { textContent: '' };
+ const pending: Array<(value: any) => void> = [];
+ const sets: any[] = [];
+ const context = vm.createContext({
+ createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, getElementById(id: string) {
+ return id === 'project-driver-toggle' ? toggle : id === 'project-driver-device' ? suffix : null;
+ } },
+ window: { addEventListener() {}, orkas: { invoke(channel: string, payload: any) {
+ if (channel === 'projects.driver.set') sets.push(payload);
+ return new Promise(resolve => pending.push(resolve));
+ } } }, t: String,
+ });
+ vm.runInContext(source, context);
+ vm.runInContext("_projectDetailPid = 'p_old'; _bindProjectDriver();", context);
+ const old = context._loadProjectDriver('p_old');
+ expect(toggle.disabled).toBe(true);
+ await click();
+ expect(sets).toEqual([]);
+ vm.runInContext("_projectDetailPid = 'p_new';", context);
+ const fresh = context._loadProjectDriver('p_new');
+ pending[1]({ config: { enabled: true, device_id: 'device-b', device_name: 'Remote B' }, device: { id: 'device-a' } });
+ await fresh;
+ expect(toggle.disabled).toBe(false);
+ expect(suffix.textContent).toBe(' · Remote B');
+ pending[0]({ config: { enabled: false }, device: { id: 'device-a' } });
+ await old;
+ expect(toggle._pressed).toBe('true');
+ expect(suffix.textContent).toBe(' · Remote B');
+ });
+
it('surfaces a driver-advanced conversation into the shared conversation list', () => {
const conversationsArr: any[] = [];
let renderCalls = 0;
@@ -719,8 +1042,8 @@ describe('project to-do controls', () => {
// A background driver advance pushes its new conversation; it lands in the
// shared list (like a human-started run) and the list re-renders.
context._onProjectAdvance({ projectId: 'p_test', conversation: { conversation_id: 'c_drv1', project_id: 'p_test' } });
- expect(conversationsArr).toHaveLength(1);
- expect(conversationsArr[0]).toMatchObject({ conversation_id: 'c_drv1' });
+ expect(context.conversations).toHaveLength(1);
+ expect(context.conversations[0]).toMatchObject({ conversation_id: 'c_drv1' });
expect(renderCalls).toBe(1);
// It also attaches the run observer so the conversation shows the in-progress
// breathing badge, like a human-started run.
@@ -730,8 +1053,8 @@ describe('project to-do controls', () => {
// Same cid again updates in place — never duplicates the running task.
context._onProjectAdvance({ projectId: 'p_test', conversation: { conversation_id: 'c_drv1', project_id: 'p_test', title: 'x' } });
- expect(conversationsArr).toHaveLength(1);
- expect(conversationsArr[0]).toMatchObject({ title: 'x' });
+ expect(context.conversations).toHaveLength(1);
+ expect(context.conversations[0]).toMatchObject({ title: 'x' });
});
it('refreshes the open project to-do list on a background task-change broadcast', async () => {
@@ -794,6 +1117,7 @@ describe('project to-do controls', () => {
ensureModelConfigured: () => true,
_getQuotes: () => [],
_referenceSnapshotsForQuotes: () => [],
+ _chatAttachList: () => [],
consumeChatUseSelections: () => [],
getChatRecipient: () => ({ kind: 'commander' }),
transformWithChatUse: (value: string) => value,
@@ -1022,6 +1346,7 @@ describe('project to-do controls', () => {
});
it('keeps the project composer intact and records failure when attachment adoption fails', async () => {
+ const messages = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
const invocations: any[] = [];
const alerts: string[] = [];
const input = { value: 'Review the attached brief' };
@@ -1054,7 +1379,8 @@ describe('project to-do controls', () => {
},
conversations: [],
currentCid: null,
- t: (key: string) => key,
+ t: (key: string, params: Record<string, unknown> = {}) => String(messages[key] || key)
+ .replace(/\{(\w+)\}/g, (_: string, name: string) => String(params[name] ?? `{${name}}`)),
ensureModelConfigured: () => true,
_getQuotes: () => [{ id: 'quote-1' }],
_referenceSnapshotsForQuotes: () => [],
@@ -1071,7 +1397,7 @@ describe('project to-do controls', () => {
apiFetch: async (url: string) => ({
json: async () => url.endsWith('/create')
? { ok: true, conversation: { conversation_id: 'c_failed_adopt', title: 'New task' } }
- : { ok: false, error: 'disk unavailable' },
+ : { ok: false, error: 'EPERM: rename C:\\PRIVATE_ATTACHMENT_PATH\\draft to conversation' },
}),
uiAlert: async (message: string) => { alerts.push(message); },
renderConversationList() {},
@@ -1097,7 +1423,8 @@ describe('project to-do controls', () => {
expect(clearedQuotes).toBe(0);
expect(consumedSelections).toBe(0);
expect(sends).toBe(0);
- expect(alerts).toEqual(['chat.attach_adopt_failed']);
+ expect(alerts).toEqual(['Could not confirm the attachments. Your message and files are still here; try again.']);
+ expect(alerts.join(' ')).not.toContain('PRIVATE_ATTACHMENT_PATH');
});
it('sends the server-assigned attachment name after successful adoption', async () => {
@@ -1241,3 +1568,31 @@ describe('todo attachment preview recovery', () => {
&& call.payload.projectId === 'p_other' && call.payload.taskId === 't_123456abcdef')).toBe(true);
});
});
+
+
+describe('todo chip track wheel ownership', () => {
+ it.each(['ltr', 'rtl'])('scrolls forward/backward and releases the page at both %s boundaries', direction => {
+ const parsed = ts.createSourceFile('todos.js', fs.readFileSync(path.join(rendererDir, 'modules/todos.js'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+ const binding = parsed.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === '_bindTodoScrollTrack')!;
+ let wheel: any;
+ let position = 0;
+ const track = {
+ get scrollLeft() { return position; },
+ set scrollLeft(value: number) { position = direction === 'rtl' ? Math.max(-500, Math.min(0, value)) : Math.max(0, Math.min(500, value)); },
+ addEventListener(type: string, callback: any) { if (type === 'wheel') wheel = callback; },
+ };
+ const context = vm.createContext({getComputedStyle: () => ({direction}), _updateTodoScrollTrackFade() {}});
+ vm.runInContext(binding.getText(parsed), context);
+ context._bindTodoScrollTrack(track);
+ const event = (deltaY: number, deltaX = 0) => ({deltaY, deltaX, preventDefault: vi.fn()});
+ const forward = event(400); wheel(forward);
+ expect(Math.abs(position)).toBe(400); expect(forward.preventDefault).toHaveBeenCalledOnce();
+ const horizontal = event(1, 20); wheel(horizontal);
+ expect(Math.abs(position)).toBe(400); expect(horizontal.preventDefault).not.toHaveBeenCalled();
+ wheel(event(400)); expect(Math.abs(position)).toBe(500);
+ const end = event(400); wheel(end); expect(end.preventDefault).not.toHaveBeenCalled();
+ const back = event(-500); wheel(back);
+ expect(position).toBe(0); expect(back.preventDefault).toHaveBeenCalledOnce();
+ const start = event(-400); wheel(start); expect(start.preventDefault).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/renderer/project-todo-refresh-race.test.ts b/test/renderer/project-todo-refresh-race.test.ts
index 8c412186..30d1fb49 100644
--- a/test/renderer/project-todo-refresh-race.test.ts
+++ b/test/renderer/project-todo-refresh-race.test.ts
@@ -9,10 +9,12 @@ const source = fs.readFileSync(
);
describe('project to-do refresh ordering', () => {
+
it('counts every status including collapsed completed tasks and resets for an empty scope', async () => {
const count = { textContent: '' };
const list = { innerHTML: '', style: {}, appendChild() {} };
const context = vm.createContext({
+ currentUserId: 'me',
console,
createLogger: () => ({ warn() {}, info() {}, error() {} }),
document: {
diff --git a/test/renderer/recycle-bin-clear.test.ts b/test/renderer/recycle-bin-clear.test.ts
new file mode 100644
index 00000000..26811ccd
--- /dev/null
+++ b/test/renderer/recycle-bin-clear.test.ts
@@ -0,0 +1,211 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+import { LOCALES } from '../../src/main/i18n';
+
+function harness(initial = [
+ { id: 'cloud-one', source: 'cloud_sync' },
+ { id: 'cloud-two', source: 'cloud_sync' },
+ { id: 'local-one', source: 'app' },
+]) {
+ let batches = initial.map(batch => ({ ...batch, created_at_ms: 1, display_items: [] }));
+ let listener: (event: unknown) => Promise<void>;
+ const body = { innerHTML: '', addEventListener: vi.fn((_: string, cb: typeof listener) => { listener = cb; }) };
+ const messages = JSON.parse(readFileSync(resolve(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
+ const confirm = vi.fn(async () => true);
+ const toast = vi.fn();
+ const warnings: unknown[] = [];
+ const events: unknown[] = [];
+ const list = vi.fn(async () => ({ batches: [...batches] }));
+ const removeRecord = async (id: string) => {
+ batches = batches.filter(batch => batch.id !== id);
+ return { deleted: true };
+ };
+ const remove = vi.fn(removeRecord);
+ const restore = vi.fn();
+ const window: any = { orkas: { recycleBin: { list, delete: remove, restore } },
+ addEventListener() {}, Monitor: { event: (name: string, data: unknown) => events.push({ name, data }) } };
+ const context: any = { console, setTimeout, clearTimeout, setInterval, clearInterval, URL,
+ escapeHtml: (value: unknown) => String(value ?? '').replace(/[&<>"']/g, (char: string) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[char]!)),
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: { querySelectorAll: () => [], documentElement: { lang: 'en' } },
+ };
+ vm.createContext(context);
+ vm.runInContext(readFileSync(resolve(__dirname, '../../src/renderer/modules/settings.js'), 'utf8'), Object.assign(context, {
+ window, document: { querySelectorAll: () => [], documentElement: { lang: 'en' }, getElementById: (id: string) => id === 'settings-recycle-body' ? body : null },
+ t: (key: string) => messages[key] || key,
+ uiConfirmDanger: confirm, uiConfirm: vi.fn(async () => true), uiToast: toast, Monitor: window.Monitor,
+ createLogger: () => ({ warn: (...args: unknown[]) => warnings.push(args) }),
+ }));
+ const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); };
+ const click = (attribute: string, value = '') => listener({ target: {
+ closest: (selector: string) => selector.includes(`[${attribute}]`) ? {
+ disabled: false, getAttribute: () => value,
+ hasAttribute: (name: string) => name === attribute,
+ } : null,
+ } });
+ return { body, confirm, toast, remove, removeRecord, restore, warnings, events, list, flush, click,
+ refresh: () => window.initRecycleBin(),
+ boundListeners: () => body.addEventListener.mock.calls.length,
+ remaining: () => batches.map(batch => batch.id),
+ add: (id: string) => batches.push({ id, source: 'cloud_sync', created_at_ms: 1, display_items: [] }),
+ async show() { context._settingsBindRecycleBinOnce(); await context._settingsRefreshRecycleBin(); await flush(); },
+ };
+}
+
+describe('empty the selected recycle bin source', () => {
+ it('confirms and empties the local list including retained historical records', async () => {
+ const app = harness();
+ await app.show();
+ await app.flush();
+ expect(app.body.innerHTML).toContain('data-recycle-clear');
+ await app.click('data-recycle-clear');
+ await app.flush();
+ expect(app.confirm).toHaveBeenCalledWith(expect.objectContaining({
+ message: expect.stringContaining('Recycle Bin'),
+ }));
+ expect(app.remaining()).toEqual([]);
+ expect(app.body.innerHTML).toContain('No recoverable data');
+ expect(app.toast).toHaveBeenCalledWith('Recycle bin emptied', { variant: 'success' });
+ });
+
+ it('cancels without deleting any records and allows another attempt', async () => {
+ const app = harness();
+ await app.show();
+ app.confirm.mockResolvedValueOnce(false);
+ await app.click('data-recycle-clear');
+ expect(app.remove).not.toHaveBeenCalled();
+ expect(app.remaining()).toHaveLength(3);
+ await app.click('data-recycle-clear');
+ expect(app.remaining()).toEqual([]);
+ });
+
+ it('disables clearing an empty source without opening a confirmation', async () => {
+ const app = harness([]);
+ await app.show();
+ expect(app.body.innerHTML).toMatch(/<button[^>]*data-recycle-clear[^>]*disabled/);
+ await app.click('data-recycle-clear');
+ expect(app.confirm).not.toHaveBeenCalled();
+ expect(app.remove).not.toHaveBeenCalled();
+ });
+
+ it('locks concurrent actions from confirmation through deletion and preserves newly arriving records', async () => {
+ const app = harness();
+ await app.show();
+ let approve!: (value: boolean) => void;
+ app.confirm.mockImplementationOnce(() => new Promise(resolve => { approve = resolve; }));
+ let finish!: () => void;
+ app.remove.mockImplementationOnce(id => new Promise(resolve => {
+ finish = () => { resolve(app.removeRecord(id)); };
+ }));
+ const pending = app.click('data-recycle-clear');
+ await app.click('data-recycle-clear');
+ await app.click('data-recycle-tab', 'app');
+ await app.click('data-recycle-restore', 'cloud-one');
+ expect(app.confirm).toHaveBeenCalledTimes(1);
+ expect(app.restore).not.toHaveBeenCalled();
+ app.add('cloud-new');
+ approve(true);
+ await app.flush();
+ expect(app.body.innerHTML).toContain('Emptying');
+ expect(app.remove).toHaveBeenCalledTimes(1);
+ finish();
+ await pending;
+ expect(app.remove.mock.calls.map(([id]) => id)).toEqual(['cloud-one', 'cloud-two', 'local-one']);
+ expect(app.remaining()).toContain('cloud-new');
+ });
+
+ it('reports a partial failure safely and retries only the remaining records', async () => {
+ const app = harness();
+ await app.show();
+ app.remove.mockImplementationOnce(app.removeRecord)
+ .mockRejectedValueOnce(new Error('EACCES /private/user-data secret'));
+ await app.click('data-recycle-clear');
+ await app.flush();
+ expect(app.remaining()).toEqual(['cloud-two', 'local-one']);
+ expect(app.toast).toHaveBeenCalledWith('Could not finish emptying the recycle bin. Please try again.', { variant: 'error' });
+ expect(JSON.stringify(app.events)).not.toContain('/private');
+ expect(JSON.stringify(app.warnings)).not.toContain('secret');
+ await app.click('data-recycle-clear');
+ expect(app.remaining()).toEqual([]);
+ });
+
+ it('rejects a malformed deletion response without reporting success or deleting later records', async () => {
+ const app = harness();
+ await app.show();
+ app.remove.mockResolvedValueOnce({} as any);
+ await app.click('data-recycle-clear');
+ expect(app.remove).toHaveBeenCalledTimes(1);
+ expect(app.remaining()).toHaveLength(3);
+ expect(app.toast).toHaveBeenCalledWith(expect.any(String), { variant: 'error' });
+ });
+
+ it('waits for an already running restore before allowing destructive clearing', async () => {
+ const app = harness();
+ await app.show();
+ let finish!: (value: unknown) => void;
+ app.restore.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const pending = app.click('data-recycle-restore', 'cloud-one');
+ await app.flush();
+ await app.click('data-recycle-clear');
+ expect(app.remove).not.toHaveBeenCalled();
+ expect(app.confirm).not.toHaveBeenCalled();
+ finish({ restored: 1, changed: 1 });
+ await pending;
+ await app.click('data-recycle-clear');
+ expect(app.remaining()).toEqual([]);
+ });
+
+ it('provides clear and confirmation copy in every registered locale', () => {
+ for (const locale of LOCALES) {
+ const messages = JSON.parse(readFileSync(resolve(__dirname, `../../src/renderer/locales/${locale.code}.json`), 'utf8'));
+ for (const key of ['clear', 'clear_title', 'clear_confirm', 'clearing', 'cleared', 'clear_failed']) {
+ expect(messages[`settings.recycle.${key}`], `${locale.code}: ${key}`).toBeTruthy();
+ }
+ expect(messages['settings.recycle.clear_confirm']).toContain('{source}');
+ expect(messages['settings.recycle.clear_confirm']).toContain('{count}');
+ }
+ });
+});
+
+
+describe('local recycle refresh and restore feedback', () => {
+ it('refreshes the existing local list through the shared cleanup hook without rebinding', async () => {
+ const app = harness([]);
+ await app.show();
+ app.add('new-cleanup-batch');
+ await app.refresh();
+ expect(app.body.innerHTML).toContain('data-recycle-restore="new-cleanup-batch"');
+ expect(app.body.innerHTML).not.toContain('data-recycle-tab=');
+ expect(app.boundListeners()).toBe(1);
+ expect(app.list).toHaveBeenCalledTimes(2);
+ });
+
+ for (const fixture of [
+ { result: { ok: true, restored: 2, skipped: 1, reactivated: 1 }, text: 'Restored 4 files', variant: 'success' },
+ { result: { ok: true, restored: 1, failed_paths: ['missing.txt'] }, text: 'Some content could not be restored: 1 file(s) failed. The recycle bin copy was kept so you can retry.', variant: 'warning' },
+ { result: { ok: true, restored: 0 }, text: 'Nothing was restored. The data may already exist or may have been restored before.', variant: 'warning' },
+ ]) it(`reports ${fixture.variant} for the actual restore outcome: ${fixture.text}`, async () => {
+ const app = harness();
+ await app.show();
+ app.restore.mockResolvedValueOnce(fixture.result);
+ await app.click('data-recycle-restore', 'local-one');
+ expect(app.restore).toHaveBeenCalledWith('local-one');
+ expect(app.toast).toHaveBeenCalledWith(fixture.text, { variant: fixture.variant });
+ expect(app.events).toEqual([]);
+ });
+
+ for (const result of [{ ok: false, restored: 2 }, { ok: true }]) {
+ it(`does not report a successful restore for an invalid result ${JSON.stringify(result)}`, async () => {
+ const app = harness();
+ await app.show();
+ app.restore.mockResolvedValueOnce(result);
+ await app.click('data-recycle-restore', 'local-one');
+ expect(app.restore).toHaveBeenCalledWith('local-one');
+ expect(app.toast).not.toHaveBeenCalled();
+ expect(app.warnings).toHaveLength(1);
+ expect(app.remaining()).toContain('local-one');
+ });
+ }
+});
diff --git a/test/renderer/recycle-bin-display.test.ts b/test/renderer/recycle-bin-display.test.ts
new file mode 100644
index 00000000..86f3517f
--- /dev/null
+++ b/test/renderer/recycle-bin-display.test.ts
@@ -0,0 +1,102 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+import { LOCALES } from '../../src/main/i18n';
+
+function harness(displayItems: unknown[], lang = 'zh') {
+ const body = { innerHTML: '', addEventListener: vi.fn() };
+ const events = new Map<string, () => void>();
+ const translations = new Map(LOCALES.map(locale => [locale.code, JSON.parse(readFileSync(
+ resolve(__dirname, `../../src/renderer/locales/${locale.code}.json`), 'utf8',
+ ))]));
+ let language = lang;
+ const list = vi.fn(async () => ({ batches: [{ id: 'batch', source: 'app', created_at_ms: 1,
+ display_items: displayItems }] }));
+ const window: any = { orkas: { recycleBin: { list } },
+ addEventListener: (name: string, cb: () => void) => events.set(name, cb) };
+ const context: any = { console, setTimeout, clearTimeout, setInterval, clearInterval, URL,
+ escapeHtml: (value: unknown) => String(value ?? '').replace(/[&<>"']/g, (char: string) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;', "'":'&#39;'}[char]!)),
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: { querySelectorAll: () => [], documentElement: { lang: 'en' } },
+ };
+ vm.createContext(context);
+ vm.runInContext(readFileSync(resolve(__dirname, '../../src/renderer/modules/settings.js'), 'utf8'), Object.assign(context, {
+ window, document: { querySelectorAll: () => [], documentElement: { lang: 'en' }, getElementById: (id: string) => id === 'settings-recycle-body' ? body : null },
+ getLang: () => language,
+ t: (key: string) => translations.get(language as any)?.[key] || key,
+ }));
+ const flush = async () => { await Promise.resolve(); await Promise.resolve(); };
+ return { body, list,
+ async show() { context._settingsBindRecycleBinOnce(); await context._settingsRefreshRecycleBin(); await flush(); },
+ async expand() {
+ const click = body.addEventListener.mock.calls[0][1];
+ await click({ target: { closest: (selector: string) => selector === '[data-recycle-view]'
+ ? { getAttribute: () => 'batch' } : null } });
+ await flush();
+ },
+ changeLang(lang: string) { language = lang; context._settingsRenderRecycleBin(); },
+ };
+}
+
+describe('recycle automation display', () => {
+ it('counts distinct tasks even when names match, and expands to readable names with hidden technical details', async () => {
+ const app = harness([
+ { category: 'auto_task', id: 'at_one', title: 'Weekly report <safe>', detail: 'Client Launch', path: 'cloud/auto_tasks/at_one/config.json' },
+ { category: 'auto_task', id: 'at_two', title: 'Weekly report <safe>', path: 'cloud/auto_tasks/at_two/config.json' },
+ ]);
+ await app.show();
+ expect(app.body.innerHTML).toContain('自动化 · 2 个任务');
+ await app.expand();
+ expect(app.body.innerHTML).toContain('Weekly report &lt;safe&gt;');
+ expect(app.body.innerHTML).toContain('Client Launch');
+ expect(app.body.innerHTML).not.toContain('settings-recycle-detail-path');
+ expect(app.body.innerHTML).not.toContain('settings-recycle-detail-category');
+ expect(app.body.innerHTML).toContain('at_one/config.json');
+ expect(app.body.innerHTML).not.toContain('<safe>');
+ const reads = app.list.mock.calls.length;
+ app.changeLang('en');
+ expect(app.body.innerHTML).toContain('Automation · 2 tasks');
+ expect(app.list).toHaveBeenCalledTimes(reads);
+ });
+
+ it('keeps a single automation name and other deleted categories visible', async () => {
+ const app = harness([
+ { category: 'auto_task', id: 'at_one', title: 'Daily digest' },
+ { category: 'attachment', id: 'notes', title: 'notes.txt', path: 'cloud/chat_attachments/c_one/notes.txt' },
+ ], 'en');
+ await app.show();
+ expect(app.body.innerHTML).toContain('Automation: Daily digest');
+ expect(app.body.innerHTML).toContain('Attachment: notes.txt');
+ await app.expand();
+ expect(app.body.innerHTML).toContain('settings-recycle-detail-path');
+ expect(app.body.innerHTML).toContain('chat_attachments/c_one/notes.txt');
+ });
+
+ it('counts tasks rather than their configuration files and keeps distinct legacy IDs in details', async () => {
+ const files = harness([
+ { category: 'auto_task', id: 'cloud/auto_tasks/at_one/state.json', title: 'Digest', path: 'cloud/auto_tasks/at_one/state.json' },
+ { category: 'auto_task', id: 'cloud/auto_tasks/at_one/config.json', title: 'Digest', path: 'cloud/auto_tasks/at_one/config.json' },
+ { category: 'auto_task', id: 'at_two', title: 'Report', path: 'cloud/projects/p_launch/auto_tasks/at_two/config.json' },
+ ], 'en');
+ await files.show();
+ expect(files.body.innerHTML).toContain('Automation · 2 tasks');
+ await files.expand();
+ expect(files.body.innerHTML.match(/class="settings-recycle-detail-title"/g)).toHaveLength(2);
+ const legacy = harness([
+ { category: 'auto_task', id: 'at_one', title: 'Same name' },
+ { category: 'auto_task', id: 'at_two', title: 'Same name' },
+ ], 'en');
+ await legacy.show();
+ await legacy.expand();
+ expect(legacy.body.innerHTML.match(/class="settings-recycle-detail-title"/g)).toHaveLength(2);
+ });
+
+ it('provides automation count copy in every registered locale', () => {
+ for (const locale of LOCALES) {
+ const messages = JSON.parse(readFileSync(resolve(__dirname,
+ `../../src/renderer/locales/${locale.code}.json`), 'utf8'));
+ expect(messages['settings.recycle.automation_count'], locale.code).toContain('{count}');
+ }
+ });
+});
diff --git a/test/renderer/resource-edit-parity.test.ts b/test/renderer/resource-edit-parity.test.ts
index f98c3c4a..1a2710fa 100644
--- a/test/renderer/resource-edit-parity.test.ts
+++ b/test/renderer/resource-edit-parity.test.ts
@@ -24,6 +24,7 @@ function loadRenderer(module: 'agents' | 'skills') {
escapeHtml: (s: string) => s, renderMarkdownFull: (s: string) => `<p>${s}</p>`,
normalizeDisplayText: (s: string) => s, pickDesc: (agent: any) => agent.description,
uiAlert: vi.fn(),
+ renderCliAccountUsage: vi.fn(),
};
vm.createContext(context);
vm.runInContext(fs.readFileSync(path.join(process.cwd(), `src/renderer/modules/${module}.js`), 'utf8'), context);
diff --git a/test/renderer/saved-app-telemetry.test.ts b/test/renderer/saved-app-telemetry.test.ts
new file mode 100644
index 00000000..cba171d2
--- /dev/null
+++ b/test/renderer/saved-app-telemetry.test.ts
@@ -0,0 +1,138 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+
+const modulesDir = resolve(__dirname, '../../src/renderer/modules');
+const fileViewerSource = readFileSync(resolve(modulesDir, 'chat-file-viewer.js'), 'utf8');
+const conversationInfoSource = readFileSync(resolve(modulesDir, 'conversation-info.js'), 'utf8');
+
+function extractFunction(source: string, name: string): string {
+ const asyncMarker = `async function ${name}`;
+ const syncMarker = `function ${name}`;
+ const start = source.indexOf(asyncMarker) >= 0
+ ? source.indexOf(asyncMarker)
+ : source.indexOf(syncMarker);
+ if (start < 0) throw new Error(`missing ${name}`);
+ const braceStart = source.indexOf('{', source.indexOf(')', start));
+ let depth = 0;
+ for (let i = braceStart; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(start, i + 1);
+ }
+ }
+ throw new Error(`unterminated ${name}`);
+}
+
+describe('Save-as-App failure alerts', () => {
+ // Raw IPC/main errors can carry absolute local paths and English internals;
+ // the user sees only the localized action copy, and logs stay code-only.
+ const localeTable = (lang: string) => JSON.parse(readFileSync(resolve(modulesDir, `../locales/${lang}.json`), 'utf8'));
+ const privateDetail = '/Users/test/private/project/app.html: EACCES permission denied';
+ const outcomes = [
+ ['rejected', async () => { throw new Error(privateDetail); }],
+ ['refused', async () => ({ ok: false, error: privateDetail })],
+ ['root_refused', async () => ({ ok: false, error: 'app_bundle_root' })],
+ ] as const;
+ const cases = (['zh', 'en'] as const).flatMap(lang => outcomes.map(([mode, invoke]) => [lang, mode, invoke] as const));
+
+ it.each(cases)('file preview shows only "%s" save failure copy when the save is %s', async (lang, _mode, invoke) => {
+ const table = localeTable(lang);
+ const alerts: string[] = [];
+ const warnings: any[] = [];
+ const context: any = {
+ Date, Math, Object, String,
+ t: (key: string) => table[key] || key,
+ _viewerCurrentPath: '/Users/test/private/project/app.html',
+ _viewerSaveAppBtn: { disabled: false, innerHTML: '' },
+ _viewerDirty: false,
+ _kindOf: () => 'html',
+ _viewerLogFailure: (name: string, payload: any) => warnings.push({ name, payload }),
+ _viewerShowAlert: async (message: string) => { alerts.push(message); },
+ _viewerSaveAppButtonHtml: () => '<button>',
+ _setSaveAppVisible: () => {},
+ _viewerFileActionPayload: () => ({ path: '/Users/test/private/project/app.html' }),
+ _scheduleSaveAppButtonRestore: () => {},
+ window: { orkas: { invoke: vi.fn(invoke) } },
+ };
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction(fileViewerSource, '_viewerLabel'),
+ extractFunction(fileViewerSource, '_viewerStableFailure'),
+ extractFunction(fileViewerSource, '_viewerDurationSince'),
+ extractFunction(fileViewerSource, '_onSaveAppClick'),
+ ].join('\n'), context);
+
+ await context._onSaveAppClick();
+
+ expect(alerts).toEqual([table[_mode === 'root_refused' ? 'apps.save_root_folder_required' : 'apps.save_failed']]);
+ expect(JSON.stringify(warnings)).not.toContain('/Users/');
+ expect(JSON.stringify(warnings)).not.toContain('EACCES');
+ });
+
+ it.each(cases)('conversation info shows only "%s" save failure copy when the save is %s', async (lang, _mode, invoke) => {
+ const table = localeTable(lang);
+ const alerts: string[] = [];
+ const warnings: any[] = [];
+ const context: any = {
+ Date, Math, Object, String,
+ t: (key: string) => table[key] || key,
+ window: { orkas: { invoke: vi.fn(invoke) } },
+ _infoLog: { warn: (_message: string, payload: any) => warnings.push(payload) },
+ _fileActionPayload: () => ({ path: '/Users/test/private/project/app.html' }),
+ uiAlert: async (message: string) => { alerts.push(message); },
+ };
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction(conversationInfoSource, '_label'),
+ extractFunction(conversationInfoSource, '_baseName'),
+ extractFunction(conversationInfoSource, '_extForName'),
+ extractFunction(conversationInfoSource, '_savedAppSaveFailure'),
+ extractFunction(conversationInfoSource, '_logSavedAppSaveFailure'),
+ extractFunction(conversationInfoSource, '_saveEntryAsApp'),
+ ].join('\n'), context);
+
+ await context._saveEntryAsApp('/Users/test/private/project/app.html', 'private-cid');
+
+ expect(alerts).toEqual([table[_mode === 'root_refused' ? 'apps.save_root_folder_required' : 'apps.save_failed']]);
+ expect(JSON.stringify(warnings)).not.toContain('/Users/');
+ });
+});
+
+
+describe('historical web receipts at file entry points', () => {
+ it.each(['preview save', 'conversation save', 'preview open'])('guides once without a generic error or local success effects: %s', async entry => {
+ const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' };
+ const show = vi.fn(async () => {}), alert = vi.fn(), warn = vi.fn(), restore = vi.fn();
+ const invoke = vi.fn(async () => receipt);
+ const context: any = {
+ window: { orkas: { invoke }, OrkasPreviewWindows: { open: invoke, options: () => ({}) } },
+ _viewerCurrentPath: '/fixture/app.html', _viewerSaveAppBtn: { disabled: false }, _viewerDirty: false,
+ _viewerLabel: (_key: string, fallback: string) => fallback,
+ _viewerSaveAppButtonHtml: () => '<button>', _setSaveAppVisible: vi.fn(),
+ _viewerFileActionPayload: () => ({ path: '/fixture/app.html' }),
+ _fileActionPayload: () => ({ path: '/fixture/app.html' }),
+ _scheduleSaveAppButtonRestore: restore, _viewerShowAlert: alert, uiAlert: alert,
+ _viewerLogFailure: warn, _logSavedAppSaveFailure: warn,
+ _ensureViewerFileExists: async () => true, _kindOf: () => 'html',
+ };
+ vm.createContext(context);
+ vm.runInContext(readFileSync(resolve(modulesDir, 'commercial-entry.js'), 'utf8'), context);
+ context.window.OrkasCommercialEntry.show = show;
+ if (entry === 'conversation save') {
+ vm.runInContext(extractFunction(conversationInfoSource, '_saveEntryAsApp'), context);
+ await context._saveEntryAsApp('/fixture/app.html', 'task');
+ } else if (entry === 'preview save') {
+ vm.runInContext(extractFunction(fileViewerSource, '_onSaveAppClick'), context);
+ await context._onSaveAppClick();
+ expect(restore).toHaveBeenCalledExactlyOnceWith('/fixture/app.html', '<button>');
+ } else {
+ vm.runInContext(extractFunction(fileViewerSource, 'openChatFileViewer'), context);
+ await expect(context.openChatFileViewer('/fixture/app.html')).resolves.toBe(receipt);
+ }
+ expect(show).toHaveBeenCalledOnce(); expect(invoke).toHaveBeenCalledOnce();
+ expect(alert).not.toHaveBeenCalled(); expect(warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/renderer/settings-tabs.test.ts b/test/renderer/settings-tabs.test.ts
index b71b745e..f445e931 100644
--- a/test/renderer/settings-tabs.test.ts
+++ b/test/renderer/settings-tabs.test.ts
@@ -99,6 +99,13 @@ function loadSettingsTabsModule() {
}
describe('settings tabs module', () => {
+ it('initializes shared task cleanup on entering Data without requiring hosted data hooks', () => {
+ const { window, tabs } = loadSettingsTabsModule();
+ window.initTaskCleanup = vi.fn();
+ tabs[2].click(); expect(window.initTaskCleanup).not.toHaveBeenCalled();
+ tabs[0].click(); expect(window.initTaskCleanup).toHaveBeenCalledOnce();
+ });
+
it('loads tabs eagerly and the settings page on demand', () => {
const indexHtml = fs.readFileSync(path.join(root, 'src/renderer/index.html'), 'utf8');
const lazyFeatures = fs.readFileSync(path.join(root, 'src/renderer/modules/lazy-features.js'), 'utf8');
diff --git a/test/renderer/sidebar-sections.test.ts b/test/renderer/sidebar-sections.test.ts
index a1de0409..7659db8f 100644
--- a/test/renderer/sidebar-sections.test.ts
+++ b/test/renderer/sidebar-sections.test.ts
@@ -169,7 +169,7 @@ describe('sidebar top-level section collapse', () => {
it('treats corrupt or non-boolean stored values as expanded', () => {
const storage = { getItem: () => '{bad json', setItem() {} };
- expect(readCollapsedState(storage)).toEqual({});
+ expect(readCollapsedState(storage)).toEqual({ today: false, projects: false, tasks: false });
const harness = createHarness({ today: 'yes', projects: 'true', tasks: 1 });
initSidebarSections(harness.document, harness.storage, harness.translate);
@@ -179,3 +179,60 @@ describe('sidebar top-level section collapse', () => {
expect(harness.tasksBody.hidden).toBe(false);
});
});
+
+describe('sidebar section preferences after the navigation groups were retired', () => {
+ it('ignores and drops collapse values stored for the retired navigation groups', () => {
+ // An upgraded installation still carries the old group keys; they must
+ // neither leak into task-section state nor survive the next write.
+ const harness = createHarness({ operations: false, capabilities: true, projects: true });
+ initSidebarSections(harness.document, harness.storage, harness.translate);
+
+ expect(harness.todayBody.hidden).toBe(false);
+ expect(harness.projectsBody.hidden).toBe(true);
+ expect(harness.tasksBody.hidden).toBe(false);
+
+ harness.tasksToggle.click();
+
+ expect(JSON.parse(harness.values.get(STORAGE_KEY)!)).toEqual({ today: false, projects: true, tasks: true });
+ });
+
+ it.each(['{bad json', 'null', '[]', '{"projects":"true","tasks":0}'])('recovers invalid storage %s to expanded sections and lets the first click collapse', (stored) => {
+ const harness = createHarness();
+ harness.values.set(STORAGE_KEY, stored);
+ initSidebarSections(harness.document, harness.storage, harness.translate);
+ expect(harness.projectsBody.hidden).toBe(false);
+ harness.projectsToggle.click();
+ expect(harness.projectsBody.hidden).toBe(true);
+ expect(JSON.parse(harness.values.get(STORAGE_KEY)!)).toEqual({ today: false, projects: true, tasks: false });
+ });
+
+ it('keeps section toggles usable when local storage is unavailable', () => {
+ const harness = createHarness();
+ const blockedStorage = {
+ getItem() { throw new Error('Storage unavailable'); },
+ setItem() { throw new Error('Storage unavailable'); },
+ };
+ initSidebarSections(harness.document, blockedStorage, harness.translate);
+ expect(harness.todayBody.hidden).toBe(false);
+ harness.todayToggle.click();
+ expect(harness.todayBody.hidden).toBe(true);
+ harness.todayToggle.click();
+ expect(harness.todayBody.hidden).toBe(false);
+ });
+
+ it('refreshes accessible labels after a language change without resetting user choices', () => {
+ const harness = createHarness({ projects: true });
+ let language = 'en';
+ const translate = (key: string, params?: { section?: string }) => language === 'zh'
+ ? ({ 'sidebar.projects': '项目', 'sidebar.conversations': '任务', 'sidebar.today_tasks': '当天任务',
+ 'sidebar.section_expand': `展开${params?.section}`, 'sidebar.section_collapse': `收起${params?.section}` } as Record<string, string>)[key] || key
+ : harness.translate(key, params);
+ const controller = initSidebarSections(harness.document, harness.storage, translate);
+ language = 'zh';
+ controller.applyAll();
+ expect(harness.projectsToggle.getAttribute('aria-label')).toBe('展开项目');
+ expect(harness.tasksToggle.getAttribute('aria-label')).toBe('收起任务');
+ expect(harness.projectsBody.hidden).toBe(true);
+ expect(harness.tasksBody.hidden).toBe(false);
+ });
+});
diff --git a/test/renderer/task-board-background-cid.test.ts b/test/renderer/task-board-background-cid.test.ts
index 5d40bc69..c386a632 100644
--- a/test/renderer/task-board-background-cid.test.ts
+++ b/test/renderer/task-board-background-cid.test.ts
@@ -49,12 +49,15 @@ function extractFunction(source: string, name: string): string {
type BoardContext = {
_taskBoardTasks: Map<string, Map<string, { status: string }>>;
renders: string[];
+ deliveries: Array<[string, unknown]>;
+ visibilityChecks: string[];
};
/** Drive the real `_taskBoardOnEvent` with `visibleCid` on screen. */
function applyEvents(
visibleCid: string,
events: Array<[string, unknown]>,
+ throughBus = false,
): BoardContext {
const ctx: Record<string, unknown> = {
_taskBoardTasks: new Map(),
@@ -63,17 +66,39 @@ function applyEvents(
_TASK_BOARD_TERMINAL: new Set(['done', 'stopped', 'failed', 'cancelled']),
currentCid: visibleCid,
renders: [] as string[],
+ deliveries: [] as Array<[string, unknown]>,
+ visibilityChecks: [] as string[],
+ _lastGroupWorkEventAt: new Map(),
+ _conversationHistoryLoad: null,
+ _offViewLiveDisplayDirty: new Set(),
+ _isSnapshottedProcess: () => false,
+ _deferHistoryLoadProcess: () => false,
+ _refreshVisibleConversationDisplay: () => {},
+ };
+ ctx._isConversationDisplayVisible = (cid: string) => {
+ (ctx.visibilityChecks as string[]).push(cid);
+ return cid === visibleCid;
};
ctx._taskBoardRender = (cid: string) => { (ctx.renders as string[]).push(cid); };
vm.createContext(ctx);
- const src = [
+ let src = [
extractFunction(boardSource, '_taskBoardMapFor'),
extractFunction(boardSource, '_taskBoardLiveRows'),
extractFunction(boardSource, '_taskBoardBatchAfterCreate'),
extractFunction(boardSource, '_taskBoardOnEvent'),
].join('\n');
+ if (throughBus) {
+ const start = conversationSource.indexOf('function _handleGroupBusEvent');
+ if (start < 0) throw new Error('missing _handleGroupBusEvent');
+ const end = conversationSource.indexOf('\nfunction ', start + 1);
+ src += '\n' + extractFunction(conversationSource, '_taskBoardEventBypassesViewGuard');
+ src += '\n' + conversationSource.slice(start, end > 0 ? end : undefined);
+ src += `\nwindow = { TaskBoard: { onEvent(cid, event) {
+ deliveries.push([cid, event]); _taskBoardOnEvent(cid, event);
+ } } };`;
+ }
vm.runInContext(
- `${src}\nfor (const [cid, ev] of ${JSON.stringify(events)}) _taskBoardOnEvent(cid, ev);`,
+ `${src}\nfor (const [cid, ev] of ${JSON.stringify(events)}) ${throughBus ? '_handleGroupBusEvent(cid, null, ev)' : '_taskBoardOnEvent(cid, ev)'};`,
ctx,
);
return ctx as unknown as BoardContext;
@@ -122,26 +147,23 @@ describe('task board › a background conversation still settles', () => {
});
describe('task board › events are settled above the cross-cid view guard', () => {
- // An ordering invariant inside a DOM-coupled function, so it is pinned on
- // the source: putting the board branch back below `cid !== currentCid`
- // silently restores the stuck-running row and nothing else would fail.
- const body = (() => {
- const start = conversationSource.indexOf('function _handleGroupBusEvent');
- if (start < 0) throw new Error('missing _handleGroupBusEvent');
- const end = conversationSource.indexOf('\nfunction ', start + 1);
- return conversationSource.slice(start, end > 0 ? end : undefined);
- })();
- const guard = body.indexOf('if (cid !== currentCid) return;');
-
- it('handles task_created / task_state before the guard runs', () => {
- const bypass = body.indexOf('_taskBoardEventBypassesViewGuard(evData)');
- expect(bypass).toBeGreaterThan(-1);
- expect(guard).toBeGreaterThan(-1);
- expect(bypass).toBeLessThan(guard);
+ it('delivers background creation and settlement once without consulting view eligibility', () => {
+ const ctx = applyEvents('visible-cid', [['bg-cid', RUNNING], ['bg-cid', DONE]], true);
+ expect(ctx._taskBoardTasks.get('bg-cid')?.get('t1')?.status).toBe('done');
+ expect(ctx.deliveries.map(([cid, event]) => [cid, (event as { type: string }).type]))
+ .toEqual([['bg-cid', 'task_created'], ['bg-cid', 'task_state']]);
+ expect(ctx.visibilityChecks).toEqual([]);
+ expect(ctx.renders).toEqual([]);
});
- it('leaves no second board delivery below the guard', () => {
- expect(body.indexOf('TaskBoard.onEvent', guard)).toBe(-1);
+ it('keeps background process events behind view eligibility without redelivering board events', () => {
+ const ctx = applyEvents('visible-cid', [
+ ['bg-cid', RUNNING], ['bg-cid', DONE],
+ ['bg-cid', { type: 'process', display_seq: 1 }],
+ ], true);
+ expect(ctx.deliveries).toHaveLength(2);
+ expect(ctx.visibilityChecks).toEqual(['bg-cid']);
+ expect(ctx.renders).toEqual([]);
});
it('routes exactly the two board event types past the guard', () => {
diff --git a/test/renderer/task-board.test.ts b/test/renderer/task-board.test.ts
index 35af870c..dc1e465d 100644
--- a/test/renderer/task-board.test.ts
+++ b/test/renderer/task-board.test.ts
@@ -144,6 +144,7 @@ describe('renderer task board › Send now eligibility', () => {
function canSend(task: unknown, activeTurns: unknown[]): boolean {
return vm.runInNewContext(
`const _latestActiveTurns = new Map([['c1', ${JSON.stringify(activeTurns)}]]);
+ ${extractFunction('_taskBoardDeps')};
${extractFunction('_taskBoardCanSendNow')};
_taskBoardCanSendNow('c1', ${JSON.stringify(task)});`,
{ Map },
@@ -157,8 +158,11 @@ describe('renderer task board › Send now eligibility', () => {
expect(canSend(task, [{ actor: 'agentA', steerable: false }])).toBe(false);
expect(canSend({ ...task, created_by: 'commander' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
expect(canSend({ ...task, status: 'running' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
- // A chained row keeps its start order (§4.8) — folding would jump it.
+ // A dependent row keeps its start order (§4.8) — folding would jump it,
+ // whether the snapshot carries a legacy single id or a D29 list.
expect(canSend({ ...task, after: 't0' }, [{ actor: 'agentA', steerable: true }])).toBe(false);
+ expect(canSend({ ...task, after: ['t0', 't1'] }, [{ actor: 'agentA', steerable: true }])).toBe(false);
+ expect(canSend({ ...task, after: [] }, [{ actor: 'agentA', steerable: true }])).toBe(true);
});
it('wires the eligible row action to the backend task promotion endpoint', () => {
@@ -169,6 +173,20 @@ describe('renderer task board › Send now eligibility', () => {
expect(source).toContain("'chat.queue_send_now'");
});
+ it('shows Send now on a user correction while the same Agent runs a Commander-dispatched task', () => {
+ const { context, list, board } = boardHarness();
+ context._latestActiveTurns = new Map([['c1', [{ actor: 'agentA', steerable: true }]]]);
+ board.onEvent('c1', { task: { task_id: 'child', assignee: 'agentA', created_by: 'commander',
+ status: 'running', instruction: 'Implement the feature.' } });
+ board.onEvent('c1', { task: { task_id: 'correction', assignee: 'agentA', created_by: 'user',
+ status: 'queued', instruction: 'Discuss the plan first.' } });
+ const queuedRow = list.innerHTML.split('data-task-id="correction"')[1];
+ expect(queuedRow).toContain('data-act="task-send-now"');
+ expect(queuedRow).toContain('data-act="task-edit"');
+ expect(queuedRow).toContain('data-act="task-cancel"');
+ expect(list.innerHTML.match(/data-act="task-send-now"/g)).toHaveLength(1);
+ });
+
it('keeps the row locked after acceptance, but restores it when promotion fails', async () => {
const sendNow = `async ${extractFunction('_taskBoardSendNow')}`;
const run = async (result: any) => {
@@ -244,6 +262,17 @@ describe('renderer task board › assignee label', () => {
expect(html).not.toMatch(/data-act="task-(reassign|after)"/);
expect(html).not.toMatch(/<select|<input|contenteditable/);
});
+
+ it('names every unfinished predecessor of a multi-dependency row and drops finished ones (D29)', () => {
+ const html = renderBoardRows([
+ { task_id: 'a1', status: 'running', assignee: 'agentA', instruction: 'draft A', created_at: '2026-01-01T00:00:00Z' },
+ { task_id: 'b1', status: 'done', assignee: 'agentB', instruction: 'draft B', created_at: '2026-01-01T00:00:01Z' },
+ { task_id: 'c1', status: 'running', assignee: 'agentC', instruction: 'draft C', created_at: '2026-01-01T00:00:02Z' },
+ { task_id: 'merge', status: 'queued', assignee: 'agentD', instruction: 'merge drafts', after: ['a1', 'b1', 'c1'], created_at: '2026-01-01T00:00:03Z' },
+ ]);
+ expect(html).toContain('chat.task_waiting_on:agentA and agentC');
+ expect(html).not.toContain('agentB and');
+ });
});
describe('renderer task board › agent groups and queued drag order', () => {
diff --git a/test/renderer/task-cleanup.test.ts b/test/renderer/task-cleanup.test.ts
new file mode 100644
index 00000000..170e5afa
--- /dev/null
+++ b/test/renderer/task-cleanup.test.ts
@@ -0,0 +1,143 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+import { LOCALES } from '../../src/main/i18n';
+
+function harness() {
+ const listeners: Record<string, any> = {};
+ const body = { innerHTML: '', addEventListener: (type: string, fn: any) => { listeners[type] = fn; }, querySelector: () => null };
+ const picker = { setOptions: vi.fn(), setAriaLabel: vi.fn(), close() {}, onChange(fn: any) { this.change = fn; }, change: null as any };
+ const rows = [{ cid: 'one', title: '<unsafe title>', activeAt: '2020-01-01T00:00:00Z' },
+ { cid: 'two', title: 'Second', activeAt: '2020-01-02T00:00:00Z' }];
+ const invoke = vi.fn(async (channel: string, _payload?: any) => !channel.endsWith('remove')
+ ? { ok: true, token: 'receipt', total: 2, rows, nextOffset: null }
+ : { ok: true, status: 'deleted' });
+ const store = new Map<string, string>();
+ const refresh = vi.fn(); const forgot = vi.fn();
+ const messages = JSON.parse(readFileSync(resolve(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
+ const scope: any = { currentUserId: 'u1', currentCid: '', conversations: [], currentView: 'settings',
+ window: { orkas: { invoke }, TaskUnread: { list: () => [], isUnread: () => false },
+ addEventListener() {}, initRecycleBin: refresh },
+ document: { getElementById: (id: string) => id === 'settings-task-cleanup-body' ? body : {},
+ querySelector: () => null },
+ localStorage: { get length() { return store.size; }, key: (i: number) => [...store.keys()][i], getItem: (key: string) => store.get(key) ?? null },
+ t: (key: string, vars: any = {}) => Object.entries(vars).reduce((text, [k, v]) => text.replaceAll(`{${k}}`, String(v)), messages[key] || key),
+ escapeHtml: (v: string) => String(v).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('"', '&quot;'),
+ _aiSelectMount: () => picker, _forgetConvLocal: forgot, loadConversations: refresh,
+ _composerHoldsUnsentInput: () => false, _chatAttachList: () => [],
+ createLogger: () => ({ warn: vi.fn() }), setTimeout, clearTimeout, Date,
+ };
+ vm.runInNewContext(readFileSync(resolve(__dirname, '../../src/renderer/modules/task-cleanup.js'), 'utf8'), scope);
+ const click = async (action: string, cid = '') => listeners.click({ target: { closest: () => ({ dataset: { cleanupAction: action, cid } }) } });
+ const check = async (cid: string | null, checked: boolean) => listeners.change({ target: {
+ checked, getAttribute: () => cid, hasAttribute: () => !cid,
+ } });
+ return { scope, body, invoke, store, picker, refresh, forgot, click, check,
+ show: () => scope.window.initTaskCleanup() };
+}
+describe('inline history cleanup', () => {
+ it('retries only failed tasks after a partial success', async () => {
+ const h = harness(); await h.show();
+ const original = h.invoke.getMockImplementation()!;
+ let fail = true;
+ h.invoke.mockImplementation(async (channel, payload) => {
+ if (channel.endsWith('remove') && payload.cid === 'two' && fail) throw new Error('backup unavailable');
+ return original(channel, payload);
+ });
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.body.innerHTML).toContain('Moved to recycle bin: 1. Skipped: 0. Failed: 1.');
+ fail = false; await h.click('retry');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two', 'two']);
+ expect(h.forgot.mock.calls.map(([cid]) => cid)).toEqual(['one', 'two']);
+ });
+ it('retains selection across pages and executes the frozen receipt once per selected task', async () => {
+ const h = harness();
+ const rows = Array.from({ length: 25 }, (_, n) => ({ cid: `task_${n}`, title: `Task ${n}`, activeAt: '2020-01-01' }));
+ h.invoke.mockImplementation(async (channel, payload) => channel.endsWith('remove')
+ ? { ok: true, status: 'deleted' } as any
+ : { ok: true, token: 'frozen', total: 25, rows: rows.slice(payload.offset || 0, (payload.offset || 0) + 20), nextOffset: payload.offset === 20 ? null : 20 });
+ await h.show(); await h.click('view'); await h.check('task_0', false);
+ await h.click('next'); expect(h.body.innerHTML).toContain('Task 24');
+ await h.check('task_24', false); await h.click('previous');
+ expect(h.body.innerHTML).toContain('Selected tasks: 23');
+ await h.click('prepare'); await h.click('confirm');
+ const removals = h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p);
+ expect(removals.map(p => p.cid)).toEqual(rows.slice(1, 24).map(row => row.cid));
+ expect(removals.every(p => p.token === 'frozen')).toBe(true);
+ });
+ it('deselects all without fetching every page and cleans only a subsequent individual selection', async () => {
+ const h = harness(); await h.show(); await h.check(null, false);
+ expect(h.invoke).toHaveBeenCalledTimes(1);
+ await h.check('two', true); await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['two']);
+ });
+ it('stops between tasks and prevents duplicate confirmation while an item is being deleted', async () => {
+ const h = harness(); await h.show();
+ const original = h.invoke.getMockImplementation()!;
+ let finish!: (value: any) => void;
+ h.invoke.mockImplementation((channel, payload) => channel.endsWith('remove')
+ ? new Promise(resolve => { finish = resolve; }) : original(channel, payload));
+ await h.click('prepare'); const pending = h.click('confirm');
+ for (let i = 0; i < 5; i++) await Promise.resolve();
+ expect(h.body.innerHTML).toContain('Cleaning 0 / 2');
+ expect(h.body.innerHTML.match(/role="status"/g)).toHaveLength(1);
+ expect(h.body.innerHTML).not.toContain('Moved to recycle bin:');
+ await h.click('confirm'); await h.click('stop');
+ expect(h.body.innerHTML.match(/role="status"/g)).toHaveLength(1);
+ finish({ ok: true, status: 'deleted' }); await pending;
+ expect(h.body.innerHTML).toContain('Moved to recycle bin: 1. Skipped: 0. Failed: 0.');
+ expect(h.body.innerHTML).not.toContain('Cleaning ');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(1);
+ expect(h.forgot).toHaveBeenCalledWith('one');
+ });
+ it('shows a preview, confirms inline, cancels without deleting and escapes titles', async () => {
+ const h = harness(); await h.show();
+ expect(h.invoke.mock.calls[0][0]).toBe('conversations.cleanup.preview');
+ expect(h.body.innerHTML).toContain('2');
+ await h.click('view'); expect(h.body.innerHTML).toContain('&lt;unsafe title>');
+ await h.click('prepare'); expect(h.body.innerHTML).toContain('data-cleanup-action="confirm"');
+ await h.click('cancel'); expect(h.invoke).toHaveBeenCalledTimes(1);
+ expect(h.body.innerHTML).not.toContain('data-cleanup-action="confirm"');
+ });
+ it('cleans the selected snapshot and refreshes the recycle bin', async () => {
+ const h = harness(); await h.show(); await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two']);
+ expect(h.forgot).toHaveBeenCalledWith('one'); expect(h.refresh).toHaveBeenCalled();
+ });
+ it('sends draft protection and rechecks newly unread tasks before deletion', async () => {
+ const h = harness(); h.store.set('draft_other', JSON.stringify({ text: 'Keep me' })); await h.show();
+ expect((h.invoke.mock.calls[0] as any)[1].protectedIds).toContain('other');
+ await h.click('prepare'); h.scope.window.TaskUnread.isUnread = (cid: string) => cid === 'two';
+ await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one']);
+ });
+ it('keeps failures visible and never reports a malformed response as success', async () => {
+ const h = harness(); await h.show();
+ const original = h.invoke.getMockImplementation()!;
+ h.invoke.mockImplementation(async (channel: string, payload: any) => channel.endsWith('remove') ? { ok: true } as any : original(channel, payload));
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.forgot).not.toHaveBeenCalled(); expect(h.body.innerHTML).toContain('2');
+ expect(h.body.innerHTML).toContain('data-cleanup-action="retry"');
+ });
+ it('does not execute a previous account selection after an account switch', async () => {
+ const h = harness(); await h.show(); await h.click('prepare'); h.scope.currentUserId = 'u2';
+ await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ });
+ it('distinguishes a failed scan from an empty result and provides retry', async () => {
+ const h = harness(); h.invoke.mockRejectedValueOnce(new Error('private path'));
+ await h.show(); expect(h.body.innerHTML).toContain('data-cleanup-action="refresh"');
+ expect(h.body.innerHTML).not.toContain('private path');
+ expect(h.body.innerHTML).not.toContain('data-cleanup-action="prepare"');
+ });
+ it('translates every cleanup key in every supported locale', () => {
+ const en = JSON.parse(readFileSync(resolve(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
+ const keys = Object.keys(en).filter(key => key.startsWith('settings.cleanup.'));
+ expect(keys.length).toBeGreaterThan(10);
+ for (const { code } of LOCALES) {
+ const messages = JSON.parse(readFileSync(resolve(__dirname, `../../src/renderer/locales/${code}.json`), 'utf8'));
+ for (const key of keys) expect(messages[key], `${code}: ${key}`).toBeTruthy();
+ }
+ });
+});
diff --git a/test/renderer/task-unread-indicators.test.ts b/test/renderer/task-unread-indicators.test.ts
index 9cdd5c6d..13bf770f 100644
--- a/test/renderer/task-unread-indicators.test.ts
+++ b/test/renderer/task-unread-indicators.test.ts
@@ -600,6 +600,51 @@ describe('unread task reply indicators', () => {
});
});
+ it('lists unread runs newest first with the outcome of their latest terminal for the home', () => {
+ const persisted = new Map([['task_unread_v1_u1', JSON.stringify({
+ // Written before outcomes were kept: no status or entry point.
+ unread: [{ cid: 'legacy-task', projectId: '', finishedAt: 50 }],
+ read: [],
+ })]]);
+ const context = loadUnreadRenderer(persisted);
+ const changes: string[] = [];
+ context.CustomEvent = class { type: string; constructor(type: string) { this.type = type; } };
+ context.window.dispatchEvent = (event: any) => { changes.push(event.type); return true; };
+ context.conversations.push({ conversation_id: 'chat-task', project_id: 'p1' });
+ const terminal = (cid: string, status: string, at: number, entry: string) => context._handleTaskTerminalUnread({
+ type: 'terminal', conversation_id: cid, status, finished_at_ms: at, entry_point: entry,
+ });
+
+ expect(terminal('chat-task', 'waiting_input', 100, 'chat_send')).toBe(true);
+ expect(terminal('auto-run', 'failed', 300, 'automation')).toBe(true);
+ // The newest terminal decides what the home says; an older replay does not.
+ expect(terminal('chat-task', 'completed', 200, 'conversation')).toBe(true);
+ expect(terminal('chat-task', 'failed', 150, 'chat_send')).toBe(true);
+ expect(terminal('odd-entry', 'stopped', 120, 'Not An Entry!')).toBe(true);
+
+ const expected = [
+ { cid: 'auto-run', projectId: null, finishedAt: 300, status: 'failed', entryPoint: 'automation' },
+ { cid: 'chat-task', projectId: 'p1', finishedAt: 200, status: 'completed', entryPoint: 'conversation' },
+ { cid: 'odd-entry', projectId: null, finishedAt: 120, status: 'stopped' },
+ { cid: 'legacy-task', projectId: '', finishedAt: 50 },
+ ];
+ expect(JSON.parse(JSON.stringify(context.window.TaskUnread.list()))).toEqual(expected);
+ expect(changes.length).toBeGreaterThanOrEqual(4);
+ expect(new Set(changes)).toEqual(new Set(['task-unread-change']));
+
+ // Outcomes survive a relaunch.
+ const relaunched = loadUnreadRenderer(persisted);
+ relaunched._restoreUnreadTaskState();
+ expect(JSON.parse(JSON.stringify(relaunched.window.TaskUnread.list()))).toEqual(expected);
+
+ // Opening one removes it from the list and announces the change.
+ changes.length = 0;
+ context._markConversationRead('auto-run', { readAt: 400 });
+ expect(context.window.TaskUnread.list().map((row: any) => row.cid))
+ .toEqual(['chat-task', 'odd-entry', 'legacy-task']);
+ expect(changes).toEqual(['task-unread-change']);
+ });
+
it('ships small red right-of-copy mounts only on sidebar surfaces', () => {
const html = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
const projects = fs.readFileSync(
diff --git a/test/renderer/today-tasks-section.test.ts b/test/renderer/today-tasks-section.test.ts
index c6aba7a8..e1be32f0 100644
--- a/test/renderer/today-tasks-section.test.ts
+++ b/test/renderer/today-tasks-section.test.ts
@@ -1,4 +1,5 @@
-// Sidebar "Today's Tasks" aggregate. The section mirrors rows that also live
+// Sidebar "Recent Tasks" aggregate (today + yesterday; DOM ids and i18n keys
+// keep the historical "today" names). The section mirrors rows that also live
// under a Project or in the catch-all Tasks list, so these cases load the real
// conversation row renderer/handlers (conversation.js) next to the module and
// assert what the user sees: which tasks appear, in what order, that opening
@@ -47,14 +48,16 @@ function makeContainer() {
const rows: any[] = [];
const container: any = {
rows,
+ more: null as any,
renameInput: null as any,
querySelector(selector: string) {
+ if (selector === '[data-recent-conv-more]') return container.more;
return selector.startsWith('input.conv-item-title-input') ? container.renameInput : null;
},
querySelectorAll(selector: string) {
return selector === '.conv-item' ? rows : [];
},
- insertAdjacentHTML() {},
+ insertAdjacentHTML(_position: string, value: string) { container.innerHTML = html + value; },
cids() { return rows.map((row) => row.dataset.cid); },
};
Object.defineProperty(container, 'innerHTML', {
@@ -63,6 +66,8 @@ function makeContainer() {
html = value;
rows.length = 0;
for (const match of value.matchAll(/\sdata-cid="([^"]+)"/g)) rows.push(makeRow(match[1]));
+ container.more = value.includes('data-recent-conv-more') ? makeRow('more') : null;
+ if (container.more) container.more.focus = () => {};
},
});
return container;
@@ -83,6 +88,7 @@ function loadTodayTasksRenderer() {
const navigations: Array<[string, string]> = [];
const trackedClicks: Array<[string, Record<string, unknown>]> = [];
const projectReloads: unknown[] = [];
+ const windowListeners = new Map<string, Function[]>();
let unreadRefreshes = 0;
const context: any = {
console, setTimeout, clearTimeout, setInterval, clearInterval,
@@ -126,7 +132,12 @@ function loadTodayTasksRenderer() {
getElementById: (id: string) => (id === 'today-list' ? container : id === 'conversation-list' ? conversationList : null),
},
window: {
- addEventListener() {},
+ addEventListener(type: string, listener: Function) {
+ windowListeners.set(type, [...(windowListeners.get(type) || []), listener]);
+ },
+ dispatchEvent(event: any) {
+ for (const listener of windowListeners.get(event.type) || []) listener(event);
+ },
Monitor: true,
uiIconHtml: () => '',
ConversationRuntime: {},
@@ -137,6 +148,17 @@ function loadTodayTasksRenderer() {
vm.runInContext(readModule('conv-bucket.js'), context);
vm.runInContext(readModule('conversation.js'), context);
vm.runInContext(readModule('today-tasks.js'), context);
+ const recentToggle = makeRow('today-section-toggle');
+ recentToggle.setAttribute = () => {};
+ const { initSidebarSections } = require('../../src/renderer/modules/sidebar-sections.js');
+ initSidebarSections({
+ querySelector: (selector: string) => selector === '.sidebar-today-section'
+ ? { classList: { toggle() {} } } : null,
+ getElementById: (id: string) => id === 'today-section-toggle' ? recentToggle
+ : id === 'today-list' ? container : null,
+ }, context.localStorage, context.t, (detail: any) => {
+ context.window.dispatchEvent({ type: 'sidebar-section-toggle', detail });
+ });
return {
context,
container,
@@ -144,25 +166,213 @@ function loadTodayTasksRenderer() {
navigations,
trackedClicks,
projectReloads,
+ recentToggle,
unreadRefreshes: () => unreadRefreshes,
};
}
describe('sidebar Today aggregate', () => {
- it('lists every task active today across projects and the unprojected list, pinned first then newest', () => {
+ it.each([0, 10, 11])('shows at most ten recent tasks and offers more only when needed (%i tasks)', (count) => {
+ const h = loadTodayTasksRenderer();
+ h.context.conversations = Array.from({ length: count }, (_, i) => ({
+ conversation_id: `recent-${i}`, title: `Task ${i}`, last_active_at: at(HOUR - i),
+ }));
+ h.context.renderConversationList();
+ expect(h.container.cids()).toHaveLength(Math.min(count, 10));
+ expect(Boolean(h.container.more)).toBe(count > 10);
+ // Pagination belongs only to the mirror, not the shared cache or Tasks list.
+ expect(h.context.conversations).toHaveLength(count);
+ expect(h.conversationList.cids()).toHaveLength(count);
+ });
+
+ it('reveals ten more at a time, preserves expansion on refresh and paints newly visible running tasks', () => {
+ const h = loadTodayTasksRenderer();
+ h.context.conversations = Array.from({ length: 21 }, (_, i) => ({
+ conversation_id: `recent-${i}`, title: `Task ${i}`, project_id: 'p1', last_active_at: at(HOUR - i),
+ }));
+ h.context.pendingConvs.set('recent-10', { aborted: false });
+ h.context.renderConversationList();
+ expect(h.container.cids()).toEqual(Array.from({ length: 10 }, (_, i) => `recent-${i}`));
+ h.container.more.click();
+ expect(h.container.cids()).toEqual(Array.from({ length: 20 }, (_, i) => `recent-${i}`));
+ expect(h.container.rows[10].badges()).toEqual(['conv-status-badge is-streaming']);
+ h.context.renderConversationList();
+ expect(h.container.cids()).toHaveLength(20);
+ h.container.more.click();
+ expect(h.container.cids()).toEqual(Array.from({ length: 21 }, (_, i) => `recent-${i}`));
+ expect(h.container.more).toBeNull();
+ h.container.rows[20].click();
+ expect(h.navigations).toEqual([['conversation', 'recent-20']]);
+ });
+
+ it.each([1, 2])('returns to the first ten tasks after reopening with %i extra pages previously revealed', (pages) => {
+ const h = loadTodayTasksRenderer();
+ h.context.conversations = Array.from({ length: 21 }, (_, i) => ({
+ conversation_id: `recent-${i}`, title: `Task ${i}`, last_active_at: at(HOUR - i),
+ }));
+ h.context.pendingConvs.set('recent-0', { aborted: false });
+ h.context.renderConversationList();
+ for (let i = 0; i < pages; i += 1) h.container.more.click();
+ expect(h.container.cids()).toHaveLength(pages === 1 ? 20 : 21);
+
+ // Other section controls must not discard the Recent list's expansion.
+ h.context.window.dispatchEvent({ type: 'sidebar-section-toggle', detail: { name: 'projects', collapsed: false } });
+ h.context.renderConversationList();
+ expect(h.container.cids()).toHaveLength(pages === 1 ? 20 : 21);
+ h.recentToggle.click();
+ expect(h.container.hidden).toBe(true);
+ h.recentToggle.click();
+
+ expect(h.container.hidden).toBe(false);
+ expect(h.container.cids()).toEqual(Array.from({ length: 10 }, (_, i) => `recent-${i}`));
+ expect(h.container.rows[0].badges()).toEqual(['conv-status-badge is-streaming']);
+ expect(h.context.conversations).toHaveLength(21);
+ expect(h.conversationList.cids()).toHaveLength(21);
+ expect(h.projectReloads).toEqual([]);
+ h.container.more.click();
+ expect(h.container.cids()).toHaveLength(20);
+ });
+
+ it.each([
+ ['project page', 'list-first'],
+ ['project page', 'receipt-first'],
+ ['startup refresh', 'list-first'],
+ ['startup refresh', 'receipt-first'],
+ ['pagination', 'list-first'],
+ ['pagination', 'receipt-first'],
+ ])('keeps one running task when %s and its run receipt arrive %s', async (listKind, order) => {
+ const h = loadTodayTasksRenderer();
+ vm.runInContext(readModule('project-detail.js'), h.context);
+ const original = { conversation_id: 'run-one', project_id: 'p1', title: 'Original task',
+ created_at: at(HOUR), updated_at: at(HOUR) };
+ const current = { ...original, title: 'Renamed running task', title_manually_set: true,
+ updated_at: at(2 * HOUR), last_active_at: at(2 * HOUR), processing: true,
+ agent_ids: ['worker'], pinned_at: at(2 * HOUR) };
+ // The main process creates one conversation while admission is in flight.
+ // A concurrent read may observe it before the original run call returns.
+ const persisted = [current];
+ let releaseRun!: (value: unknown) => void;
+ let runCalls = 0;
+ h.context.window.orkas = { invoke: () => {
+ runCalls += 1;
+ return new Promise((resolve) => { releaseRun = resolve; });
+ } };
+ h.context.ensureModelConfigured = () => true;
+ h.context.apiFetch = async () => ({ json: async () => ({ ok: true,
+ conversations: persisted.map((row) => ({ ...row })), total: 1, next_offset: null,
+ unprojected_pagination: { total: 0, next_offset: null }, loaded_project_ids: [],
+ }) });
+ h.context.conversations.push({ conversation_id: 'unrelated', project_id: 'p-other',
+ title: 'Other task', last_active_at: at(3 * HOUR) });
+ const scope = { pid: 'p1', project: {}, tasks: [{ id: 't_one', status: 'todo' }] };
+ const run = h.context._runTodoTask('t_one', scope);
+ // Repeated user input while the same admission is pending must not
+ // produce a second run, independent of how the sidebar is refreshed.
+ await h.context._runTodoTask('t_one', scope);
+ const load = () => listKind === 'project page'
+ ? h.context.loadConversationProject('p1')
+ : listKind === 'startup refresh' ? h.context.loadConversations()
+ : Promise.resolve(h.context._appendConversationSlice(persisted));
+ if (order === 'list-first') await load();
+ releaseRun({ ok: true, cid: original.conversation_id, conversation: original });
+ await run;
+ if (order === 'receipt-first') await load();
+ h.context.renderConversationList();
+
+ expect(runCalls).toBe(1);
+ expect(persisted).toHaveLength(1);
+ expect(h.context.conversations.filter((row: any) => row.conversation_id === 'run-one'))
+ .toEqual([current]);
+ expect(h.container.cids().filter((cid: string) => cid === 'run-one')).toEqual(['run-one']);
+ if (listKind !== 'startup refresh') {
+ expect(h.context.conversations.some((row: any) => row.conversation_id === 'unrelated')).toBe(true);
+ }
+ // Navigation uses that one row; it does not dispatch the task again.
+ h.container.rows.find((row: any) => row.dataset.cid === 'run-one').click();
+ expect(h.navigations).toEqual([['conversation', 'run-one'], ['conversation', 'run-one']]);
+ expect(runCalls).toBe(1);
+ });
+
+ it('preserves a refreshed running task when an older auto-advance receipt is repeated', () => {
+ const h = loadTodayTasksRenderer();
+ vm.runInContext(readModule('project-detail.js'), h.context);
+ h.context._observeConversationRunFromPlanAction = () => {};
+ const current = { conversation_id: 'auto-one', project_id: 'p1', title: 'Updated title',
+ created_at: at(HOUR), updated_at: at(2 * HOUR), last_active_at: at(2 * HOUR),
+ processing: true, agent_ids: ['worker'] };
+ h.context._appendConversationSlice([current]);
+ const receipt = { projectId: 'p1', conversation: { conversation_id: 'auto-one', project_id: 'p1',
+ title: 'Creation title', created_at: at(HOUR), updated_at: at(HOUR) } };
+ h.context._onProjectAdvance(receipt);
+ h.context._onProjectAdvance(receipt);
+ expect(h.context.conversations).toEqual([current]);
+ expect(h.container.cids()).toEqual(['auto-one']);
+ });
+
+ it('keeps an optimistic request title while preserving list-only metadata', () => {
+ const h = loadTodayTasksRenderer();
+ const original = { conversation_id: 'new-one', created_at: at(HOUR), updated_at: at(HOUR) };
+ h.context._appendConversationSlice([{ ...original, title: 'Untitled',
+ last_active_at: at(HOUR), processing: false }]);
+ h.context._cacheCreatedConversation({ ...original, title: 'Review the brief' }, 'Review the brief');
+ h.context.renderConversationList();
+ expect(h.context.conversations).toEqual([{ ...original, title: 'Review the brief',
+ last_active_at: at(HOUR), processing: false }]);
+ expect(h.container.cids()).toEqual(['new-one']);
+ });
+
+ it('preserves a manual rename when creation and rename share the same timestamp', () => {
+ const h = loadTodayTasksRenderer();
+ const renamed = { conversation_id: 'renamed', title: 'User title', title_manually_set: true,
+ created_at: at(HOUR), updated_at: at(HOUR), last_active_at: at(HOUR) };
+ h.context._appendConversationSlice([renamed]);
+ h.context._cacheCreatedConversation({ conversation_id: 'renamed', title: 'Creation title',
+ created_at: at(HOUR), updated_at: at(HOUR) });
+ expect(h.context.conversations).toEqual([renamed]);
+ });
+
+ it('keeps admitted participants when creation and admission share the same timestamp', () => {
+ const h = loadTodayTasksRenderer();
+ const admitted = { conversation_id: 'admitted', title: 'Run task', created_at: at(HOUR),
+ updated_at: at(HOUR), last_active_at: at(HOUR), agent_ids: ['worker'],
+ commander_in_chat: true, participant_summary_updated_at: at(HOUR), processing: true };
+ h.context._appendConversationSlice([admitted]);
+ // Real createConversation receipts carry empty participant summaries.
+ // Second-resolution timestamps cannot order that receipt against admission.
+ h.context._cacheCreatedConversation({ ...admitted, agent_ids: [], commander_in_chat: false });
+ expect(h.context.conversations).toEqual([admitted]);
+ });
+
+ it('keeps one identity when a project page observes a conversation moved from another project', () => {
+ const h = loadTodayTasksRenderer();
+ const old = { conversation_id: 'moved', project_id: 'old-project', title: 'Moved task', last_active_at: at(HOUR) };
+ const unrelated = { conversation_id: 'unrelated', project_id: 'old-project', title: 'Other task', last_active_at: at(HOUR) };
+ h.context._appendConversationSlice([old, unrelated]);
+ h.context._replaceConversationSlice([{ ...old, project_id: 'new-project' }],
+ (row: any) => row.project_id === 'new-project');
+ h.context.renderConversationList();
+ expect(h.context.conversations).toHaveLength(2);
+ expect(h.context.conversations.filter((row: any) => row.conversation_id === 'moved'))
+ .toEqual([{ ...old, project_id: 'new-project' }]);
+ expect(h.context.conversations).toContainEqual(unrelated);
+ expect(h.container.cids().filter((cid: string) => cid === 'moved')).toEqual(['moved']);
+ });
+
+ it('lists every task active today or yesterday across projects and the unprojected list, pinned first then newest', () => {
const h = loadTodayTasksRenderer();
h.context.conversations.push(
{ conversation_id: 'unprojected-10', title: 'u', last_active_at: at(10 * HOUR) },
// Lives under a collapsed project: never painted in the Projects tree.
{ conversation_id: 'collapsed-project-09', title: 'c', project_id: 'p-collapsed', last_active_at: at(9 * HOUR) },
{ conversation_id: 'yesterday-2359', title: 'y', project_id: 'p1', last_active_at: at(-1) },
+ { conversation_id: 'day-before-2359', title: 'd', project_id: 'p1', last_active_at: at(-24 * HOUR - 1) },
{ conversation_id: 'pinned-08', title: 'p', project_id: 'p1', pinned_at: at(8 * HOUR), last_active_at: at(8 * HOUR) },
{ conversation_id: 'ancient', title: 'a', updated_at: '2020-01-01T00:00:00.000Z' },
);
h.context.renderTodayTasksSection();
- expect(h.container.cids()).toEqual(['pinned-08', 'unprojected-10', 'collapsed-project-09']);
+ expect(h.container.cids()).toEqual(['pinned-08', 'unprojected-10', 'collapsed-project-09', 'yesterday-2359']);
// Same row markup as every other sidebar list, no bucket header inside
// an all-today section.
expect(h.container.innerHTML).toContain('class="conv-item');
@@ -183,9 +393,9 @@ describe('sidebar Today aggregate', () => {
});
it.each([
- ['a task from yesterday', [{ conversation_id: 'yesterday', title: 'y', last_active_at: at(-HOUR) }]],
+ ['a task from the day before yesterday', [{ conversation_id: 'day-before', title: 'd', last_active_at: at(-25 * HOUR) }]],
['no task at all', []],
- ])('shows the empty hint when nothing ran today and the list render clears the header cue (%s)', (_name, rows) => {
+ ])('shows the empty hint when nothing ran today or yesterday and the list render clears the header cue (%s)', (_name, rows) => {
const h = loadTodayTasksRenderer();
h.context.conversations.push(...rows);
@@ -235,7 +445,7 @@ describe('sidebar Today aggregate', () => {
expect(h.unreadRefreshes()).toBe(renameInList ? 2 : 1);
});
- it('refreshes the project list only when the deleted Today row belonged to a project', async () => {
+ it('refreshes the project list only when the deleted Recent row belonged to a project', async () => {
const h = loadTodayTasksRenderer();
let bindOpts: any = null;
h.context._bindConversationSidebarItems = (_container: unknown, opts: any) => { bindOpts = opts; };
@@ -245,7 +455,7 @@ describe('sidebar Today aggregate', () => {
);
h.context.renderTodayTasksSection();
- expect(bindOpts?.scope).toBe('today');
+ expect(bindOpts?.scope).toBe('recent');
await bindOpts.afterDelete('unprojected');
expect(h.projectReloads).toEqual([]);
await bindOpts.afterDelete('projected');
diff --git a/test/renderer/todo-editor-agent.test.ts b/test/renderer/todo-editor-agent.test.ts
index 05faf7cd..e5f37ec7 100644
--- a/test/renderer/todo-editor-agent.test.ts
+++ b/test/renderer/todo-editor-agent.test.ts
@@ -12,9 +12,13 @@ function harness(load?: (channel: string, args: any) => Promise<any>) {
const elements: Record<string, any> = {};
const selects: Record<string, any> = {};
for (const id of ['input', 'add', 'agent', 'project', 'status', 'save', 'cancel']) {
+ const trigger = { disabled: false };
+ const classes = new Set<string>();
elements['project-todo-' + id] = {
id: 'project-todo-' + id, value: '', maxLength: 4000, dataset: {}, hidden: false,
- focus() {}, setSelectionRange() {}, classList: { toggle() {} }, querySelector() { return null; },
+ focus() {}, setSelectionRange() {}, classes, trigger,
+ classList: { toggle(name: string, active: boolean) { if (active) classes.add(name); else classes.delete(name); } },
+ querySelector(selector: string) { return selector === '.ai-select-trigger' ? trigger : null; },
};
}
const context = vm.createContext({
@@ -42,8 +46,8 @@ function harness(load?: (channel: string, args: any) => Promise<any>) {
},
});
vm.runInContext(source, context);
- const open = async (task: any = null, pid = '') => {
- context._openProjectTodoEditor(task, { pid, global: !pid, projects: [{ project_id: 'p', name: 'Project' }] });
+ const open = async (task: any = null, pid = '', extra: any = {}) => {
+ context._openProjectTodoEditor(task, { pid, global: !pid, projects: [{ project_id: 'p', name: 'Project' }], ...extra });
await tick();
};
return { context, calls, alerts, elements, selects, open };
@@ -92,7 +96,7 @@ describe('todo editor assignment', () => {
await tick();
release({ agentDetails: [{ agent_id: 'wrong', name: 'Wrong project' }] });
await tick();
- expect(h.selects['project-todo-agent'].state.options.map((o: any) => o.value)).toEqual(['', 'p']);
+ expect(h.selects['project-todo-agent'].state.options.map((o: any) => o.value)).toEqual(['', 'commander', 'p']);
expect(h.selects['project-todo-agent'].getValue()).toBe('');
h.elements['project-todo-input'].value = 'New';
await h.context._saveProjectTodoEditor();
diff --git a/test/renderer/todos-refresh.test.ts b/test/renderer/todos-refresh.test.ts
index 2629650e..dcf33e99 100644
--- a/test/renderer/todos-refresh.test.ts
+++ b/test/renderer/todos-refresh.test.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import vm from 'node:vm';
const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/todos.js'), 'utf8');
+const projectSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/project-detail.js'), 'utf8');
function harness(invoke: (channel: string, args: any) => Promise<any>) {
const error = { hidden: true };
@@ -42,7 +43,7 @@ function backlogFixture(options: { gate?: (channel: string, args: any) => Promis
calls.push(`${channel}:${pid || '-'}`);
await options.gate?.(channel, args);
if (channel === 'projects.list') {
- return { ok: true, projects: [{ project_id: 'b', name: 'Beta' }, { project_id: 'a', name: 'Alpha' }] };
+ return { ok: true, projects: [{ project_id: 'a', name: 'Alpha' }, { project_id: 'b', name: 'Beta' }] };
}
if (channel === 'agents.list') return { agents: [] };
if (channel === 'projects.bindings.list') return { ok: true, agentDetails: [{ agent_id: `agent-${pid}` }] };
@@ -59,6 +60,98 @@ function backlogFixture(options: { gate?: (channel: string, args: any) => Promis
const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
+describe('creating a to-do from the account page', () => {
+ it('follows the selected project on each open but uses global in status grouping', async () => {
+ const h = backlogFixture();
+ await h.context.loadGlobalTodos();
+ const opened: any[] = [];
+ const listeners: Record<string, () => void> = {};
+ h.context.document.getElementById = (id: string) => ({ addEventListener: (_: string, fn: () => void) => { listeners[id] = fn; } });
+ h.context.document.querySelectorAll = () => [];
+ h.context.window.addEventListener = () => {};
+ h.context._bindTodoListActions = () => {};
+ h.context._openProjectTodoEditor = (_: any, context: any) => opened.push(context);
+ h.context._initGlobalTodos();
+ vm.runInContext("_globalTodoActiveScope = 'a'", h.context);
+ listeners['todos-add-btn']();
+ vm.runInContext("_globalTodoMode = 'status'", h.context);
+ listeners['todos-add-btn']();
+ vm.runInContext("_globalTodoMode = 'project'", h.context);
+ listeners['todos-add-btn']();
+ vm.runInContext("_globalTodoActiveScope = 'b'", h.context);
+ listeners['todos-add-btn']();
+ expect(opened.map(context => context.pid)).toEqual(['a', '', 'a', 'b']);
+ expect(opened[0]).toMatchObject({ global: false, agents: [{ agent_id: 'agent-a' }], project: { project_id: 'a', name: 'Alpha' } });
+ expect(opened[0].projects.map((project: any) => project.project_id)).toEqual(['a', 'b']);
+ });
+
+ it.each([null, '', 'removed'])('falls back to global for unavailable selection %s', async (scope) => {
+ const h = backlogFixture();
+ await h.context.loadGlobalTodos();
+ h.context.selection = scope;
+ vm.runInContext(`_globalTodoActiveScope = selection;
+ _globalTodoGroups.push({ project: { project_id: 'removed', name: 'Stale' }, tasks: [], agents: [] });`, h.context);
+ expect(h.context._globalTodoCreateContext()).toMatchObject({ pid: '', global: true });
+ });
+});
+
+describe('todo auto-advance device names', () => {
+ it.each([['', 'throw'], ['p', 'throw'], ['', 'rejected'], ['p', 'rejected']])(
+ 'keeps the device name through scope %s loading, regrouping and toggling, retaining it on %s failure', async (pid, failure) => {
+ let config: any = { enabled: true, device_id: 'remote', device_name: '<Office Mac>' };
+ const device = { id: 'local', name: 'Laptop' };
+ let fail = false;
+ const writes: any[] = [], buttons: any[] = [], alerts: string[] = [];
+ const element = () => ({ dataset: {}, attributes: {} as Record<string, string>, innerHTML: '', textContent: '', disabled: false,
+ setAttribute(key: string, value: string) { this.attributes[key] = value; }, addEventListener() {} });
+ const context = vm.createContext({
+ currentView: 'todos', createLogger: () => ({ warn() {} }),
+ document: { readyState: 'loading', addEventListener() {}, createElement: element,
+ querySelectorAll: () => buttons, getElementById: () => null },
+ window: { addEventListener() {}, orkas: { async invoke(channel: string, args: any) {
+ if (channel === 'projects.tasks.list') return { ok: true, tasks: [{ id: 't_one', status: 'todo' }] };
+ if (channel === 'projects.bindings.list') return { ok: true, agentDetails: [] };
+ if (channel === 'agents.list') return { agents: [] };
+ if (channel === 'projects.driver.set') {
+ writes.push(args);
+ if (fail) {
+ if (failure === 'rejected') return { ok: false, config: { enabled: false } };
+ throw new Error('fixture write unavailable');
+ }
+ config = { enabled: args.enabled, ...(args.enabled ? { device_id: device.id, device_name: device.name } : {}) };
+ }
+ return { config, device };
+ } } }, t: String, uiAlert: (message: string) => alerts.push(message),
+ escapeHtml: (value: string) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'),
+ });
+ vm.runInContext(projectSource + '\n' + source, context);
+ const group = await context._loadGlobalTodoGroup({ project_id: pid, name: 'Scope' });
+ const byProject = context._renderGlobalTodoDriverToggle(group, false);
+ const byStatus = context._renderGlobalTodoDriverToggle(group, true);
+ buttons.push(byProject, byStatus);
+ expect(byProject.attributes['aria-label']).toBe('project.driver.toggle · <Office Mac>');
+ expect(byStatus.innerHTML).toContain(pid ? 'Scope' : 'todo.global');
+ expect(byStatus.innerHTML).toContain('&lt;Office Mac&gt;');
+ expect(byStatus.innerHTML).not.toContain('<Office Mac>');
+ fail = true;
+ await context._toggleGlobalTodoDriver(group);
+ expect(byProject.attributes['aria-label']).toBe('project.driver.toggle · <Office Mac>');
+ expect(byProject.attributes['aria-pressed']).toBe('true');
+ expect(byProject.disabled).toBe(false);
+ expect(alerts).toEqual(['project.todo.failed']);
+ fail = false;
+ await context._toggleGlobalTodoDriver(group);
+ expect(byProject.attributes['aria-label']).toBe('project.driver.toggle');
+ expect(byStatus.innerHTML).not.toContain('Office Mac');
+ await context._toggleGlobalTodoDriver(group);
+ expect(byProject.attributes['aria-label']).toBe('project.driver.toggle · auto.device_current');
+ expect(byStatus.innerHTML).toContain('auto.device_current');
+ expect(byStatus.innerHTML).not.toContain('Laptop');
+ expect(byProject.attributes['aria-pressed']).toBe('true');
+ expect(writes).toEqual([{ projectId: pid, enabled: false }, { projectId: pid, enabled: false }, { projectId: pid, enabled: true }]);
+ });
+});
+
describe('global backlog scope refresh', () => {
it('reloads only the changed project after a tasks-changed push and keeps the other sections', async () => {
const f = backlogFixture();
@@ -207,7 +300,7 @@ describe('global backlog refresh and recovery', () => {
it('retains the last complete view when one project fails, then retries without duplicating tasks', async () => {
let fail = false;
const h = harness(async (channel, args) => {
- if (channel === 'projects.list') return { ok: true, projects: [{ project_id: 'b', name: 'Beta' }, { project_id: 'a', name: 'Alpha' }] };
+ if (channel === 'projects.list') return { ok: true, projects: [{ project_id: 'a', name: 'Alpha' }, { project_id: 'b', name: 'Beta' }] };
if (channel === 'agents.list') return { agents: [] };
if (channel === 'projects.bindings.list') return { ok: true, agentDetails: [] };
if (channel === 'projects.tasks.list' && !args.projectId) return { ok: true, tasks: [] };
@@ -252,3 +345,65 @@ describe('global backlog refresh and recovery', () => {
expect(h.warnings).toEqual([]);
});
});
+
+describe('opening a to-do from a shortcut', () => {
+ function todoRow(tid: string, columnHidden = false) {
+ const classes = new Set<string>();
+ const toggle = { expanded: '', setAttribute: (_: string, value: string) => { toggle.expanded = value; } };
+ const body = { hidden: columnHidden, parentElement: { querySelector: () => toggle } };
+ return {
+ dataset: { tid },
+ classes,
+ toggle,
+ body,
+ scrolled: 0,
+ classList: { add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name) },
+ closest: (selector: string) => (selector === '.todo-column-body' ? body : null),
+ scrollIntoView() { this.scrolled += 1; },
+ };
+ }
+
+ it.each(['project', 'status'])('switches from %s grouping to the to-do scope, reveals and highlights the row once after loading', async (mode) => {
+ const f = backlogFixture();
+ vm.runInContext(`_globalTodoMode = '${mode}'; _globalTodoActiveScope = 'a'`, f.context);
+ const views: any[] = [];
+ const other = todoRow('a1');
+ const target = todoRow('b1', true);
+ const host = {
+ setAttribute() {},
+ querySelectorAll: (selector: string) => (selector === '.project-todo-item[data-tid]' ? [other, target] : []),
+ };
+ f.context.setView = (...args: any[]) => { views.push(JSON.parse(JSON.stringify(args))); };
+ f.context.document.getElementById = (id: string) => (id === 'todos-error' ? f.error : host);
+
+ f.context.focusTodo('b', 'b1', { entryPoint: 'home' });
+ expect(views).toEqual([['todos', null, { entryPoint: 'home' }]]);
+ expect(vm.runInContext('_globalTodoMode', f.context)).toBe('project');
+ expect(vm.runInContext('_globalTodoActiveScope', f.context)).toBe('b');
+ expect(target.classes.size).toBe(0);
+
+ await f.context.loadGlobalTodos();
+ expect(target.classes.has('is-highlighted')).toBe(true);
+ expect(target.scrolled).toBe(1);
+ expect(target.body.hidden).toBe(false);
+ expect(target.toggle.expanded).toBe('true');
+ expect(other.classes.size).toBe(0);
+
+ // Applied once: a later reload of the page does not jump back to it.
+ target.classes.clear();
+ await f.context.loadGlobalTodos();
+ expect(target.classes.size).toBe(0);
+ expect(target.scrolled).toBe(1);
+ });
+
+ it('just opens the page when the to-do is gone by the time it loads', async () => {
+ const f = backlogFixture();
+ const host = { setAttribute() {}, querySelectorAll: () => [] };
+ f.context.setView = () => {};
+ f.context.document.getElementById = (id: string) => (id === 'todos-error' ? f.error : host);
+ f.context.focusTodo('a', 'missing', { entryPoint: 'home' });
+ await f.context.loadGlobalTodos();
+ expect(f.error.hidden).toBe(true);
+ expect(vm.runInContext('_globalTodoPendingFocus', f.context)).toBe(null);
+ });
+});
diff --git a/test/renderer/validation-report-view.test.ts b/test/renderer/validation-report-view.test.ts
index 26724ed9..246f37f9 100644
--- a/test/renderer/validation-report-view.test.ts
+++ b/test/renderer/validation-report-view.test.ts
@@ -165,20 +165,6 @@ describe('quality validation report renderer', () => {
expect(ctx._documentListeners.has('keydown')).toBe(false);
});
- it('shows operator guidance verbatim and removes the force action for policy failures', async () => {
- const ctx = loadValidationReportView();
- const result = ctx.showValidationReport({ report: { ok: false, violations: [{
- rule: 'no_eval_with_external_input', source: 'operator-policy', level: 'EXTREME',
- field: 'run.sh', snippet: '', suggested_fix: 'Operator <private> guidance',
- }] }, forceLabel: 'Install anyway' });
- const overlay = ctx._overlays[0] as FakeOverlay;
- expect(overlay.innerHTML).toContain('Operator &lt;private&gt; guidance');
- expect(overlay.innerHTML).not.toContain('Use a fixed command.');
- expect(overlay.innerHTML).not.toContain('Install anyway');
- overlay.okButton.click();
- await expect(result).resolves.toBe('close');
- });
-
it('lets keyboard activation of the focused override button choose force', async () => {
const ctx = loadValidationReportView();
const result = ctx.showValidationReport({