Repository navigation
refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended - #5337
Conversation
🦋 Changeset detectedLatest commit: 1433248 The changes in this PR will be included in the next version bump. This PR includes changesets to release 5 packages
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: 1767667be9
ℹ️ 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".
| generation !== null && | ||
| this.endedGeneration !== undefined && | ||
| this.endedGeneration !== null && | ||
| generation <= this.endedGeneration | ||
| ) return; |
There was a problem hiding this comment.
Reset lifecycle deduplication when replacing the session
When a TUI user finishes generation N in one session and then switches to a new or resumed session whose generation is ≤ N, resetSessionRuntime() retains this controller's endedGeneration, so this condition discards the new session's loop.ended events. Since finalizeTurn() has already moved the UI to waiting, terminal notification and queued-message dispatch remain stuck until that session exceeds the previous session's generation; reset endedGeneration and heldLoopEnd on session replacement or scope them by session ID.
Useful? React with 👍 / 👎.
| @@ -0,0 +1,5 @@ | |||
| --- | |||
| "@moonshot-ai/core": minor | |||
There was a problem hiding this comment.
Version the exported event removal as a breaking change
For SDK or klient consumers that handle loop.drained/loop.idle, this commit removes those exported event names (packages/node-sdk/src/events.ts re-exports the agent-core event union) while the only changeset gives the private core package a minor bump and omits the affected SDK/klient contracts. A semver-compatible release can therefore silently stop invoking existing listeners or break consumers at compile time; the affected public contract package needs a major changeset after the required maintainer confirmation, rather than only this core minor entry.
AGENTS.md reference: AGENTS.md:L89-L89
Useful? React with 👍 / 👎.
| if (!this.open() || this.lifecycleSettled) return; | ||
| this.lifecycleSettled = true; |
There was a problem hiding this comment.
Keep an open generation open while restoring a turn
When the service restarts after loop.started was persisted but before its turn wrote loop.ended, the restored lifecycle has settled: false; however, actor construction reaches this idle hook before loopService subscribes or resumes the unfinished turn, so this code silently marks that generation settled without publishing its end. The subsequent turn.resumed is then treated as new work and emits loop.started for generation N+1, leaving the durable journal with started(N), started(N+1) and no ended(N); suppress the constructor idle settlement for a restored unfinished generation so the resumed turn can end the original generation.
AGENTS.md reference: AGENTS.md:L111-L114
Useful? React with 👍 / 👎.
| (event.type === 'prompt.submitted' || | ||
| event.type === 'prompt.notified' || | ||
| event.type === 'prompt.reminded' || |
There was a problem hiding this comment.
Do not open a generation for parked notifications
When task reconciliation restores a completed background task, loopService passes its completion to recordNotification(), which deliberately leaves the notify inbox populated while setting the loop's intake hold. Counting that prompt.notified as a generation start makes the actor immediately emit loop.ended because held work is considered idle; when drainPendingToLoop() subsequently releases the notification, turn.started opens another generation for the actual prompt-only turn. This creates an empty persisted started/ended pair and can publish terminal lifecycle before the restored completion is consumed, so parked promptOnly notifications should join the generation opened when they are released rather than starting one here.
AGENTS.md reference: AGENTS.md:L112-L114
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd36cf6e4d
ℹ️ 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.lifecycleIdle = true; | ||
| this.record({ type: 'loop.idle', generation: this.lifecycleGeneration }); | ||
| } | ||
| if (!this.open() || this.lifecycleSettled || !this.lifecycleWorkSeen) return; |
There was a problem hiding this comment.
Close a restored generation whose turn already ended
If the service crashes after persisting turn.ended but before persisting the corresponding loop.ended, restoration marks the lifecycle unsettled even though there is no unfinished turn. This guard then suppresses settlement because no post-restore work has been seen; when the next independent prompt arrives, it is absorbed into the old generation without emitting loop.started, and only emits the old generation's loop.ended afterward. Distinguish an actually resumable turn from this completed-turn crash window so the next prompt opens its own generation.
AGENTS.md reference: AGENTS.md:L111-L114
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 313c3ff29e
ℹ️ 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 isWork = | ||
| event.type === 'prompt.submitted' || | ||
| event.type === 'prompt.notified' || | ||
| event.type === 'prompt.reminded' || |
There was a problem hiding this comment.
Keep parked reminders out of lifecycle generations
When remind() is called while intake is held—such as on an otherwise idle newly created loop—it deliberately leaves the reminder parked until a later non-promptOnly turn, but classifying prompt.reminded as work emits loop.started followed immediately by loop.ended because the hold prevents scheduling. The later prompt then opens another generation before consuming the reminder, leaving an empty persisted lifecycle pair and notifying lifecycle consumers before the queued work is processed; start the generation when the reminder is actually flushed or consumed instead.
AGENTS.md reference: AGENTS.md:L111-L114
Useful? React with 👍 / 👎.
17c19d2 to
100b3b9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 100b3b913f
ℹ️ 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".
| private settleLoopEnd(held: boolean): { outcome: LoopEndOutcome } | undefined { | ||
| if (!this.open() || this.hasPendingCompletions) return undefined; | ||
| if (!held && this.mailbox.hasTrigger) return undefined; | ||
| return { outcome: this.hasActiveBackgroundTasks ? 'drained' : 'idle' }; |
There was a problem hiding this comment.
Emit idle after a suppressed background task completes
When a detached task is still running as its turn ends and shouldQueueTaskNotification returns false—as happens after runAgentTurn.stopChildTasks() suppresses the child's task notifications—this records only drained. Once the task completes, drainDetachedCompletions() removes it without queuing another turn, so this turn-only calculation can never publish the later idle settlement that the previous onIdle path emitted; lifecycle consumers waiting for full quiescence therefore remain permanently drained. Preserve an idle signal for suppressed background-task completions.
AGENTS.md reference: AGENTS.md:L111-L114
Useful? React with 👍 / 👎.
| const turn = this.active; | ||
| if (turn === undefined) return; | ||
| return this.finishTurn(turn, outcome); | ||
| return this.finishTurn(turn, outcome, event.loopEnd); |
There was a problem hiding this comment.
Forward loop end when the prompt gate rejects
When a turn.starting hook blocks or fails before AgentTurnProjection.active is created, the preceding branch calls gateRejected() and returns, so this active-turn-only path never forwards the core event's loopEnd. The public stream then contains only prompt.completed and neither a marked turn.ended nor the removed loop lifecycle events; in the TUI, handlePromptCompleted() leaves lifecycle-enabled sessions in waiting, so subsequent user messages remain queued indefinitely. Publish the loop-end settlement for the gate-rejection path as well.
Useful? React with 👍 / 👎.
| const loopEnd = this.postTurnLoopEnd(this.turn, event.outcome); | ||
| this.record(loopEnd === undefined ? event : { ...event, loopEnd }); | ||
| this.finishTurn(this.turn, event.outcome); |
There was a problem hiding this comment.
Publish loopEnd after transitioning the loop to idle
For a subscriber that reacts synchronously to a turn.ended carrying loopEnd by starting an idle-only operation, the marker is emitted while this.turn and the actor state are still running; finishTurn() does not transition to idle until after every listener returns. For example, a direct Loop consumer replacing a loop.idle listener with this field and calling runTurn() from the callback now gets runTurn is only accepted while idle, whereas the removed lifecycle event was emitted from onIdle after the transition. Defer the settled marker until the state actually satisfies the lifecycle condition.
Useful? React with 👍 / 👎.
100b3b9 to
1433248
Compare
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
TurnEnded gains an optional loopEnd ({drained|idle}) on the wire contract,
payload, schema and serialization; the journal records it and the turn
projection forwards it into endTurn. The core loop actor does not compute the
outcome yet and the TUI does not consume it (the loopLifecycleEvents flag is
missing here), so the field currently serializes only when a caller supplies
it (MoonshotAI#5337, plumbing half). loop+journal suites 75 pass.
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
finishTurn attaches loopEnd (drained when detached tasks are still running, idle otherwise) only when the loop settles with no pending completions and no queued trigger; closeUnfinished takes followedByWork and omits the end info when work follows. A core loop test covers the settled idle case (MoonshotAI#5337). The TUI display stays out by deliberate deviation: the fork never carried the upstream loopLifecycleEvents flag (PLAYBOOK row).
Requirement or Bug
TUI 用户在连续 turn(排队、steer、后台任务完成接力)中会收到重复的终端完成通知。根因是 loop 生命周期事件(
loop.drained/loop.idle)在 core 与 agent-core-v2 各有一套独立推导和 generation 簿记,且 core 的计数器绑定单个 loop 实例,服务重启或会话恢复重建实例后会对空闲会话发出幻影终态事件。本 PR 删除独立的 loop 生命周期事件与全部 generation 簿记,把「本 turn 结束后 loop 随之静止」作为可选字段loopEnd挂在已有的turn.ended上,由 core 唯一判定、v2 原样透传。Bug Reproduction Steps
N/A(架构收敛与通知去重;原始现象为排队/接力 turn 中途及后台任务完成后重复弹出「task complete」通知。)
Root Cause
生命周期判定存在两个权威来源:core 的
settleLifecycle与 v2 的maybeSettle(维护macroGeneration)。v2 之所以要重推导,是因为 core 的lifecycleGeneration在createLoopFromSnapshot重建时归零,无法直接透传。事实上「loop 是否在本 turn 结束后静止」的全部判定输入在 core 发射turn.ended时都已同步可读,根本不需要跨实例的 generation 配对。本 PR 是根本修复:在发射点同步计算 post-turn 处置并写入turn.ended.loopEnd,v2 只经既有TurnEnded通道透传。Code Changes
核心思路
turn.ended新增可选字段loopEnd?: { outcome: 'drained' | 'idle' }。当且仅当该 turn 结束后 loop 不再立即调度后续工作(队列已空或处于调度挂起held的静止态,且没有待结算的后台完成通知)时携带:仍有活跃后台任务为drained,否则为idle。它是「截至该 turn 结束时刻」的终态快照,不是「之后不会再有新工作」的承诺。结构图
flowchart LR subgraph core["packages/core"] A["Turn machine emits turn.ended"] --> B["postTurnLoopEnd / settleLoopEnd<br/>同步判定是否 settle"] B --> C["record(turn.ended + loopEnd)"] C --> D["finishTurn → onSchedule 消费同一队列状态"] end subgraph v2["packages/agent-core-v2"] C --> E["turnProjection 透传 loopEnd"] E --> F["TurnEnded (durable wire + event bus)"] G["loopService.maybeSettle"] --> H["仅解析 settleWaiters<br/>删除 macroGeneration 重推导"] end F --> I["klient / node-sdk / vis-web"] F --> J["TUI finalizeLoopEnd(turnId)<br/>派发队列或按 outcome 通知一次"]core 在
record(turn.ended)与finishTurn之间同一同步调用链内完成判定,不存在异步窗口;因此不再需要 generation 配对、journal lifecycle reduce 或跨实例连续性注入。关键决策
turn.ended.loopEnd,不新增记录类型loop.started/loop.ended配对事件turn.ended发射点同步计算postTurnLoopEndonIdle另发事件再关联held、hasPendingCompletions、mailbox.hasTrigger、后台任务)在发射点同步可读,与实际调度同源held语义held=true且无可调度工作时视为静止,携带loopEndheld=true一律不携带held是调度挂起而非「未结束」(abort()的releaseTurn会置held=true);旧模型isIdle此时同样为 true,否则会卡住 Escape 取消后的 UIturnId(拒绝turnId <= endedTurnId)generationturnId单调、持久、跨重启连续,无需额外计数器loopLifecycleEvents能力标志loopEnd字段」与「新服务端本 turn 后还有连续工作」判定逻辑与旧路径功能清单
旧路径各项职责的去向:
lifecycleGeneration/lifecycleDrained/lifecycleIdle/settleLifecycle:删除,由postTurnLoopEnd+settleLoopEnd取代;崩溃恢复结算closeUnfinished(followedByWork)按同一规则决定是否带loopEnd。LoopDrained/LoopIdle(loopOps.ts)、macroGeneration/lifecycleDrained/lifecycleIdle/hasActiveBackgroundTasks:删除;loopService.maybeSettle保留settleWaiters(prompt()/settled()RPC)解析;quiescence / history-snapshot 谓词(hasPendingRequests/tryAcquireQuiescence)保持不变。finalizeDrained/finalizeIdle/flushIdle:合并为finalizeLoopEnd/resumeLoopEnd/settleLoopEnd,保留 compaction 挂起恢复、排队消息派发不通知、会话切换重置(resetLoopLifecycle)。阅读指南
packages/core/src/loop/loop-actor.ts:postTurnLoopEnd/settleLoopEnd与closeUnfinished的判定。packages/agent-core-v2/src/agent/loop/turnProjection.ts、turnOps.ts:loopEnd经finishTurn → endTurn → TurnEnded的透传与 schema。packages/agent-core-v2/src/agent/loop/loopService.ts:删除平行推导后的maybeSettle。apps/kimi-code/src/tui/controllers/streaming-ui.ts:按turnId去重的通知与队列派发。其余为 klient 契约、vis-web
turn.ended的loopEnd徽标、wire-manifest 重生成及测试/快照更新。Behavior Changes and Affected Users
loop.drained、loop.idle(带generation)turn.ended新增可选loopEnd: { outcome: 'drained' | 'idle' }loop.drained/loop.idle的 klient 与 SDK 外部消费者@moonshot-ai/corechangeset;迁移为检查turn.ended.loopEnd)drained+idleturn.ended上出现一次loopEndturn.ended.loopEndwire-manifest.d.ts)loop.drained/loop.idle两条记录类型;turn.ended无loopEndturn.ended增加可选loopEnd字段loop.drained/loop.idle记录不参与 loop 状态恢复,读取不受影响loop.drained/loop.idleloopLifecycleEvents能力时,TUI 回退到原有finalizeTurn单 turn 结束逻辑loopEnd的主 agentturn.ended触发一次通知:drained为「background tasks still running」,idle为「task complete」;连续 turn 中途不通知held静止态并发出终态事件abort()在turn.ended上携带loopEnd;有排队工作或崩溃 turn 后立即接新 turn 时不携带cancel()的客户端heldLoopEnd暂存,resumeLoopEnd在结束后派发队列或补发通知测试覆盖
wait.test.ts(连续 turn、remind 静默、崩溃窗口结算、parked 通知、无/有后续工作的abort())、record.test.ts(关闭路径不带loopEnd、恢复后新 turn 携带)。loop.test.ts、journal.test.ts、task-tools.test.ts(RPC 层drained → idle序列)、index.test.tswire 词表,以及tool/config/plan内联快照。facade.test.ts、node-sdksession-event-types.test.ts、TUIkimi-tui-message-flow.test.ts(含真实引擎 Escape 取消视频上传后恢复idle与/clear)。验证记录
core、agent-core-v2、klient、node-sdk、apps/kimi-code、apps/vis/server、apps/vis/web全部通过。tool.test.ts3 个timeoutMs=0假定时器用例为已知 macOS 平台超时,Linux 远程通过);wait/record/loop/journal/index102/102;klient + node-sdk + TUI message-flow 587/587。@moonshot-ai/core36/36 文件通过;@moonshot-ai/agent-core-v2370 文件通过,仅test/remote/process.test.ts2 个假定时器用例在全量负载下失败,单跑该文件 23/23 通过(与 loop 生命周期无代码交集的既有环境 flake)。lint-pool:完整pnpm lint+check:duplication(对基线e42d4a53b8b1)全部通过。Checklist
/approve). (内部重构;问题与根因见上文。)gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update. (无面向最终用户的文档页描述 loop 内部事件名;变更已写入 changeset 与契约清单。)