Skip to content

fix(kap-server): wait for an agent's history before accepting its prompt - #4659

Merged
wbxl2000 merged 2 commits into
release/2026-11-04from
qer/btw-backfill-before-reply
Nov 3, 2026
Merged

wbxl2000 merged 2 commits into
release/2026-11-04from
qer/btw-backfill-before-reply

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

在 web / desktop 里用 /btw 问题 开侧边对话时,第一轮有时显示的是主会话上一轮的回答,或者整轮从界面上消失;刷新页面不能恢复,过一段时间(会话被空闲回收后再打开)会自己恢复。这个 PR 之后,侧边对话的第一轮始终是它自己的问答。

Bug Reproduction Steps

  1. 打开一个已有回答的会话,让服务端为它建立实时 transcript(客户端打开会话即可)。
  2. 创建侧边对话(POST /sessions/{id}:btw),立刻提交第一问,同时读取这个 fork 的 transcript(客户端开侧边对话时就是这样:几乎同时提交问题和订阅 transcript)。
  3. 读取 fork 的 transcript:侧边对话的问题那一轮里装的是主会话的回答;侧边对话自己的回答落在另一条同提问的重复轮次里。重启服务端后冷读,同一个侧边对话是正确的。

Root Cause

fork 出来的 agent 带着从主 agent 继承的上下文,这段历史在两边的表示不一样:

  • 冷读(foldWireRecordFacts)把继承的上下文分组成一个轮次,占用 t0,fork 自己的第一问是 t1;
  • 实时 transcript 里继承的上下文只是 undo 标记,不占轮次编号。

所以 fork 的第一问如果在任何人读取 fork transcript 之前就开始了,它的实时轮次拿到 t0。随后的历史回填(ensureAgentHistory → backfillAgent)按 turnId 把冷数据合并进实时数据:冷数据的 t0(继承的主会话那一轮)被 healTurnOps 合并到实时的 t0(侧边对话第一问)上,较长的主回答覆盖了较短的侧边回答;冷数据里侧边对话自己的那一轮再作为新轮次插进来。前端识别出这一轮的文本与主会话相同,按继承历史过滤掉,第一轮就消失了。

sequenceDiagram
    participant C as Client
    participant S as kap-server
    C->>S: POST :btw
    S-->>C: agent_id
    C->>S: POST prompts (agent_id)
    Note over S: live turn of the first prompt takes t0
    C->>S: GET transcript (agent_id)
    Note over S: backfill merges cold t0 (inherited main turn) into live t0
Loading

回合结束后的 heal(healEndedTurns)用同样的方式匹配,所以没有回填时它也会对错轮次。只要回填先于第一问完成,继承的那一轮就先占住 t0,第一问拿到 t1,两边编号一致,回填和 heal 都不会再错配。

本 PR 让提问接口在 fork 的历史回填完成之后才接受它的提问,从服务端固定了先后顺序,修掉了这个竞争;冷读与实时对继承历史的表示仍然不同,统一表示留作后续改动(见下方"未覆盖")。

Code Changes

往非主 agent 提交问题时,先等这个 agent 的历史回填完成,再把问题放进队列:

 POST /sessions/{id}/prompts
   resolve the target agent
+  if agent_id is not main
+    await transcriptService.ensureAgentHistory(sessionId, agent_id)
   reserve prompt id, enqueue the prompt

registerPromptsRoutes 新增 transcriptService 参数,registerApiV1Routes 传入已有的 opts.transcriptService。ensureAgentHistory 在会话没有实时 transcript 时直接返回,不会新建;同一 agent 的回填结果有缓存,只有第一次提问需要等。

之所以放在提问接口而不是 :btw:fork 创建时 agent 列表就会把它广播给同会话的其他客户端,推迟 :btw 的响应挡不住别的客户端提前提问;放在提问入口,无论问题从哪个客户端来都会排在回填之后。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
往非主 agent 的第一次提问(会话有实时 transcript) 立刻入队 先等该 agent 的历史回填(读一次 agent 的 wire 文件),再入队 无;响应体不变 不需要
往同一非主 agent 的后续提问 立刻入队 不变(回填结果已缓存) — —
会话没有实时 transcript 时往非主 agent 提问 立刻入队 不变(ensureAgentHistory 直接返回) — —
往主 agent 提问、POST :btw — 不变 — —
fork 第一问抢在回填之前开始时的侧边对话 transcript 第一轮装着主会话回答,另有一条重复轮次 第一轮是侧边对话自己的问答,无重复轮次 无 不需要

受影响的客户端:web 与 desktop 的侧边对话,以及任何带 agent_id 提问的 REST 客户端。回填本来就会在客户端订阅 agent transcript 时发生,这里只是保证它先于第一次提问完成;响应体和 apiSurface 契约不变。

测试:packages/kap-server/test/sessions.test.ts 新增 server-v2 /api/v1/sessions:btw,用 stub 的 OpenAI 兼容模型复现"fork 后立刻提问、回答返回前读取 fork transcript"的时序,断言侧边对话的问题只有一轮、回答是它自己的、turnId 唯一。去掉修复后该用例稳定失败(同一问题出现两轮)。kap-server 全部测试、typecheck、lint 通过。

未覆盖:

  • 提问时会话还没有实时 transcript,之后在 fork 回合进行中才有人订阅,仍可能出现同样的错配(客户端打开会话后才能开侧边对话,所以很少见)。
  • 回填读文件失败时沿用原有的尽力而为语义(记日志、继续),此时与修复前行为一致。
  • 按轮次 fork 出来的会话,其主 agent 同样带继承历史,可能有同类问题,未验证。

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, 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, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

A fork's inherited history folds into a cold turn at t0, while the live
transcript only records it as markers. When the fork's first prompt
started before anything read the fork transcript, its live turn took t0;
the history backfill then merged the inherited main turn into it by turn
id, so the first side chat turn carried the main answer and the real
answer landed in a duplicate turn. Finish the fork's history backfill
before :btw replies, so the inherited turn holds t0 before the first
prompt can start.
@changeset-bot

changeset-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d838490

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 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T18:02:07.666340Z d838490 Manual request
ℹ️ 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 3, 2026 •

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

commit: d838490

@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: 9c045323d6

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

Delaying the :btw reply did not order the fork's first prompt after its
history backfill: other clients learn the fork from the agent roster as
soon as it is created, and checking for a live transcript with
forSessionLive created one, so every :btw also waited for the whole main
history. Move the wait to prompt submission: a prompt for a non-main
agent awaits that agent's history backfill before it is enqueued, which
covers every client and leaves :btw unchanged. The backfill is cached
per agent, so later prompts do not wait again.
@wbxl2000 wbxl2000 changed the title fix(kap-server): backfill a side chat fork before replying to :btw fix(kap-server): wait for an agent's history before accepting its prompt Nov 3, 2026
@wbxl2000

wbxl2000 commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@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: d838490c67

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

@wbxl2000
wbxl2000 merged commit b5f14f7 into release/2026-11-04 Nov 3, 2026
15 checks passed
@wbxl2000
wbxl2000 deleted the qer/btw-backfill-before-reply branch November 3, 2026 18:07
@github-actions github-actions Bot mentioned this pull request Nov 3, 2026
Grapedge pushed a commit that referenced this pull request Nov 4, 2026
* fix(tui): read welcome cwd and footer git status from the session environment (#4649)

* fix(tui): show remote cwd in welcome panel

* fix(tui): read footer git status through the session environment

The footer ran git and gh on the local machine, so a remote-bound session
hid the git badge. Read branch, working-tree, and pull request state through
the SDK instead: a live session's own environment, or the local work dir
before the lazy session exists. The local HEAD poll stays as a refresh
trigger only.

Core git commands now time out after 30s, and the pull request cache is
keyed by branch so a branch switch no longer serves the previous branch's
pull request.

* fix(agent-core-v2): resolve local git and gh outside the working directory

GitService spawned bare git and gh with the workspace as cwd. On Windows a
bare name is looked up in the cwd before PATH, so a binary planted in the
workspace could run, and the TUI footer now reads git status at startup,
before the workspace trust gate. Resolve both through PATH for the local
environment and refuse any match inside the working directory.

* chore: merge changesets for remote cwd and git status

* fix(tui): drop the startup Ready. row once startup succeeds

The startup progress row turned into a permanent "Ready." line under the
welcome panel. Remove it on success; a failed startup still leaves the
"Startup failed." row.

* fix(agent-core-v2): compare workspace containment case-insensitively on Windows

resolveProgramPath compared the PATH candidate against the working directory
case-sensitively, so on Windows a PATH entry spelled with different casing
(c:\repo\bin vs C:\Repo) let a workspace-local executable through.

* fix(tui): keep the footer git badge through a remote disconnect

The git cache key included the environment status, so a remote dropping to
connecting or disconnected rebuilt the cache and lost the last badge. Key
the cache by session and work dir only, and refresh it when the environment
turns ready again.

* feat: isolate plugin availability by client (#4653)

* fix: preserve marketplace descriptions

* fix: preserve localized plugin display names

* feat: isolate plugin availability by client

* fix: preserve cli marketplace loading

* fix: harden plugin availability reconciliation

* fix: hash plugin marketplace provenance

* fix: complete plugin availability reconciliation

* fix(transcript): keep realigned turn ids unique when folding cold facts (#4658)

* fix(transcript): keep realigned turn ids unique when folding cold facts

Realigning base turns to their wire ids only skipped ordinals held by
turns without a wire id. When an inherited turn held a forked turn's
wire id, that turn kept its base ordinal, and the next turn's wire id
could land on the same ordinal, so two turns shared a turn id and the
later one replaced the earlier in clients. Claim ordinals in order:
turns without a wire id or already at their wire id first, then each
realigned turn takes its wire id when free, else keeps its ordinal or
moves to the next free one.

* chore: add changeset for side chat turn order fix

* fix(kap-server): wait for an agent's history before accepting its prompt (#4659)

* fix(kap-server): backfill a side chat fork before replying to :btw

A fork's inherited history folds into a cold turn at t0, while the live
transcript only records it as markers. When the fork's first prompt
started before anything read the fork transcript, its live turn took t0;
the history backfill then merged the inherited main turn into it by turn
id, so the first side chat turn carried the main answer and the real
answer landed in a duplicate turn. Finish the fork's history backfill
before :btw replies, so the inherited turn holds t0 before the first
prompt can start.

* fix(kap-server): wait for an agent's history before accepting its prompt

Delaying the :btw reply did not order the fork's first prompt after its
history backfill: other clients learn the fork from the agent roster as
soon as it is created, and checking for a live transcript with
forSessionLive created one, so every :btw also waited for the whole main
history. Move the wait to prompt submission: a prompt for a non-main
agent awaits that agent's history backfill before it is enqueued, which
covers every client and leaves :btw unchanged. The backfill is cached
per agent, so later prompts do not wait again.

* fix: safely launch Windows SSH executors (#4664)

* feat: support Windows SSH remote environments

* Delete .changeset/windows-remote-environments.md

Signed-off-by: 7Sageer <[email protected]>

---------

Signed-off-by: 7Sageer <[email protected]>

* fix(agent-core-v2): match regional plugin locales (#4666)

* fix(plugins): confirm stopping Windows CU processes before install (#4670)

* fix(plugins): confirm stopping Windows CU processes before install

* test(plugins): cover capability install confirmation contract

* fix(plugins): preserve bodyless installs and plugin-only repairs

* chore: sync web dist from code-app (#4667)

* chore: sync web dist from code-app

code-app: 63661fc449e2ec0ce024bc08fe87f2c757d483e8

* chore: sync web dist from code-app

code-app: d0e913a6c9607be778c62f0c74ee7310bfb8862a

* chore: sync web dist from code-app

code-app: b306f4a2f9be8944e5a8064ecb076e3137c968f1

---------

Co-authored-by: kimi-agent-bot <[email protected]>

* ci: release packages (#4672)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Signed-off-by: 7Sageer <[email protected]>
Co-authored-by: 7Sageer <[email protected]>
Co-authored-by: liruifengv <[email protected]>
Co-authored-by: qer <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 4, 2026
Port of upstream MoonshotAI/kimi-code b5f14f7 (MoonshotAI#4659).

A fork's inherited history folds into a cold turn at t0, while the live
transcript only records it as markers. When the fork's first prompt
started before anything read the fork transcript, its live turn took t0;
the history backfill then merged the inherited main turn into it by turn
id, so the first side chat turn carried the main answer and the real
answer landed in a duplicate turn.

A prompt for a non-main agent now awaits that agent's history backfill
before it is enqueued, which covers every client. The backfill is cached
per agent, so later prompts do not wait again.

The added test drives :btw through the server, holds the side answer on
a gate, and fails on the pre-change tree by timing out.

Fork adaptation: the upstream vitest helpers become bun:test's spyOn and
the repo's waitForAssertion, and the fetch double is typed structurally.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 4, 2026
Fifteen rows enter the ledger: the six commits that landed on
upstream/main after the last refresh, and the nine commits that reach
main only through the release/2026-11-04 sync (MoonshotAI#4674), which is where
the 2.5.0 changelog entries come from.

Each 2.5.0 row records what it needs from this tree, so the next batch
starts from the blocker instead of rediscovering it:

- MoonshotAI#4658 and MoonshotAI#4659 are ported (79a4199, 7a531f5) with tests that
  fail on the pre-change tree.
- MoonshotAI#4649 is in_progress: its agent-core-v2 half landed in 2fa7b6b,
  while the footer and welcome half needs the pull-request API of MoonshotAI#4527
  and the session workdir of MoonshotAI#4062.
- MoonshotAI#4653, MoonshotAI#4666 and MoonshotAI#4670 build on the MoonshotAI#4525 plugin marketplace, absent
  here; MoonshotAI#4670 additionally needs isError2.
- MoonshotAI#4664 needs the MoonshotAI#4062 remote environments.
- MoonshotAI#4667 and MoonshotAI#4672 are generated-bundle and release commits; settling
  them as not-applicable needs a signature.

Rows were appended by a one-off writer because --refresh fetches and
that fetch does not complete on this network; the file still parses
under the tool's own column contract, and --verify --batch B5 passes
both new probes.
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