Skip to content

fix: show a failed context compaction in the conversation - #5478

Merged
wbxl2000 merged 4 commits into
mainfrom
fix/show-compaction-failure-reason
Nov 26, 2026
Merged

wbxl2000 merged 4 commits into
mainfrom
fix/show-compaction-failure-reason

Conversation

@RealKai42

@RealKai42 RealKai42 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Screenshots / Recordings

在 Web 上手动 /compact,模型服务拒绝压缩请求(400)之后的画面。修复前只有右下角一条 6 秒就消失的提示;修复后,失败作为一条压缩分隔线留在对话里,紧跟失败原因(截图里第二次 /compact 成功了,是正常的「Context compacted」分隔线,可以对照;图里的 token 数来自假模型):

修复前 修复后
修复前:右下角只有 Note「Context compaction did not finish」 修复后:对话里是红色的「Context compaction failed」分隔线和拒绝原因,下面是一次成功压缩的分隔线

Requirement or Bug

在 Desktop 和 Web 上压缩上下文,压缩请求被模型服务拒绝时,界面只在右下角弹一条 6 秒就消失的「Note:Context compaction did not finish」。用户不知道是模型服务拒绝了,分不清是失败还是被取消,对话里也不留任何痕迹,刷新页面或换一个客户端打开就什么都看不到。TUI 在同样的情形下会在转录里显示 Error: [compaction.failed] …。

这个 PR 之后,压缩失败和压缩成功一样,作为一条压缩分隔线写进对话:标题「Context compaction failed」(自动压缩是「Auto-compaction failed」),后面是失败原因,悬停可以看到错误码、HTTP 状态和 request ID。它随会话保存,刷新、恢复会话、第二个客户端都能看到。

Bug Reproduction Steps

  1. 在 Desktop 或 Web 上发一条消息,等回复结束。
  2. 输入 /compact 发送,让模型服务对压缩请求返回 400(新 E2E 里是 model.lane('compaction').script(httpError(400, …)))。
  3. 修复前:右下角弹出「Note:Context compaction did not finish」,6 秒后消失,页面上任何地方都看不到拒绝原因。新 E2E 的 compact() 在 Desktop、Web 上看不到失败信号,只能等到 30 秒限时,所以 self-test/compact.spec.ts 的反例原来用 onlyOn: ['tui', 'acp'] 排除了这两个面。

Root Cause

压缩成功时,kap-server 把 wire 里的 full_compaction.complete 投影成对话里的一条压缩 item,客户端据此画出「Context compacted」分隔线。压缩失败时,引擎写下的是 full_compaction.cancel,它不带任何原因,kap-server 的会话投影遇到它只是把进行中的压缩丢掉。失败的信息只通过两条实时 notice 送达客户端:一条写死的警告「Context compaction did not finish」,一条错误码为 compaction.failed、带原因的错误。

客户端处理错误 notice 时有一条规则:当前打开的会话里的错误 notice 一律不弹提示,因为回合失败的原因已经显示在失败卡上。手动压缩不属于任何回合,没有失败卡,于是原因被这条规则丢掉了;而 notice 本来就不进对话、订阅时也不重发,所以就算弹出来,刷新之后也没了。

所以根因不在提示怎么弹,而在于失败没有进入会话的持久记录。这个 PR 是根本修复:把失败原因写进 wire 记录,投影成对话里的 item,客户端照着画。回合内失败交给失败卡的去重规则保持不变。

Code Changes

核心思路:压缩失败和压缩成功走同一条路径。引擎在压缩失败、且没有回合在等它时,把错误写进 full_compaction.cancel;kap-server 的会话投影把带错误的 cancel 变成一条 outcome: 'failed'、带 error 的压缩 item;Desktop 和 Web 把它画成压缩分隔线的失败样式。失败因此像成功一样可以回放、跨客户端可见,客户端也不再需要从 notice 的先后顺序里倒推。

sequenceDiagram
    participant Engine as 引擎(fullCompaction)
    participant Fold as kap-server 会话投影
    participant Client as Desktop / Web 客户端
    Engine->>Fold: full_compaction.cancel { error }(持久 wire 记录)
    Fold->>Client: item:kind compaction,outcome failed,error
    Client->>Client: 画失败分隔线,结算这次压缩
    Engine->>Client: notice compaction.cancelled(did not finish)
    Client->>Client: 已由 item 结算,跳过这条提示
    Engine->>Client: notice compaction.failed
    Client->>Client: 当前会话:不弹(对话里已有);后台会话:弹一条错误提示
Loading

kap-server 在发 notice 之前会先把待发的回合更新推出去,所以失败 item 先于两条 notice 到达客户端。客户端收到失败 item 时结算压缩并记一笔,随后那条「did not finish」被跳过;用户主动取消时没有失败 item,警告照旧显示。

关键决策

决策 选择 没选 理由
失败显示在哪 对话里的压缩分隔线 右下角的错误提示(本 PR 的第一版) 提示会消失、不随会话保存、刷新和第二个客户端都看不到;成功的压缩本来就在对话里,失败应该对称。第一版为了去重要比对失败卡上的错误、按约 6 毫秒的先后撤掉警告,比较脆
什么时候在 cancel 上记错误 只在引擎会另发错误事件时,也就是没有回合在等这次压缩 每次失败都记 回合在等压缩时,回合以同一个错误失败,失败卡已经显示原因;引擎自己在这里也不发错误事件。沿用同一个判断,对话里不会出现两份原因
失败 item 的形状 复用 kind: 'compaction',用已有的 outcome: 'failed' 加新的可选 error 新增一种 item 协议里 item 本来就有 outcome,错误结构复用回合已有的 ErrorInfo,改动只是加一个可选字段
外层的系统回合 保持 completed 标成 failed 标成失败会让渲染端按失败回合处理,再画一张失败卡
后台会话 保留一条错误提示,标题改成「Context compaction failed」 不弹 用户不在那个会话里,需要一个信号;原来的标题「Model request failed」会误导

阅读顺序

  1. packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts 的 compactionWorker 和 cancelActive:什么时候把错误写进 cancel。
  2. packages/kap-server/src/services/conversation/conversationFold.ts 的 cancelCompaction 和 appendCompaction:cancel 怎样变成失败 item,以及 applyCompactionSummary 不再把后来的摘要并进失败 item。
  3. packages/app-client/src/client/useKimiWebClient.ts 的 settleMainCompaction 和 onMainNotice:用失败 item 结算压缩、跳过随后的警告;删掉了第一版的提示去重和撤警告逻辑。
  4. packages/app-components/src/chat/ChatPane.vue:失败分隔线;undoableTurnIds 只把成功的压缩当作撤销边界。

可以略读:packages/app-core 里类型和投影的透传、i18n、wire-manifest.d.ts 和 kap-server schema/ 下的生成文件、E2E 驱动。

失败分隔线的结构
 <ChatPane>
   turn.role === 'compaction'
+    compaction.error 存在
+      <div class="compact-divider compact-divider--failed" role="separator">
+        <span class="cd-card cd-failed" title="原因 + 错误码 · HTTP 状态 · request ID">
+          cd-chip(折叠图标,红色底) · cd-title「Context compaction failed」 · cd-reason(失败原因,过长截断)
     否则
       原来的 Context compacted 分隔线

Behavior Changes and Affected Users

行为 改动前 改动后 谁依赖旧行为 退路
Desktop、Web:当前会话手动压缩失败 只弹警告「Note:Context compaction did not finish」,6 秒消失,没有原因 对话里出现失败分隔线和原因,不弹提示;警告不再出现 无 无
Desktop、Web:回合结束后的自动压缩失败(没有回合在等它) 同上 同上,标题「Auto-compaction failed」 无 无
Desktop、Web:回合内的自动压缩失败,但回合没在等它 同上 失败分隔线出现在这个回合里 无 无
Desktop、Web:回合在等自动压缩、压缩失败导致回合失败 失败卡显示原因,另有「did not finish」警告 不变(不写失败 item,没有分隔线) — —
Desktop、Web:后台会话压缩失败 「did not finish」警告加一条标题为「Model request failed」的错误提示 会话已在客户端加载时:对话里有失败分隔线,只弹一条标题为「Context compaction failed」的错误提示;未加载时:警告加错误提示,标题改正 无 无
Desktop、Web:用户主动取消压缩 「did not finish」警告 不变 — —
刷新、恢复会话、第二个客户端 看不到压缩失败过 看得到失败分隔线。升级前写下的会话里 cancel 不带错误,回放结果和以前一样 无 无
撤销:失败压缩之前的消息 失败压缩不在对话里,不影响撤销 失败分隔线不算撤销边界,之前的消息仍可撤销 — —
wire:full_compaction.cancel 只有 agentId 失败时多一个可选的 error(KimiErrorPayload) 读 wire 的工具(vis、回放) 字段可选,旧读法照常工作
KAP:会话里的压缩 item 只有成功的压缩,outcome 总是 completed 可能出现 outcome: 'failed'、带 error 的压缩 item 本仓库的 Desktop、Web;读 /turns 或 WebSocket item 的外部 KAP 客户端 无。见下文兼容性
新 E2E:Desktop、Web 上 compact() 遇到压缩失败 等满 30 秒超时 对话里出现失败分隔线,立即报错 场景作者 —
TUI、ACP 显示 Compaction cancelled 和错误 不变;TUI 的 replayBuilder 仍把 cancel 当作取消 — —

契约文件:packages/agent-core-v2/docs/wire-manifest.d.ts(full_compaction.cancel 加可选 error)、packages/kap-server/schema/contract.txt、openapi.json、asyncapi.json(压缩 item 加可选 error),apiSurface.test.ts 里的 HOST_CONTRACT 摘要随之更新,HOST_API_LEVEL 保持 1。

  • 新客户端连旧服务端:旧服务端不会发失败 item,客户端回到原来的 notice 路径,当前会话的失败只剩「did not finish」警告,和这个 PR 之前一样,不会坏。
  • 旧客户端连新服务端(例如旧版 Desktop 连远程主机上的新版 kap-server):旧客户端不看压缩 item 的 outcome,会把失败的压缩画成「Context compacted」分隔线,也会把它当成撤销边界。这是误导,但不会让客户端出错;所以没有升 HOST_API_LEVEL。需要维护者确认是否接受。
  • 外部 KAP 客户端:如果把所有压缩 item 都当作成功,需要开始看 outcome。

测试覆盖

  • packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts:手动压缩失败时 full_compaction.cancel 带 compaction.failed 错误;回合在等压缩时 cancel 不带错误。
  • packages/kap-server/test/services/conversation.test.ts:带错误的 cancel 投影成失败 item(回合之间是系统回合,回合内是 item),后来的摘要不会并进失败 item;不带错误的 cancel 仍然不显示(原有用例)。
  • packages/app-client/test/conversation-events.test.ts:当前会话的失败进对话、压缩被结算、不弹提示;只有取消时警告保留;失败之后再取消一次,警告照常;后台会话只有一条标题正确的错误提示。
  • tests/e2e/self-test/compact.spec.ts:反例去掉 onlyOn,在 Desktop、Web 上也跑。

上面三个单元测试文件里的新断言在没有修复的代码上都失败。

本机验证(macOS)
  • 先红后绿:把引擎、kap-server、客户端的源码改动临时撤掉,上面三个文件里各有 1 条用例失败;恢复后全过。
  • 受影响的单元测试:kap-server 的契约和会话测试、agent-core-v2 的 fullCompaction 和 replayBuilder、packages/app-client 的会话事件、packages/app-core 和 packages/app-components 全部,211 个文件、2643 条通过。
  • E2E:self-test/compact.spec.ts 在 web、tui、acp 上 9/9 通过;改成分隔线样式后,重新 pnpm sync:web,Web 上 3/3 通过。Web 的反例约 7 秒报错,不再等满 30 秒。Desktop 和 Windows 没有跑。
  • 手动:用假模型(压缩请求交替返回 400 和成功)起 kimi web,确认失败分隔线出现、没有提示、刷新后还在、之后能继续发消息,第二次压缩成功后显示正常的分隔线。
  • 检查:pnpm lint 以 0 退出;pnpm run check:duplication 通过;agent-core-v2、kap-server、tests/e2e 的类型检查和 pnpm --filter kimi-code-app run typecheck 通过。

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.

When a manual compaction failed on Desktop or Web, the open session only
showed a six-second "Context compaction did not finish" note. The error
notice that carries the reason was dropped, because error notices of the
open session are left to the failed-turn card, and a manual compaction
belongs to no turn.

Toast a compaction.failed notice in the open session unless the last
turn already failed with that same error, title it "Context compaction
failed", and dismiss the did-not-finish note it follows. The E2E
compact() driver now fails at once on that notice, so its refusal case
runs on Desktop and Web too.
@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: e19e138

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

This PR includes changesets to release 4 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kap-server Patch
kimi-code-app Patch
@moonshot-ai/kimi-code 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 26, 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-26T09:29:24.515311Z e19e138 Manual request
🔒 Security Review ✅ Completed 2026-11-26T03:23:28.451920Z 4fd0061 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.

RealKai42 added a commit that referenced this pull request Nov 26, 2026
@pkg-pr-new

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

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

commit: e19e138

A failed compaction only reached Desktop and Web as notices: a
"did not finish" warning and an error notice that the open session
drops, so the reason never showed and nothing stayed in the transcript.

The engine now records the error on full_compaction.cancel when no turn
owns the failure, kap-server projects it as a compaction item with
outcome "failed" and an error, and the renderer draws it as a failed
compaction divider with the reason. The client settles the compaction
from that item and skips the did-not-finish note that follows it. A
failed compaction is not an undo boundary and never absorbs a later
summary. Background sessions keep one error toast titled "Context
compaction failed".
wbxl2000 added a commit that referenced this pull request Nov 26, 2026
@wbxl2000 wbxl2000 changed the title fix(app-client): show why a context compaction failed fix: show a failed context compaction in the conversation Nov 26, 2026
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

…ilure

# Conflicts:
#	packages/kap-server/test/apiSurface.test.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2323d2bc1a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const open = openTurn(state);
const turn = open ?? addTurn(state, time, 'system');
turn.items.push({
type: 'system',
kind: 'compaction',
item_id: nextItemId(turn),
status: 'ended',
outcome: 'completed',
outcome: error === undefined ? 'completed' : 'failed',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Negotiate failed-compaction items before sending them

When an older Desktop/Web client connects to an upgraded kap-server and a compaction fails, this new item is sent unconditionally; the released client ignores outcome/error, renders it as “Context compacted,” settles any compaction wait as completed, and treats it as an undo boundary. Preserve the prior response shape for unnegotiated clients, or gate the new item behind an opt-in parameter/capability, because core turn and item responses must remain backward compatible.

AGENTS.md reference: packages/kap-server/AGENTS.md:L7-L10

Useful? React with 👍 / 👎.

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.

Keeping this ungated, on purpose. Here's why:

  • The response shape stays compatible. outcome on items already allowed "failed", and error is a new optional field. A caller that reads the documented fields can tell a failed compaction from a completed one, so external agents and bots that read /turns see a correct record.
  • The old-client problem is limited to released first-party Desktop/Web clients that ignore outcome. Those clients only reach a newer server through a remote host (SSH or Remote Control) whose version doesn't match. A local Desktop always ships with its own server.
  • Gating would add an opt-in parameter to /turns and the WebSocket subscribe, plus an entry in meta.capabilities, just to hide a record that the protocol already describes correctly.

This caveat is also listed in the PR description. Maintainers, please confirm this trade-off is acceptable. If it isn't, I'll add the opt-in.

@@ -248,6 +247,7 @@ export const compactionItemSchema = z.object({
tokens_after: z.number().nonnegative().optional(),
compacted_count: z.number().int().nonnegative().optional(),
summary: z.string().optional(),
error: errorInfoSchema.optional(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Document persisted compaction failures in the KAP guide

Adding error and emitting failed compaction items changes the core conversation workflow, but packages/kap-server/docs/kap.md remains unchanged: consumers of the built-in GET /api/v1/kap.md guide are not told that a failed :compact operation is now persisted as a system item, how to distinguish it from a completed compaction, or that it can be recovered after reconnect despite notices themselves not being replayed. Update the built-in guide alongside this protocol change.

AGENTS.md reference: packages/kap-server/AGENTS.md:L13-L16

Useful? React with 👍 / 👎.

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.

Fixed in e19e138. The item section of kap.md now explains:

  • how outcome separates a completed compaction from a failed one;
  • the shape of error on a failed compaction;
  • that a failed compaction stays in the turns after a reconnect, even though its notices are not replayed;
  • that a compaction a running turn was waiting on fails that turn instead.

Comment on lines +634 to +635
const payload = toKimiErrorPayload(error);
this.cancelActive(active, payload);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve provider metadata on the failure item

For ordinary HTTP compaction failures, compactionRound wraps the provider error in a compaction.failed Error2 whose details are empty and whose status code/request ID exist only in cause; serializing that wrapper here therefore puts the metadata under cause, while kap-server's errorInfoOf reads only the top-level details. Consequently the new divider cannot show the promised HTTP status or request ID for typical 400/429 failures. Copy those diagnostics onto the outer payload or make the conversation projection traverse the cause chain.

Useful? React with 👍 / 👎.

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.

Good catch. Fixed in e19e138. The real payload has the status code only under cause.details, and serialize.ts deliberately strips statusCode from coded outer errors. So the conversation projection now reads status_code and request_id from the cause chain when they're missing at the top level. The fold test now uses that real shape, and it failed before the fix.

Comment on lines +1968 to +1969
if (notice.code === 'compaction.cancelled') {
if (failedCompactionSettled.delete(sessionId)) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep a background warning for compaction authentication failures

When a loaded background session's compaction fails with a 401/403, the persisted item carries provider.auth_error, so this branch consumes the compaction.cancelled warning; the following error notice is then discarded by isModelTurnErrorNotice because provider.auth_error is classified as a turn error. A user viewing another session therefore receives no toast or warning at all, whereas the cancellation note was visible before this change. Avoid consuming the warning unless the corresponding error notice will be surfaced, or exempt compaction failures from the model-turn suppression.

Useful? React with 👍 / 👎.

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.

Confirmed and fixed in e19e138. When the cancelled notice is skipped because a failed compaction item already settled the compaction, the next error notice for that session is marked as the compaction failure. That notice no longer goes through the model-turn suppression, so a background session gets one toast titled "Context compaction failed". There's a regression test for the 401 case, plus a check that an unrelated auth error notice is still hidden.

Read the HTTP status and request ID of a failed compaction from the
error's cause chain, raise a background toast for a compaction that fails
on authentication, and describe failed compaction items in the KAP guide.
@wbxl2000

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: e19e1381b6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@wbxl2000
wbxl2000 merged commit e74f142 into main Nov 26, 2026
29 checks passed
@wbxl2000
wbxl2000 deleted the fix/show-compaction-failure-reason branch November 26, 2026 11:20
@7Sageer 7Sageer mentioned this pull request Nov 27, 2026
6 tasks done
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