Skip to content

feat(bot): add scheduled proactive discovery and quoted feedback - #6730

Merged
M4n5ter merged 19 commits into
apache:rust-previewfrom
sunrioa:codex/feat-rust-discovery-desktop
Nov 18, 2026
Merged

M4n5ter merged 19 commits into
apache:rust-previewfrom
sunrioa:codex/feat-rust-discovery-desktop

Conversation

@sunrioa

@sunrioa sunrioa commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refs #6716. Consolidates #6724, #6728, and the desktop work in this PR on rust-preview.

  • Run scheduled investigations in fresh worker Sessions through the existing Scheduler. Manual checks share the same investigation slot. The Bot reviews findings before sending them to the user.
  • Share investigation records, corrections, notification decisions, and quoted user feedback by Bot and workspace. Open original material using the standard Session readers from feat(agent): redesign AX prompts, universal maka:// Read, and human-symmetric Session* tools #6958.
  • Manage plans, approve execution, check now, delete a plan, and open the original investigation from the desktop.
  • Default new plans to read-only. Standard Session mode requires a preview and approval of the actual tool list. Recurring runs and in-scope follow-ups retain that grant. If execution authority expires, the plan pauses for renewed approval.
  • Store quoted excerpts with their draft and preserve the original publication identity through sending and retry. Escape quoted text through the shared renderer.

Follow-up PR

Grouped tool approvals build on the read-only and standard Session presets in this PR. The follow-up addresses three review findings. Grouped tool approvals (#6991)

  • Determine read-only eligibility from the bound service and method, so aliases are classified correctly.
  • Preview the tools available to a fresh investigation Session. Client MCP tools attached only to the Bot are omitted from that preview.
  • Correct the desktop and agent guides that currently describe file exclusions. Enforcing exclusions for files, directories, or suffixes would require a separate workspace or Session policy.

The report-delivery issue where a change in workspace MCP trust can hold the investigation slot remains open in #6730.

Proactive discovery flow

flowchart TD
    plan["Approved discovery plan"]
    scheduler["Host Scheduler<br/>One active investigation"]
    authority{"Approval current?"}
    paused["Pause for renewed approval"]
    worker["Fresh worker Session<br/>Approved tool list"]
    complete{"DiscoveryComplete"}
    settled["Settle quietly"]
    bot["Existing Bot Session<br/>Review queued report"]
    outbox["Bot outbox<br/>User sees the finding"]
    asleep["End Bot turn quietly"]
    memory[("DiscoveryMemory<br/>Results, notes, decisions and feedback")]

    plan -->|"Timer or Check now"| scheduler
    scheduler --> authority
    authority -->|Yes| worker
    authority -->|No| paused
    worker --> complete
    complete -->|no_report| settled
    complete -->|"report via Session queue"| bot
    bot -->|SendUser| outbox
    bot -->|sleep| asleep
    complete -. "Persist on settlement" .-> memory
    memory -. "Read records on demand" .-> worker
    bot -. "Record notification decision" .-> memory
    outbox -. "User quotes finding, Bot records feedback" .-> memory
Loading

Review notes on existing behavior

  • The scheduler counts settled triggers. A blocked one-time trigger, or the last trigger allowed by maxFires, can complete the plan even when the worker has not started. This follows the existing trigger-counting rule.
  • Some pre-release Bots persisted their coordination-tool list as the Session tool ceiling. Reusing one of those Sessions can exclude file tools from an investigation and DiscoveryMemory from the Bot that handles quoted feedback. Migrating those development records is a separate compatibility decision.

Verification

Validated on macOS at 8c5d0711c, rebased onto rust-preview at 9ac917f17.

Check Result
Native discovery integration, using a local model fixture and real workspace file and Shell bindings 10 passed
Scheduler and conversation/external quote regressions 4 passed
Desktop renderer, including approval, renewed approval and plan deletion 1 passed
Draft journal and quote rendering 3 passed
Workbench discovery tests 5 passed
Generated SDK, SDK/product TypeScript and whitespace checks Passed

The native tests verify read-only file access, a successful Shell call after explicit scope expansion, in-scope follow-ups, stable quoted feedback after an authorization change, and pagination through older records. The branch uses the new pre-release discovery and draft storage layouts.

The packaging and live-provider observations below are from earlier development builds.

Live-provider checks used Command Code → DeepSeek V4.1 Flash with isolated synthetic data:

Scenario Observed result
Scheduled investigation with a new actionable finding One linked notification
Recheck without new information No repeated notification
Quote a finding and report it resolved Feedback linked to the original discovery
Investigate again in a fresh Session Feedback retrieved; no repeated notification
Introduce an independent finding New notification delivered
Read actual sample files, then correct their contents Files reread; corrected findings not repeated
Terminate the Host during a real model request Original investigation settled as failed without replay; the next investigation completed normally

All investigating workers used read-only permissions. Test plans were paused after verification.

The live checks also exposed model-quality limitations: one investigation incorrectly treated an additional, permitted language file as a mismatch, and the Bot initially described background file access inaccurately. Corrective feedback was retained and respected in subsequent investigations. These checks validate the integration, not general discovery accuracy.

Windows/Linux desktop validation and full repository CI were not run locally. The macOS package was a local smoke-test artifact, not a signed or source-bound publication candidate.

Live use in an approved workspace

This snapshot comes from macOS runtime records for an existing approved workspace. Both builds used Command Code / DeepSeek V4.1 Flash. The post-sync local build was based on this PR with #6874, #6907 and a local adapter for the existing schedule.

Observation window (UTC+8) Investigations Bot notifications with an original Session link Worker model attempts with token counts / total Input tokens Output tokens Share of input read from cache
Earlier local build, 2026-11-14 20:13 to 23:29 4 completed with reports, 2 failed 4 216 / 220 19,044,923 113,708 92.0%
Post-sync local build, 2026-11-14 23:29 to 2026-11-15 01:35 1 completed with a report in 2h 5m 14s 1 171 / 173 16,440,532 72,285 97.2%
  • The four completed reports took 17m 58s to 27m 02s. Their linked notifications reached the Bot outbox 22 to 82 seconds after the investigations settled. One failure followed a model-step error and the other settled during restart recovery.
  • The post-sync investigation settled at 01:35:12, and the Bot published one notification with a link to the original investigation Session at 01:35:30 (about 18 seconds later, UTC+8).
  • The post-sync worker recorded 110 Shell calls returning without a tool-level error, including four issued in a later model step than the one that started the code cell. The runtime recorded zero agent_cell_origin_mismatch errors in that round.
  • Three non-overlapping searches (recent media files, a broad local scan, and a quota ledger lookup) took 43m 14s in total from call to return. The worker called wait 32 times and made 10 separate checks of the same repository fix across commits, branches, and worktrees. This run had no execution deadline.
  • Input includes cached tokens. Token totals cover attempts with provider-reported usage. The four linked Bot runs on the earlier build separately recorded 891,165 input and 4,413 output tokens across eight model attempts. The Bot run that published the post-sync notification separately recorded 224,778 input and 1,202 output tokens across two model attempts.

Follow-up observation after restart

This 15h 33m sample comes from local integration build 0cacbd4aa on macOS, from 2026-11-15 20:05:33 to 2026-11-16 11:38:28 (UTC+8). It used Command Code / DeepSeek V4.1 Flash in the same approved workspace. The build included the Shell cancellation guidance now isolated in #6939. The sample predates local use of the updated memory pagination from #6728.

  • 22 investigations started. 18 submitted reports to the Bot, 3 failed, and 1 was active at the cutoff. The Bot persisted 15 in-app messages and withheld 3 reports because they repeated earlier notifications.
  • The 21 settled investigations had a median duration of 29m 25s. The longest took 52m 12s, and 10 exceeded the 30-minute schedule interval. Each failed investigation released the slot, and later investigations started.
Model request source Attempts Input tokens Input read from cache Other input tokens Output tokens
Investigation workers 2,330 191,727,243 187,883,520 3,843,723 1,008,076
Bot decision runs 35 6,502,118 4,302,336 2,199,782 16,963
Bot auxiliary requests 15 2,944,430 2,938,880 5,550 1,574
Total 2,380 201,173,791 195,124,736 6,049,055 1,026,613

The ledger recorded 202,200,404 input and output tokens. Cache reads accounted for 97.0% of reported input. Usage was unavailable for 14 interrupted attempts.

  • Failures. Two investigations ended after a model stream idle timeout with no safe replay or continuation available. One ended at the 8,000-output-token limit, which truncated the exec arguments and left no submitted result. Twelve TLS handshake interruptions were retried successfully.
  • Tool waits. Of 2,005 foreground Shell calls, 37 took at least one minute. Of those, 35 ran without a timeout, and the longest call lasted 4m 56s. Cleanup was confirmed for all 31 cancelled calls. In 121 model requests, wait was the only tool called.
  • Memory retrieval and coverage. Of 93 filtered memory queries, 37 returned an empty page with a continuation cursor and stopped there. Fifteen of 18 submitted reports covered one customer project. The morning included four reviews of that project's pricing, quota and deliverable terms, and the later review corrected an earlier interpretation. Other investigations covered sales follow-up, procurement deadlines, release troubleshooting and operational risks.

AI use

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: OpenAI Codex assisted with implementation, regression tests, local verification and drafting this description.

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No
简体中文

概述

关联 #6716。基于 rust-preview 将 #6724、#6728 和本 PR 的桌面改动收敛到一个 PR。

  • 通过已有调度器在新 worker Session 中运行定时调查。立即检查复用同一调查位。Bot 审阅发现后决定是否通知用户。
  • 按 Bot 和工作区共享调查记录、修正、通知决定和引用反馈。原始资料使用 feat(agent): redesign AX prompts, universal maka:// Read, and human-symmetric Session* tools #6958 的标准会话读取能力。
  • 桌面端可批准、管理、删除计划,立即检查,并打开原调查过程。
  • 新计划默认只读。选择普通会话工具后,先预览实际工具清单再批准。后续定时调查和同范围复查沿用授权。执行授权失效时暂停排期,等待重新授权。
  • 引用与草稿一同保存,发送和重试保留原通知身份。引用文本使用共享渲染器转义。

后续 PR

后续 PR 在本 PR 的「只读工具」和「普通会话工具」两种预设之上增加分组审批,并处理以下三项评审意见。分组审批 #6991

  • 按工具实际绑定的服务和方法判断只读资格,正确处理改过名称的工具。
  • 审批清单按新建调查会话实际可用的工具生成,仅挂在 Bot 会话上的客户端 MCP 工具会从预览中排除。
  • 更正桌面和 Agent 指南中提前写入的文件排除说明。按文件、目录或后缀排除资料,另需工作区或会话层的持久权限设计。

工作区 MCP 需要重新信任时,报告投递可能持续占用调查位,这个问题仍在 #6730 跟踪。

主动发现流程

flowchart TD
    plan["已批准的主动发现计划"]
    scheduler["Host 调度器<br/>同时只运行一轮调查"]
    authority{"授权仍有效?"}
    paused["暂停排期,等待重新授权"]
    worker["每轮新建调查会话<br/>使用获准的工具清单"]
    complete{"DiscoveryComplete<br/>提交调查结果"}
    settled["静默结算"]
    bot["原有 Bot 会话<br/>判断是否通知用户"]
    outbox["Bot 发件箱<br/>用户收到发现"]
    asleep["静默结束 Bot 本轮"]
    memory[("DiscoveryMemory<br/>调查结果、笔记、通知决定和反馈")]

    plan -->|"定时到点或点击立即检查"| scheduler
    scheduler --> authority
    authority -->|是| worker
    authority -->|否| paused
    worker --> complete
    complete -->|"no_report 无需汇报"| settled
    complete -->|"report 报告进入会话队列"| bot
    bot -->|SendUser| outbox
    bot -->|sleep| asleep
    complete -. "结算时写入" .-> memory
    memory -. "按需读取历史调查记录" .-> worker
    bot -. "记录通知决定" .-> memory
    outbox -. "用户引用通知,Bot 记录反馈" .-> memory
Loading

现有行为的评审记录

  • 调度器按已结算的触发次数计数。单次计划或 maxFires 允许的最后一次触发若受阻,即使调查 worker 尚未启动,计划也可能进入 Completed。这是现有的触发计数规则。
  • 部分早期开发版 Bot 把协调工具清单持久化成了会话工具上限。复用这些会话时,调查可能缺少文件工具,Bot 也可能缺少处理引用反馈所需的 DiscoveryMemory。是否迁移这些开发数据属于单独的兼容性决策。

验证

已在 macOS 验证 8c5d0711c,基于 rust-preview 的 9ac917f17。

检查 结果
使用本机模型夹具和真实文件、Shell 绑定的主动发现集成测试 10 项通过
调度和会话、外部执行器引用回归 4 项通过
桌面渲染,覆盖批准、重新授权和删除计划 1 项通过
草稿和引用渲染 3 项通过
Workbench 主动发现用例 5 项通过
生成 SDK、SDK 和产品 TypeScript、空白检查 通过

原生用例验证了只读文件访问、批准扩权后成功执行 Shell、同范围复查、授权变化后的旧通知引用反馈,以及跨页搜索历史记录。分支采用开发期的新计划与草稿存储格式。

下面的 release 打包和真实模型数据来自此前的开发构建。

使用 Command Code → DeepSeek V4.1 Flash,材料均为隔离的合成数据:

场景 实际结果
定时调查发现新的可行动问题 发出一条关联原调查的通知
没有新信息时再次检查 未重复通知
引用发现并反馈已经解决 反馈关联到原始发现
使用新的 Session 再次调查 读取反馈,未重复通知
加入独立的新问题 正常发送新通知
读取实际样例文件,再修改文件内容 重新读取文件,未重复报告已修正的问题
真实模型请求期间终止 Host 原调查明确结算为失败,没有重复执行;下一轮正常完成

调查 worker 均使用只读权限,测试结束后已暂停计划。

真实联调也暴露出模型判断的局限:一次调查把允许存在的额外语言文件误判为差异,Bot 最初也未准确说明后台调查的文件读取能力。纠正反馈得到保存,并在后续调查中生效。这些检查验证的是集成链路,不能作为普遍发现准确率的证明。

本地未执行 Windows/Linux 桌面验证或完整仓库 CI。macOS 包仅用于本地安装冒烟,不是已签名或绑定源码归档的正式发布候选产物。

已授权工作区的真实运行数据

以下数据来自现有已授权工作区的 macOS 运行记录。两个构建均使用 Command Code / DeepSeek V4.1 Flash。同步后的本地构建以本 PR 为基础,包含 #6874、#6907 和用于读取原有计划的本地适配。

观察窗口(UTC+8) 调查结果 带原 Session 链接的 Bot 通知 Worker 模型尝试(有 token 记录/总数) 输入 token 输出 token 输入缓存读取占比
较早的本地构建,2026-11-14 20:13 至 23:29 4 轮完成并提交报告,2 轮失败 4 216 / 220 19,044,923 113,708 92.0%
同步后的本地构建,2026-11-14 23:29 至 2026-11-15 01:35 1 轮完成并提交报告,耗时 2 小时 5 分 14 秒 1 171 / 173 16,440,532 72,285 97.2%
  • 四轮产出报告的调查耗时 17 分 58 秒至 27 分 2 秒。带原调查链接的通知在结算后 22 至 82 秒写入 Bot 发件箱。一轮在模型步骤报错后失败,另一轮在重启恢复时结算为失败。
  • 同步后的调查于 01:35:12 结算。Bot 于 01:35:30 发出 1 条带原调查 Session 链接的通知,相隔约 18 秒,均为北京时间。
  • 同步后的 Worker 有 110 次 Shell 调用返回且没有工具级错误,其中 4 次由此前模型步骤启动的代码单元在后续步骤发起。这轮没有记录 agent_cell_origin_mismatch。
  • 三条慢查询分别检索近期媒体文件、广泛扫描本地文件和查找额度台账,从发起到返回合计 43 分 14 秒,时间互不重叠。Worker 调用了 32 次 wait,另有 10 次围绕同一个仓库修复核对提交、分支和工作树。本轮没有执行截止时间。
  • 输入包含缓存 token,表内用量按供应商实际返回的计数求和。较早构建的四个关联 Bot 执行另有 8 次模型尝试,记录到 891,165 输入和 4,413 输出 token。同步后发送通知的 Bot 执行另有 2 次模型尝试,记录到 224,778 输入和 1,202 输出 token。

重启后的后续观察

本次数据来自 macOS 本地集成构建 0cacbd4aa,观察窗口为 2026-11-15 20:05:33 至 2026-11-16 11:38:28(UTC+8),约 15 小时 33 分钟。在原有已授权工作区使用 Command Code / DeepSeek V4.1 Flash。该构建包含后来单独提交到 #6939 的 Shell 取消指引。采样时本机仍使用 #6728 更新前的记忆分页。

  • 启动 22 轮调查。 18 轮向 Bot 提交报告,3 轮失败,截点时 1 轮仍在运行。Bot 写入 15 条应用内消息,另有 3 份报告因重复此前的通知而未发送。
  • 已结算的 21 轮中位耗时 29 分 25 秒,最长 52 分 12 秒,有 10 轮超过 30 分钟调度间隔。3 轮失败后都释放了调查位,后续轮次正常启动。
模型请求来源 尝试次数 输入 token 缓存读取 其余输入 token 输出 token
调查 Worker 2,330 191,727,243 187,883,520 3,843,723 1,008,076
Bot 判读 35 6,502,118 4,302,336 2,199,782 16,963
Bot 辅助请求 15 2,944,430 2,938,880 5,550 1,574
合计 2,380 201,173,791 195,124,736 6,049,055 1,026,613

账本共记录 202,200,404 个输入和输出 token,缓存读取占已记录输入的 97.0%。14 次中断请求没有回传用量。

  • 失败原因。 两轮在模型流空闲超时后结束,适配器无法确认可安全重放或续接。一轮达到 8,000 输出 token 上限,exec 参数被截断,调查结果未提交。另有 12 次 TLS 握手中断通过重试恢复。
  • 工具等待。 2,005 次前台 Shell 调用中,37 次等了至少一分钟,其中 35 次未设置超时,最长 4 分 56 秒。31 次取消均确认清理。121 次模型请求发出的工具调用只有 wait。
  • 记忆检索与调查方向。 93 次带过滤条件的记忆查询中,有 37 次返回空页和下一页游标,并停在该页。18 份调查报告中有 15 份涉及同一个客户项目。上午有 4 轮核对该项目的定价、额度和交付口径,后续调查修正了先前的理解。其他方向包括销售跟进、采购窗口、发版故障和运维风险。

AI 使用说明

OpenAI Codex 协助完成实现、回归测试、本地验证及本说明起草。

检查清单

  • 测试覆盖本次改动,缺少相应实现时无法通过
  • 格式、类型检查和受影响套件在本地通过

本 PR 存在行为变化,已在概述中说明。

@github-actions github-actions Bot added the effort/XXL Over 2500 readable lines label Nov 10, 2026

@liugddx liugddx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated code review by Codex. I found two correctness issues and called them out inline. The focused workbench checks could not run because this environment is missing /opt/homebrew/opt/simdjson/lib/libsimdjson.33.dylib; Rust checks were unavailable because cargo is not installed.

@liugddx liugddx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review of head eb3758d29. I read the code only: nothing was built or run.

Summary: 8 inline findings, 2 × P1, 4 × P2 and 2 × P3. The two to fix before merging are (1) discovery workers now get the Bot's full permissions and nearly every tool, which contradicts the PR description and widens already-approved read-only plans on Resume, and (2) the quick launcher's draft save wipes persisted quotes.

Related, posted on #6728: this PR contains the same backend code as #6728, built on an older commit (9d1ca95f3, without fd69101c7). Backend findings are on #6728 only to avoid duplicates: the Recall scope split (records.rs), the unbounded list_discovery_memory loop, query matching serialized JSON, the Delivering → Stopping rewrite, external executors dropping quotes, queue paths for quote-only messages (including the desktop checks in SessionSurface.tsx:2881 and Conversation.tsx:3385), and the Stop exemption for BotWorker messages. Please re-check them once the two PRs are merged.


针对头提交 eb3758d29 的代码评审。只读了代码:没有构建,也没有运行。

摘要: 共 8 条行内意见:2 条 P1、4 条 P2、2 条 P3。合入前建议先处理两条:(1) 调查 worker 现在拿到 Bot 的完整权限和几乎全部工具,与 PR 描述矛盾,并且点 Resume 会放宽已批准的只读计划;(2) 快速启动器保存草稿时会清空已存的引用。

关联评审(发在 #6728): 本 PR 包含与 #6728 相同的后端代码,但基于更早的提交(9d1ca95f3,不含 fd69101c7)。为避免重复,后端问题只发在 #6728:Recall scope 不一致(records.rs)、list_discovery_memory 无界循环、query 匹配序列化 JSON、Delivering → Stopping 的改写、外部执行器丢弃 quotes、只有引用的消息在队列路径上的处理(含桌面端 SessionSurface.tsx:2881 和 Conversation.tsx:3385 的判断),以及对 BotWorker 消息的 Stop 豁免。两个 PR 合并后请再核对这些问题。

compaction_prompt: None,
applied_preset: None,
collaboration_mode: CollaborationMode::Agent,
tools: (!job.session_tools)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep unattended discovery workers read-only, or make the widening explicit at approval

With session_tools set (every new approval; dispatch.rs:193 writes session_tools: true on every Resume/Approve/Update), tools is None and permissions is the Bot's approved sandbox mode instead of permissions() (read-only). select_catalog_tools only excludes DiscoveryComplete, the context tool and the memory tool, so Shell, Write, MCP, SessionCreate, ScheduledTask and Recall/RecallMore stay available, even when the approval's frozen recall is false as long as the live setting is on. A ScheduledTask create with the default session target is active immediately and is not blocked for a worker. A worker that reads untrusted workspace or web content can therefore be steered into persistent automations, shell commands or writes.

This contradicts the PR description ("All investigating workers used read-only permissions" / "does not change … investigation permissions"), although the README documents the new behaviour. The prompt sentence "do not modify files or schedule more work" was removed, and the test that asserted the worker lacks ScheduledTask/Bash/SessionCreate now only forbids SendUser and sleep. In addition, because Resume/Approve rewrite session_tools: true, a plan approved under the read-only contract is widened simply by clicking "Resume discovery"; the permission notice only appears in the edit form (DiscoveryPanel.tsx:455).

Suggest keeping the read-only tool set and permissions for workers, or at least requiring explicit re-approval whenever the effective permissions widen, and showing the notice on Resume/Approve too.


[P1] 无人值守的调查 worker 应保持只读,或在批准时明确说明权限被放宽

设置了 session_tools 时(所有新批准的计划;dispatch.rs:193 在每次 Resume / Approve / Update 时都会写入 session_tools: true),tools 为 None,permissions 是 Bot 批准的沙箱模式,而不是 permissions()(只读)。select_catalog_tools 只排除 DiscoveryComplete、上下文工具和记忆工具,所以 Shell、Write、MCP、SessionCreate、ScheduledTask 以及 Recall/RecallMore 都可用;即使批准时冻结的 recall 是 false,只要实时设置是开的,Recall 也可用。默认 session 目标的 ScheduledTask 创建会立即生效,对 worker 也不拦截。读取了不可信的工作区或网页内容的 worker 因此可能被提示注入,去创建持久自动化、执行 shell 命令或写文件。

这与 PR 描述(「所有调查 worker 使用只读权限」/「不改变……调查权限」)矛盾,尽管 README 记录了新的行为。提示词里「不要修改文件或安排更多工作」这句被删掉了;原来断言 worker 没有 ScheduledTask / Bash / SessionCreate 的测试,现在只禁止 SendUser 和 sleep。另外,由于 Resume / Approve 会重写 session_tools: true,在只读约定下批准的计划,只要点一下「Resume discovery」就被放宽了权限;权限提示只出现在编辑表单里(DiscoveryPanel.tsx:455)。

建议 worker 继续使用只读的工具集和权限,或至少在有效权限放宽时要求显式重新批准,并在 Resume / Approve 上也展示该提示。

attachments: serde_json::from_str(row.try_get("attachments").map_err(error)?)
.map_err(error)?,
};
sqlx::query("INSERT INTO draft_quotes(owner,revision,quotes) VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET revision=excluded.revision,quotes=excluded.quotes")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] A draft save that omits quotes wipes the persisted quotes

save_draft always upserts draft_quotes with edit.quotes. DraftEdit.quotes is #[serde(default)] and the generated TS ClientDraftEdit.quotes is optional, so callers that don't know about quotes still compile and silently write []. QuickLauncher.tsx:573 (not part of this diff) is such a caller: saveDraft(session, draft.revision, { text, attachments }).

Effects: (1) a Bot draft with text plus quotes, or a "/command", loses its quotes after a launcher save. (2) The empty-draft test just above (line 569: draft.text === '' && draft.attachments.length === 0 && !text.startsWith('/')) ignores quotes, so for a quote-only draft the launcher calls props.open(sessionId, text); Conversation.takePrefill(false) is then called because stored.quotes.length > 0, the typed text is dropped, and the user sees "The draft changed before confirmation".

Suggest passing quotes: draft.quotes there and adding && !draft.quotes?.length to the test. To stop this from recurring, consider making quotes required in ClientDraftEdit, or leaving the stored quotes untouched when the field is absent.


[P1] 保存草稿时漏传 quotes 会清空已保存的引用

save_draft 总是用 edit.quotes 去 upsert draft_quotes。DraftEdit.quotes 是 #[serde(default)],生成的 TS ClientDraftEdit.quotes 是可选的,所以不了解引用的调用方仍能编译通过,并悄悄写入 []。QuickLauncher.tsx:573(不在本次差异中)就是这样的调用方:saveDraft(session, draft.revision, { text, attachments })。

影响:(1) 带文字加引用(或 "/command")的 Bot 草稿,经启动器保存后引用丢失。(2) 上面的空草稿判断(第 569 行:draft.text === '' && draft.attachments.length === 0 && !text.startsWith('/'))没有考虑引用,所以只有引用的草稿会走 props.open(sessionId, text);Conversation.takePrefill(false) 又因 stored.quotes.length > 0 被调用,输入的文字被丢弃,用户看到「草稿在确认前已变更」。

建议在那里传 quotes: draft.quotes,并在判断里加上 && !draft.quotes?.length。为避免再次发生,可以考虑把 ClientDraftEdit 的 quotes 改成必填,或在该字段缺省时保持已存引用不变。

initial = false;
if (rows[0]) await select(rows[0].id);
else await edit(true);
} else if (selected()) await readDetail(selected()!);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Don't let a failed detail refresh end the schedule subscription

readDetail(selected()!) runs inside the for (;;) of the outer try. It throws UiError('Discovery plan changed') when the task has no detail (lines 133-139), which is exactly what a plan deleted through the Bot's ScheduledTask tool looks like; a transient get failure, or a scheduler_page_changed error from discoveryTasks, ends the stream the same way. The catch only sets the error and leaves the loop, and finally closes the stream, so the dialog stops receiving live updates.

"Refresh" calls watch() again, but initial (declared at line 106, shared across calls) is already false, so the first page goes straight to readDetail(selected()) and throws again because selected is never cleared: Refresh cannot recover. Suggest handling errors from this refresh per page (clear selected/detail, show the error and keep looping), or falling back to select(rows[0]?.id) / edit(true) when the selected plan is gone.


[P2] 详情刷新失败不应终止计划订阅

readDetail(selected()!) 在外层 try 的 for (;;) 里执行。当任务没有 detail 时它会抛 UiError('Discovery plan changed')(133-139 行),而这正是计划被 Bot 的 ScheduledTask 工具删除后的表现;get 瞬时失败,或 discoveryTasks 抛出 scheduler_page_changed,也会以同样方式终止流。catch 只设置错误并退出循环,finally 随后关闭流,于是对话框不再收到实时更新。

「Refresh」会重新调用 watch(),但 initial(第 106 行声明,跨调用共享)已经是 false,所以第一页直接走 readDetail(selected()),而 selected 从未被清空,会再次抛错:Refresh 无法恢复。建议按页处理这次刷新的错误(清空 selected / detail、显示错误并继续循环),或在所选计划已不存在时回退到 select(rows[0]?.id) / edit(true)。

}[phase] as MessageKey;
if (current.pendingFire) return 'Discovery queued';
if (!current.approved) return 'Discovery needs approval';
return current.task.status === 'active' ? 'Discovery active' : 'Discovery paused';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Show completed/expired plans as such and disable Resume/Edit for them

state() here and the buttons at lines 482-496 only distinguish active from everything else. TaskStatus also has completed and expired, and a Bot-proposed once plan, or one with maxFires/expiresAt, becomes terminal after it fires. The dialog then says "Discovery paused" with next check "-", while "Resume discovery" and "Edit discovery plan" stay enabled; the server rejects them ("only paused tasks can resume" / "terminal task cannot be edited") and the user only sees a generic error. Automations.tsx already distinguishes expired and completed.

The panel itself only creates interval plans, so this affects plans created by the Bot.


[P2] 已完成 / 已过期的计划应如实显示,并禁用 Resume / Edit

这里的 state() 和 482-496 行的按钮只区分 active 与其他状态。TaskStatus 还有 completed 和 expired,Bot 提议的 once 计划,或带 maxFires / expiresAt 的计划,触发后就会进入终态。此时对话框显示「Discovery paused」、下次检查为「-」,而「Resume discovery」和「Edit discovery plan」仍可点击;服务端会拒绝(「only paused tasks can resume」/「terminal task cannot be edited」),用户只看到一个泛化的错误。Automations.tsx 已经区分了 expired 和 completed。

面板自己只会创建 interval 计划,所以这个问题影响的是 Bot 创建的计划。

Comment thread plugins/agent/composer/ui/Composer.tsx Outdated
>
<If when={owner !== null}>
<DraftAttachments draft={owner!.attachments} preview={owner!.previewImage} />
<Each of={owner?.quotes() ?? []}>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] CompactComposer needs the same quote handling as Composer

Quote chips and quote-aware guards are added here, but CompactComposer.tsx (not part of this diff; it is the pane the launcher shows for a Bot session) was not updated. Conversation restores stored.quotes into the shared quotes signal, but CompactComposer renders only attachment chips, so the quotes are invisible there and cannot be removed, while Enter → session.submit({ text }) → send(text) captures quotes() and sends them with the message. Its guard at line 66 (text.trim() === '' && session.attachments.files().length === 0) also ignores quotes, so a quote-only draft silently does nothing on Enter.

Suggest showing the chips (or calling expand() when session.quotes().length > 0) and including quotes in the empty check.


[P2] CompactComposer 需要与 Composer 一致的引用处理

这里新增了引用 chip 和识别引用的判断,但 CompactComposer.tsx(不在本次差异中;启动器里 Bot 会话显示的就是这个面板)没有同步。Conversation 会把 stored.quotes 恢复到共享的 quotes signal,但 CompactComposer 只渲染附件 chip,引用在这里不可见也无法删除;而按 Enter → session.submit({ text }) → send(text) 会读取 quotes() 并随消息发出。第 66 行的判断(text.trim() === '' && session.attachments.files().length === 0)同样没算引用,所以只有引用的草稿按 Enter 什么也不会发生。

建议显示引用 chip(或在 session.quotes().length > 0 时调用 expand()),并把引用计入「是否为空」的判断。

};
};
const readDetail = async (id: string, fill = false) => {
const ticket = ++generation;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Give form filling its own ticket so a watch refresh can't supersede it

readDetail bumps the shared generation on every call and returns early when its ticket is stale (lines 132 and 142). Only select() passes fill=true (line 157) to populate intent/minutes. If a schedule-watch update arrives while select() is awaiting (a fire claimed or settled, any plan change), the watch loop's readDetail(selected()!) (line 215, fill=false) takes the newer ticket: select()'s call returns without filling, and the winning call does not fill either. The form keeps intent='' / minutes='30' (or the previous plan's values), and a later Save makes discoveryInput see 30 minutes differing from the stored interval, so it replaces the schedule with a 30-minute interval and clears the direction.

I have not reproduced this; delaying host.query('agent', 'schedules', { kind: 'get' }) and emitting a watch page during it should show it. Suggest carrying fill over to the winning call (e.g. remember a pending fill), or keeping the fill under select()'s own formGeneration ticket.


[P2] 表单填充应使用独立的 ticket,避免被 watch 刷新顶掉

readDetail 每次调用都会递增共享的 generation,ticket 过期就提前返回(132 和 142 行)。只有 select() 会传 fill=true(157 行)来填充 intent / minutes。如果 select() 在 await 期间收到一次计划 watch 更新(某次触发被领取或结算,或计划有任何变化),watch 循环里的 readDetail(selected()!)(215 行,fill=false)会拿到更新的 ticket:select() 的那次调用不填充就返回,而胜出的调用也不填充。表单于是保持 intent='' / minutes='30'(或上一个计划的值),之后点保存,discoveryInput 会发现 30 分钟与已存间隔不同,把计划改成 30 分钟间隔并清空方向说明。

尚未复现;可以延迟 host.query('agent', 'schedules', { kind: 'get' }) 并在此期间推送一页 watch 来验证。建议把 fill 传递给胜出的那次调用(例如记住待填充状态),或让填充使用 select() 自己的 formGeneration ticket。

intent(),
Number(minutes()),
Date.now(),
'UTC',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Resolve the timezone instead of hard-coding 'UTC'

discoveryInput(..., 'UTC', current) stores timezone: existing?.timezone ?? timezone. dispatch_discovery passes plan.timezone to context::environment and report_message, which tell the model "Current time: …+00:00" and to "judge urgency against this time and use explicit dates and times in the notification". For a UTC+8 user, the worker and the Bot notification therefore judge "today" and deadlines against UTC clock times. The instant is right and interval cadence is not zone-sensitive, but dates and times in notifications will be in the wrong zone.

Automations.tsx already uses new Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'. Only new plans are affected, because edits keep existing.timezone.


[P3] 应解析本地时区,而不是写死 'UTC'

discoveryInput(..., 'UTC', current) 会存入 timezone: existing?.timezone ?? timezone。dispatch_discovery 把 plan.timezone 传给 context::environment 和 report_message,它们会告诉模型「Current time: …+00:00」,并要求「按此时间判断紧急程度,通知里使用明确的日期和时间」。因此对 UTC+8 的用户,worker 和 Bot 通知会按 UTC 时刻判断「今天」和截止时间。时刻本身是对的,interval 周期也与时区无关,但通知里的日期和时间会落在错误的时区。

Automations.tsx 已经用 new Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'。只有新建的计划受影响,因为编辑会沿用 existing.timezone。

)}
{action('Edit discovery plan', () => void edit(false), !!detail()!.pendingFire)}
</View>
<If when={!!(detail()?.investigation?.sessionId || last()?.sessionId)}>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] "Open investigation" opens the previous fire's worker while the current fire is queued

discovery_status builds investigation with job.execution.as_ref()? for both session_id and turn_id, so it is None until the worker run is delivered or DiscoveryComplete writes the result. The panel then falls back to last()?.sessionId, which is the previous fire's worker Session (the worker id is derived per fire). While the panel says "Discovery queued", the button therefore opens an older investigation. session_id equals job.worker and is known when the job is created, so it need not wait for execution.

Also, the PR description says publications link to "the original worker Session and Turn", but DiscoveryPublication.worker_turn_id (contract/bot.rs) and ScheduledInvestigation.turn_id have no consumer: openWorker → openSessionBeside/openSessionHere only take a sessionId, so the Turn link is not implemented.


[P3]「Open investigation」在当前触发仍在排队时会打开上一次触发的 worker

discovery_status 用 job.execution.as_ref()? 同时生成 session_id 和 turn_id,所以在 worker 运行被投递、或 DiscoveryComplete 写入结果之前,investigation 都是 None。面板随后回退到 last()?.sessionId,也就是上一次触发的 worker Session(worker id 按每次触发派生)。因此当面板显示「Discovery queued」时,这个按钮打开的是更早的一次调查。session_id 等于 job.worker,在创建 job 时就已知,不必等 execution。

另外,PR 描述说发布内容会链接到「原始 worker Session 和 Turn」,但 DiscoveryPublication.worker_turn_id(contract/bot.rs)和 ScheduledInvestigation.turn_id 都没有使用方:openWorker → openSessionBeside / openSessionHere 只接收 sessionId,所以 Turn 链接并未实现。

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found one P2 in the new Discovery test fixture at 3371058fb32c97bc0a53ba5cce0e4abf97082ea1: forcing Asia/Shanghai through the native Intl.DateTimeFormat makes the Workbench regression test fail on runners whose device time zone differs.

I checked the original Ubuntu job log, which ran merge commit d92c86619f8747014a44b424d3868533382b3630 (second parent: this head). The Workbench suite reports 112 passed and 1 failed; discovery_panel_approves_scope_controls_runs_and_rejects_stale_edits throws Invalid time zone specified: Asia/Shanghai when opening DiscoveryDialog. The fixture and the native formatter's zone validation are identical in that merge and the PR head. The formatter supports the device's zone, UTC and fixed offsets; wrapping its constructor does not change the native device zone.

This is a scoped CI follow-up, not a complete review of the 86-file PR. I did not run Rust or a native application locally. My earlier checks using Node's full Intl implementation do not validate this native fixture.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

const systemTimezone = 'Asia/Shanghai';
Intl.DateTimeFormat = new Proxy(Intl.DateTimeFormat, {
construct(formatter, [locale, options]) {
return new formatter(locale, { timeZone: systemTimezone, ...options });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid forcing an unsupported named zone into native Intl

This proxy passes Asia/Shanghai to the real native formatter without changing the device's time zone. On the Ubuntu runner, opening DiscoveryDialog therefore throws instead of reaching the approval/control assertions. The original job 133341250493 confirms this exact failure, and nsh-js/src/web/format/mod.rs::zone_option only accepts the device zone, UTC or fixed offsets. Use a supported deterministic offset (and update the fixture's expected scheduling zone consistently), or configure/mock the device zone through the native test mechanism rather than forwarding an arbitrary IANA name to the native constructor.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the incremental change from 3371058fb32c97bc0a53ba5cce0e4abf97082ea1 to 765e5519c471816811b151c5049c04de6f9d3a18. It changes only the Discovery fixture's systemTimezone from Asia/Shanghai to +08:00.

This addresses the cause of my previous P2: the native formatter explicitly accepts fixed offsets through fixed_zone / parse_offset, and the fixture's scheduling-zone assertion uses the same systemTimezone constant. The expected UTC+8 clock values remain consistent. I withdraw that finding for this head.

This is source verification of that one fix. I did not rerun Rust or the native Workbench test locally, and the new hosted CI run is still in progress. It is not a complete review of the 86-file PR or a claim that all checks pass.


Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.

@liugddx

liugddx commented Nov 17, 2026

Copy link
Copy Markdown
Member

Follow-up on my earlier review (head eb3758d29), re-checked against the current head 765e5519c. I read the code only: nothing was built or run.

Summary: 7 of my 8 inline findings are resolved, 1 is partly resolved, and 2 smaller points remain. The remaining blocker is that CI is red on the current head.

Earlier finding Status at 765e5519c
Worker permissions widened silently (P1) Largely addressed. The plan now carries an explicit worker_tools (read-only or session tools), the panel shows it, and Resume no longer rewrites it. New plans still default to session tools, i.e. the Bot's full permissions; please confirm that default is intended.
Launcher draft save wiped quotes (P1) Resolved. quotes is passed and the empty-draft check counts them.
Detail refresh failure ended the subscription Resolved. Errors are handled per page.
Completed/expired plans shown as paused Resolved. Status text and buttons distinguish them.
CompactComposer and quotes Partly resolved. The send guard, queue command and composer occupancy now count quotes, but CompactComposer still shows no quote chips, so quotes it cannot display or remove are still sent with the message.
Form fill superseded by a watch refresh Resolved. readDetail no longer fills the form.
Hard-coded 'UTC' Resolved. The system time zone is used.
"Open investigation" opened the previous fire's worker Resolved. While a fire is queued the button now reads "Open previous investigation".

Still open

  1. PR description: it still says "does not change … investigation permissions" and "All investigating workers used read-only permissions", which no longer matches the default above. Please update it.
  2. CI is red on both heads. On 765e5519c: nsh, native-macos, native-windows, both root-tests slices and the aggregate test. feat(assistant): retain bounded discovery records and feedback #6728 (a1bb6b295) fails native-macos, native-windows and test. I only looked at which steps failed, not at the failing tests, so I can't say whether they come from this PR. Please rerun and note the diagnosis, as requested earlier on feat(assistant): retain bounded discovery records and feedback #6728.

The backend findings I posted on #6728 (Recall scope, list/query bounds, external-executor quotes, queue paths, Stop exemption, delivered-report ordering) also look resolved in the code now included here, but I have not re-run any tests for them.


对我之前评审(头提交 eb3758d29)的跟进,已按当前头提交 765e5519c 重新核对。只读了代码:没有构建,也没有运行。

摘要: 我之前的 8 条行内意见中,7 条已解决,1 条部分解决,另有 2 个较小的遗留点。目前剩下的阻塞项是当前头提交的 CI 仍是红的。

之前的问题 765e5519c 上的状态
worker 权限被悄悄放宽(P1) 基本解决。计划现在带有明确的 worker_tools(只读或会话工具),面板会展示,Resume 不再改写它。新建计划默认仍是会话工具,即 Bot 的完整权限,请确认这个默认值是有意为之。
启动器保存草稿时清空 quotes(P1) 已解决。quotes 会传,空草稿判断也算上了引用。
详情刷新失败终止订阅 已解决。错误按页处理。
已完成 / 已过期计划显示为暂停 已解决。状态文案和按钮都做了区分。
CompactComposer 与引用 部分解决。发送判断、queue 命令和输入框占用判断都已计入引用,但 CompactComposer 仍不显示引用 chip,用户看不到也删不掉的引用仍会随消息发出。
表单填充被 watch 刷新顶掉 已解决。readDetail 不再负责填表。
时区写死 'UTC' 已解决。改用系统时区。
「Open investigation」打开上一次触发的 worker 已解决。当前触发排队时,按钮显示「Open previous investigation」。

仍未解决

  1. PR 描述: 仍写着「不改变……调查权限」和「所有调查 worker 使用只读权限」,与上面的默认值不一致,请更新。
  2. 两个头提交的 CI 都是红的。 765e5519c 上失败的有:nsh、native-macos、native-windows、两个 root-tests 分片和汇总的 test。feat(assistant): retain bounded discovery records and feedback #6728(a1bb6b295)失败的有 native-macos、native-windows 和 test。我只看了失败的步骤,没有看具体用例,所以无法判断是否由本 PR 引起。请重跑并写明诊断,这是此前在 feat(assistant): retain bounded discovery records and feedback #6728 上就提过的要求。

我之前发在 #6728 上的后端意见(Recall 范围、list / query 的范围限制、外部执行器的引用、队列路径、Stop 豁免、已投递报告的处理顺序),在这里包含的代码里看起来也都解决了,但我没有为它们跑任何测试。

@liugddx liugddx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second review pass on head 765e5519c, after the fixes pushed on 11-16. I read the code only: nothing was built or run. None of these repeat my earlier comments.

Summary: 5 inline findings, 2 × P1, 2 × P2 and 1 × P3. The two P1s are about discovery plan authority: the Bot's resume can override a user pause, and Bot-proposed plans are always created with full Session tools. The discovery.rs finding rests on a premise I have not confirmed, and says so.

The backend files are shared with #6728, so findings 1-4 apply to its code as well; I have posted them here only, to avoid duplicates.


针对头提交 765e5519c 的第二轮评审,基于 11-16 推送的修复。只读了代码:没有构建,也没有运行。这些意见与我之前的评论都不重复。

摘要: 共 5 条行内意见:2 条 P1、2 条 P2、1 条 P3。两条 P1 都与调查计划的权限有关:Bot 的 resume 能覆盖用户的暂停,Bot 提议的计划总是以完整的会话工具创建。discovery.rs 那条依赖一个我没有核实的前提,评论里已写明。

这些后端文件与 #6728 共用,所以前 4 条同样适用于它的代码;为避免重复,我只发在这里。

}
};
self.validate_background(&basis).await?;
Some(saved.plan.resume(now() as i64).map_err(reason)?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] The Bot's resume re-activates a discovery plan the user paused, without a fresh approval

For Approval::Discovery this path only runs prepare_approved_background and then plan.resume(..). pause_plan keeps plan.authorization, so after the user pauses an approved plan from the panel, the Bot can call ScheduledTask resume and the plan goes Active and fires again, using the stored approval. The check at the top of the branch only rejects plans that have no authorization at all (scheduler_user_approval_required). The plan may run with the Bot's full Session tools (see the comment on line 285), so a model-initiated resume overrides an explicit user pause on a high-authority plan. (A pause the user made from the desktop panel is not distinguishable here from one the Bot made.)

I have confirmed the code path by reading; I have not checked whether the desktop UI is meant to treat Resume as a re-approval, which would make this inconsistent with it. Suggest rejecting resume from the Bot tool for Approval::Discovery plans (return scheduler_user_approval_required), or recording who paused the plan and only allowing the Bot to resume its own pause.


[P1] Bot 的 resume 会在没有重新批准的情况下,恢复用户已暂停的调查计划

对 Approval::Discovery,这条路径只做 prepare_approved_background,然后调用 plan.resume(..)。pause_plan 会保留 plan.authorization,所以用户在面板里暂停一个已批准的计划后,Bot 调用 ScheduledTask 的 resume 就能让计划回到 Active 并再次触发,沿用的是之前存下的批准。分支开头的检查只拒绝完全没有 authorization 的计划(scheduler_user_approval_required)。这类计划可能以 Bot 的完整会话工具运行(见第 285 行的评论),所以模型发起的 resume 会覆盖用户明确做出的暂停,而且对象是高权限的计划。(这里也区分不出是用户在桌面面板暂停的,还是 Bot 自己暂停的。)

代码路径是我读代码确认的;我没有核实桌面端是否本意把 Resume 当作重新批准,如果是,这里就与它不一致。建议对 Approval::Discovery 的计划,Bot 工具的 resume 直接拒绝(返回 scheduler_user_approval_required),或者记录是谁暂停的,只允许 Bot 恢复自己暂停的计划。

target: target.clone(),
model: model.clone(),
thinking_level,
worker_tools: DiscoveryWorkerTools::Session,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] A Bot-proposed discovery plan is always created with worker_tools: Session

When the model calls ScheduledTask create with effect: discovery, the plan is hard-coded to DiscoveryWorkerTools::Session; the Bot cannot choose read-only. When the user approves it, the unattended worker runs with the Bot's full read/write permissions and tools. The panel does show a permission notice before approval, but the plan's title and intent come from the model, so what the Bot says the plan will do is not a reliable signal of what it can do. This is the opposite of the earlier read-only contract.

Suggest creating Bot-proposed plans as read-only by default, and letting the user opt in to session tools in the panel when approving (the panel already has the selector).


[P1] Bot 提议的调查计划总是以 worker_tools: Session 创建

模型调用 ScheduledTask 创建 effect: discovery 时,计划被写死为 DiscoveryWorkerTools::Session,Bot 无法选择只读。用户批准后,无人值守的 worker 会以 Bot 的完整读写权限和工具运行。面板在批准前确实会显示权限提示,但计划的标题和意图由模型生成,所以 Bot 描述的计划内容,并不能可靠地反映它实际能做什么。这与此前「只读」的约定相反。

建议 Bot 提议的计划默认创建为只读,由用户在面板批准时自行选择是否开启会话工具(面板里已经有这个选项)。

compaction_prompt: None,
applied_preset: None,
collaboration_mode: CollaborationMode::Agent,
tools: (!job.session_tools)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] In session-tools mode the worker is created with tools: None, not the Bot session's own tool set

tools: (!job.session_tools).then(..) gives the worker None, i.e. the full catalog, and permissions are copied from the target. It does not inherit the Bot session's configuration.tools. If the Bot session restricts its own tools, an approved discovery worker can still use tools the Bot itself does not have (ScheduledTask, goals, subagents), and the old prompt line "do not schedule more work or expand permissions" was removed.

I have confirmed the tools: None code by reading; I have not confirmed that a Bot session can have a restricted tool set in practice, so please check that premise. If it can, suggest intersecting the worker's tools with the Bot session's tools.


[P2] 会话工具模式下,worker 以 tools: None 创建,没有沿用 Bot 会话自己的工具集

tools: (!job.session_tools).then(..) 给 worker 的是 None,也就是完整的工具目录,permissions 则从目标复制。它没有继承 Bot 会话的 configuration.tools。如果 Bot 会话限制了自己的工具,被批准的调查 worker 仍可使用 Bot 自己没有的工具(ScheduledTask、目标、子代理),而原来的提示词「不要安排更多工作或扩大权限」也被删掉了。

tools: None 这部分是我读代码确认的;「Bot 会话实际上可以限制工具集」这个前提我没有核实,请先确认。如果成立,建议让 worker 的工具集与 Bot 会话的工具集取交集。

);
text.push('\n');
}
text.push_str(&quote.text);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Escape quote text and label, not just the provenance

The provenance JSON is escaped (<, >, &), but quote.text is appended as-is, and label only has " replaced. A quote whose text contains </quoted_excerpt> followed by instructions (for example text the Bot echoed from a web page) closes the excerpt early, and everything after it sits outside the quoted block as if the user had typed it. A label containing > or a newline breaks the opening tag in the same way. The ACP driver and external executors now build their prompts with this helper too, so the exposure is wider than before.

The text comes from what the user selects in a Bot reply, not from arbitrary callers, so I rate it P2. Suggest escaping </>/& in both the label and the text (or neutralizing only a literal </quoted_excerpt), and adding a test with a closing tag in the quote.


[P2] 引用正文和 label 也需要转义,不只是来源信息

来源 JSON 做了转义(<、>、&),但 quote.text 是原样拼接的,label 也只替换了 "。如果引用正文里含有 </quoted_excerpt> 加后续指令(例如 Bot 回显的网页内容),摘录会被提前关闭,后面的内容就像用户亲手输入的一样处于引用块之外。label 里含 > 或换行也会以同样方式破坏开始标签。ACP 驱动和外部执行器现在也用这个函数拼 prompt,所以暴露面比以前更大。

引用文字来自用户在 Bot 回复中选中的内容,不是任意调用方传入的,所以我定为 P2。建议对 label 和正文都转义 < / > / &(或只处理字面的 </quoted_excerpt),并补一个引用里含结束标签的测试。

mentions: serde_json::from_str(row.try_get("mentions").map_err(error)?).map_err(error)?,
reply_to: row.try_get("reply_to").map_err(error)?,
};
sqlx::query("INSERT INTO draft_quotes(owner,revision,quotes) VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET revision=excluded.revision,quotes=excluded.quotes")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Skip the draft_quotes write when there are no quotes

Every draft autosave now runs this upsert, even when the draft has no quotes and there is no existing draft_quotes row, and when quotes is omitted it first does an extra SELECT (lines 308-316). save_draft runs on each debounced edit, so this adds a write per keystroke batch inside the SQLite transaction for the common case of a draft without quotes. The write-cost figure is my estimate, not a measurement.

Suggest writing only when the quotes are non-empty or a row already exists, and deleting the row when they become empty.


[P3] 没有引用时可以跳过 draft_quotes 的写入

现在每次草稿自动保存都会执行这条 upsert,即使草稿没有引用、也没有已存的 draft_quotes 行;quotes 缺省时还会先多做一次 SELECT(308-316 行)。save_draft 在每次防抖后的编辑都会运行,所以对最常见的「没有引用的草稿」,会在 SQLite 事务里多出一次写入。写入成本翻倍是我的估计,不是实测。

建议只在引用非空、或已存在对应行时才写入,引用变空时删除该行。

M4n5ter

This comment was marked as outdated.

@M4n5ter
M4n5ter dismissed their stale review November 17, 2026 05:40

Switching to review comment

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

Stack Consolidation (#6724 / #6728 / #6730)

#6724 (68c63b5d8) is a strict ancestor of #6728 (f0d09f19f), which is a strict ancestor of #6730 (8ac260577), and 22 of the 29 files touched in #6724 were already rewritten in #6728 / #6730. Please consolidate this stack into #6730 (rebased onto current rust-preview) and close #6724 and #6728 instead of rebasing and merging three overlapping slices.

(Note: the failing nsh check on #6730 is rich_editor::* in third-party/nsh and is unrelated to this PR.)


Blocking Issues (Correctness & Authority)

  1. ReadOnly discovery workers do not get the Read tool (and miss RecallMaterial)

    • plugins/agent/native/src/tools.rs:378-382 builds discovery_reads by matching maka.workspace.Files bindings against "readText" | "readImage" | "glob" | "grep". However, plugins/workspace/api/src/files.rs:60-68 unified file reading onto "read", so discovery_reads is always empty. A read_only worker currently gets zero workspace file tools (["DiscoveryComplete", "DiscoveryMemory"], plus Recall / RecallMore / DiscoveryContext when Recall is on).
    • plugins/agent/native/src/owner/discovery.rs:457 also omits "RecallMaterial" when Recall is enabled.
  2. Unsafe default (Session instead of ReadOnly) and parent tool-ceiling bypass

    • DiscoveryWorkerTools marks #[default] ReadOnly in plugins/agent/api/src/contract/scheduler.rs:58-63, yet plugins/agent/native/src/owner/scheduler/tools.rs:395-397, products/maka/workbench/app/discoveryCore.ts:61, and products/maka/workbench/app/DiscoveryPanel.tsx:107, 186 all default new plans to Session (full Bot write/shell capabilities). Unattended background discovery should default to ReadOnly across contract, tool schema, and UI.
    • In plugins/agent/native/src/owner/discovery.rs:728-729, session_tools == true sets tools: None (all tools in the global catalog) instead of inheriting/intersecting source.configuration.tools from the parent Bot session. A Bot session explicitly restricted to ["Read", "ScheduledTask"] still spawns a discovery worker with Write, Recall*, etc.
  3. Desktop Approve / Resume breaks after any Bot permission or boundary_revision change, and plans cannot be deleted

    • products/maka/workbench/app/DiscoveryPanel.tsx:262-275, 604-611 sends { kind: 'approve' | 'resume', taskId, revision } without capturing/updating effect.target or model, and snapshot() (DiscoveryPanel.tsx:348-352) displays the stale stored task.effect in view mode rather than the live Bot target/model. Whenever the user grants a runtime permission in Bot chat (boundary_revision increments) or changes Bot permissions/workspace/binding after a proposal is created or paused, prepare_schedule_grant (plugins/agent/native/src/owner/scheduler.rs:422-440) rejects Approve / Resume with scheduler_authorization_changed.
    • ScheduleRead::List (plugins/agent/native/src/owner/scheduler.rs:306-314) hides Discovery plans from Automations.tsx, while DiscoveryPanel.tsx has no delete action at all. Worse, DiscoveryPanel.tsx:236 auto-selects !plan.approved && plan.status === 'paused' on open, so a single declined proposal can never be removed and permanently hijacks the panel's initial view.
  4. DiscoveryMemory scope hashing causes infinite background Outcome::Blocked loops and wipes memory/feedback on routine state changes

    • plugins/agent/native/src/owner/discovery/records.rs:208-215, 543-559 hashes the entire (ScheduledTarget, recall)—including boundary_revision, permissions, and recall—into the KV prefix discovery/memory/{scope}/..., and discovery.rs:472 blocks runs when job.recall != self.discovery_recall_enabled().
    • Infinite blocked loop: Toggling Recall or bumping boundary_revision / permissions leaves active recurring plans in status = "active", while plan.settle (plugins/agent/scheduler/engine/src/plan.rs:274-290) keeps advancing next_fire_at on every Outcome::Blocked forever without pausing the plan or surfacing a re-approval state.
    • Memory amnesia & broken quoted feedback: Any boundary_revision increment, permission change, or Recall toggle changes scope, orphaning 100% of existing DiscoveryMemory keys in SQLite KV, resetting visible memory to [] (causing dismissed findings to be re-notified), and breaking DiscoveryMemory { action: "feedback" } (discovery_record_unavailable) when quoting a finding published right before the change. Memory scope should bind to stable identity (bot_session_id, workspace, binding), not boundary_revision, permissions, or recall.

Architecture, #6958 Alignment & Pre-Release Compatibility Policy

  1. Align with #6958 on rust-preview instead of inventing parallel session/source readers

    • #6958 already landed cross-session discovery and reading via SessionList + Read("maka://session/<id>"), along with render_quotes / render_session_references.
    • Remove DiscoveryContext (plugins/agent/native/src/owner/discovery/context.rs, which duplicates SessionList + Read("maka://session/...") and is even exposed alongside Session* tools in session mode), as well as custom NotificationSource / FeedbackSource pagination (records.rs:634-643 currently slices serialized JSON strings by 4096-char offsets). Store canonical session/message references and reuse the platform Read / Session* primitives.
    • When rebasing onto #6958 (plugins/agent/facts/src/input/references.rs, plugins/agent/engine/src/history/references.rs, plugins/agent/native/src/executor/external/attachments.rs), fold #6730's XML entity escaping (append_escaped_quote) into #6958's maka_agent_facts::input::render_quotes and preserve render_session_references.
  2. Remove all backwards-compatibility shims and dual-table workarounds

    • Maka has not had an official release yet; we do not guarantee on-disk or wire backwards compatibility in production code during pre-release development (only developers hit local format changes). Do not add compatibility tables, fallback decoders, or serde default shims—if migrating existing local dev state is useful, just attach a Python migration script Gist in the PR body.
    • Specifically, please strip:
      • Separate draft_quotes table/migration (products/maka/client/migrations/202611100001_draft_quotes.sql), LEFT JOIN draft_quotes, dual writes/deletes in products/maka/client/src/journal.rs & journal/write.rs, and pre_quote_journal_upgrade_* plumbing—store quotes directly on drafts alongside attachments, mentions, and reply_to.
      • legacy_tools / legacy_discovery_tools (discovery.rs:166, 454, send.rs:206, driver_assembly.rs:96, scheduler/dispatch.rs:69).
      • SubmittedNotes::Encoded(String) stringified-JSON fallback (discovery.rs:46-63).
      • #[serde(default)] shims and nil-UUID DiscoveryAuthority::default() (plugins/agent/api/src/contract/scheduler.rs:58-85), legacy phase comments, etc. Make required fields explicit in types.
  3. Do not hold scheduler and session run locks across sequential KV reads

    • plugins/agent/native/src/owner/discovery/records.rs:516-535, 369-382 holds both global scheduler.gate and the Bot's runs.ordered(source) mutex while executing read-only List (up to 64 sequential single-key KV reads across SEARCH_WINDOW = 32), Get, NotificationSource, and FeedbackSource. Snapshot the required metadata briefly and perform storage reads outside those locks.

Test Suite Overhaul

  • Delete plugins/agent/native/src/owner/scheduler/storage_fault.rs (plus the #[cfg(test)] storage type swap in scheduler.rs / repository.rs that pattern-matches internal JSON fields and key prefixes) and trim the 2,198-line white-box recovery matrix in plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs + trivial match-arm tests (discovery.rs:1071).
  • Note that Fixture in model_recovery/discovery.rs initialized "tools": [] without binding real maka.workspace.Files (Read), which is why 2,200 lines of tests completely missed ReadOnly workers lacking Read, while encoding broken behavior (discovery_enabling_recall_requires_a_new_approval_before_writing_memory). Replace them with concise end-to-end behavioral tests wired to real tool bindings.
简体中文

PR 合并与收敛建议(#6724 / #6728 / #6730)

#6724(68c63b5d8)是 #6728(f0d09f19f)的严格祖先,#6728 又是 #6730(8ac260577)的严格祖先,且 #6724 改动的 29 个文件里有 22 个已经在 #6728 / #6730 中被重写。建议直接基于最新 rust-preview 在 #6730 中收敛合并整组改动,关闭 #6724 和 #6728,不要再分三个重叠的 PR 反复 rebase。

(注:目前 #6730 上挂掉的 nsh CI 来自 third-party/nsh 的 rich_editor::*,与本 PR 无关。)


阻塞性问题(正确性与权限边界)

  1. ReadOnly 模式的 worker 拿不到 Read 工具(且漏掉了 RecallMaterial)

    • plugins/agent/native/src/tools.rs:378-382 在收集 discovery_reads 时匹配的是 maka.workspace.Files 的 "readText" | "readImage" | "glob" | "grep";但 plugins/workspace/api/src/files.rs:60-68 早已把文件读取统一收敛成了 "read",导致 discovery_reads 恒为空。read_only worker 实际上没有任何工作区读文件工具(不开 Recall 时只有 ["DiscoveryComplete", "DiscoveryMemory"])。
    • plugins/agent/native/src/owner/discovery.rs:457 在开启 Recall 时只注入了 ["Recall", "RecallMore", "DiscoveryContext"],漏掉了 "RecallMaterial"。
  2. 默认权限过宽(默认成了 Session 而非 ReadOnly),且 session 模式绕过了父会话的工具上限

    • plugins/agent/api/src/contract/scheduler.rs:58-63 里 DiscoveryWorkerTools 标了 #[default] ReadOnly,但 plugins/agent/native/src/owner/scheduler/tools.rs:395-397、products/maka/workbench/app/discoveryCore.ts:61 和 products/maka/workbench/app/DiscoveryPanel.tsx:107, 186 创建新计划时全都默认给了 Session(完整写文件/执行命令权限)。后台无人值守的巡检任务在协议、工具缺省值和前端都应默认 ReadOnly。
    • plugins/agent/native/src/owner/discovery.rs:728-729 在 session_tools == true 时直接传了 tools: None(放开全局工具目录),无视了父 Bot 会话上的 source.configuration.tools 限制——即使父 Bot 只被允许用 ["Read", "ScheduledTask"],派生出的 worker 依然能拿到 Write、Recall* 等越权工具。
  3. 桌面端在 Bot 发生过任何权限变更或 boundary_revision 递增后无法 Approve / Resume,且没有任何删除入口

    • products/maka/workbench/app/DiscoveryPanel.tsx:262-275, 604-611 在 Approve / Resume 时只发了 { kind: 'approve' | 'resume', taskId, revision },没有携带/更新当前 Bot 的 effect.target 和 model;snapshot()(DiscoveryPanel.tsx:348-352)在只读态下展示的也是旧的 task.effect。只要用户在提案创建或暂停后在 Bot 聊天里点过一次运行时授权(导致 boundary_revision 自增),或改过权限/工作区/模型绑定,prepare_schedule_grant(plugins/agent/native/src/owner/scheduler.rs:422-440)就会直接报 scheduler_authorization_changed 拒绝操作。
    • ScheduleRead::List(plugins/agent/native/src/owner/scheduler.rs:306-314)把 Discovery 任务从 Automations.tsx 过滤掉了,而 DiscoveryPanel.tsx 又没有提供 delete 操作;再加上 DiscoveryPanel.tsx:236 每次打开面板都会优先自动选中 !plan.approved && plan.status === 'paused' 的提案,一旦用户不想批准某个 Bot 提案,它既删不掉,还会永久霸占面板默认视图。
  4. DiscoveryMemory 的 scope 摘要算法导致后台 Outcome::Blocked 死循环,且常规状态变化会清空全部记忆与反馈

    • plugins/agent/native/src/owner/discovery/records.rs:208-215, 543-559 把完整的 (ScheduledTarget, recall)(包含 boundary_revision、permissions、recall)做哈希拼进 KV 前缀 discovery/memory/{scope}/...,同时 discovery.rs:472 在 job.recall != self.discovery_recall_enabled() 时拦截执行。
    • 后台静默空转:开关 Recall 或变更 boundary_revision / 权限后,已激活的周期计划仍保持 status = "active",plan.settle(plugins/agent/scheduler/engine/src/plan.rs:274-290)每次收到 Outcome::Blocked 都会继续推进 next_fire_at 无限轮询,既不会自动暂停,也没有明确的重授权状态。
    • 记忆失忆与引用反馈失效:只要 boundary_revision 自增、权限调整或切换 Recall,scope 哈希就会改变,之前写入 SQLite KV 的 DiscoveryMemory 记录全部变成孤儿数据——不仅记忆列表重置为空(已忽略的话题会被重复打扰),用户引用刚发布的通知提交反馈时也会因新 scope 下查不到记录直接报错 discovery_record_unavailable。Memory 的路由身份应绑定稳定的 (bot_session_id, workspace, binding),不应耦合 boundary_revision、permissions 或 recall。

架构对齐(#6958)、锁粒度与未发版兼容性策略

  1. 对齐 rust-preview 上的 #6958,删掉重复造轮子的会话/来源读取工具

    • #6958 已经在主干落地了通用的跨会话检索与读取能力(SessionList + Read("maka://session/<id>"))以及统一的 render_quotes / render_session_references。
    • 请删掉专用的 DiscoveryContext(plugins/agent/native/src/owner/discovery/context.rs,它和 SessionList + Read("maka://session/...") 能力重复,甚至在 session 模式下与 Session* 工具同时暴露给模型),以及自定义的 NotificationSource / FeedbackSource 分页(records.rs:634-643 甚至是对序列化后的 JSON 字符串按 4096 字符硬切片)。通知与反馈直接记录标准会话/消息引用并复用现有平台原语即可。
    • Rebase 到 #6958 解决 plugins/agent/facts/src/input/references.rs、plugins/agent/engine/src/history/references.rs、plugins/agent/native/src/executor/external/attachments.rs 冲突时,请把本 PR 的 XML 转义逻辑(append_escaped_quote)合入 #6958 的 maka_agent_facts::input::render_quotes,并保留 render_session_references。
  2. 清理所有向后兼容兜底与双表妥协(当前阶段不承诺旧数据兼容)

    • 目前项目尚未正式发版,开发期间我们不保证旧数据/旧协议兼容性(只有开发者本地会碰到格式演进)。业务代码里严禁预埋兼容层、双表迁移或反序列化兜底;如果确实需要迁移本地开发数据,写个 Python 脚本放到 Gist 并贴在 PR body 里即可。
    • 请直接删掉以下兼容包袱:
      • 独立的 draft_quotes 表及迁移(products/maka/client/migrations/202611100001_draft_quotes.sql)、LEFT JOIN draft_quotes、products/maka/client/src/journal.rs 与 journal/write.rs 中的双写/双删逻辑,以及 pre_quote_journal_upgrade_* 升级兼容代码——直接像 attachments、mentions、reply_to 一样把 quotes 合进 drafts 表结构。
      • legacy_tools / legacy_discovery_tools(discovery.rs:166, 454、send.rs:206、driver_assembly.rs:96、scheduler/dispatch.rs:69)。
      • SubmittedNotes::Encoded(String) 字符串化 JSON 兜底解析(discovery.rs:46-63)。
      • plugins/agent/api/src/contract/scheduler.rs:58-85 里的 #[serde(default)] 与全零 UUID DiscoveryAuthority::default() 等兼容填充,直接用类型明确必填契约。
  3. 只读查询不要跨越顺序 KV 扫描持有全局调度锁与会话运行锁

    • plugins/agent/native/src/owner/discovery/records.rs:516-535, 369-382 在执行 List(单页最多串行读 64 次单 key KV)、Get、NotificationSource 和 FeedbackSource 等只读操作时,全程同时持有全局 scheduler.gate 和父会话 runs.ordered(source) 锁。锁内只做必要的内存元数据快照,存储读取放到锁外执行。

测试套件瘦身与重写

  • 请删掉侵入生产代码的 plugins/agent/native/src/owner/scheduler/storage_fault.rs(以及 scheduler.rs / repository.rs 里通过 #[cfg(test)] 替换存储类型、按内部 JSON 字段和 key 前缀做模式匹配的白盒故障注入),并大幅精简 plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs(2,198 行)及测 match 分支的凑数单测(discovery.rs:1071)。
  • 值得一提的是,model_recovery/discovery.rs 的 Fixture 初始化的是 "tools": [],全程没有绑定真实的 maka.workspace.Files(Read)工具——这也是为什么两千多行测试都没发现 ReadOnly worker 根本没有 Read 工具,反而把一些错误体验固化成了断言(如 discovery_enabling_recall_requires_a_new_approval_before_writing_memory)。请改为绑定真实工具集、只验证核心端到端可观测行为的精简测试。

…agement

Combine the changes from apache#6724, apache#6728, and apache#6730 on rust-preview. Keep the upstream session readers and share the escaped quote renderer.

Generated-by: Codex
Default to read-only, preview and pin approved tools, reuse canonical session references, and keep scoped memory across changes in authorization.

Generated-by: Codex
Preserve the upstream memory privacy boundary on delegated Session creation and regenerate the SDK from the reconciled contracts.

Generated-by: Codex
@sunrioa
sunrioa force-pushed the codex/feat-rust-discovery-desktop branch from 8ac2605 to 8c5d071 Compare November 17, 2026 08:34
@sunrioa sunrioa changed the title feat(bot): add desktop discovery controls and quoted feedback feat(bot): add scheduled proactive discovery and quoted feedback Nov 17, 2026
Show readable discovery permission groups with preset and custom grants.
Keep approvals tied to the tool list shown to the user.

Apply profile-wide file, directory, and suffix exclusions to discovery
workers and automatic follow-ups through the Host sandbox.

Generated-by: Codex
Keep the discovery guides in the consolidated product and Agent READMEs.
Add quotes to the existing client draft journal schema upgrade.

Generated-by: Codex
Settle blocked investigations when the approved model route changes and pause the affected plan for reapproval. Interpret legacy Bot coordination lists separately from explicit tool ceilings.

Generated-by: Codex
Settle investigations when an approved model is disabled or removed, preserve inherited tool ceilings on legacy Bots, and persist worker cancellation before the ready queue resumes after activation.

Generated-by: Codex

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

Re-reviewed at 64920e54f. Thanks for consolidating #6724 / #6728 and addressing most of the previous round (ReadOnly default + "read" / "RecallMaterial", plan Delete, PauseSource separation, DiscoveryMemory scope & lock lifetime, single-table drafts.quotes, CompactComposer quotes, and removing storage_fault.rs).

There are still merge conflicts and several new blocking/design issues introduced in the latest commits:


1. Rebase Conflicts & Zero CI Runs (StageFloatingComposer Alignment)

  • The branch is currently CONFLICTING against rust-preview (plugins/agent/conversations/ui/SessionSurface.tsx and products/maka/client/src/lib.rs), so GitHub Actions ran zero checks on 64920e54f.
  • When rebasing onto #6980, please also wire hasComposerContent(..., session.quotes()) and <DraftQuotes> into products/maka/workbench/app/StageFloatingComposer.tsx:61-78 so quote-only drafts behave the same as in CompactComposer.

2. Blocking: Disabling/Deleting a Model or Connection Permanently Wedges the Global Discovery Slot and Breaks Resume

  • 64920e54f only handled endpoint URL changes where model selection still succeeds (!same_execution_route -> MODEL_ROUTE_CHANGED at plugins/agent/native/src/owner/discovery.rs:730-742).
  • In practice, if a user toggles off a model (#6982), disables/deletes the connection, or removes its credential:
    1. dispatch_discovery writes discovery/active (save_investigation at plugins/agent/native/src/owner/discovery.rs:574-578) before calling capture_current_run (discovery.rs:716-728), which then returns Err("agent_model_unavailable") via ? without settling the fire or releasing discovery/active.
    2. dispatch_scheduled (plugins/agent/native/src/owner/scheduler/dispatch.rs:554-563) loops in FireRetry forever: pendingFire stays non-null with lastError: null (which disables both Edit plan and Delete in products/maka/workbench/app/DiscoveryPanel.tsx:609-612), and permanently starves every other discovery plan on the Host (even plans on healthy connections). The same unhandled failure occurs in deliver_discovery_report (discovery.rs:955-985) if the Bot's model becomes unavailable before report delivery.
    3. On a paused plan whose model/connection became unavailable, clicking Resume rejects with "agent_model_unavailable", which is missing from DiscoveryPanel.tsx:346-350's re-approval list (['scheduler_authorization_changed', 'background_model_route_changed', 'scheduler_user_approval_required']), surfacing a raw error instead of opening re-approval to pick a valid model.

3. Blocking: Cut Unrequested DiscoveryExclusions + 8-Group Custom Matrix (64a60f5a5) — Scope Creep & Worker Session Sandbox Bypass

64a60f5a5 added ~900+ lines of unrequested surface area: an 8-switch Custom(DiscoveryToolGroups) matrix, DiscoveryExclusions (Directory / File / Suffix), changeDiscoveryExclusions RPC, DiscoveryAccessSettings.tsx, discovery/access.rs, and Windows glob special-casing in platform/sandbox/src/filesystem.rs:128-133. Beyond scope creep on an already large PR, the enforcement is broken:

  • Bypassed on any follow-up turn in the worker Session: discovery_restriction (DiscoveryExclusions + Network::Denied) is only attached to the single queued background RunSpec (discovery.rs:693-698, 756) and is never persisted on the worker Session (plugins/agent/native/src/owner/send.rs:284 sets discovery_restriction: None). As soon as the scheduled run settles and the user clicks Open investigation (DiscoveryPanel.tsx:600-601 / BotReply.tsx) and sends a follow-up message (or another session calls SessionSend), Read and Shell in that worker session read every excluded directory, file, and .pem suffix freely, and network: false (Network::Denied) disappears.
  • Collateral side effects & mismatched scope: Adding any single exclusion (even .pem) makes exclusions.is_empty() false, which silently disables AGENTS.md / workspace instruction loading (send.rs:226-228), disables all MCP/Extensions on every OS, and disables Shell on Linux/Windows (discovery/access.rs:244-254). Meanwhile ScheduleRead::DiscoveryExclusions / ChangeDiscoveryExclusions take sessionId in a Bot-scoped dialog, yet persist to a single Host-global key "discovery/exclusions" (scheduler.rs:325 ignores session_id).

Please remove DiscoveryExclusions and Custom(DiscoveryToolGroups) from this PR and keep worker modes strictly to ReadOnly (default) vs Session (previewed tool list bounded by parent ceiling). If sensitive-file exclusions are needed later, design them at the durable workspace/session sandbox layer so they hold across the entire session lifecycle.


4. Remove the New Pre-Release Legacy Bot Shim (bot.rs / access.rs)

  • 64920e54f introduced #[serde(default)] session_tool_ceiling: bool, LEGACY_COORDINATION_TOOLS, and configured_tool_ceiling (plugins/agent/native/src/owner/bot.rs:40-41, 106-109, 201-215, 823-826 and plugins/agent/native/src/owner/access.rs:375-381) solely to reinterpret pre-existing local bot records.
  • As noted in the previous round, we do not carry pre-release on-disk compatibility shims in production code (put a one-off Python migration snippet in a Gist if needed for local dev data). Worse, tools.iter().all(|tool| LEGACY_COORDINATION_TOOLS.contains(&tool.as_str())) returns true for any subset (including Some(["ScheduledTask"]) or Some([])), wiping out explicit restrictions to None whenever session_tool_ceiling is false. Since open_bot already sets tools: None and Owner::effective_tools bounds the Bot itself, please delete session_tool_ceiling and configured_tool_ceiling.

5. DiscoveryMemory Filtered list Returns Empty Pages Too Early

  • memory_page (plugins/agent/native/src/owner/discovery/records.rs:359-387) stops after SEARCH_WINDOW = 32 entries and returns {"records": [], "next_before": ...} even when older matching records exist—which, per the PR description's own live telemetry, caused 37 of 93 (40%) filtered queries to stop on an empty page. When query or related is specified, please scan further on the host side (up to a reasonable bound or via an index) to fill PAGE_SIZE before returning an empty page to the model.
简体中文

基于 64920e54f 复审。感谢收敛关闭 #6724 / #6728 并修复了上一轮的大部分问题(默认 ReadOnly + 补齐 "read" / "RecallMaterial"、计划删除、PauseSource 区分、DiscoveryMemory scope 与锁范围、drafts.quotes 单表收敛、CompactComposer 引用展示,以及移除 storage_fault.rs)。

当前分支仍有主干冲突,且最新几次提交引入了新的阻塞性缺陷与范围膨胀:


1. 主干冲突与 CI 未运行(同步补齐 StageFloatingComposer)

  • 当前分支与 rust-preview 存在冲突(plugins/agent/conversations/ui/SessionSurface.tsx、products/maka/client/src/lib.rs),导致 64920e54f 上没有跑任何 GitHub Actions 检查。
  • Rebase 到 #6980 时,请一并在 products/maka/workbench/app/StageFloatingComposer.tsx:61-78 中接入 hasComposerContent(..., session.quotes()) 和 <DraftQuotes>,避免全屏浮动输入框遗漏纯引用草稿。

2. 阻塞问题:禁用/删除模型或连接会永久卡死全局 Discovery 槽位,且导致 Resume 报错

  • 64920e54f 只处理了模型仍可解析但 URL 变化的情况(!same_execution_route -> MODEL_ROUTE_CHANGED,见 plugins/agent/native/src/owner/discovery.rs:730-742)。
  • 实际使用中,一旦用户在设置里关掉某个模型开关(#6982)、禁用/删除模型连接或移除凭据:
    1. dispatch_discovery 会先在 plugins/agent/native/src/owner/discovery.rs:574-578 写入 discovery/active 占住全局唯一槽位,随后在 discovery.rs:716-728 调用 capture_current_run 得到 Err("agent_model_unavailable") 直接 ? 返回——既不结算本轮 fire,也不释放 discovery/active。
    2. dispatch_scheduled(plugins/agent/native/src/owner/scheduler/dispatch.rs:554-563)进入无限 FireRetry:pendingFire 一直非空且 lastError 为 null(前端 DiscoveryPanel.tsx:609-612 因 !!detail()?.pendingFire 直接灰掉 Edit plan 和 Delete),同时把整个 Host 上所有其他健康连接的 Discovery 计划永久饿死。deliver_discovery_report(discovery.rs:955-985)在投递阶段遇到 Bot 模型不可用时也有同样的死锁。
    3. 对已暂停的计划,连接/模型被禁用后点击 Resume 会被拒绝并返回 "agent_model_unavailable",不在 DiscoveryPanel.tsx:346-350 的重授权白名单(['scheduler_authorization_changed', 'background_model_route_changed', 'scheduler_user_approval_required'])中,导致直接报底层错误而不是进入重新选模型的审批页。

3. 阻塞问题:砍掉未要求的 DiscoveryExclusions 与 8 开关 Custom 权限矩阵(64a60f5a5)——范围膨胀且在 worker 后续轮次中完全绕过

64a60f5a5 新增了 900+ 行未要求的功能:8 开关 Custom(DiscoveryToolGroups) 权限矩阵、DiscoveryExclusions(目录/文件/后缀排除)、changeDiscoveryExclusions RPC、DiscoveryAccessSettings.tsx、discovery/access.rs,以及 platform/sandbox/src/filesystem.rs:128-133 的 Windows glob 特判。除了让本已庞大的 PR 继续膨胀外,这套隔离机制在设计上也是漏的:

  • 进入 worker 会话发后续消息即可完全绕过:discovery_restriction(文件排除 + Network::Denied)只挂在了单次后台触发的临时 RunSpec 上(discovery.rs:693-698, 756),从未持久化到 worker Session 本身(plugins/agent/native/src/owner/send.rs:284 硬编码 discovery_restriction: None)。调查一结算,只要用户点击面板或通知卡片上的 Open investigation(DiscoveryPanel.tsx:600-601 / BotReply.tsx)进入该 worker 会话追问一句(或其他会话调用 SessionSend),该会话里的 Read 和 Shell 当场就能自由读取所有被排除的目录、文件和 .pem 后缀文件,network: false 的断网限制也随之消失。
  • 一刀切副作用与作用域错位:只要添加任意一条排除规则(哪怕只是 .pem),exclusions.is_empty() 变 false,就会在 send.rs:226-228 中静默关掉 AGENTS.md 等工作区指令加载,在全平台禁用所有 MCP 扩展,并在 Linux/Windows 上直接禁用 Shell(discovery/access.rs:244-254);同时读写接口按 Bot sessionId 传参,底层却存成全局单 key "discovery/exclusions"(scheduler.rs:325 直接忽略了 session_id)。

请从本 PR 中完整移除 DiscoveryExclusions 和 Custom(DiscoveryToolGroups),只保留清晰的 ReadOnly(默认)与 Session(预览工具清单并受父会话上限约束)两档。后续若确实需要敏感文件排除,应在持久化的 Workspace/Session 沙箱层统一设计,保证在整个会话生命周期内一致生效。


4. 删除新引入的未发版旧 Bot 兼容补丁(bot.rs / access.rs)

  • 64920e54f 在 plugins/agent/native/src/owner/bot.rs:40-41, 106-109, 201-215, 823-826 和 plugins/agent/native/src/owner/access.rs:375-381 中新增了 #[serde(default)] session_tool_ceiling: bool、LEGACY_COORDINATION_TOOLS 与 configured_tool_ceiling,专门用来兼容本地已有的旧 bot 记录。
  • 如上一轮所述,发版前业务代码不维护旧数据兼容层(本地开发库迁移放 Python Gist 即可)。而且 tools.iter().all(|tool| LEGACY_COORDINATION_TOOLS.contains(&tool.as_str())) 对任意子集(例如显式收敛到 Some(["ScheduledTask"]) 甚至 Some([]))都会返回 true,在 session_tool_ceiling == false 时反而会把显式限制清空成 None。既然 open_bot 已经改为 tools: None 且 Bot 自身工具由 Owner::effective_tools 约束,请直接删掉 session_tool_ceiling 和 configured_tool_ceiling。

5. DiscoveryMemory 带过滤条件的 list 过早返回空页

  • memory_page(plugins/agent/native/src/owner/discovery/records.rs:359-387)每次只扫 SEARCH_WINDOW = 32 条,未命中就直接返回 {"records": [], "next_before": ...}——正如 PR 正文实测数据所写,93 次过滤查询里有 37 次(40%)拿到空页后直接停掉了。带 query 或 related 过滤时,请在服务端继续向前扫描(设合理上限或建索引)凑够 PAGE_SIZE 再返回,避免扫 32 条就把空页甩给模型。

…m scheduled discovery

Keep the two approved investigation profiles and the frozen tool preview. The original access prototype is available separately for session-level design.

Generated-by: Codex
@liugddx

liugddx commented Nov 18, 2026

Copy link
Copy Markdown
Member

Follow-up on my earlier comments, re-checked against the current head d426c72a3. I read the code only: nothing was built or run, and I did not re-check the blockers in the consolidated review above, which I defer to.

Summary: all but one of my earlier findings look resolved. One is still open, and CI has not run on this head yet.

Earlier finding Status at d426c72a3
Bot resume overrides a user pause Resolved. Pauses record a PauseSource, and Bot resume is rejected unless the Bot made the pause.
Bot-proposed plans always use Session tools Resolved. New plans default to read-only, and a follow-up cannot widen its parent's profile.
Worker tools not intersected with the Bot's tool set Appears resolved: discovery_worker_tools is now called with source.configuration.tools. I did not read its body or the tests.
Quote text and label not escaped Resolved. append_escaped_quote escapes both, with a test for a closing tag.
draft_quotes written on every autosave Resolved. The separate table write is gone from write.rs.
PR description vs. default permissions Resolved. The description now says new plans default to read-only.
CompactComposer shows no quote chips Still open. Only the empty-draft guard counts quotes (CompactComposer.tsx:68); there are no chips, so quotes it cannot show or remove are still sent.

CI: the new head was pushed at 05:12Z, and only audit, plan and rust-licenses were queued when I looked, so there is no result yet. mergeable_state is unstable. Please re-check once CI finishes.

简体中文

对我之前评论的跟进,已按当前头提交 d426c72a3 重新核对。只读了代码:没有构建,也没有运行;上面合并评审里的阻塞项我没有重新核对,以那份评审为准。

摘要: 我之前的意见除一条外都已解决;还有一条未解决,且这个头提交的 CI 还没跑出结果。

之前的问题 d426c72a3 上的状态
Bot 的 resume 覆盖用户暂停 已解决。暂停会记录 PauseSource,不是 Bot 暂停的计划,Bot 的 resume 会被拒绝。
Bot 提议的计划总是使用会话工具 已解决。新计划默认只读,follow-up 不能放宽父计划的权限档位。
worker 工具集没有与 Bot 的工具集取交集 看起来已解决:discovery_worker_tools 现在会传入 source.configuration.tools。我没有读函数体和测试。
引用正文和 label 未转义 已解决。append_escaped_quote 同时转义两者,并有结束标签的测试。
每次自动保存都写 draft_quotes 已解决。write.rs 里已没有这张表的写入。
PR 描述与默认权限不符 已解决。描述现在写明新计划默认只读。
CompactComposer 不显示引用 chip 仍未解决。 只有空草稿判断计入了引用(CompactComposer.tsx:68),没有 chip,用户看不到也删不掉的引用仍会随消息发出。

CI: 新头提交在 05:12Z 推送,我查看时只有 audit、plan、rust-licenses 在排队,还没有结果;mergeable_state 为 unstable。请等 CI 跑完后再确认。

sunrioa and others added 4 commits November 18, 2026 16:17
…sages

Persist a late discovery association and its memory receipt in the same Root transaction. Refresh the displayed parts without treating them as new messages.

Generated-by: Codex
Account for the saved message before accepting concurrent quotes. Preserve the existing text and attachments and let users continue typing while the journal restores the draft.

Generated-by: Codex
Keep external tool recovery notices attached to the interrupted run and discovery reports queued for the Bot. Retain the native process service as a test dependency after the upstream manifest cleanup.

Generated-by: Codex
@M4n5ter
M4n5ter merged commit 99b0dff into apache:rust-preview Nov 18, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XXL Over 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants