Skip to content

fix(tui): preserve transcript history across trimming, folding, and replay - #4866

Merged
Grapedge merged 1 commit into
mainfrom
fix/tui-transcript-history-loss
Nov 12, 2026
Merged

Grapedge merged 1 commit into
mainfrom
fix/tui-transcript-history-loss

Conversation

@kimi-agent-bot

Copy link
Copy Markdown
Collaborator

Requirement or Bug

TUI 会话在实时长对话、单轮多步工具调用以及重放/重载(含 stale reload)时,会出现已生成的对话内容或用户问答记录静默消失的问题。本 PR 在不调大窗口或步数阈值掩盖问题的前提下,修复实时裁剪、长轮折叠与 wire 回放三处通用 transcript 生命周期缺陷,确保保留轮次、交互问答记录与有效历史不会静默丢失。

Bug Reproduction Steps

  1. 混合轮次触发实时窗口裁剪:在同一会话中交替运行普通用户轮(含带前置激活卡的提交)、后台 worker 任务通知轮与 cron 定时轮,累计超过 TRANSCRIPT_MAX_TURNS + TRANSCRIPT_HYSTERESIS(默认 20 轮)触发滑动窗口裁剪;仍在保留窗口内的 worker/cron 回复组件会被一并误删,且异步挂载在上一轮的后台终态卡在锚定到通知轮时仍保留旧 turnId。
  2. 长轮触发步数折叠:在同一轮中完成一次 AskUserQuestion,随后继续执行超过 TRANSCRIPT_KEEP_RECENT_STEPS(默认 30)次工具调用(或重放该会话);AskUserQuestion 卡片被 dispose 并压入不可展开的 StepSummaryComponent,问题与用户回答均无法找回。
  3. 非空 wire.jsonl 含损坏记录或读取/折叠失败:会话 wire.jsonl 中间存在一行损坏 JSON 或损坏记录载荷(或读取/折叠报错)时,启动恢复、切换会话或触发 stale reload;重放静默返回空历史并被视作成功 hydration,界面直接显示为空会话且无报错或警告。

Root Cause

本次为根本修复(未通过调大 TRANSCRIPT_MAX_TURNS、TRANSCRIPT_KEEP_RECENT_STEPS 或 REPLAY_FETCH_TURN_LIMIT 掩盖问题):

  1. 实时窗口裁剪边界双轨不一致,且后台终态卡重排未重绑 turnId:groupTurns(transcriptEntries) 按 turnId 切分轮次并决定 toRemove,而 trimTranscriptWindow() 仅统计 turnId === undefined 的 user/skill/plugin 条目数,并在 transcriptContainer.children 中按 isTurnBoundaryComponent 位置截断。普通轮含多张前置卡时会多算边界,后台通知轮与 cron 轮无 user 边界时则会跨过保留轮误删组件;同时流式 AssistantMessageComponent 未标记对应 TranscriptEntry,其他轮内组件未记录所属 turnId,且 moveTranscriptEntryToEnd() 将后台终态卡移至通知轮开头时未将其 entry.turnId 更新为当前通知轮。
  2. 长轮步数合并未保护 pinned 交互卡:非分组模式下 foldCurrentTurnContent() 与 mergeAllTurnSteps() 将段内所有非 StepSummaryComponent / AssistantMessageComponent 的子节点全部计入可合并 stepIndices,导致 TOOL_BOUNDARY_ROLES 中标记为 pinned 的 AskUserQuestion(以及 NotifyUser、ExitPlanMode)在超出最近 30 步上限时被销毁。
  3. 回放层吞掉全部读取/解析/折叠异常:foldAgentWireReplayFull() 用顶层 try/catch 将非 ENOENT 读取错误、中间行解析错误及记录折叠错误统一吞成 EMPTY_FOLD,窗口扫描遇到首行损坏同样返回 EMPTY_FOLD;SessionReplayRenderer.hydrateFromReplay() 无法区分“合法空会话”与“损坏/失败回放”,一律当作成功 hydration 返回 true。

Code Changes

核心思路

将实时裁剪、长轮折叠和会话回放统一到各自的数据真值上:实时窗口裁剪直接依据 groupTurns / turnsToTrim 产出的保留与淘汰集合(TranscriptEntry 引用与组件所属 turnId)移除组件,并在重锚后台终态卡时同步更新 entry.turnId;长轮折叠复用 transcript-items 已有的 pinned 工具角色判定跳过交互卡;wire.jsonl 回放将单条损坏记录隔离为跳过并保留其余有效历史 + replayWarning,将不可恢复的读取/折叠失败显式透传为 replayError,由 SessionReplayRenderer 呈现警告或错误而不再静默视作空会话。

flowchart LR
    subgraph Live["实时滑动窗口"]
        Entries["transcriptEntries (groupTurns / turnsToTrim)"] --> Meta["组件 Entry / turnId 元数据"]
        Rebind["moveTranscriptEntryToEnd 同步更新 entry.turnId"] --> Entries
        Meta --> Trim["trimTranscriptWindow 按保留集合精确移除组件"]
    end
    subgraph Fold["单轮步数折叠"]
        Pinned["isPinnedToolCallComponent (AskUserQuestion / NotifyUser / ExitPlanMode)"] --> Keep["保留原卡片挂载,不计入 StepSummary"]
    end
    subgraph Replay["wire.jsonl 回放"]
        Wire["foldAgentWireReplay"] -->|单条记录损坏且仍有有效历史| Salvage["保留有效 replay + replayWarning"]
        Wire -->|非 ENOENT 读取失败 / 全部损坏 / 头信息损坏| Err["返回 replayError"]
        Salvage --> Hydrate["SessionReplayRenderer: 渲染历史并提示 Warning"]
        Err --> Fail["SessionReplayRenderer: showError 并返回 false"]
    end
Loading

因为三处问题分别位于实时裁剪、单轮折叠和离线回放三个正交阶段,所以在各自边界内直接消除失配,无需引入额外配置开关或放大默认窗口。

阅读指南

  1. apps/kimi-code/src/tui/kimi-tui.ts、apps/kimi-code/src/tui/utils/transcript-component-metadata.ts、apps/kimi-code/src/tui/controllers/streaming-ui.ts:看实时流式组件如何绑定 TranscriptEntry / turnId、moveTranscriptEntryToEnd 如何重绑后台通知卡 turnId,以及 trimTranscriptWindow 如何按保留集合裁剪组件。
  2. apps/kimi-code/src/tui/utils/transcript-items.ts、apps/kimi-code/src/tui/kimi-tui.ts:看 isPinnedToolCallComponent 如何在实时与回放折叠中保护 AskUserQuestion 等 pinned 卡片。
  3. packages/node-sdk/src/v2/resume-replay.ts、apps/kimi-code/src/tui/controllers/session-replay.ts:看中间损坏记录的保留恢复(warning)与不可恢复错误(error)如何从 SDK 回放层传到 TUI hydration。
  4. packages/node-sdk/src/replay.ts、packages/node-sdk/src/sdk-rpc-client-v2.ts 与两处测试文件为类型透传和回归用例,可快速浏览。

具体逻辑变化

 moveTranscriptEntryToEnd(entry)
+  entry.turnId = streamingUI.getTurnContext().turnId
   move entry and component to tail
+  trimTranscriptWindow()

 trimTranscriptWindow()
-  count undefined-turnId user/skill/plugin entries -> cut children by isTurnBoundaryComponent position
+  partition turns into retainedTurnIds / trimmedTurnIds
+  remove child iff entry in toRemove, turnId in trimmedTurnIds, or untagged child precedes first retained child

 foldCurrentTurnContent() / mergeAllTurnSteps()
-  push every non-summary, non-assistant child into stepIndices
+  skip isPinnedToolCallComponent(child) so pinned interactive cards stay mounted

 foldAgentWireReplayFull(wirePath)
-  try read + parse all + fold -> catch everything as EMPTY_FOLD
+  ENOENT -> EMPTY_FOLD; other read errors -> { EMPTY_FOLD, error }
+  skip corrupt interior lines / isolate bad records -> keep valid replay + warning
+  unrecoverable fold or zero surviving records from corrupt wire -> { EMPTY_FOLD, error }

Screenshots / Recordings

以下为真实 KimiTUI 渲染器在三类复现场景下的终端文本快照对比:

  1. 混合普通 / worker 通知 / cron 轮触发实时裁剪(第 7 轮 worker、第 8 轮 cron 位于保留窗口首部,不再被跨轮误删):
BeforeAfter
 ❯ question 9
 ● NORMAL-ANSWER-9
 ● WORKER-CARD-7
 ● Ran a command · $ echo ok
   ok
 ● WORKER-ANSWER-7
 ● Scheduled reminder fired
   */5 * * * * | job job-8
   cron 8
 ● CRON-ANSWER-8
 ❯ question 9
 ● NORMAL-ANSWER-9
  1. AskUserQuestion 完成后继续执行 35 次工具调用(问答卡片保持挂载,不被 StepSummary 销毁):
BeforeAfter
 ❯ keep the question
   … call 5 tools, 15 messages
 ● Ran a command · $ ls
   ok
 ❯ keep the question
   … call 5 tools, 15 messages
 ● Collected your answers
   Q  Which option?
   →  Option A
 ● Ran a command · $ ls
   ok
  1. 非空 wire.jsonl 中间含损坏记录或不可恢复失败时回放(保留有效历史并显式告警,或显式报错):

BeforeAfter
(静默视作成功 hydration,显示空历史)
 Warning: Skipped 1 corrupt record while replaying session history (line 3).
 ❯ preserved question

Error: Failed to replay session history: Agent wire metadata is malformed

Behavior Changes and Affected Users

行为 修改前 修改后 依赖旧行为的人群 退路
混合普通轮、后台通知轮、cron 轮触发实时窗口裁剪 组件侧仅按 user 边界位置截断,无 user 边界的保留轮组件会被误删或残留;重锚的后台终态卡保留旧 turnId 组件与 TranscriptEntry 统一按 turnId / 条目集合同步裁剪,重锚后台终态卡同步更新 turnId 无(旧行为导致 TUI 交互用户保留轮次内容消失) none
非分组模式下单轮步数超过 TRANSCRIPT_KEEP_RECENT_STEPS(30)时的工具卡合并 AskUserQuestion、NotifyUser、ExitPlanMode 与普通工具卡一起被 dispose 并合入不可展开的 StepSummary 上述 pinned 工具卡保留挂载,不计入可销毁步数列表 TUI 经典模式或关闭分组的 fullscreen 用户 none
foldAgentWireReplay 处理含中间损坏记录的非空 wire.jsonl 任一中间损坏记录导致整份回放降级为空 replay: [],无警告 跳过损坏记录并保留其余有效历史与 toolStore,返回 warning;TUI 回放展示黄色 Warning: 提示 TUI 交互用户、VS Code 扩展用户及读取 ResumedAgentState 的 SDK 调用方(旧版本写的或异常中断留下的损坏会话日志) none
foldAgentWireReplay 处理非 ENOENT 读取错误、头信息损坏或整份损坏的非空 wire.jsonl 静默返回空 replay: [],SessionReplayRenderer.hydrateFromReplay 返回 true FoldedAgentReplay.error / ResumedAgentState.replayError 返回明确原因;hydrateFromReplay 调用 showError 并返回 false(ENOENT 缺失文件、空文件与末尾截断半行保持原行为不变) TUI 交互用户及 SDK 调用方 none

受影响模块:apps/kimi-code/src/tui(实时流式渲染、窗口裁剪、长轮折叠、会话回放)、packages/node-sdk(v2/resume-replay 与 ResumedAgentState 可选诊断字段)。未修改 CLI 参数、环境变量默认值、kap-server HTTP/WS 契约、prompt 文本或磁盘写入格式。

验证结论:已覆盖混合普通/worker/cron 轮实时裁剪与后台卡 turnId 重绑、AskUserQuestion 后 35 次工具调用保留问答、非空 wire.jsonl 中间损坏记录(含非法 JSON 与损坏记录载荷)保留有效历史并告警、不可恢复回放显式报错,以及现有 TUI 通知/折叠、Tower 命令、fullscreen 布局和 kap-server conversation 套件。

测试覆盖与运行结果
  • pnpm vitest run apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts apps/kimi-code/test/tui/message-replay.test.ts apps/kimi-code/test/tui/utils/transcript-window.test.ts apps/kimi-code/test/tui/fullscreen-layout.test.ts apps/kimi-code/test/tui/commands/tower.test.ts apps/kimi-code/test/tui/controllers/notify.test.ts apps/kimi-code/test/tui/controllers/session-event-handler-background-task.test.ts apps/kimi-code/test/tui/components/messages/transcript-container.test.ts apps/kimi-code/test/tui/chalk-named-color-guard.test.ts apps/kimi-code/test/tui/printable-key-guard.test.ts:10 files, 842 passed
  • pnpm vitest run packages/node-sdk/test/sdk-rpc-client-v2.test.ts -t 'foldAgentWireReplay':26 passed
  • pnpm vitest run packages/node-sdk/test/replay.test.ts packages/kap-server/test/services/conversation.test.ts packages/kap-server/test/conversationContract.e2e.test.ts:3 files, 41 passed(sdk-rpc-client-v2.test.ts 全文件运行中唯一失败的 serves suggestFiles through the workspace handler fs service 在未修改基线同样复现,与本次改动无关)
  • pnpm --filter @moonshot-ai/kimi-code-sdk run build && pnpm --filter @moonshot-ai/kimi-code-sdk run typecheck && pnpm --filter @moonshot-ai/kimi-code run typecheck && pnpm --filter kimi-code run typecheck:全部通过
  • pnpm exec oxlint --type-aware <changed files>:0 errors
  • pnpm run sherif:通过

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 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-12T06:56:37.344182Z 5d1842a Manual request
ℹ️ 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.

@changeset-bot

changeset-bot Bot commented Nov 12, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5d1842a

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

This PR includes changesets to release 1 package
Name Type
@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

@kimi-agent-bot

Copy link
Copy Markdown
Collaborator Author

@codex review

@pkg-pr-new

pkg-pr-new Bot commented Nov 12, 2026

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

commit: 5d1842a

@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: 5d1842af87

ℹ️ 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".

Comment on lines +103 to +105
const probe = header === undefined ? [entry.record] : [header.record, entry.record];
try {
const probed = foldWireRecords(probe, fromPersistentWireRecord);

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 Probe replay records with their dependencies

When salvage runs because any record in the journal is malformed, each remaining record is tested only with the metadata header. Valid content.part and tool.call records therefore make foldWireRecords throw because their preceding step.begin is absent; the catch then labels those valid lines corrupt and omits them from kept. As a result, one unrelated bad record can replay every assistant step without its text or tool calls, so probe against the retained valid prefix or otherwise preserve dependency groups while isolating the bad record.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +133 to +135
if (main.replayError !== undefined) {
this.host.showError(`Failed to replay session history: ${main.replayError}`);
return false;

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 Restore independent snapshots before returning on replay errors

When the wire fold reports an unrecoverable replay error, this return also skips hydrateSnapshot and notifications.restore, even though loadAgentResumeState fetched the current context and background-task snapshot independently of that fold. After resuming a damaged session with active background jobs, the event handler's task map and footer therefore remain empty until new lifecycle events happen, hiding already-running tasks for a failure that only concerns transcript rendering. Hydrate the independent snapshot state before reporting the replay failure, while continuing to skip only renderRecords.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@Grapedge
Grapedge merged commit 0ea324c into main Nov 12, 2026
28 of 29 checks passed
@Grapedge
Grapedge deleted the fix/tui-transcript-history-loss branch November 12, 2026 18:01
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