Skip to content

fix(tui): defer queued prompts until the loop drains - #5166

Merged
sailist merged 3 commits into
release/2026-11-20from
bug-394-11-18-loop-drained-idle-events-release
Nov 20, 2026
Merged

sailist merged 3 commits into
release/2026-11-20from
bug-394-11-18-loop-drained-idle-events-release

Conversation

@sailist

@sailist sailist commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

TUI 用户在后台任务停止、重启等操作触发通知回合时,会提前看到下一条按 Enter 排队的消息离开队列并显示为已发送,尽管引擎仍在处理前一个任务的通知接续。这个 PR 让排队消息一直保留到所有待处理回合清空,再按顺序派发;没有单独建立 issue,原始复现和根因记录如下。

Bug Reproduction Steps

  1. 让当前任务启动一个后台进程,并在修复后停止、重新部署它。
  2. 在当前工作尚未最终结束时,按 Enter 提交下一条消息,使其进入待命队列,而不是显式 steer。
  3. 后台任务状态变化触发一个或多个通知回合。
  4. 旧行为在通知回合的 turn.ended 就提前将下一条消息移出队列;修复后,消息在通知接续期间保持青色排队状态,直到 loop.drained 才派发。

Root Cause

turn.ended 只表示一个前台或通知回合结束,不代表 normal、notify、remind、外层 pending 以及后续通知回合都已清空。TUI 此前把这个局部回合边沿当成全局空闲边沿,因此过早出队并发送完成提醒。

这是根本修复:Core 和 v2 明确发布队列 drained 与全局 idle 两类实时边沿,TUI 不再从单个回合结束推断全局状态,而不是再给 turn.ended 增加局部布尔标记。

Code Changes

核心思路是把“回合输出收尾”“可处理队列已清空”“后台任务也已清空”拆成三个独立语义。新事件只实时发布,不写入 Wire、不做持久化回放;新 TUI 通过可选能力标记识别支持新事件的引擎,旧引擎仍沿用原路径。

概念 回答的问题 本 PR 之后的含义
turn.ended 当前回合是否结束 只收尾当前回合的输出
loop.drained 所有可处理输入是否清空 Core 与 v2 的 normal、notify、remind、外层 pending 和回合收尾均完成;TUI 此时取一条排队消息
loop.idle 是否可以视为全局空闲 drained 之外,detached 后台任务也已清空;TUI 仅在无待派发工作时发完成提醒
sequenceDiagram
    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: 无待派发工作时才提醒完成
Loading

关键变化:

  • Core Loop:跟踪 normal、notify、remind、actor 消息与事件、completion pending 和 detached 后台任务。每次从 drained 进入新工作递增 lifecycleGeneration,drained/idle 携带当前代次;drained 先独立投递,后续调度边界重新确认后才生成 idle。只剩 remind 时复用现有无模型消费路径;关闭 Loop 时仍结算已有 idle waiter,但不补发生命周期事件。
  • v2 Loop 服务:聚合外层 submissions、notifications、reminders、quiescence 和回合 drain。异步等待取消令牌与 macro generation 分开跟踪;同步 publish drained 后再次检查取消令牌、队列和后台 Task,只有当前 macro 仍满足条件才发布同代 idle。
  • SDK / Klient:注册并转发携带 generation 的两类事件,SessionStatus.loopLifecycleEvents 标识引擎能力。未声明能力的新 TUI + 旧引擎组合自动回退,不需要用户配置。
  • TUI:只比较 drained/idle 的 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 后
队列渲染为空
 ──────────────────────────────────────────────────────────────────────────────
❯ next task
↑ to edit · ctrl-s to steer immediately

新路径随后收到 loop.drained,同一队列渲染为空。临时渲染采集代码未纳入提交;正式回归测试覆盖上述事件顺序和队列状态。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
后台通知接续中的 TUI 出队 每个 turn.ended 都可能提前取走排队消息 仅在 loop.drained 后按顺序取一条 使用后台任务通知接续的 TUI 用户;旧行为会误报发送状态 无配置项,直接修复错误时序
compaction 期间的 TUI 出队 drained 或 delayed dispatch 可能在压缩中提交输入 两处检查 isCompacting;必要时重新入队,完成/取消后恢复 自动或手动压缩期间有排队输入的 TUI 用户 无配置项,直接修复竞态
新 TUI 连接旧引擎 在 turn.ended 出队 行为不变 使用旧引擎的 TUI 用户 能力标记缺失时自动回退,无需配置
只剩被动 remind 的 Loop 等待后续 prompt 才能继续 无模型消费 remind 后发出 drained/idle 使用被动提醒的 Core / SDK 调用方 无需配置;不启动额外模型回合
SDK / Klient 事件流 没有 drained/idle 边沿 新增两类实时事件和可选能力标记 订阅事件或驱动自定义界面的 SDK / Klient 调用方 可忽略新事件;旧会话不迁移,新事件不回放
drained / idle 的 macro 边界 drained 生成时已预先确定 idle,回调新工作仍可能收到 idle Loop 投递后重新确认 macro,事件携带 generation;TUI 只接受同代且未被队列派发失效的 idle,detached Task 运行仍允许 drained 在生命周期回调中提交新工作的 Core / v2 / SDK 调用方 无配置项,旧代次 idle 直接失效
终端完成提醒 单个回合结束即可触发 仅在当前 macro 的 idle 且没有新工作、压缩或待派发工作时触发 启用终端完成提醒的 TUI 用户 无配置项,避免通知接续中的误报

没有删除配置、环境变量、命令行参数或持久化数据格式,也没有修改模型提示词。旧引擎回退、旧会话不回放和多条排队消息顺序均有对应测试。

覆盖关系:

  • Core wait / record / toolAdapter:直接结束顺序、remind-only、关闭时 waiter 结算及关闭后不补发事件。
  • v2 Loop 与 task 工具:tool-only notify 交接、连续回合、detached 后台任务期间 drained 与完成后 idle。
  • TUI 消息流:通知回合中两条输入保持排队、drained 后只派发首条、idle 不提前提醒,以及旧引擎回退。
  • Klient / Node SDK:事件注册与转发、能力标记和事件类型契约。
验证记录

以下结果均来自当前 release/2026-11-20 基线:

  • Core wait / hooks / record / toolAdapter:26/26。
  • v2 通知交接:1/1;后台任务:2/2。
  • TUI kimi-tui-message-flow:539/539。
  • Klient facade:1/1;Node SDK 能力标记:1/1;Node SDK 事件类型:9/9。
  • Core、agent-core-v2、Klient、Node SDK、CLI 的 tsc --noEmit 均以 0 退出。
  • 中英文 VitePress 文档构建通过。
  • 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

  • I have read the CONTRIBUTING document.
  • Related issue: N/A — no separate issue was filed; the reproduction and root cause are documented above.
  • 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; included the requested CLI patch changeset.
  • Ran gen-docs skill and translate-docs sync for the bilingual interaction guide.

- 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-bot

changeset-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 3f3f485

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T05:07:40.635669Z 3f3f485 New commits
ℹ️ 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 20, 2026 •

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

commit: 3f3f485

@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: 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".

Comment on lines +557 to +558
this.host.setAppState({ streamingPhase: 'idle' });
this.host.resetLivePane();

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 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

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 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 👍 / 👎.

Comment on lines +534 to +536
if (state.appState.loopLifecycleEvents !== true) return;
const next = this.host.shiftQueuedMessage();
if (next !== undefined) {

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 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 👍 / 👎.

Comment thread packages/core/src/loop/loop-actor.ts Outdated
Comment on lines +575 to +577
if (publishIdle) {
this.lifecycleIdle = true;
this.record({ type: 'loop.idle' });

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 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

@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: 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);

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 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)

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 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

@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: 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);

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 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 👍 / 👎.

@sailist
sailist merged commit f0ea8ac into release/2026-11-20 Nov 20, 2026
17 checks passed
@sailist
sailist deleted the bug-394-11-18-loop-drained-idle-events-release branch November 20, 2026 05:21
Grapedge added a commit that referenced this pull request Nov 23, 2026
* 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]>
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