Skip to content

fix(delegate): coalesce simultaneous completion notifications into one batched message - #230

Merged
ranxianglei merged 3 commits into
masterfrom
2026-08-25_coalesce-delegate-notifications
Sep 1, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
2026-08-25_coalesce-delegate-notifications

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Problem (#157)

When multiple subagents finish near-simultaneously (or one after another while the main window is busy), each completion enqueues its own follow-up notification via sendUserMessage(deliverAs: followUp). Every enqueued message triggers a full model turn, so N finishing delegates cost N extra turns — and notifications keep firing even after the model has already confirmed everything done. The user also observed the model idling between these queued notifications.

Fix

Trailing-edge coalescing window in the async completion path (src/delegate-tool.ts):

  • Finalize no longer injects directly; it queues the run (scheduleRunNotification) and arms a 2s debounce (hard cap 10s from the first queued completion, so a stream of staggered finishes cannot starve delivery).
  • When the window closes, flushDelegateNotifications delivers one batched message: header with counts ([acp_delegate] 3 delegates finished (2 completed, 1 FAILED)), one compact section per run (status, exit code, timeout note, task, result file, error excerpt for failures), then a single trailer with the still-running count, session delegate usage, and closing instructions.
  • Queued runs that gained a waiter or were consumed via acp_delegate_wait/acp_delegate_cancel during the window drop out of the batch (no duplicate delivery).
  • Runs whose earlier notification send failed are still recovered (findUndeliveredRuns now treats queued-but-unflushed as scheduled, not lost) and piggyback on the next flush.
  • Send failures leave runs unmarked so a later carrier message can recover them; single-run flushes keep the previous one-notification format.

Net effect: N simultaneous completions → 1 model turn instead of N; the main window stops getting peppered after it has wrapped up.

Tests

6 new tests in tests/delegate-tool.test.ts covering coalescing, waiter/consumed exclusion, failed-send recovery, single-run legacy format, findUndeliveredRuns exclusion of queued runs, and section formatting. Full suite: 434 passed, typecheck clean, build clean.

Closes #157

@github-actions

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Extension Artifact

Branch: 2026-08-25_coalesce-delegate-notifications (20abff5)

Option A — Install from npm PR tag (recommended)

pi install npm:billion-context-pi@pr-230

Each push to this PR publishes a new version under the pr-230 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pi-pr230.tgz
pi install ./package

This comment is automatically updated on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

review 这个是否还存在 看代码是否冲突 是否有回归问题 是否兼容多系统

@ranxianglei

Copy link
Copy Markdown
Owner Author

Review 结论:可以合并(1 个小建议 + 2 个已知边界,均非阻塞)

在 PR head e20d59d 上完整跑过:typecheck 干净、434/434 测试通过、tsup build 干净(dist 525.84 KB,acp-kernel 正常内联)。

1. 问题是否还存在 → 存在,PR 仍然必要

master 当前 src/delegate-tool.ts:900 的 finalize 仍是同步直调 injectResult,notifyTerminalFailure 也是直注。N 个 delegate 同时完成 = N 个 follow-up turn 的 #157 问题在 master 上原样存在,没有被其他 PR 顺带修掉。

2. 代码是否冲突 → 无冲突

PR 分支基于 90bcefc,正是当前 master HEAD(v0.1.52)。git merge-base = master HEAD,可干净 fast-forward,零冲突。改动面也收敛:只有 src/delegate-tool.ts(+216/-37)和 tests/delegate-tool.test.ts(+89)。

3. 回归问题 → 未发现回归,关键交互路径逐条核对过

  • close handler 时序正确:waiter 唤醒和 consumed 检查都发生在 scheduleRunNotification 之前,入队 run 不会挂着 parked waiter;flush 里的 owned() 检查是二次防御。
  • 窗口期内 wait 不重复投递:flush 前 run.injected 仍为 false → wait 走完整 payload 并置 consumed=true → flush 跳过。模型拿到结果更快,无重复。
  • cancel 交互:对已终止 run 的 cancel 直接 early-return,run 留在队列由 flush 投递,无泄漏。
  • 恢复机制与 fix: nudge rendered blockId with double prefix (bb3, not b3) #16 设计一致:findUndeliveredRuns 排除 notifyQueued(排队 ≠ 丢失),recovery notice 不会二次投递;发送失败时 injected 不置位、notifyQueued 已清 → 后续 carrier(下一个 delegate 工具结果)可恢复。
  • usage 口径与 master 完全一致:separate 模式发送前 addDelegateUsage + 无论发送成败都置 usageReported(与 master injectResult 行为相同);merged 模式发送成功才置位。
  • 单 run flush 复用 injectResult:保留旧格式 + recovery carrier 语义,行为不漂移。
  • debounce 数学正确:trailing edge,delay = max(0, min(2000, 10000 - elapsed)),连续流式完成会在 10s 硬上限处强制 flush,不会饿死。
  • 测试:现有 spawn-error e2e 测试轮询窗口 5s > 2s 窗口,兼容新异步路径(实测通过)。

两个已知边界(记录即可,不阻塞):

  1. 通知延迟 2s(连续流最坏 10s)——设计内权衡,但单 delegate 场景模型看到结果会比以前晚 2s。
  2. timer 已 unref():若 Pi 进程在最后一条完成后的 2–10s 窗口内退出,排队通知会丢(以前是同步入队)。风险低——sendUserMessage 本来就是 fire-and-forget,交互式 CLI 不会在此窗口退出。

一个小建议:PR 没更新 CHANGELOG.md。仓库惯例是每个 fix PR 在 "Unreleased" 下加一条(参考 #223、#16、#210 的提交),建议合并前补一条,或合并时带上。

4. 多系统兼容性 → 兼容

  • OS:无平台相关 API(setTimeout.unref?.()、tmpdir()、spawn 路径未动),Windows/macOS/Linux 均可。
  • Pi host:只用 master 已在用的 pi.sendUserMessage(text, { deliverAs: "followUp" }),无新 host API 依赖,兼容 Pi >= 0.83 的声明不变。
  • 多会话/嵌套:模块状态(notifyQueue/notifyTimer/notifyPi)是 per-process 的;每个 Pi 会话独立进程,嵌套 delegate(depth ≤ 2)各自独立队列,无跨会话干扰。
  • 依赖:无新增依赖,acp-kernel 版本未动,无需跨仓发布。

@ranxianglei

Copy link
Copy Markdown
Owner Author

修复这个问题,然后本机实际测试一下。实际调起 Agent 测试是不是有问题?

@ranxianglei

Copy link
Copy Markdown
Owner Author

[bot] 两件事都完成了。

1. CHANGELOG 已补(已推送到 PR 分支)

commit e4d2382:在 Unreleased (master, since v0.1.38) 顶部新增条目,按仓库惯例写了机制细节(2s 尾沿防抖 + 10s 硬上限、批量消息结构、wait/cancel 出批、发送失败留未送达集、单 run 保留旧格式、净效果 N 个同时完成 → 1 个模型轮次)。推送后 PR 的 CI 会重跑。

2. 本机实际测试(真实进程级 e2e)

先说限制:这台机器没有 pi CLI,也没有任何 LLM 凭据(WORK_PI_* 全空),所以无法调起真正的 LLM agent。我用了 resolvePiCliEntry 的 PI_CLI_PATH 覆盖,让 delegate 工具 spawn 真实子进程(mock agent 脚本,按 pi 的 JSON event stream 协议输出 message_update/message_end/agent_settled)——除 LLM 本身外,整条链路都是真的:真实 spawn()、真实 stdin 任务投递、真实事件流解析、真实结果文件落盘、真实防抖/flush 计时。同一套 harness 分别跑 master 和 PR 的 src:

S1 — 3 个 delegate 同时完成(2 成功 + 1 失败,完成时刻 300/700/1100ms):

  • master:3 条独立通知(t=345/741/1142ms),各吃一个模型轮次 → 原问题复现
  • PR:恰好 1 条批量消息(t=3155ms = 最后完成时刻 + 2s 窗口,数学吻合):
    • 头部 [acp_delegate] 3 delegates finished (2 completed, 1 FAILED).
    • 3 个 run 各一节(runId/exit code/任务/结果文件路径),FAILED 节带 stderr 错误摘录
    • 尾部:No delegates are currently running. + session usage 汇总 240 in / 90 out(= 2 个成功 run 的 120/45 精确累加,FAILED 不计)+ 重派指引

S2 — 错峰完成(300/4000/4300ms):

  • PR → 2 条消息:先落单的走旧单条格式(t=2344ms,带 "2 delegates are still running"),后两个同窗完成的合并为 1 条批量(t=6352ms)。2 个模型轮次而非 3 个,且单 run 格式与 master 完全一致(向后兼容确认)。

S3 — 窗口期内 wait 消费:

  • run 在 ~500ms 完成(仍在 2s 队列窗口内),~1200ms 调 acp_delegate_wait → 返回完整 payload(任务 + 结果文件 + 输出正文),run 标记 consumed,窗口关闭后 0 条重复通知。无双重投递。

落盘验证: /tmp/acp-delegate/<runId>.out 全部真实存在,内容为 mock agent 的真实回复(.activity 文件也按协议生成)。

3. 推送后的分支状态

e4d2382 上重跑:typecheck 干净、434/434 测试通过、tsup build 干净。

结论:修复有效、无回归、单 run 格式兼容旧行为。剩下可以合了(merge 留给你)。

# Conflicts:
#	CHANGELOG.md
#	src/delegate-tool.ts
#	tests/delegate-tool.test.ts
@ranxianglei
ranxianglei merged commit 7d03e97 into master Sep 1, 2026
9 checks passed
HangxiangMa pushed a commit to HangxiangMa/billion-context-pi that referenced this pull request Sep 10, 2026
coreOutToAgentMessages now consumes kernel-rewritten tool-call text
(hide-consumed dead-range filtering + summary stubbing, acp-kernel
ranxianglei#230/ranxianglei#232) and syncs the compacted JSON back into toolCall.arguments
for both projection paths (plain-id single-call and base#callId
multi-call). Fail-safe: unparseable/absent kernel text keeps originals;
string-form content (non-strict providers) keeps its shape.

Bumps acp-kernel pin 0.0.56 -> 0.0.60 (published).

Fixes ranxianglei#340
HangxiangMa pushed a commit to HangxiangMa/billion-context-pi that referenced this pull request Sep 21, 2026
…ce-delegate-notifications

fix(delegate): coalesce simultaneous completion notifications into one batched message
HangxiangMa pushed a commit to HangxiangMa/billion-context-pi that referenced this pull request Sep 21, 2026
coreOutToAgentMessages now consumes kernel-rewritten tool-call text
(hide-consumed dead-range filtering + summary stubbing, acp-kernel
ranxianglei#230/ranxianglei#232) and syncs the compacted JSON back into toolCall.arguments
for both projection paths (plain-id single-call and base#callId
multi-call). Fail-safe: unparseable/absent kernel text keeps originals;
string-form content (non-strict providers) keeps its shape.

Bumps acp-kernel pin 0.0.56 -> 0.0.60 (published).

Fixes ranxianglei#340
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

subagent相关消息结束通知在队列中冗余入队

1 participant