Repository navigation
fix(tui): defer queued prompts until the loop drains - #5166
Conversation
- add core and v2 drained/idle lifecycle events - consume reminder-only queues without starting a model turn - gate TUI queue dispatch and completion notifications on lifecycle state - document notification-handoff queue behavior and add a CLI patch changeset
🦋 Changeset detectedLatest commit: 3f3f485 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 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. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 881b6ade67
ℹ️ 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".
| this.host.setAppState({ streamingPhase: 'idle' }); | ||
| this.host.resetLivePane(); |
There was a problem hiding this comment.
Preserve active work when handling loop.idle
When loop.drained dispatches a queued prompt, shell command, or /compact while a detached background task is still running, that new work starts before the later loop.idle event. If the task finishes while the dispatched work is active—or just before the prompt reaches the server—finalizeIdle() unconditionally resets streamingPhase and the live pane, making the TUI appear idle during an active request, shell command, or compaction and allowing subsequent input to bypass the queue. Treat loop.idle as a notification boundary without resetting newer work, or correlate it with the lifecycle generation it completes.
Useful? React with 👍 / 👎.
| @@ -0,0 +1,5 @@ | |||
| --- | |||
| '@moonshot-ai/kimi-code': patch | |||
There was a problem hiding this comment.
Add a changeset for the public SDK additions
This commit adds the public SessionStatus.loopLifecycleEvents capability and the loop.drained/loop.idle SDK event types, but the changeset bumps only @moonshot-ai/kimi-code. When the SDK is released independently, the release PR therefore has no SDK version or changelog entry for these additions; include @moonshot-ai/kimi-code-sdk in a changeset as required for affected publishable library APIs.
AGENTS.md reference: AGENTS.md:L168-L169
Useful? React with 👍 / 👎.
| if (state.appState.loopLifecycleEvents !== true) return; | ||
| const next = this.host.shiftQueuedMessage(); | ||
| if (next !== undefined) { |
There was a problem hiding this comment.
Wait for compaction before draining queued input
When automatic compaction remains active after the final step, the loop can still publish loop.drained because compaction is managed outside the loop's pending-request state. Although compaction.started sets isCompacting, this handler ignores that flag, removes the first queued item, and dispatches it during compaction; prompts can then be rejected as occupied and queued /compact operations can race the active compaction. Keep the item queued and let the existing compaction completion/cancellation path dispatch it once isCompacting is false.
Useful? React with 👍 / 👎.
| if (publishIdle) { | ||
| this.lifecycleIdle = true; | ||
| this.record({ type: 'loop.idle' }); |
There was a problem hiding this comment.
Re-check idleness after delivering loop.drained
When a loop subscriber reacts to loop.drained by submitting the next prompt, both lifecycle events have already been recorded, so event delivery continues with loop.idle even though the submission has populated the mailbox and started a new turn. Submitting follow-up work from the drained callback is a natural use of this new lifecycle API, and consumers will incorrectly observe an idle loop during active work. Deliver loop.drained first and recompute the state before recording loop.idle.
Useful? React with 👍 / 👎.
- emit idle only after the current macro is revalidated - keep queued input pending through compaction and delayed dispatch - reject stale idle after new work starts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 31d0f3a144
ℹ️ 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".
| this.host.updateQueueDisplay(); | ||
| return; | ||
| } | ||
| sendQueued(next); |
There was a problem hiding this comment.
Re-check loop state after a queued shell command
When this dispatches a queued Bash command while a detached task is still running, that task can finish and start a notification turn before the shell exits. finishShellOutput() then unconditionally sets the UI to idle and calls drainOneQueuedMessage(), so the following prompt is removed from the visible queue and submitted during the active notification turn instead of waiting for its later loop.drained. Have shell completion defer queue draining whenever lifecycle work restarted while the command was running.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| this.phase === 'idle' && | ||
| !this.held && | ||
| !this.hasPendingCompletions && | ||
| (this.mailbox.hasTrigger || this.mailbox.hasReminders) |
There was a problem hiding this comment.
Preserve queued reminder ordering while idle
When remind() is called while the loop is idle, treating reminders as schedulable work now immediately runs flushReminders(), emitting and persisting a message.appended for the next turn ID before that turn has even started. Previously the reminder stayed in the mailbox and was appended after the next triggering prompt, so direct core consumers can now observe an orphaned pre-turn event and the model receives the reminder before rather than after the next user message. Keep idle reminders queued while computing lifecycle state instead of scheduling them as standalone work.
Useful? React with 👍 / 👎.
- track macro generations in the core and v2 loop state - replace TUI macro inference with event-generation correlation - preserve compaction guards for queued dispatch
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3f3f485d16
ℹ️ 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 hasActiveTurn = this.host.streamingUI.hasActiveTurn(); | ||
| if (!hasActiveTurn && this.host.state.appState.loopLifecycleEvents === true) { | ||
| this.host.setAppState({ isCompacting: false }); | ||
| if (!this.host.state.queuedMessageDispatchPending) this.host.streamingUI.finalizeDrained(sendQueued); |
There was a problem hiding this comment.
Preserve pending idle when compaction finishes
When loop.idle arrives while compaction is active and no queued message remains, finalizeIdle caches the generation but defers its notification because isCompacting is true. On completion, this call invokes finalizeDrained first, which clears idleGeneration, so the immediately following finalizeIdle(undefined, false) cannot flush it; users with terminal notifications enabled never receive the task-complete notification. Preserve the cached idle state when resuming after compaction, or flush it before re-finalizing drained.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
* fix(core): add Claude 5 output token ceilings (#5096) * fix(core): add Claude 5 output token ceilings * chore: add Claude 5 output ceiling changeset * fix(markdown): keep table actions inside clipped containers (#5098) * fix(markdown): keep table actions inside clipped containers * fix(markdown): observe table action clipping ancestors --------- Co-authored-by: kimi-agent-bot <[email protected]> * fix(hosts): keep project lists usable with SSH hosts (#5102) * ci: release packages (#5094) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix: preserve first prompt through project creation (#5161) Co-authored-by: kimi-agent-bot <[email protected]> * fix(agent-core-v2): align fork slicing with restored turn ids (#5165) * fix(agent-core-v2): align fork slicing with restored turn ids * chore: add restored fork fix changeset * fix(core): prevent AJV diagnostics from polluting TUI input (#5168) * refactor(core): route AJV logs through utils logger * chore(core): add AJV logger changeset * chore(core): clarify AJV logger changeset * fix: support UUID generation in insecure browser contexts (#5173) * fix: support UUID generation in insecure browser contexts * chore: update pnpm deps hash * fix: resolve crypto bindings in UUID lint rule --------- Co-authored-by: kimi-agent-bot <[email protected]> * fix(client): keep draft thinking effort after sending (#5170) * fix(client): keep draft thinking effort after sending * chore: add cli changeset for draft thinking fix * test(client): use function stub for websocket in thinking test * fix(client): preserve thinking effort during model normalization * fix(client): reconcile profile updates and model fallbacks * fix(client): scope draft thinking preservation * fix(tui): defer queued prompts until the loop drains (#5166) * fix(tui): defer queued prompts until the loop drains - add core and v2 drained/idle lifecycle events - consume reminder-only queues without starting a model turn - gate TUI queue dispatch and completion notifications on lifecycle state - document notification-handoff queue behavior and add a CLI patch changeset * fix(tui): close loop lifecycle races - emit idle only after the current macro is revalidated - keep queued input pending through compaction and delayed dispatch - reject stale idle after new work starts * fix(loop): correlate lifecycle events by generation - track macro generations in the core and v2 loop state - replace TUI macro inference with event-generation correlation - preserve compaction guards for queued dispatch * fix(desktop): simplify multi-select folder picker actions (#5174) * fix(kap-server): report :wait settled only after the session is on disk (#5176) :wait settled as soon as the turn left the in-memory activity view, but the engine writes wire records through a batched log that flushes in a later task. A server killed right after :wait reported idle could lose the end of the finished turn. Before it replies with a settled session, :wait now flushes the wire of every agent in the session and drains pending metadata writes. A failed write surfaces as an error instead of a settled reply. The KAP guide states the guarantee. A new test in sessions.test.ts slows down the disk write of the turn end and checks that the record is on disk when :wait returns. (cherry picked from commit fc33c6d) Co-authored-by: kai <[email protected]> * ci: release packages (#5163) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(client): keep config-derived draft thinking effort after sending (#5191) Co-authored-by: liruifengv <[email protected]> * ci: release packages (#5192) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(kap-server): resume sessions with unavailable models (#5212) * fix(kap-server): resume sessions with unavailable models * fix: let users replace unavailable session models * fix: scope unavailable model recovery state --------- Co-authored-by: kimi-agent-bot <[email protected]> * fix(plugins): detect MCP OAuth with targeted probes (#5197) * fix(plugins): detect MCP OAuth with targeted probes * fix(plugins): use the MCP inspect route * fix(plugins): preserve OAuth requirements across inspection and disconnect * fix(chat): show pending MCP browser authorization (#5246) * fix(chat): show pending MCP browser authorization * fix(chat): resolve MCP authorization lint findings * fix(chat): preserve MCP authorization failure details * fix(mcp): preserve cancellation during OAuth reconnect * fix(desktop): cache feedback form per host and let reply reasons wrap (#5303) * ci: release packages (#5232) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * test: port removed-model recovery coverage to testkit * test: dedupe anthropic output ceiling cases --------- Co-authored-by: Haozhe <[email protected]> Co-authored-by: kimi-agent-bot <[email protected]> Co-authored-by: 7Sageer <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: kimi-agent-bot <[email protected]> Co-authored-by: liruifengv <[email protected]> Co-authored-by: qer <[email protected]> Co-authored-by: kai <[email protected]> Co-authored-by: Luyu Cheng <[email protected]> Co-authored-by: grapedge <[email protected]>
Requirement or Bug
TUI 用户在后台任务停止、重启等操作触发通知回合时,会提前看到下一条按
Enter排队的消息离开队列并显示为已发送,尽管引擎仍在处理前一个任务的通知接续。这个 PR 让排队消息一直保留到所有待处理回合清空,再按顺序派发;没有单独建立 issue,原始复现和根因记录如下。Bug Reproduction Steps
Enter提交下一条消息,使其进入待命队列,而不是显式 steer。turn.ended就提前将下一条消息移出队列;修复后,消息在通知接续期间保持青色排队状态,直到loop.drained才派发。Root Cause
turn.ended只表示一个前台或通知回合结束,不代表 normal、notify、remind、外层 pending 以及后续通知回合都已清空。TUI 此前把这个局部回合边沿当成全局空闲边沿,因此过早出队并发送完成提醒。这是根本修复:Core 和 v2 明确发布队列 drained 与全局 idle 两类实时边沿,TUI 不再从单个回合结束推断全局状态,而不是再给
turn.ended增加局部布尔标记。Code Changes
核心思路是把“回合输出收尾”“可处理队列已清空”“后台任务也已清空”拆成三个独立语义。新事件只实时发布,不写入 Wire、不做持久化回放;新 TUI 通过可选能力标记识别支持新事件的引擎,旧引擎仍沿用原路径。
turn.endedloop.drainedloop.idlesequenceDiagram participant Engine as Core / v2 participant SDK as Node SDK / Klient participant TUI as TUI Engine-->>SDK: turn.ended SDK-->>TUI: turn.ended TUI->>TUI: 收尾输出,保留排队消息 Engine-->>SDK: loop.drained SDK-->>TUI: loop.drained TUI->>TUI: 按顺序取一条排队消息 Engine-->>SDK: loop.idle SDK-->>TUI: loop.idle TUI->>TUI: 无待派发工作时才提醒完成关键变化:
lifecycleGeneration,drained/idle 携带当前代次;drained 先独立投递,后续调度边界重新确认后才生成 idle。只剩 remind 时复用现有无模型消费路径;关闭 Loop 时仍结算已有 idle waiter,但不补发生命周期事件。generation分开跟踪;同步 publish drained 后再次检查取消令牌、队列和后台 Task,只有当前 macro 仍满足条件才发布同代 idle。generation的两类事件,SessionStatus.loopLifecycleEvents标识引擎能力。未声明能力的新 TUI + 旧引擎组合自动回退,不需要用户配置。generation以及哪一代 drained 已派发队列,不通过 turn.started 或本地 dispatch 推断 macro。drained 到达和 delayed dispatch 前均检查isCompacting;若压缩在定时器前开始,消息放回队首,compaction 完成或取消后按原顺序派发。合法的同代 pending idle 可在 compaction 后收尾;多条排队输入保持顺序。阅读顺序建议:先看
packages/core/src/loop/loop-actor.ts的内层边沿,再看packages/agent-core-v2/src/agent/loop/loopService.ts的外层聚合,然后看apps/kimi-code/src/tui/controllers/streaming-ui.ts的出队决策。事件声明、SDK/Klient 注册、类型透传和中英文文档可以略读。Screenshots / Recordings
以下文本来自本 PR 代码的真实 TUI 组件渲染。两侧使用相同输入
next task;左侧关闭能力标记以执行旧出队路径,右侧启用本 PR 的生命周期路径。turn.ended后turn.ended后新路径随后收到
loop.drained,同一队列渲染为空。临时渲染采集代码未纳入提交;正式回归测试覆盖上述事件顺序和队列状态。Behavior Changes and Affected Users
turn.ended都可能提前取走排队消息loop.drained后按顺序取一条isCompacting;必要时重新入队,完成/取消后恢复turn.ended出队generation;TUI 只接受同代且未被队列派发失效的 idle,detached Task 运行仍允许 drained没有删除配置、环境变量、命令行参数或持久化数据格式,也没有修改模型提示词。旧引擎回退、旧会话不回放和多条排队消息顺序均有对应测试。
覆盖关系:
wait/record/toolAdapter:直接结束顺序、remind-only、关闭时 waiter 结算及关闭后不补发事件。验证记录
以下结果均来自当前
release/2026-11-20基线:wait/hooks/record/toolAdapter:26/26。kimi-tui-message-flow:539/539。tsc --noEmit均以 0 退出。881b6ade的完整pnpm lint曾因本地 jj-only 目录结构和远程 npm socket timeout 未验证,随后该提交的 GitHub CI 全部通过,test-windows 按工作流条件跳过。31d0f3a1的 CI 中 test (3) / test (5) 曾因 partial mock 缺少 TUI macro 方法而失败;3f3f485d已删除该 TUI macro 接口并改为 generation 事件关联,Linux controller 19 个文件、393/393 条测试通过。3f3f485d的架构收敛与回归:Core 26/26、完整 v2 Loop 69/69、TUI 539/539、后台任务 2/2、Klient 1/1、Node SDK 事件类型 9/9;Core、agent-core-v2、Klient、Node SDK、CLI 的tsc --noEmit通过;oxlint 在 5276 个文件上 0 warnings / 0 errors,导入边界通过 1422 个文件。远程完整 lint 仍受既有 Oxc arm64 原生绑定缺失阻塞,新提交的 GitHub CI 正在运行。Checklist
gen-changesetsskill; included the requested CLI patch changeset.gen-docsskill andtranslate-docssync for the bilingual interaction guide.