Skip to content

refactor(core): simplify loop and turn contracts - #5208

Closed
sailist wants to merge 3 commits into
refact-405-11-20-turn-state-machinefrom
refact-405-loop-contracts
Closed

sailist wants to merge 3 commits into
refact-405-11-20-turn-state-machinefrom
refact-405-loop-contracts

Conversation

@sailist

@sailist sailist commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

独立 Turn 与 Actor 接入后,Loop/Turn 内部仍存在重复状态、重复消息映射和未接入生产的通用历史重写结果,增加了理解与维护成本。本层在 #5195 之上整理内部接口与状态契约,不引入新的生命周期或执行模型。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

  • 按关注点整理 Loop 接口:本地化 LoopCommand 与 LLM timing 映射,区分 HookToolResult,将公开状态视图与内部 live 状态分离,并用 Pick 复用 Turn/ToolCall 字段来源。
  • 简化 TurnState、TurnStep、TurnMessage 与 LoopActor 的运行状态,删除重复的 mailbox/completion 数据结构和冗余映射。
  • 将 prompt-id 版 sendNow 明确命名为 sendNowQueued,与 message 版分开;v2 自身的公开重载不变。
  • 删除未被生产消费的 step.starting 返回 Message[] 通用历史重写路径及 rewrittenBy 追踪;replaceHistory()、setContext() 与 compaction/splice 通道保留。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
core 内部 Loop 接口 prompt-id 与 message 发送共用名称,状态字段存在多份映射 sendNowQueued 独立命名,状态类型复用单一字段来源 仅 core/v2 内部调用方 v2 公开 API 与协议不变
step.starting 通用消息重写 可返回 Message[] 并触发 context.settled 该通用返回路径删除;生产仅保留 undefined/blocked 全仓检索没有生产消费者 运行中 replaceHistory()/setContext() 仍可使用
Loop/v2 消息与生命周期事件 现有载荷与顺序 不改变 客户端、SDK 与持久化消费者 N/A

验证:core 与 agent-core-v2 tsc --noEmit 通过;Linux 远程环境相关回归 52 个文件、628/628;仓库完整 lint 通过;本层 diff 检查通过。

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; this layer only changes private internal implementation and has no publishable-package API change, so no release changeset is required.
  • No user documentation update is required for these internal contract changes.

@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5e7cc92

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T10:18:50.884989Z 010a307 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.

- flatten the turn runtime and consolidate active turn and step state
- align loop contracts and hook result naming
- split queued prompt sending from immediate notification
- limit step-start decisions to blocking
- remove hook chain rewrite metadata and context settlement emission
- retain explicit history replacement coverage during requests
@sailist
sailist force-pushed the refact-405-loop-contracts branch from 010a307 to 5e7cc92 Compare November 21, 2026 10:16
@sailist
sailist force-pushed the refact-405-11-20-turn-state-machine branch from 4d12d05 to 0320214 Compare November 21, 2026 10:16
@pkg-pr-new

pkg-pr-new Bot commented Nov 21, 2026

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

commit: 5e7cc92

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

if (!this.host.state.queuedMessageDispatchPending) this.host.streamingUI.finalizeDrained(sendQueued);
this.host.streamingUI.finalizeIdle(undefined, false);

P2 Badge Preserve the idle generation after compaction

When loop.idle arrives while isCompacting is true, finalizeIdle() retains the generation so completion can be finalized after compaction. This path then calls finalizeDrained(), which clears idleGeneration, immediately before calling finalizeIdle(..., false); with no queued message, that second call becomes a no-op and the configured terminal task-complete notification is never emitted. Preserve the stored idle generation or avoid resetting it when completing compaction.


if (!sideChatRunningOf(agentId) && !sideChatSendingOf(agentId)) return false;
try {
const result = await api.cancelSession(parent, { agentId });
return result.cancelled;

P2 Badge Cancel pending side-chat submissions when stopping

When the stop button is used while a side-chat prompt is still inside submitWithNetworkRetry()—particularly during its network retry delay—this only calls cancelSession. If the daemon has not accepted the prompt yet, cancellation returns false, but the un-aborted submission subsequently retries and can start the turn after the user stopped it. Track or abort the pending submission so stopping during the advertised sending state cannot launch work afterward.


function handleResumeTurn(): void {
if (!gateSubmit()) return;
followAfterUserAction();
emit('continue');

P2 Badge Keep a fallback for servers without session continuation

When the desktop connects to a previous-release KAP daemon, such as an SSH host not upgraded alongside the client, this button now always emits the new :continue request even though /meta advertises session_continue specifically as a capability. Those servers return a missing-route error, whereas this button previously sent the synthetic Continue prompt successfully. Gate this path on the capability and retain the old submit fallback when the server does not advertise it.


@click="handleSendOrContinue()"

P2 Badge Route the send shortcut through continuation

When an interrupted turn is continuable and the composer is empty, the button now invokes handleSendOrContinue(), but the configured send keyboard binding still calls handleSubmit() directly. Since canSend is false in this state, pressing the normal send key is a no-op even though the visible button says Continue. Route the keyboard binding through the same handler so keyboard users can activate continuation.

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

@sailist

sailist commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #5211.

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.

1 participant