Repository navigation
fix(tui): preserve transcript history across trimming, folding, and replay - #4866
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
🦋 Changeset detectedLatest commit: 5d1842a The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
|
@codex review |
commit: |
There was a problem hiding this comment.
💡 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".
| const probe = header === undefined ? [entry.record] : [header.record, entry.record]; | ||
| try { | ||
| const probed = foldWireRecords(probe, fromPersistentWireRecord); |
There was a problem hiding this comment.
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 👍 / 👎.
| if (main.replayError !== undefined) { | ||
| this.host.showError(`Failed to replay session history: ${main.replayError}`); | ||
| return false; |
There was a problem hiding this comment.
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 👍 / 👎.
Requirement or Bug
TUI 会话在实时长对话、单轮多步工具调用以及重放/重载(含 stale reload)时,会出现已生成的对话内容或用户问答记录静默消失的问题。本 PR 在不调大窗口或步数阈值掩盖问题的前提下,修复实时裁剪、长轮折叠与 wire 回放三处通用 transcript 生命周期缺陷,确保保留轮次、交互问答记录与有效历史不会静默丢失。
Bug Reproduction Steps
TRANSCRIPT_MAX_TURNS + TRANSCRIPT_HYSTERESIS(默认 20 轮)触发滑动窗口裁剪;仍在保留窗口内的 worker/cron 回复组件会被一并误删,且异步挂载在上一轮的后台终态卡在锚定到通知轮时仍保留旧turnId。AskUserQuestion,随后继续执行超过TRANSCRIPT_KEEP_RECENT_STEPS(默认 30)次工具调用(或重放该会话);AskUserQuestion卡片被dispose并压入不可展开的StepSummaryComponent,问题与用户回答均无法找回。wire.jsonl含损坏记录或读取/折叠失败:会话wire.jsonl中间存在一行损坏 JSON 或损坏记录载荷(或读取/折叠报错)时,启动恢复、切换会话或触发 stale reload;重放静默返回空历史并被视作成功 hydration,界面直接显示为空会话且无报错或警告。Root Cause
本次为根本修复(未通过调大
TRANSCRIPT_MAX_TURNS、TRANSCRIPT_KEEP_RECENT_STEPS或REPLAY_FETCH_TURN_LIMIT掩盖问题):turnId:groupTurns(transcriptEntries)按turnId切分轮次并决定toRemove,而trimTranscriptWindow()仅统计turnId === undefined的 user/skill/plugin 条目数,并在transcriptContainer.children中按isTurnBoundaryComponent位置截断。普通轮含多张前置卡时会多算边界,后台通知轮与 cron 轮无 user 边界时则会跨过保留轮误删组件;同时流式AssistantMessageComponent未标记对应TranscriptEntry,其他轮内组件未记录所属turnId,且moveTranscriptEntryToEnd()将后台终态卡移至通知轮开头时未将其entry.turnId更新为当前通知轮。foldCurrentTurnContent()与mergeAllTurnSteps()将段内所有非StepSummaryComponent/AssistantMessageComponent的子节点全部计入可合并stepIndices,导致TOOL_BOUNDARY_ROLES中标记为pinned的AskUserQuestion(以及NotifyUser、ExitPlanMode)在超出最近 30 步上限时被销毁。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因为三处问题分别位于实时裁剪、单轮折叠和离线回放三个正交阶段,所以在各自边界内直接消除失配,无需引入额外配置开关或放大默认窗口。
阅读指南
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如何按保留集合裁剪组件。apps/kimi-code/src/tui/utils/transcript-items.ts、apps/kimi-code/src/tui/kimi-tui.ts:看isPinnedToolCallComponent如何在实时与回放折叠中保护AskUserQuestion等 pinned 卡片。packages/node-sdk/src/v2/resume-replay.ts、apps/kimi-code/src/tui/controllers/session-replay.ts:看中间损坏记录的保留恢复(warning)与不可恢复错误(error)如何从 SDK 回放层传到 TUI hydration。packages/node-sdk/src/replay.ts、packages/node-sdk/src/sdk-rpc-client-v2.ts与两处测试文件为类型透传和回归用例,可快速浏览。具体逻辑变化
Screenshots / Recordings
以下为真实
KimiTUI渲染器在三类复现场景下的终端文本快照对比:AskUserQuestion完成后继续执行 35 次工具调用(问答卡片保持挂载,不被StepSummary销毁):wire.jsonl中间含损坏记录或不可恢复失败时回放(保留有效历史并显式告警,或显式报错):Behavior Changes and Affected Users
turnIdTranscriptEntry统一按turnId/ 条目集合同步裁剪,重锚后台终态卡同步更新turnIdTRANSCRIPT_KEEP_RECENT_STEPS(30)时的工具卡合并AskUserQuestion、NotifyUser、ExitPlanMode与普通工具卡一起被dispose并合入不可展开的StepSummaryfoldAgentWireReplay处理含中间损坏记录的非空wire.jsonlreplay: [],无警告toolStore,返回warning;TUI 回放展示黄色Warning:提示ResumedAgentState的 SDK 调用方(旧版本写的或异常中断留下的损坏会话日志)foldAgentWireReplay处理非ENOENT读取错误、头信息损坏或整份损坏的非空wire.jsonlreplay: [],SessionReplayRenderer.hydrateFromReplay返回trueFoldedAgentReplay.error/ResumedAgentState.replayError返回明确原因;hydrateFromReplay调用showError并返回false(ENOENT缺失文件、空文件与末尾截断半行保持原行为不变)受影响模块:
apps/kimi-code/src/tui(实时流式渲染、窗口裁剪、长轮折叠、会话回放)、packages/node-sdk(v2/resume-replay与ResumedAgentState可选诊断字段)。未修改 CLI 参数、环境变量默认值、kap-serverHTTP/WS 契约、prompt 文本或磁盘写入格式。验证结论:已覆盖混合普通/worker/cron 轮实时裁剪与后台卡
turnId重绑、AskUserQuestion后 35 次工具调用保留问答、非空wire.jsonl中间损坏记录(含非法 JSON 与损坏记录载荷)保留有效历史并告警、不可恢复回放显式报错,以及现有 TUI 通知/折叠、Tower 命令、fullscreen 布局和kap-serverconversation 套件。测试覆盖与运行结果
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 passedpnpm vitest run packages/node-sdk/test/sdk-rpc-client-v2.test.ts -t 'foldAgentWireReplay':26 passedpnpm 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 errorspnpm run sherif:通过Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.