Repository navigation
feat(bot): add scheduled proactive discovery and quoted feedback - #6730
Conversation
liugddx
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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") |
There was a problem hiding this comment.
[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()!); |
There was a problem hiding this comment.
[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'; |
There was a problem hiding this comment.
[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 创建的计划。
| > | ||
| <If when={owner !== null}> | ||
| <DraftAttachments draft={owner!.attachments} preview={owner!.previewImage} /> | ||
| <Each of={owner?.quotes() ?? []}> |
There was a problem hiding this comment.
[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; |
There was a problem hiding this comment.
[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', |
There was a problem hiding this comment.
[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)}> |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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 }); |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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.
|
Follow-up on my earlier review (head 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.
Still open
The backend findings I posted on #6728 (Recall scope, 对我之前评审(头提交 摘要: 我之前的 8 条行内意见中,7 条已解决,1 条部分解决,另有 2 个较小的遗留点。目前剩下的阻塞项是当前头提交的 CI 仍是红的。
仍未解决
我之前发在 #6728 上的后端意见(Recall 范围、 |
liugddx
left a comment
There was a problem hiding this comment.
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)?) |
There was a problem hiding this comment.
[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, |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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("e.text); |
There was a problem hiding this comment.
[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") |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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)
-
ReadOnlydiscovery workers do not get theReadtool (and missRecallMaterial)plugins/agent/native/src/tools.rs:378-382buildsdiscovery_readsby matchingmaka.workspace.Filesbindings against"readText" | "readImage" | "glob" | "grep". However,plugins/workspace/api/src/files.rs:60-68unified file reading onto"read", sodiscovery_readsis always empty. Aread_onlyworker currently gets zero workspace file tools (["DiscoveryComplete", "DiscoveryMemory"], plusRecall/RecallMore/DiscoveryContextwhen Recall is on).plugins/agent/native/src/owner/discovery.rs:457also omits"RecallMaterial"when Recall is enabled.
-
Unsafe default (
Sessioninstead ofReadOnly) and parent tool-ceiling bypassDiscoveryWorkerToolsmarks#[default] ReadOnlyinplugins/agent/api/src/contract/scheduler.rs:58-63, yetplugins/agent/native/src/owner/scheduler/tools.rs:395-397,products/maka/workbench/app/discoveryCore.ts:61, andproducts/maka/workbench/app/DiscoveryPanel.tsx:107, 186all default new plans toSession(full Bot write/shell capabilities). Unattended background discovery should default toReadOnlyacross contract, tool schema, and UI.- In
plugins/agent/native/src/owner/discovery.rs:728-729,session_tools == truesetstools: None(all tools in the global catalog) instead of inheriting/intersectingsource.configuration.toolsfrom the parent Bot session. A Bot session explicitly restricted to["Read", "ScheduledTask"]still spawns a discovery worker withWrite,Recall*, etc.
-
Desktop
Approve/Resumebreaks after any Bot permission orboundary_revisionchange, and plans cannot be deletedproducts/maka/workbench/app/DiscoveryPanel.tsx:262-275, 604-611sends{ kind: 'approve' | 'resume', taskId, revision }without capturing/updatingeffect.targetormodel, andsnapshot()(DiscoveryPanel.tsx:348-352) displays the stale storedtask.effectin view mode rather than the live Bot target/model. Whenever the user grants a runtime permission in Bot chat (boundary_revisionincrements) 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) rejectsApprove/Resumewithscheduler_authorization_changed.ScheduleRead::List(plugins/agent/native/src/owner/scheduler.rs:306-314) hidesDiscoveryplans fromAutomations.tsx, whileDiscoveryPanel.tsxhas nodeleteaction at all. Worse,DiscoveryPanel.tsx:236auto-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.
-
DiscoveryMemoryscope hashing causes infinite backgroundOutcome::Blockedloops and wipes memory/feedback on routine state changesplugins/agent/native/src/owner/discovery/records.rs:208-215, 543-559hashes the entire(ScheduledTarget, recall)—includingboundary_revision,permissions, andrecall—into the KV prefixdiscovery/memory/{scope}/..., anddiscovery.rs:472blocks runs whenjob.recall != self.discovery_recall_enabled().- Infinite blocked loop: Toggling
Recallor bumpingboundary_revision/ permissions leaves active recurring plans instatus = "active", whileplan.settle(plugins/agent/scheduler/engine/src/plan.rs:274-290) keeps advancingnext_fire_aton everyOutcome::Blockedforever without pausing the plan or surfacing a re-approval state. - Memory amnesia & broken quoted feedback: Any
boundary_revisionincrement, permission change, or Recall toggle changesscope, orphaning 100% of existingDiscoveryMemorykeys in SQLite KV, resetting visible memory to[](causing dismissed findings to be re-notified), and breakingDiscoveryMemory { 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), notboundary_revision,permissions, orrecall.
Architecture, #6958 Alignment & Pre-Release Compatibility Policy
-
Align with
#6958onrust-previewinstead of inventing parallel session/source readers#6958already landed cross-session discovery and reading viaSessionList+Read("maka://session/<id>"), along withrender_quotes/render_session_references.- Remove
DiscoveryContext(plugins/agent/native/src/owner/discovery/context.rs, which duplicatesSessionList+Read("maka://session/...")and is even exposed alongsideSession*tools insessionmode), as well as customNotificationSource/FeedbackSourcepagination (records.rs:634-643currently slices serialized JSON strings by 4096-char offsets). Store canonical session/message references and reuse the platformRead/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'smaka_agent_facts::input::render_quotesand preserverender_session_references.
-
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_quotestable/migration (products/maka/client/migrations/202611100001_draft_quotes.sql),LEFT JOIN draft_quotes, dual writes/deletes inproducts/maka/client/src/journal.rs&journal/write.rs, andpre_quote_journal_upgrade_*plumbing—storequotesdirectly ondraftsalongsideattachments,mentions, andreply_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-UUIDDiscoveryAuthority::default()(plugins/agent/api/src/contract/scheduler.rs:58-85), legacy phase comments, etc. Make required fields explicit in types.
- Separate
-
Do not hold scheduler and session run locks across sequential KV reads
plugins/agent/native/src/owner/discovery/records.rs:516-535, 369-382holds both globalscheduler.gateand the Bot'sruns.ordered(source)mutex while executing read-onlyList(up to 64 sequential single-key KV reads acrossSEARCH_WINDOW = 32),Get,NotificationSource, andFeedbackSource. 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 inscheduler.rs/repository.rsthat pattern-matches internal JSON fields and key prefixes) and trim the 2,198-line white-box recovery matrix inplugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs+ trivial match-arm tests (discovery.rs:1071). - Note that
Fixtureinmodel_recovery/discovery.rsinitialized"tools": []without binding realmaka.workspace.Files(Read), which is why 2,200 lines of tests completely missedReadOnlyworkers lackingRead, 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 无关。)
阻塞性问题(正确性与权限边界)
-
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_onlyworker 实际上没有任何工作区读文件工具(不开 Recall 时只有["DiscoveryComplete", "DiscoveryMemory"])。plugins/agent/native/src/owner/discovery.rs:457在开启 Recall 时只注入了["Recall", "RecallMore", "DiscoveryContext"],漏掉了"RecallMaterial"。
-
默认权限过宽(默认成了
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*等越权工具。
-
桌面端在 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 提案,它既删不掉,还会永久霸占面板默认视图。
-
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)、锁粒度与未发版兼容性策略
-
对齐
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。
-
清理所有向后兼容兜底与双表妥协(当前阶段不承诺旧数据兼容)
- 目前项目尚未正式发版,开发期间我们不保证旧数据/旧协议兼容性(只有开发者本地会碰到格式演进)。业务代码里严禁预埋兼容层、双表迁移或反序列化兜底;如果确实需要迁移本地开发数据,写个 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)]与全零 UUIDDiscoveryAuthority::default()等兼容填充,直接用类型明确必填契约。
- 独立的
-
只读查询不要跨越顺序 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)工具——这也是为什么两千多行测试都没发现ReadOnlyworker 根本没有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
8ac2605 to
8c5d071
Compare
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
left a comment
There was a problem hiding this comment.
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
CONFLICTINGagainstrust-preview(plugins/agent/conversations/ui/SessionSurface.tsxandproducts/maka/client/src/lib.rs), so GitHub Actions ran zero checks on64920e54f. - When rebasing onto
#6980, please also wirehasComposerContent(..., session.quotes())and<DraftQuotes>intoproducts/maka/workbench/app/StageFloatingComposer.tsx:61-78so quote-only drafts behave the same as inCompactComposer.
2. Blocking: Disabling/Deleting a Model or Connection Permanently Wedges the Global Discovery Slot and Breaks Resume
64920e54fonly handled endpoint URL changes where model selection still succeeds (!same_execution_route->MODEL_ROUTE_CHANGEDatplugins/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:dispatch_discoverywritesdiscovery/active(save_investigationatplugins/agent/native/src/owner/discovery.rs:574-578) before callingcapture_current_run(discovery.rs:716-728), which then returnsErr("agent_model_unavailable")via?without settling the fire or releasingdiscovery/active.dispatch_scheduled(plugins/agent/native/src/owner/scheduler/dispatch.rs:554-563) loops inFireRetryforever:pendingFirestays non-null withlastError: null(which disables bothEdit planandDeleteinproducts/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 indeliver_discovery_report(discovery.rs:955-985) if the Bot's model becomes unavailable before report delivery.- On a paused plan whose model/connection became unavailable, clicking
Resumerejects with"agent_model_unavailable", which is missing fromDiscoveryPanel.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 backgroundRunSpec(discovery.rs:693-698, 756) and is never persisted on the worker Session (plugins/agent/native/src/owner/send.rs:284setsdiscovery_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 callsSessionSend),ReadandShellin that worker session read every excluded directory, file, and.pemsuffix freely, andnetwork: false(Network::Denied) disappears. - Collateral side effects & mismatched scope: Adding any single exclusion (even
.pem) makesexclusions.is_empty()false, which silently disablesAGENTS.md/ workspace instruction loading (send.rs:226-228), disables all MCP/Extensions on every OS, and disablesShellon Linux/Windows (discovery/access.rs:244-254). MeanwhileScheduleRead::DiscoveryExclusions/ChangeDiscoveryExclusionstakesessionIdin a Bot-scoped dialog, yet persist to a single Host-global key"discovery/exclusions"(scheduler.rs:325ignoressession_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)
64920e54fintroduced#[serde(default)] session_tool_ceiling: bool,LEGACY_COORDINATION_TOOLS, andconfigured_tool_ceiling(plugins/agent/native/src/owner/bot.rs:40-41, 106-109, 201-215, 823-826andplugins/agent/native/src/owner/access.rs:375-381) solely to reinterpret pre-existing localbotrecords.- 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()))returnstruefor any subset (includingSome(["ScheduledTask"])orSome([])), wiping out explicit restrictions toNonewheneversession_tool_ceilingis false. Sinceopen_botalready setstools: NoneandOwner::effective_toolsbounds the Bot itself, please deletesession_tool_ceilingandconfigured_tool_ceiling.
5. DiscoveryMemory Filtered list Returns Empty Pages Too Early
memory_page(plugins/agent/native/src/owner/discovery/records.rs:359-387) stops afterSEARCH_WINDOW = 32entries 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. Whenqueryorrelatedis specified, please scan further on the host side (up to a reasonable bound or via an index) to fillPAGE_SIZEbefore 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)、禁用/删除模型连接或移除凭据: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。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 模型不可用时也有同样的死锁。- 对已暂停的计划,连接/模型被禁用后点击
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);同时读写接口按 BotsessionId传参,底层却存成全局单 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 条就把空页甩给模型。
Generated-by: Codex
…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
…overy Generated-by: Codex
… throughout admission Generated-by: Codex
Generated-by: Codex
…etrieval Generated-by: Codex
…issions Generated-by: Codex
Generated-by: Codex
|
Follow-up on my earlier comments, re-checked against the current head Summary: all but one of my earlier findings look resolved. One is still open, and CI has not run on this head yet.
CI: the new head was pushed at 05:12Z, and only 简体中文对我之前评论的跟进,已按当前头提交 摘要: 我之前的意见除一条外都已解决;还有一条未解决,且这个头提交的 CI 还没跑出结果。
CI: 新头提交在 05:12Z 推送,我查看时只有 |
…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
Summary
Refs #6716. Consolidates #6724, #6728, and the desktop work in this PR on
rust-preview.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)
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" .-> memoryReview notes on existing behavior
maxFires, can complete the plan even when the worker has not started. This follows the existing trigger-counting rule.DiscoveryMemoryfrom the Bot that handles quoted feedback. Migrating those development records is a separate compatibility decision.Verification
Validated on macOS at
8c5d0711c, rebased ontorust-previewat9ac917f17.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:
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.
agent_cell_origin_mismatcherrors in that round.wait32 times and made 10 separate checks of the same repository fix across commits, branches, and worktrees. This run had no execution deadline.Follow-up observation after restart
This 15h 33m sample comes from local integration build
0cacbd4aaon 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.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.
execarguments and left no submitted result. Twelve TLS handshake interruptions were retried successfully.waitwas the only tool called.AI use
Tool(s) and scope: OpenAI Codex assisted with implementation, regression tests, local verification and drafting this description.
Checklist
Does this PR entail a change in behavior?
简体中文
概述
关联 #6716。基于
rust-preview将 #6724、#6728 和本 PR 的桌面改动收敛到一个 PR。后续 PR
后续 PR 在本 PR 的「只读工具」和「普通会话工具」两种预设之上增加分组审批,并处理以下三项评审意见。分组审批 #6991
工作区 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现有行为的评审记录
maxFires允许的最后一次触发若受阻,即使调查 worker 尚未启动,计划也可能进入Completed。这是现有的触发计数规则。DiscoveryMemory。是否迁移这些开发数据属于单独的兼容性决策。验证
已在 macOS 验证
8c5d0711c,基于rust-preview的9ac917f17。原生用例验证了只读文件访问、批准扩权后成功执行 Shell、同范围复查、授权变化后的旧通知引用反馈,以及跨页搜索历史记录。分支采用开发期的新计划与草稿存储格式。
下面的 release 打包和真实模型数据来自此前的开发构建。
使用 Command Code → DeepSeek V4.1 Flash,材料均为隔离的合成数据:
调查 worker 均使用只读权限,测试结束后已暂停计划。
真实联调也暴露出模型判断的局限:一次调查把允许存在的额外语言文件误判为差异,Bot 最初也未准确说明后台调查的文件读取能力。纠正反馈得到保存,并在后续调查中生效。这些检查验证的是集成链路,不能作为普遍发现准确率的证明。
本地未执行 Windows/Linux 桌面验证或完整仓库 CI。macOS 包仅用于本地安装冒烟,不是已签名或绑定源码归档的正式发布候选产物。
已授权工作区的真实运行数据
以下数据来自现有已授权工作区的 macOS 运行记录。两个构建均使用 Command Code / DeepSeek V4.1 Flash。同步后的本地构建以本 PR 为基础,包含 #6874、#6907 和用于读取原有计划的本地适配。
agent_cell_origin_mismatch。wait,另有 10 次围绕同一个仓库修复核对提交、分支和工作树。本轮没有执行截止时间。重启后的后续观察
本次数据来自 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 更新前的记忆分页。账本共记录 202,200,404 个输入和输出 token,缓存读取占已记录输入的 97.0%。14 次中断请求没有回传用量。
exec参数被截断,调查结果未提交。另有 12 次 TLS 握手中断通过重试恢复。wait。AI 使用说明
OpenAI Codex 协助完成实现、回归测试、本地验证及本说明起草。
检查清单
本 PR 存在行为变化,已在概述中说明。