Repository navigation
Conversation
…1170) The Claude CLI never reads stdin while a tool_use waits for its tool_result: the loopback MCP response it blocks on is the only way out. Input steered into that window is silently lost — the exact shape an answered ask_user produces, where the conclusion tool result and the user's answer ride the same step and stdin is always written before the HTTP response unblocks the CLI. Queue the input instead and let the drain send it as the next prompt when the turn closes, inside the same step — the design's own fallback for a CLI that cannot take the steer. Permission and hook waits keep steering: the control protocol answers those over stdin, so the CLI must keep reading there. The fake CLI fixture now models both behaviours: input arriving during a tool_result wait queues for the turn boundary, and --drop-mid-tool-input makes it vanish, matching the observed real CLI.
…for #1170 A user answer consumed as the open bridged call's result and input arriving in the same step must each reach the CLI exactly once, in order: the answer as the tool result the CLI waits on, the input as the next prompt after the turn closes. The settled continuation never duplicates the answer — the drain only fires it when the turn produced no output, which cannot happen once the answer unblocks the CLI.
|
Review: approved Scope reviewed: the two source files, the fixture rewrite, the four new tests, plus the adapter's drain/continuation/markHanded machinery they interlock with. Diff is exactly the 4 declared files, nothing else. Verified on this head:
Findings by the review questions: 1. 2. Settled/queue interleaving — exactly-once holds; I verified the chain independently. (a) When the conclusion tool result rides the step, 3. Queue mechanics — consistent with the existing ACP branch. Identical push shape; 4. Tests — they pin the real behavior, not mock tautology. The fixture models the actual protocol faithfully: the loopback MCP 5. Scope — clean. 4 files, no unrelated changes. P2 (suggestions, not blocking)
Not verifiedBehavior against the real Claude CLI (none on this machine — same limitation the PR declares). Everything above is established against the fixture and the adapter/drain control flow. |
klarkxy
left a comment
There was a problem hiding this comment.
Reviewed via Gemini App · Model: Gemini · Commit:
988aa538b6ed1c85aaa12f870392a8f7298eb3d5
整体评估
本 PR 针对 #1170 定位并修复了 Claude Code CLI 在等待 tool_result(尤其是 ask_user、show_view、request_secret 等调用 concludeTurn 的桥接 MCP 工具)期间不读取 stdin、导致同一 step 内紧随工具结算写入的用户回答或新消息静默丢失的问题。核心机制设计合理:
- 入队与轮次边界冲刷(Flush)时序安全,不破坏 Anthropic API
tool_use -> tool_result紧邻约束:ds-bot/src/host/local-agents/adapter.js的sendInput()在live.engine.steerDropsInput?.(live.engineSession) === true时将输入推入live.queue,不在工具等待窗口期向stdin写入用户文本。live.queue仅在stream()的case 'done':(即收到 Claude CLI 的本轮result事件、整轮结束且live.state置回'idle'后)才出队冲刷,并通过startTurn()->ClaudeSession.prompt()作为下一轮独立 Prompt 发送,绝不会在tool_use与tool_result之间穿插user文本块而触发 Anthropic API400错误。- 多工具并发
tool_use边界成立:当同一条assistant消息包含多个并发tool_use块时,ClaudeSession.noteAssistantBlocks()会将每个非空block.id加入session.pendingToolUses集合,case 'user':仅按收到的block.tool_use_id逐个删除。若部分工具先返回tool_result而仍有其他工具挂起,session.pendingToolUses.size > 0持续为真,期间到达的新输入仍会进入live.queue直至整轮result收尾。
openCall结算回答与同 step 额外输入的exactly-once保证成立:- 当用户消息直接充当挂起桥接调用的返回值(
openCall分支)时,settled仅随即时steer/startTurn的body发送,入队项只保存原始blocks;live.continuation仅在case 'done':且index === 0(零输出静默结束)时兜底触发,CLI 被唤醒并产生输出后index > 0会自动清空live.continuation,不会重复发送回答。
- 当用户消息直接充当挂起桥接调用的返回值(
- 延迟确认
handed水位:入队时仅将{ id: last.id, promptHash }挂在队列项的delivery上,待case 'done':真正出队发送时才调用markHanded(),因此在取消或进程退出后可由下一轮从消息日志重算增量。
在异常恢复、多步交错排队与流式事件窗口边界上,核查出 1 项建议修复问题 与 2 项建议改进项,建议修复后再合入:
分级问题与修改建议
1. 建议修复(逻辑缺陷:会导致消息重复投递)
- 协议内轮次报错(
case 'error':且子进程未退出)未清理live.queue,导致后续重试或下一轮重复发送排队消息- 位置:
ds-bot/src/host/local-agents/adapter.js中的stream()(case 'error':约第 2075 行、末尾queued = live.queue.at(-1)及catch块);关联ds-bot/src/host/local-agents/claude.js中的ClaudeSession.onLine()(case 'result':对is_error === true发出{ type: 'error' })。 - 触发条件:
- Turn 1 因桥接工具(如
ask_user/message_bot)挂起; - Step 2 同时结算该工具并携带用户输入
m3(如'blue'),sendInput()命中steerDropsInput === true将m3推入live.queue并挂载queued.delivery = { id: 'm3' },此时live.handed尚未推进到m3; - Claude CLI 收到
tool_result后若遭遇上游过载或执行错误(如返回{ type: 'result', is_error: true, result: 'API Error: 529 overloaded_error' }或error_during_execution,参见fake-claude.mjs第 100、178 行),--input-format stream-json常驻子进程不会退出(session.dead === false,live.dead === false),ClaudeSession将running置为false并发出{ type: 'error', error }; adapter.js的case 'error':将live.state设为'idle'后直接throw toLlmError(event.error, live),既未调用stopTurn()清空live.queue,catch块也因live.engineSession?.dead !== true未做清理,导致旧的{ blocks, delivery: { id: 'm3' } }残留在常驻live.queue中;- 随后触发
529自动重试或用户重试/发送新消息时,stream()复用同一个live会话,因live.handed未推进而从delta重新提取m3并通过startTurn()立即发给 CLI;紧接着const queued = live.queue.at(-1)又命中残留队列项覆盖其delivery,等该轮case 'done':到达时,live.queue.shift()会把残留的旧m3第二次发送给 Claude CLI。
- Turn 1 因桥接工具(如
- 修改建议:
- 在
stream()的case 'error':分支(以及异常退出清理路径)显式清空live.queue(清空前先归还队列项携带的flushedContext,见下方第 3 点); - 将
stream()中绑定queued.delivery的逻辑限制为“本次stream()调用确实向live.queue推入了新项”时才挂载,避免误绑历史残留项。
- 在
- 位置:
2. 建议改进(顺序一致性、状态回滚与流式窗口闭合)
-
非空
live.queue未阻断后续steer造成消息逆序(FIFO 破坏),以及pendingHooks/stream_event窗口缝隙- 位置:
ds-bot/src/host/local-agents/adapter.js中的sendInput()(第 2062–2074 行);ds-bot/src/host/local-agents/claude.js中的ClaudeEngine.steerDropsInput()(第 82–89 行)与ClaudeSession.onLine()(case 'stream_event':的content_block_start分支)。 - 触发条件与影响:
- 队列插队逆序:若
M1在steerDropsInput === true期间已进入live.queue,而 Claude 收到首个tool_result后未直接结束本轮(case 'done':尚未执行,M1仍在live.queue中),转而触发权限审批卡片(can_use_tool使pendingPermissions.size > 0并挂起 DSH)或进入其他steerDropsInput === false的运行阶段;此时若下一 step 带来新消息M2,sendInput()未检查live.queue.length > 0,会绕过队列直接将M2通过steer()写入stdin,导致 CLI 先收到M2、等轮次结束后才收到M1,且stream()中live.queue.at(-1)会用M2的delivery覆盖M1.delivery。 pendingHooks豁免过宽:claude.js中的session.pendingHooks仅由--include-hook-events输出的观测性system事件(hook_started/hook_response,对应用户本地 Shell Hooks 如PreToolUse/PostToolUse)维护,DS Bot 从不通过stdin回复任何 Hook(case 'control_request':仅处理can_use_tool)。要求session.pendingHooks.size === 0会导致工具执行伴随本地 Hook 运行(或某次 Hook 未发hook_response)时steerDropsInput退回false,重新暴露stdin丢包窗口。stream_event到assistant的微窗口:开启--include-partial-messages时,content_block_start(content_block.type === 'tool_use')早于完整assistant行到达,此时仅置了this.messageHasToolUse = true而尚未写入pendingToolUses;若回环 HTTPtools/call在assistant行刷出stdout管道前先一步挂起并结算,pendingToolUses.size仍为0。
- 队列插队逆序:若
- 修改建议:
- 在
adapter.js的sendInput()中增加非空队列保序守卫:if (live.spec.kind === 'acp' || live.queue.length > 0 || live.engine.steerDropsInput?.(live.engineSession) === true),确保一旦当前轮有排队项,后续到达的输入严格追加在队尾按 FIFO 顺序冲刷; - 在
ClaudeEngine.steerDropsInput()中移除&& session.pendingHooks.size === 0(仅保留真正依赖stdincontrol_response的session.pendingPermissions.size === 0); - 在
ClaudeSession.onLine()的content_block_start(inner.content_block?.type === 'tool_use')分支同步记录inner.content_block.id到this.pendingToolUses(无id时置this.awaitingToolResult = true),与后续noteAssistantBlocks()幂等对齐。
- 在
- 位置:
-
随队列项暂存的
flushedContext在stopTurn()/closeLive()/ 崩溃回滚时未归还至live.pendingContext- 位置:
ds-bot/src/host/local-agents/adapter.js中的stopTurn()、rollbackUnread()、closeLive()与sendInput()。 - 触发条件与影响:若前序纯上下文轮次(如
remaining.length === 0的[Memory update])已将消息计入live.handed并暂存于live.pendingContext,随后在steerDropsInput === true窗口期收到用户消息时,stream()因willDispatchNow === true执行flushedContext = live.pendingContext.splice(0)并将其挂在live.queue队列项{ blocks, flushedContext }上(此时live.flushedContext为undefined)。若在case 'done':冲刷前发生用户点击停止(stopTurn()直接执行live.queue.length = 0)、会话切换关闭(closeLive())或进程崩溃(rollbackUnread()仅检查live.flushedContext),这部分已推进过live.handed的flushedContext既不在live.pendingContext中也不会出现在后续delta里,会被静默丢弃(注:ACP 原有队列路径同受影响)。 - 修改建议:提取辅助函数(如
restoreQueuedContext(live)),在stopTurn()、case 'error':、rollbackUnread()与closeLive()清空或丢弃live.queue前,将所有未冲刷队列项上的flushedContext按entry.id去重归还至live.pendingContext头部。
- 位置:
测试覆盖与 CI 状态核验
- 现有测试评估:
ds-bot/test/fixtures/fake-claude.mjs(真实回环 HTTPmcpCall+--drop-mid-tool-input丢弃模拟)与ds-bot/test/local-agents.test.js新增的 4 组用例有效覆盖了单桥接工具等待期丢包回归、非丢包排队一致性、openCall结算回答与同 step 额外输入的单次有序投递,以及轮次结束后的常规直发路径。 - 建议补充测试:
- 同一
assistant消息含两个并行tool_use(toolu_1、toolu_2),toolu_1已产出tool_result而toolu_2仍在等待时到达用户输入,验证其保持入队直至整轮result结束后才发送; live.queue非空期间遭遇协议内result(is_error: true)或AbortController.abort()(含已暂存pendingContext的场景),验证下一轮重试时用户消息与上下文均精确送达一次、不丢失且不重复发送。
- 同一
- CI 检查状态:当前提交
988aa538b6ed1c85aaa12f870392a8f7298eb3d5上功能测试与构建门禁全部通过(Test result、ubuntu-latest · Node 24 (1/3, 2/3, 3/3)、Leak scan、Desktop app profile、Package result均为success);唯一标红的Evaluate merge guard(PR merge guard)仅因仓库维护者人工签核标签needs-product-ok阻塞,无代码或测试失败。
Issue
Fixes #1170
Agent
Agent: DS Bot (SWE-2.1)
What changed / 改了什么
Root cause: the Claude CLI never reads stdin while a tool_use waits for its tool_result — the loopback MCP response it blocks on is the only way out of that state. Input written into that window is silently lost. This is deterministic for the most common case: an answered
ask_usercard produces a step in which the conclusion tool result and the user's answer are processed together, so the adapter writes the answer to stdin microseconds before the CLI even receives the HTTP response that unblocks it. The answer vanishes — never enqueued, never echoed, never seen.Fix (
claude.js+adapter.js):ClaudeEngine.steerDropsInput(session)reports exactly that window: a tool_result is pending (pendingToolUses/awaitingToolResult) and no permission or hook wait is open. Permission and hook waits are excepted deliberately — the control protocol answers those over stdin, so the CLI must keep reading there, and existing steered-input behaviour depends on it.sendInputqueues input arriving in that window (same mechanism ACP already uses). The drain sends it as the next prompt when the turn closes, inside the same step — the design's own fallback for a CLI that cannot take the steer (docs/plans/2026-11-04-local-agents.md: "Steering while a CLI turn runs is passed to the CLI when it supports it, else it goes out as the next prompt in the same step"). Queued input is not counted as handed until it is actually sent, so aborts and session closes re-deliver it instead of losing it.Tests (
fake-claude.mjsfixture +local-agents.test.js):call-tooldrives a real loopback MCPtools/call) and models stdin fidelity: input arriving during a tool_result wait queues for the turn boundary;--drop-mid-tool-inputmakes it vanish, matching the observed real CLI.Settled/queue interleaving — why exactly-once delivery holds (pinned by the test
a settled answer and simultaneous input during the wait each arrive exactly once, in order):An answer consumed as the open bridged call's result (
stream(), theopenCallbranch) is delivered to the CLI as that call's HTTP response — the tool result it is waiting on. Thesettledentry recorded at the same time becomeslive.continuationonly as a fallback for a turn that ended silently: the drain fires it solely when the finished turn produced no output at all (donehandler,live.continuation !== undefined && index === 0). Once the answer unblocks the CLI, the turn continues and emits output, soindex > 0atdoneand the continuation is discarded instead — the answer cannot be delivered twice. Input arriving in the same step goes throughsendInputwithsettledriding only on the steer/startTurn paths (body); the queue entry deliberately carries the raw input blocks, since the settled content has already reached the CLI as the tool result. Drain order is continuation-first (when it applies) then queue — answer before input, never interleaved, never duplicated.Changelog
Fixed Claude Code Bots silently losing messages sent while a card or tool call was open — answers to questions now reliably reach the agent.
How I checked it / 怎么验证的
npm test(inds-bot/) — fullnpm run test:windows: 8624 pass / 0 fail / 7 skippednode scripts/build-client.mjs --check— no client changes, check cleannpm run lint— 0 errorsindex.jsorsrc/host// 改了index.js或src/host/时跑冒烟测试 — cannot run locally (no deepseek-harness source on this machine); see Not verified belowRed/green evidence: on the pre-fix sources the drop-mode regression test fails (
ok: bluenever arrives — the answer is written into the tool_result wait window and lost), and the queue-mode companion also fails; after the fix all three pass. Targeted:test/local-agents.test.js244 pass / 0 fail / 1 skipped; related files (local-agent-context,local-agent-lifecycle,local-agents-2479-2564,local-agents-2918,context-pr2-local-agents) 95/95. Leak scan: must fix 0.Verified on Mac.
Not verified: behaviour against the real Claude CLI (no Claude CLI on this machine) — the drop-window model rests on the issue's transcript evidence (inputs mid-turn show enqueue records, inputs during the suspension window do not). Whether the real CLI consumes steered input during permission waits is likewise unverified; this PR deliberately keeps the existing steer behaviour there and changes nothing for it.
Checklist / 检查
src/client/changed →npm run buildran andclient.jsis committed. / 改了src/client/就已重新 build 并提交client.js。(N/A — no client changes)Co-authored-by. / 没有把 AI 工具写成作者或Co-authored-by。Co-authored-by(GitHub noreply, unless opted out), or N/A. / 促成改动的高质量外部 Issue/想法已按规范加Co-authored-by(GitHub noreply 邮箱,对方介意除外),或不适用。(N/A)