Skip to content

fix(local-agents): queue input while Claude waits on a tool result (#1170) - #3262

Open
Fei2411 wants to merge 3 commits into
devfrom
fix/1170-claude-suspended-input
Open

Fei2411 wants to merge 3 commits into
devfrom
fix/1170-claude-suspended-input

Conversation

@Fei2411

@Fei2411 Fei2411 commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

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_user card 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.
  • sendInput queues 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.mjs fixture + local-agents.test.js):

  • The fixture gained a faithful MCP-bridge mode (call-tool drives a real loopback MCP tools/call) and models stdin fidelity: input arriving during a tool_result wait queues for the turn boundary; --drop-mid-tool-input makes it vanish, matching the observed real CLI.
  • Regression test (red before the fix, green after): the conclusion tool result + user answer in one step, CLI in drop mode → the answer must still reach the CLI after the turn closes.
  • Companion tests: same flow against the queueing (non-drop) CLI, and the normal path — input after the turn settled starts its own turn, unqueued.

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(), the openCall branch) is delivered to the CLI as that call's HTTP response — the tool result it is waiting on. The settled entry recorded at the same time becomes live.continuation only as a fallback for a turn that ended silently: the drain fires it solely when the finished turn produced no output at all (done handler, live.continuation !== undefined && index === 0). Once the answer unblocks the CLI, the turn continues and emits output, so index > 0 at done and the continuation is discarded instead — the answer cannot be delivered twice. Input arriving in the same step goes through sendInput with settled riding 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 (in ds-bot/) — full npm run test:windows: 8624 pass / 0 fail / 7 skipped
  • node scripts/build-client.mjs --check — no client changes, check clean
  • npm run lint — 0 errors
  • Smoke test, for changes to index.js or src/host/ / 改了 index.js 或 src/host/ 时跑冒烟测试 — cannot run locally (no deepseek-harness source on this machine); see Not verified below
  • Screenshot attached, for interface changes / 界面改动已附截图 — no interface changes

Red/green evidence: on the pre-fix sources the drop-mode regression test fails (ok: blue never 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.js 244 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 / 检查

  • One issue, one subject. / 只做一件事。
  • src/client/ changed → npm run build ran and client.js is committed. / 改了 src/client/ 就已重新 build 并提交 client.js。(N/A — no client changes)
  • No keys, tokens or personal data, also in screenshots. / 没有密钥、token 或个人信息,截图里也没有。
  • No AI tool as author or Co-authored-by. / 没有把 AI 工具写成作者或 Co-authored-by。
  • Substantive external issue/idea credited with Co-authored-by (GitHub noreply, unless opted out), or N/A. / 促成改动的高质量外部 Issue/想法已按规范加 Co-authored-by(GitHub noreply 邮箱,对方介意除外),或不适用。(N/A)

…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.
@Fei2411 Fei2411 added agent/dsbot Opened by a DS Bot team Bot model/swe-2-1 Written by a Bot on Devin SWE 2.1 needs-product-ok Waiting for maintainer product/UI approval before merging to dev labels Dec 5, 2026
…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.
@Fei2411

Fei2411 commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Review: approved
Reviewer: DS Bot (SWE-2.1 Max) @ 988aa53

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:

  • test/local-agents.test.js: 245 pass / 0 fail / 1 skipped (the skip pre-exists).
  • Red-green check: with adapter.js/claude.js reset to origin/dev, exactly the three fix-pinning tests fail — the drop-mode regression, the queue-mode companion, and the exactly-once interleaving test — while the normal-path test passes (it guards pre-existing behavior, correctly). Restored: green.
  • npm run lint: 0 errors (192 pre-existing warnings); build-client --check clean.
  • Commit author is the repo account, no AI authorship; no keys or personal data in the diff.

Findings by the review questions:

1. steerDropsInput judgment — sound. The window (tool_use pending, no permission/hook wait) matches the mechanism in the issue's transcript: stdin writes are only lost while the CLI blocks on a tool_result. Permission/hook waits are correctly excepted — control answers travel over stdin, so the CLI must read there, and queuing instead would break approvals. retryingApi is correctly not part of the window: the CLI is not blocked on a tool result while waiting out an API retry. Dead/retired sessions fall through to the normal steer → recover → startTurn path, which is the right outcome for them (the input must start a fresh turn, not queue behind a corpse).

2. Settled/queue interleaving — exactly-once holds; I verified the chain independently. (a) When the conclusion tool result rides the step, settled content reaches the CLI only as that call's HTTP response; the queue entry carries only the user's raw input blocks, so nothing is duplicated. (b) When the user's answer is consumed as the open call's result (openCall branch), live.continuation is armed but fires solely on done with index === 0; once the answer unblocks the CLI, the turn continues and emits output, so the continuation is discarded — pinned by the interleaving test, which asserts the answer text appears exactly once, in order, and the continuation preamble never appears. (c) The adversarial case (CLI ends its turn with zero output events after consuming the result) would fire the continuation — but that turn then carries the answer instead of the tool result doing so, and the queue still only holds the raw input, so exactly-once survives that case too.

3. Queue mechanics — consistent with the existing ACP branch. Identical push shape; queued.delivery is pinned before the drain and markHanded runs only when the drain actually sends the prompt. Since handing is deferred, aborts and session closes leave the input unhanded and the next stream re-derives it from the message log — redelivery instead of loss, as claimed. The drain order (continuation first when it applies, then queue) matches the PR's claim.

4. Tests — they pin the real behavior, not mock tautology. The fixture models the actual protocol faithfully: the loopback MCP tools/call is real HTTP against the adapter's bridge, and stdin lines written during the wait are held to the turn boundary (or dropped in drop mode). The drop-mode test is the one that would catch a regression to steering: a steer lands inside the window and vanishes. The queue-mode companion alone would indeed be insufficient (a faithful CLI queues mid-turn input itself), but it does not stand alone. The interleaving test's exactly-once counts and ordering assertions are the right invariants.

5. Scope — clean. 4 files, no unrelated changes.

P2 (suggestions, not blocking)

  • The premise "the real CLI never reads stdin during a tool_result wait" rests on transcript evidence, not on a run against the real CLI (declared in the PR). Worth noting this is a safe bet either way: if the real CLI does read stdin there, queuing is semantically equivalent to steering, since the CLI only ever consumes user input at turn boundaries anyway — the fix degrades to the old behavior rather than breaking anything.
  • Permission and hook waits keep the old steer behavior on the assumption that the CLI reads stdin there. If it does not (beyond the control responses it must read), a narrow loss window remains for those states — unverifiable here, acceptable as-is.
  • A steer written in the microsecond race after the CLI's own tool_result is produced but before the process notices can still be lost (the window this PR cannot close). Pre-existing and now reduced from minutes to milliseconds; no action needed.

Not verified

Behavior 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.

@Fei2411 Fei2411 added review/approved Independent review passed — ready to merge reviewed-by/dsbot Reviewed by a DS Bot team Bot reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review) labels Dec 5, 2026
@Fei2411
Fei2411 marked this pull request as ready for review December 5, 2026 21:57

@klarkxy klarkxy 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.

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 内紧随工具结算写入的用户回答或新消息静默丢失的问题。核心机制设计合理:

  1. 入队与轮次边界冲刷(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 API 400 错误。
    • 多工具并发 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 收尾。
  2. openCall 结算回答与同 step 额外输入的 exactly-once 保证成立:
    • 当用户消息直接充当挂起桥接调用的返回值(openCall 分支)时,settled 仅随即时 steer/startTurn 的 body 发送,入队项只保存原始 blocks;live.continuation 仅在 case 'done': 且 index === 0(零输出静默结束)时兜底触发,CLI 被唤醒并产生输出后 index > 0 会自动清空 live.continuation,不会重复发送回答。
  3. 延迟确认 handed 水位:入队时仅将 { id: last.id, promptHash } 挂在队列项的 delivery 上,待 case 'done': 真正出队发送时才调用 markHanded(),因此在取消或进程退出后可由下一轮从消息日志重算增量。

在异常恢复、多步交错排队与流式事件窗口边界上,核查出 1 项建议修复问题 与 2 项建议改进项,建议修复后再合入:

分级问题与修改建议

1. 建议修复(逻辑缺陷:会导致消息重复投递)

  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' })。
    • 触发条件:
      1. Turn 1 因桥接工具(如 ask_user / message_bot)挂起;
      2. Step 2 同时结算该工具并携带用户输入 m3(如 'blue'),sendInput() 命中 steerDropsInput === true 将 m3 推入 live.queue 并挂载 queued.delivery = { id: 'm3' },此时 live.handed 尚未推进到 m3;
      3. 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 };
      4. 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 中;
      5. 随后触发 529 自动重试或用户重试/发送新消息时,stream() 复用同一个 live 会话,因 live.handed 未推进而从 delta 重新提取 m3 并通过 startTurn() 立即发给 CLI;紧接着 const queued = live.queue.at(-1) 又命中残留队列项覆盖其 delivery,等该轮 case 'done': 到达时,live.queue.shift() 会把残留的旧 m3 第二次发送给 Claude CLI。
    • 修改建议:
      • 在 stream() 的 case 'error': 分支(以及异常退出清理路径)显式清空 live.queue(清空前先归还队列项携带的 flushedContext,见下方第 3 点);
      • 将 stream() 中绑定 queued.delivery 的逻辑限制为“本次 stream() 调用确实向 live.queue 推入了新项”时才挂载,避免误绑历史残留项。

2. 建议改进(顺序一致性、状态回滚与流式窗口闭合)

  1. 非空 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;若回环 HTTP tools/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(仅保留真正依赖 stdin control_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() 幂等对齐。
  2. 随队列项暂存的 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(真实回环 HTTP mcpCall + --drop-mid-tool-input 丢弃模拟)与 ds-bot/test/local-agents.test.js 新增的 4 组用例有效覆盖了单桥接工具等待期丢包回归、非丢包排队一致性、openCall 结算回答与同 step 额外输入的单次有序投递,以及轮次结束后的常规直发路径。
  • 建议补充测试:
    1. 同一 assistant 消息含两个并行 tool_use(toolu_1、toolu_2),toolu_1 已产出 tool_result 而 toolu_2 仍在等待时到达用户输入,验证其保持入队直至整轮 result 结束后才发送;
    2. 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 阻塞,无代码或测试失败。

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

Labels

agent/dsbot Opened by a DS Bot team Bot model/swe-2-1 Written by a Bot on Devin SWE 2.1 needs-product-ok Waiting for maintainer product/UI approval before merging to dev review/approved Independent review passed — ready to merge reviewed-by/dsbot Reviewed by a DS Bot team Bot reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants