Skip to content

fix(daemon): centralize mid-turn event constant + recover timed-out drains - #5266

Merged
wenshao merged 3 commits into
QwenLM:mainfrom
wenshao:fix/mid-turn-drain-followup
Jun 18, 2026
Merged

wenshao merged 3 commits into
QwenLM:mainfrom
wenshao:fix/mid-turn-drain-followup

Conversation

@wenshao

@wenshao wenshao commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator

What this PR does

A follow-up to #5175 that addresses two /review suggestions left on that (now merged) PR. First, it makes the mid_turn_message_injected SSE event type a single shared constant instead of a bare string literal duplicated across three packages. Second, it closes a narrow window where a mid-turn message could be silently lost for one turn when the ACP child's drain request times out after the daemon has already drained and broadcast it.

Why it's needed

The mid-turn drain feature touches the same wire string 'mid_turn_message_injected' in three independent places: the daemon publisher (acp-bridge/bridgeClient.ts), the SDK validator/reducer (sdk-typescript/daemon/events.ts), and the browser consumer (webui/midTurnInjectedSidechannel.ts). A rename or typo in any one — with the others unchanged — silently breaks browser-side dedup: the drain still works, but injected messages are no longer removed from the browser's pending queue and get double-delivered next turn. The sibling craft/drainMidTurnQueue method string was already centralized; this brings the event type to parity.

Separately, the daemon answers the child's drain by splicing its in-memory queue and publishing the mid_turn_message_injected SSE frame (which the browser uses to dedup) before the response travels back to the child. The child races that response against a 2 s timeout. When the timeout fires first, the child discarded the late response — so the messages were gone from both the daemon queue and the browser queue, yet never reached the model: a silent one-turn loss. Localhost IPC rarely approaches 2 s, but the impact is silent data loss.

Reviewer Test Plan

How to verify

Constant centralization: the event type now lives once in acp-bridge/src/daemonEventTypes.ts — a dependency-free module (like mcpTimeouts.ts) so the SDK re-exports it through its build-time devDep on acp-bridge without dragging acp-bridge's type graph into the SDK's bundled .d.ts. bridgeClient.ts, the SDK, and webui all import the single binding, so a rename either propagates everywhere or fails to compile.

  • cd packages/sdk-typescript && npx vitest run test/unit/daemonEvents.test.ts test/unit/daemon-public-surface.test.ts → 102 pass, incl. the new MID_TURN_MESSAGE_INJECTED_EVENT rename-safety assertion (value === wire literal, registered in the known-event set).
  • cd packages/acp-bridge && npx vitest run src/bridgeClient.test.ts → 23 pass.
  • cd packages/webui && npx vitest run src/daemon → 141 pass.

Drain-timeout recovery: on a timed-out drain the child now recovers the late response (the daemon already drained + broadcast it) and injects it on the next tool batch instead of discarding it.

  • cd packages/cli && npx vitest run src/acp-integration/session/Session.test.ts → 146 pass, incl. the new recovers a drain that timed out and injects it on the next batch (times out batch 1, resolves the daemon's answer late, asserts it is injected on batch 2 and recorded exactly once).

Typecheck: npx tsc --noEmit clean in acp-bridge / sdk-typescript / webui / cli. Builds: npm run build clean for acp-bridge → sdk-typescript → webui; the event const inlines into the SDK's published bundle (index.cjs/mjs, daemon/index.js/cjs), so there is no new runtime acp-bridge dependency.

Evidence (Before & After)

N/A — non-user-visible (a shared constant plus a daemon/child drain-recovery code path; no UI change). Behavior is pinned by the unit tests above.

Tested on

OS Status
🍏 macOS ✅ unit tests + tsc --noEmit + package builds
🪟 Windows ⚠️ not tested (CI)
🐧 Linux ⚠️ not tested (CI)

Environment (optional)

Unit tests + tsc --noEmit + npm run build (acp-bridge, sdk-typescript, webui) on macOS. No live daemon/browser session.

Risk & Scope

  • Main risk or tradeoff: the recovered drain response is injected on the NEXT tool batch (or, if the turn already ended, the next turn's first batch) — a graceful late delivery consistent with the existing next-turn fallback, since the browser already deduped it. The recovery buffer flushes on the next drain, so a transient stall can't strand messages. The constant move adds a tiny dependency-free daemonEventTypes subpath to acp-bridge; the SDK's value is inlined at build time (same mechanism as mcpTimeouts), so there is no new runtime dependency and no SDK-bundle bloat.
  • Not validated / out of scope: a true two-phase ack protocol (publish-after-child-ack) for the drain — the recovery approach is self-contained on the child side and needs no protocol change. The publish-failed (bus-closed) degradation is unchanged and teardown-only.
  • Breaking changes / migration notes: none. MID_TURN_MESSAGE_INJECTED_EVENT is additively exported from @qwen-code/sdk/daemon; the wire string is unchanged.

Linked Issues

Follow-up to #5175 (post-merge review comments).

中文说明

这个 PR 做了什么

这是 #5175(已合并)的后续,处理该 PR 上 /review 留下的两条建议。其一,把 mid_turn_message_injected 这个 SSE 事件 type 从三个包里各自硬编码的字符串字面量,收敛为单一共享常量。其二,堵住一个狭窄窗口:当 ACP 子进程的 drain 请求在 daemon 已经排空并广播之后才超时,mid-turn 消息可能被静默丢失一轮。

为什么需要

mid-turn drain 特性在三个独立位置用到同一个 wire 字符串 'mid_turn_message_injected':daemon 发布方(acp-bridge/bridgeClient.ts)、SDK 校验/归约(sdk-typescript/daemon/events.ts)、浏览器消费方(webui/midTurnInjectedSidechannel.ts)。任何一处改名/打错而其它处不变,都会静默破坏浏览器侧去重:drain 仍工作,但注入的消息不再从浏览器待发队列移除,下一轮被重复投递。兄弟方法字符串 craft/drainMidTurnQueue 已经集中化;本 PR 让事件类型对齐。

另外,daemon 应答子进程的 drain 时,会先 splice 其内存队列并发布 mid_turn_message_injected SSE 帧(浏览器据此去重),然后响应才回传给子进程。子进程用 2 秒超时与该响应竞速。若超时先触发,子进程会丢弃这个迟到的响应——于是消息从 daemon 队列和浏览器队列都消失了,却从未到达模型:静默丢一轮。本地 IPC 极少接近 2 秒,但影响是静默数据丢失。

审阅者测试计划

如何验证

常量集中化:事件类型现在只在 acp-bridge/src/daemonEventTypes.ts 定义——一个无依赖模块(类似 mcpTimeouts.ts),这样 SDK 通过其对 acp-bridge 的构建期 devDep 再导出它,而不会把 acp-bridge 的类型图拖进 SDK 打包后的 .d.ts。bridgeClient.ts、SDK、webui 都 import 这唯一绑定,改名要么处处传播、要么编译失败。

  • cd packages/sdk-typescript && npx vitest run test/unit/daemonEvents.test.ts test/unit/daemon-public-surface.test.ts → 102 通过,含新增 MID_TURN_MESSAGE_INJECTED_EVENT 防改名断言(值 === wire 字面量、且登记在 known-event 集合)。
  • cd packages/acp-bridge && npx vitest run src/bridgeClient.test.ts → 23 通过。
  • cd packages/webui && npx vitest run src/daemon → 141 通过。

Drain 超时恢复:drain 超时后,子进程现在恢复迟到的响应(daemon 已排空+广播)并在下一批 tool 注入,而不是丢弃。

  • cd packages/cli && npx vitest run src/acp-integration/session/Session.test.ts → 146 通过,含新增 recovers a drain that timed out and injects it on the next batch(第 1 批超时,迟到 resolve daemon 的应答,断言在第 2 批注入且恰好记录一次)。

类型检查:npx tsc --noEmit 在 acp-bridge / sdk-typescript / webui / cli 干净。构建:npm run build 在 acp-bridge → sdk-typescript → webui 干净;事件常量在构建时内联进 SDK 发布包(index.cjs/mjs、daemon/index.js/cjs),因此没有新的运行时 acp-bridge 依赖。

证据(前后对比)

N/A——非用户可见(共享常量 + daemon/子进程的 drain 恢复代码路径;无 UI 变化)。行为由上述单测钉住。

测试平台

OS 状态
🍏 macOS ✅ 单测 + tsc --noEmit + 打包
🪟 Windows ⚠️ 未测(CI)
🐧 Linux ⚠️ 未测(CI)

环境(可选)

macOS 上的单测 + tsc --noEmit + npm run build(acp-bridge、sdk-typescript、webui)。无 live daemon/浏览器会话。

风险与范围

  • 主要风险/权衡:恢复的 drain 响应在下一批 tool(或若 turn 已结束,则下一轮第一批)注入——一种优雅的迟到投递,与既有的「下一轮」兜底一致,因为浏览器已去重。恢复缓冲在下一次 drain 时清空,瞬时停顿不会滞留消息。常量迁移给 acp-bridge 增加一个无依赖的 daemonEventTypes 子路径;SDK 的值在构建时内联(与 mcpTimeouts 同机制),因此无新增运行时依赖、不增大 SDK 包。
  • 未验证/范围外:真正的两阶段 ack 协议(子进程 ack 后再 publish)——恢复方案在子进程侧自洽、无需改协议。publish 失败(bus 关闭)的降级不变,且仅在 teardown 出现。
  • 破坏性变更/迁移说明:无。MID_TURN_MESSAGE_INJECTED_EVENT 是从 @qwen-code/sdk/daemon 增量导出;wire 字符串不变。

关联 Issue

#5175 的后续(合并后评审意见)。

wenshao added 2 commits June 18, 2026 04:24
…rains

Follow-up to QwenLM#5175 addressing two post-merge /review suggestions.

Centralize the `mid_turn_message_injected` SSE event `type`: it was a bare
literal in the daemon publisher (acp-bridge), the SDK validator/reducer, and the
browser consumer (webui), so a rename in one could silently break browser-side
dedup. It now lives once in acp-bridge's dependency-free `daemonEventTypes`
module (lightweight like `mcpTimeouts`, so the SDK re-exports it via its
build-time devDep without dragging acp-bridge's type graph into the SDK bundle),
and bridgeClient / the SDK / webui all import the single binding.

Close the drain-timeout message-loss window: the daemon splices + SSE-publishes
(browser dedupes) before the ACP child's response lands, so if the child's 2s
drain timeout fires first, the late response was discarded — losing the messages
from both queues (silent, one-turn loss). The child now recovers that late
response and injects it on the next batch instead of dropping it.

Tests: drain-timeout recovery (Session), and a rename-safety assertion pinning
the shared event constant to the wire literal.
…nParts

- Emit a `debugLogger.debug` line when a timed-out drain is recovered (session
  id + count), guarded on a non-empty payload, so the recovery path is
  correlatable in production logs.
- Rename `#formatMidTurnParts` → `#buildMidTurnParts`: the method records to the
  chat transcript, so a "format" verb understated its side effect.
@wenshao
wenshao dismissed a stale review via f9d4ddb June 18, 2026 00:42
origin/main refactored `#drainMidTurnUserMessages` (it now takes an
`abortSignal`, parses rich text/structured drain items via
`parseMidTurnDrainResponse`, and resolves them through
`prefixMidTurnUserMessageParts`), but kept the splice-then-discard timeout path.
Re-applied the drain-timeout recovery on top of that structure: the late
response is now parsed into `DrainedMidTurnMessage[]`, buffered, and re-injected
on the next batch through the shared `#buildMidTurnParts` loop.

Also folds in the latest review feedback:
- `#recoverLateDrain` bounds the wait with a 30s secondary deadline (unref'd)
  so a response arriving long after the turn is dropped, not injected into an
  unrelated context — and swallows a late rejection.
- no variable shadowing in the recovery handler.
- removed the orphaned constant doc-blocks in bridgeClient.ts; the import site
  carries a one-line note instead.
@wenshao

wenshao commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator Author

✅ Local verification — centralized mid-turn event constant @ e166858

Verdict: PASS for the centralization (Part 1), verified end-to-end through the built package boundaries. The drain-recovery logic (Part 2) is internal ACP-session code that can't be driven live without a full daemon + LLM + custom-client harness — scoped to the PR's unit tests below, with the SDK-side data contract it relies on verified.

Method

Isolated worktree off the PR head (e166858, which merges main and re-applies the change), clean npm ci, built @qwen-code/acp-bridge + @qwen-code/sdk. Then, under tmux, ran a Node harness that imports the built public exports (@qwen-code/acp-bridge/daemonEventTypes and @qwen-code/sdk/daemon) — i.e. the same surface the daemon publisher, the SDK validator, and the browser consumer actually resolve at runtime — not the ./src files.

Part 1 — centralized constant, real run (tmux)

node v22.22.2 — importing BUILT @qwen-code/sdk/daemon + @qwen-code/acp-bridge/daemonEventTypes
publisher  @qwen-code/acp-bridge/daemonEventTypes : "mid_turn_message_injected"
SDK re-export @qwen-code/sdk/daemon               : "mid_turn_message_injected"
PASS  value is the wire literal
PASS  publisher === SDK re-export (single source of truth)
PASS  DAEMON_KNOWN_EVENT_TYPE_VALUES includes it
PASS  isDaemonEventType(constant) === true
PASS  asKnownDaemonEvent(valid frame) recognized  — messages=["hi during tool exec","second msg"]
PASS  asKnownDaemonEvent(malformed data) -> undefined
PASS  asKnownDaemonEvent(typo type) -> undefined  — rename/typo rejected, not silently mis-deduped
=== 7 passed, 0 failed ===

This proves the PR's core claim — "a rename can't silently break browser-side dedup": the publisher literal, the SDK re-export, and the validator all share one value, and the recognizer is exact-match (a typo'd type is rejected rather than mis-handled).

Part 1 — bundling claim verified

The built @qwen-code/sdk/daemon bundle inlines the literal (1 occurrence) with 0 runtime imports of @qwen-code/acp-bridge — so the SDK carries no runtime dependency on acp-bridge; the value is baked in at build time. This confirms the "lightweight build-time devDep, same as mcpTimeouts" design described in the diff.

Part 2 — recover timed-out drains (scoped)

Session.#drainMidTurnUserMessages now, on a drain timeout, calls #recoverLateDrain(drainPromise) to bound the wait for the late daemon response (the daemon has already spliced the queue + published the mid_turn_message_injected SSE echo, so the browser deduped), stash it in midTurnRecoveredMessages, and re-inject + record it on the next batch (#takeRecoveredMidTurnMessages → #buildMidTurnParts) instead of dropping it (which would be silent loss from both queues). A late rejection is still swallowed.

  • This path requires a live ACP turn with tool execution + a client that stalls the drain ext-method past the timeout, then answers late — not reachable without an LLM-backed turn, so I did not drive it live.
  • It is covered by the PR's unit tests (Session.test.ts, 46 drain/recovery assertions; daemonEvents.test.ts, 10 constant assertions).
  • I did verify the SDK-side data contract the recovery relies on: isMidTurnMessageInjectedData accepts { sessionId, messages: string[] } and rejects malformed payloads (see Part 1 run).

Findings

  • ⚠️ Part 2 not exercised at runtime (boundary, not a defect): the timed-out-drain → recover-on-next-batch flow is verified only by unit tests here; a live daemon+LLM+stalling-client repro would close that gap if desired.
  • Centralization is clean: single source of truth resolves identically across publisher/SDK/validator in the built artifacts; exact-match gate confirmed; no runtime acp-bridge dependency leaked into the SDK bundle.
🇨🇳 中文版(点击展开)

✅ 本地验证 —— 集中化 mid-turn 事件常量 @ e166858

结论:集中化部分(第 1 部分)通过(PASS),已通过构建产物的包边界端到端验证。超时 drain 恢复逻辑(第 2 部分)属于 ACP 会话内部代码,没有完整的 daemon + LLM + 自定义客户端环境无法实跑 —— 下文限定到该 PR 的单元测试,并验证了其依赖的 SDK 侧数据契约。

方法

基于 PR head(e166858,已合并 main 并重新应用本改动)的隔离 worktree,干净 npm ci,构建 @qwen-code/acp-bridge + @qwen-code/sdk。随后在 tmux 中运行一个 Node 脚本,导入构建后的公共导出(@qwen-code/acp-bridge/daemonEventTypes 与 @qwen-code/sdk/daemon)—— 即 daemon 发布方、SDK 校验器、浏览器消费方在运行时实际解析的同一边界,而非 ./src 源文件。

第 1 部分 —— 集中化常量,实跑(tmux)

publisher  @qwen-code/acp-bridge/daemonEventTypes : "mid_turn_message_injected"
SDK re-export @qwen-code/sdk/daemon               : "mid_turn_message_injected"
PASS  值为 wire 字面量
PASS  publisher === SDK 重导出(单一事实来源)
PASS  DAEMON_KNOWN_EVENT_TYPE_VALUES 包含它
PASS  isDaemonEventType(常量) === true
PASS  asKnownDaemonEvent(合法帧) 被识别
PASS  asKnownDaemonEvent(数据非法) -> undefined
PASS  asKnownDaemonEvent(类型拼写错误) -> undefined  —— 重命名/拼写错误会被拒绝,而非被错误去重
=== 7 passed, 0 failed ===

这证明了该 PR 的核心主张 ——「重命名不会悄悄破坏浏览器侧去重」:发布方字面量、SDK 重导出、校验器共享同一个值,且识别为精确匹配(拼写错误的 type 会被拒绝)。

第 1 部分 —— 打包方式验证

构建后的 @qwen-code/sdk/daemon 产物已内联该字面量(出现 1 次),且对 @qwen-code/acp-bridge 的运行时导入为 0 —— 即 SDK 不带 acp-bridge 的运行时依赖,值在构建期写入。这与 diff 中描述的「构建期 devDep 内联,等同 mcpTimeouts」一致。

第 2 部分 —— 恢复超时的 drain(限定)

Session.#drainMidTurnUserMessages 在 drain 超时时,调用 #recoverLateDrain(drainPromise) 有界等待 daemon 的迟到响应(daemon 此时已拼接队列并发布 mid_turn_message_injected SSE 回显,浏览器已去重),暂存到 midTurnRecoveredMessages,并在下一批次重新注入并记录(#takeRecoveredMidTurnMessages → #buildMidTurnParts),而非丢弃(否则两端队列都丢失 = 静默丢消息)。迟到的拒绝仍被吞掉。

  • 该路径需要带工具执行的实时 ACP 回合 + 一个把 drain ext-method 拖过超时再迟答的客户端 —— 无 LLM 回合不可达,故未实跑。
  • 由该 PR 的单元测试覆盖(Session.test.ts,46 处 drain/恢复断言;daemonEvents.test.ts,10 处常量断言)。
  • 我验证了恢复逻辑依赖的 SDK 侧数据契约:isMidTurnMessageInjectedData 接受 { sessionId, messages: string[] } 并拒绝非法负载(见第 1 部分实跑)。

观察与结论

  • ⚠️ 第 2 部分未在运行时实测(边界,非缺陷):超时 drain → 下一批次恢复 的流程此处仅由单元测试验证;如需可用 daemon+LLM+拖延客户端 做一次实时复现来补齐。
  • 集中化干净:构建产物中发布方/SDK/校验器解析到完全一致的单一来源;精确匹配门已确认;SDK 产物未泄漏 acp-bridge 运行时依赖。

Verified locally against PR head e166858. Tested through built public package exports under tmux.

@wenshao

wenshao commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

@wenshao
wenshao enabled auto-merge (squash) June 18, 2026 06:05
@wenshao
wenshao merged commit 9a50877 into QwenLM:main Jun 18, 2026
53 checks passed

@doudouOUC doudouOUC left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM — 两个聚焦修复,正确性和测试覆盖都到位。

常量集中化

  • daemonEventTypes.ts 无依赖模块 → SDK re-export → webui 消费,与 mcpTimeouts.ts 同模式,改名编译时全链路失败
  • export const 保留字面量类型,switch 窄化和 DaemonEventEnvelope 类型参数不受影响
  • 防改名测试 expect(MID_TURN_MESSAGE_INJECTED_EVENT).toBe('mid_turn_message_injected') 钉住 wire 值

Drain 超时恢复

  • #recoverLateDrain 用 Promise.race + 30s 二级截止时间,Symbol 哨兵区分超时与真实响应,pending.catch + try/catch 双重吞掉迟到 rejection
  • recovered buffer 在 midTurnDrainUnavailable 检查之前清空 → 即使 drain 永久禁用,之前暂存的消息仍会注入,不会丢失
  • #buildMidTurnParts 提取逐行对比原内联代码完全保真,纯机械提取

建议(非阻塞)

dispose() 中未清理 midTurnRecoveredMessages。功能上无害(dispose 后不再调 #drainMidTurnUserMessages,timer 用了 unref()),但与 notificationQueue = [] / cronQueue = [] 的 dispose 模式不一致。建议加一行 this.midTurnRecoveredMessages = []; 保持防御性 cleanup。

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

Labels

category/core Core engine and logic daemon scope/session-management Session state and persistence type/bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants