Skip to content

fix(agent-core-v2): send a tool result's note the same way after a session is restored - #5640

Merged
sailist merged 2 commits into
mainfrom
fix/tool-notes-render-the-same-after-resume
Nov 27, 2026
Merged

sailist merged 2 commits into
mainfrom
fix/tool-notes-render-the-same-after-resume

Conversation

@RealKai42

Copy link
Copy Markdown
Collaborator

Requirement or Bug

一个会话里用过 Write 或 Edit 之后,只要重启产品、/reload 或者重新载入这个会话,下一个请求的 prompt 缓存前缀就从第一个 Write 或 Edit 的结果处断开,后面的历史全部重新计费。写代码的会话几乎都会用到这两个工具,用户却收不到任何信号。这个 PR 让恢复出来的工具结果和实时发出时完全一样。

这和 #5585 修的问题同一类:同一个工具结果,实时发出的样子和从日志回放的样子不一样。

Bug Reproduction Steps

  1. 让模型用 Write 写一个文件,或者用 Edit 改一个文件。
  2. 重启产品(或运行 /reload),回到这个会话,再发一条消息。
  3. 对比重启前后两次请求里的这条工具结果:
协议 实时发出 恢复后
kimi(OpenAI 兼容) "content": [{"type":"text","text":"Wrote 8 bytes to out.txt"}, {"type":"text","text":"<system>The change is applied; …</system>"}] "content": "Wrote 8 bytes to out.txt\n<system>The change is applied; …</system>"
anthropic tool_result 里两个 text 块 tool_result 里一个 text 块

Root Cause

所有请求,实时的和恢复后的,都经过同一个投影(agent/loop/projection.ts 的 projectedContent,最终调 contextMemory/toolResultRender.ts 的 renderToolResultForModel)。两边的差别在送进来的消息:

  • 实时:执行器的 legacyResult(tool/executor/legacy-adapter.ts)已经把 note 作为最后一个文本块追加在输出后面。投影认出 note 已经在内容里,不再加。
  • 恢复后:日志的 tool.result 记录把输出和 note 分开存,折叠回来的消息只有输出,note 是单独的字段。renderToolResultForModel 再把 note 加回去:输出只有一个文本块时,用 \n 把 note 拼进这一块。

所以恢复后的块结构和实时不同。同一个函数还有两处会让恢复后的结果对不上:

  • 出错的结果:单块输出会先被拼上错误前缀,再接 note。
  • 输出为空:执行器已经把它规范成 Tool output is empty.,回放时又被换成 <system>Tool output is empty.</system>。

这是根本修复:renderToolResultForModel 先照执行器的做法把 note 作为最后一块并进输出,再按普通结果渲染错误前缀和耗时。实时那边送进来的内容本来就是这个形状,所以实时请求不变,恢复后的请求变得和实时一样。

Code Changes

只改 renderToolResultForModel:

 renderToolResultForModel(result)
-  rendered = renderStatus(result)
+  rendered = renderStatus(result with output = outputWithNote(result))
   prepend the wall time header to the first text part
-  if there is a note
-    if rendered is one text part: merge "text\nnote" into it
-    else append the note as its own part
   return rendered
+
+outputWithNote({ output, note })
+  no note: output
+  otherwise: [...output, note], with an empty output shown as "Tool output is empty." first,
+             as the executor does before it appends the note

阅读顺序:

  • packages/agent-core-v2/src/agent/contextMemory/toolResultRender.ts 是修复本身;
  • packages/agent-core-v2/test/agent/loop/projection.test.ts 用执行器真实的 legacyResult 构造实时那条消息,用日志折叠后的形状构造恢复后的那条,比较两者的投影;
  • tests/e2e/scenarios/cache/tool-results-keep-the-prefix-across-a-restart-and-a-reload.spec.ts 从真实入口验证。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
恢复后的工具结果带 note、输出是一个文本块(Write、Edit、带 Next Read 提示的 Read、被截断的输出等) note 用 \n 拼进输出那一块 note 是单独的最后一块,和实时一样 无;恢复后的请求本来就该和实时一样 不需要
恢复后的出错结果带 note <system>ERROR…</system>\n输出\nnote 一块 错误前缀、输出、note 三块,和实时一样 无 不需要
恢复后的空输出结果带 note <system>Tool output is empty.</system>\nnote Tool output is empty. 和 note 两块,和实时一样 无 不需要
实时请求 见「实时」一节 不变:实时消息的内容里已经有 note,投影不会再走拼接那条路 — —
Read 读到空内容时估算模型看到的字符数(用来判断 max_chars 够不够) 按 <system>Tool output is empty.</system> + 换行 + note 估算 按模型实际看到的 Tool output is empty. + note 估算,少 18 个字符;max_chars 恰好落在这 18 个字符里的空读取,原来报「too small」,现在能读 把 max_chars 设得极小去读空文件的调用 无
升级之后第一次恢复旧会话 — 旧会话的实时请求本来就是「note 单独一块」,所以升级后恢复也能接上缓存;只有在比现在更早、实时就把 note 拼进去的版本里发出的会话,升级后第一次恢复会断一次,和现在每次恢复都断相比只少不多 — —

受影响的是所有经过引擎投影的客户端:TUI、print 模式、Desktop 和 Web、ACP、SDK、VS Code。另外 apps/vis 的上下文投影也调这个函数,恢复出来的 note 在那里同样显示成单独一块。

测试覆盖:

  • packages/agent-core-v2/test/agent/loop/projection.test.ts(新):成功的 Write、Edit,出错的结果,带耗时的 Bash,空输出,五种情况下恢复后的投影都等于实时,修复前五条全部失败。

  • tests/e2e/scenarios/cache/tool-results-keep-the-prefix-across-a-restart-and-a-reload.spec.ts(新,三个场景)。场景先让模型用一批不同的工具,然后重启或 /reload,再发一条消息,假模型的缓存账本检查前后两次主请求的前缀:

    • 重启:Bash 失败、Write、Edit、审批被拒、读不存在的文件、Grep、Glob、TodoList、回答和关掉问题、前台子 agent;
    • /reload(ACP 没有):Write 和 Edit;
    • 审批挂着时停止,再重启(TUI 上不能在审批挂着时停止)。

    修复前,重启那个在 acp、tui 上失败,/reload 那个在 tui 上失败;第三个在 acp 上本来就通过,它补上清单 A8 原来写着的缺口。

  • 清单 tests/e2e/scenarios/cache/catalog.yaml:新增 A9(重启或 reload 之前跑过各种工具),A8 补上显式覆盖、去掉缺口。

验证

基于 main 0e1ceb9c8,macOS。

  • 单测:pnpm exec vitest run --reporter=agent packages/agent-core-v2/test/agent/loop/projection.test.ts 5 条通过;把 toolResultRender.ts 换回 main 的版本,5 条全部失败。
  • 受影响的引擎测试:packages/agent-core-v2/test/ 下的 agent/loop、agent/contextMemory、agent/tokenCounting、session/tokenCounting、wire、agent/mcp、agent/toolExecutor、features/plan、agent/media、os/backends/node-local/tools、agent/tools,59 个文件,1541 条通过、1 条原本就跳过。
  • packages/kap-server/test/sessions.test.ts、tests/scenarios/prompt-cache.test.ts、apps/vis/server/test:20 个文件、362 条通过。
  • E2E:
    • 修复前(源码模式,acp 和 tui):重启场景在 acp、tui 上断在账本上,/reload 场景在 tui 上断在账本上,停止场景在 acp 上通过。
    • 修复后:
    • Desktop 没在本地跑:它和 Web 共用页面驱动,这次改的又是和面无关的引擎渲染,交给 CI。
  • pnpm lint 通过,pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmit 和 tests/e2e 的类型检查通过,node --test 'scripts/checks/*.test.mjs' 124 条通过,pnpm run check:duplication 0e1ceb9c8 没有新增重复。
  • 没有在真实的 Kimi 服务上验证缓存命中。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

…ssion is restored

Live tool messages carry the note as their last text part, because the
executor appends it to the output. A restored result keeps the note apart
from the output, and renderToolResultForModel merged it into a
single-part output with a newline. Write, Edit and other results with a
note were therefore sent differently on the first request after a
restart or /reload, which broke the prompt cache prefix from that
result on. Failed and empty results with a note differed the same way.

The renderer now appends the note the way the executor does, with an
empty output shown as "Tool output is empty." first, and then renders
the error status and the wall time. Live requests do not change.

A projection test compares the live and the restored rendering for five
kinds of result, and a new E2E cache scenario restarts and reloads after
tools of many kinds. The cache catalog gains A9, and A8 now has explicit
coverage for a turn stopped before its tool ran.
@changeset-bot

changeset-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 0fed077

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
kimi-code-app Patch
@moonshot-ai/kimi-code Patch
@moonshot-ai/agent-core-v2 Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T07:48:20.333247Z 9e1ceba PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@0fed077
npx https://pkg.pr.new/@moonshot-ai/kimi-code@0fed077

commit: 0fed077

@sailist
sailist merged commit 2799623 into main Nov 27, 2026
24 of 29 checks passed
@sailist
sailist deleted the fix/tool-notes-render-the-same-after-resume branch November 27, 2026 09:04
RealKai42 added a commit that referenced this pull request Nov 27, 2026
…sult as it did live (#5658)

expectResumeMatches compares the engine state before and after a resume,
and it drops reminders first. Two prompt cache bugs slipped past it,
because the history a resumed session sends can differ from the live one
while the state matches.

The harness gains expectResumeSendsTheSameHistory, which also projects
the next request's messages on both sides with the projection every
request goes through and compares them. A new resume test registers tools
that return results of many shapes (notes, errors, empty and multi-part
output, truncation, an image, a crash, a wall-time tool and a denied
tool, then a parallel batch) and checks the resume with it. Without the
fixes from #5585 or #5640 the test fails.

expectResumeMatches keeps its behavior for now: the new comparison still
finds three divergences in existing cases (a parallel batch with a denied
call is reordered, a tool call that failed before it started disappears,
and an interruption reminder comes back after undoing every turn). Once
they are fixed, expectResumeMatches will compare the next request too.

The cache catalog lists the new test under A8 and A9.
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.

2 participants