Skip to content

feat(btw): add agent close endpoint, side-chat stop button, and close confirmation - #5047

Merged
wbxl2000 merged 2 commits into
mainfrom
feat/kap-agent-close
Nov 20, 2026
Merged

wbxl2000 merged 2 commits into
mainfrom
feat/kap-agent-close

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

此前关闭侧边聊天(btw)标签页只在前端本地取消订阅、丢弃界面状态,服务端正在运行的侧聊 Agent 会继续跑完本轮消耗 Token 且残留在会话元数据中;同时侧边聊天输入框缺少单独停止按钮,用户想打断当前一轮生成时只能关闭整个标签页,也没有防误关确认。本 PR 在单仓内打通前后端完整闭环:引擎与 kap-server 新增 POST /api/v1/sessions/{session_id}/agents/{agent_id}:close 用于终止并清理 btw Agent,桌面端与 Web 渲染层同步补齐侧聊输入框停止按钮(仅打断当前轮次、保留上下文)、关闭非空或运行中侧聊标签页的二次确认,以及确认关闭后销毁服务端 Agent 与多窗口同步收起。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路是把侧边聊天(btw)的三个动作在协议与交互层彻底拆清:

  1. 收起右侧栏:仅隐藏视图,后台侧聊继续运行。
  2. 停止当前回复(保留侧聊继续追问):在侧聊输入框复用现有 POST /api/v1/sessions/{session_id}:cancel(携带 agent_id),仅中断该侧聊当前轮次,不影响主会话。
  3. 关闭侧聊标签页(销毁并清理):对有对话记录(turns.length > 0)或正在生成(running || sending)的标签页弹出二次确认;确认后调用新增的 POST /api/v1/sessions/{session_id}/agents/{agent_id}:close 中断运行中的侧聊、摘除持久化 agents[agentId] 元数据并广播 status: "ended" 同步收起其他已打开窗口。
sequenceDiagram
    participant U as 用户 (Desktop / Web)
    participant UI as SideChatPanel / PanelTabs
    participant S as kap-server (/api/v1)
    participant E as agent-core-v2 (Btw / Lifecycle)

    alt 点输入框停止按钮 / 面板内双击 Esc
        U->>UI: 中断当前回复
        UI->>S: POST /sessions/{id}:cancel { agent_id }
        S->>E: 仅中断该 btw 当前轮次(保留上下文)
    else 点标签页 × / 右键批量关闭 / Cmd+W
        U->>UI: 请求关闭侧聊标签页
        UI->>UI: createSideChatCloseGuard (非空或运行中弹窗确认)
        UI->>S: POST /sessions/{id}/agents/{agent_id}:close
        S->>E: SessionBtwService.close -> unregisterAgent + removeById
        E-->>S: onDidClose -> WS agent { status: "ended" }
        S-->>UI: 多窗口同步移除 btw 标签页与持久化快照
    end
Loading

阅读指南

  • 引擎与元数据清理(packages/agent-core-v2):
    • src/features/btw/btwService.ts:新增 close(agentId)(仅允许关闭带 btw 标记的侧边 Agent,主 Agent 或非侧聊抛出 AGENT_NOT_CLOSABLE / AGENT_NOT_FOUND,按 agentId 去重并发关闭)。
    • src/session/agentLifecycle/agentLifecycleService.ts:新增 removeById(agentId) 处理正在启动中或已运行 Agent 的竞态取消与卸载,清理交互挂起项,并在分配新 agent-N 编号时扫描磁盘目录避免复用已关闭的旧 ID。
    • src/session/sessionMetadata/sessionMetadataService.ts:新增 unregisterAgent(agentId) 从会话元数据中移除该侧边 Agent(不改动 updatedAt)。
  • KAP 路由与契约(packages/kap-server):
    • src/routes/conversation.ts、src/routes/meta.ts、src/protocol/error-codes.ts:新增 POST /api/v1/sessions/{session_id}/agents/{agent_id}:close(返回 { closed: true },不可关闭返回 40939),在 GET /api/v1/meta 宣告 capabilities.agent_close: true,同步更新 docs/kap.md 与 apiSurface.snapshot.test.ts(HOST_API_LEVEL 保持 1)。
  • 客户端与共享渲染层(packages/app-*、apps/desktop/src/renderer):
    • packages/app-core/src/api/daemon/client.ts、hostRouting.ts:新增 KimiWebApi.closeAgent(40401 幂等视为已关闭)并注册至 HostRouter。
    • packages/app-client/src/client/useSideChat.ts、src/panel/sideChatCloseGuard.ts、src/composables/usePanelTabs.ts:新增 cancelSideChatOn(调 cancelSession(parent, { agentId }))、createSideChatCloseGuard(空白空闲秒关、非空或运行中二次确认)、requestDaemonClose(网络/5xx 持久化指数退避重试)以及 handleAgentEnded 跨窗口同步清理。
    • packages/app-components/src/chat/SideChatPanel.vue、src/composer/Composer.vue、apps/desktop/src/renderer/components/panel/PanelTabs.vue、App.vue:为 side-chat 模式透传 workingOverride 显示停止按钮并接入面板内双击 Esc 拦截(不穿透主会话),在 Desktop 与 Web 共用 PanelTabs 及菜单/快捷键关闭入口统一接入关闭确认。

Screenshots / Recordings

侧边聊天流式生成中右下角出现停止按钮(左侧主对话不受影响),点击停止后保留上下文继续追问;点击非空或运行中标签页的 × 弹出关闭确认弹窗,确认后销毁服务端侧聊 Agent 并关闭标签页:

侧边聊天停止按钮 关闭非空侧聊二次确认
侧边聊天输入框停止按钮 关闭侧边聊天二次确认弹窗

完整交互录屏(打开侧聊 → 流式回复中停止 → 继续追问 → 点击 × 弹出确认框 → 确认关闭):

侧边聊天停止与关闭确认完整交互流程

Behavior Changes and Affected Users

行为 改动前 改动后 依赖旧行为的人群 退路
关闭侧边聊天(btw)标签页(含点击 ×、右键批量关闭、Cmd+W) 无论是否已有对话或正在运行,立即关闭标签页;仅清理前端内存状态,不通知服务端 空白且空闲的标签页仍直接关闭;若已有对话记录或正在运行,弹出确认框;确认后调用 POST /sessions/{id}/agents/{id}:close 终止并清理服务端侧聊 Agent,且跨窗口同步收起 Desktop 与 Web(kimi web)使用侧边聊天的用户 若只是想暂时藏起侧聊继续后台运行,点击右上角收起右侧栏即可
侧边聊天运行中的输入框操作 输入框不显示停止按钮,仅禁用发送 显示停止按钮并支持面板内双击 Esc,调用 :cancel(指定 agent_id)单独中断当前侧聊轮次并保留上下文继续追问 Desktop 与 Web 使用侧边聊天的用户 无破坏性变化,纯新增能力
GET /api/v1/meta 与 POST /api/v1/sessions/{session_id}/agents/{agent_id}:close 不含 capabilities.agent_close 与 :close 动作路由 新增 capabilities.agent_close: true 与 :close 路由(非侧聊返回错误码 40939) Desktop、Web 及外部 KAP 调用方 纯增量可选能力,既有接口默认行为不变
新建子 Agent ID 分配 仅扫描内存 roster 与 metadata.agents 额外扫描磁盘 agents/ 目录避免复用已被 unregisterAgent 移除的历史 agent-N 同一会话内反复创建与关闭 btw 的所有客户端 纯安全防护,不影响现有 ID 格式
  • 受影响模块:packages/agent-core-v2、packages/kap-server、packages/app-core、packages/app-client、packages/app-components、packages/app-i18n、apps/desktop(Desktop 与 Web 共用渲染层)。
  • 验证结论:已在本地跑通 pnpm lint(注释检查、oxlint --type-aware --deny-warnings、import 边界、guards、ratchet、instructions 全部 0 错误)、agent-core-v2 / kap-server / kimi-code-app(含 vue-tsc)类型检查、pnpm run build:web,以及全部 10 个相关前后端测试套件(共 349 项用例全通过)。packages/agent-core-v2/test/tool/tool.test.ts 有 3 条 fake-timer 超时用例已在干净 origin/main 上核实为存量问题。
本地运行命令与测试覆盖明细
  • pnpm lint → 通过(check-comments 5190 files、oxlint --type-aware --deny-warnings、check-import-boundaries、guards、ratchet、instructions 全部通过)
  • pnpm --filter @moonshot-ai/agent-core-v2 run typecheck → 通过
  • pnpm --filter @moonshot-ai/kap-server run typecheck → 通过
  • pnpm --filter kimi-code-app run typecheck → 通过
  • pnpm run build:web → 通过
  • pnpm exec vitest run --reporter=agent(10 files, 349 tests passed):
    • packages/agent-core-v2/test/features/btw/btw.test.ts
    • packages/agent-core-v2/test/app/sessionExport/sessionExport.test.ts
    • packages/agent-core-v2/test/session/sessionTitle/sessionTitleService.test.ts
    • packages/kap-server/test/conversationContract.e2e.test.ts
    • packages/kap-server/test/apiSurface.snapshot.test.ts
    • packages/app-core/test/daemon-client.test.ts
    • packages/app-client/test/side-chat.test.ts
    • packages/app-client/test/panel-tabs.test.ts
    • packages/app-client/test/session-work-reconnect.test.ts
    • apps/desktop/tests/renderer/sidechat-snapshot.test.ts

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.

@changeset-bot

changeset-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 030a71d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@moonshot-ai/kap-server Patch
@moonshot-ai/agent-core-v2 Patch
kimi-code-app Patch
@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 18, 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-19T14:07:40.828829Z 030a71d 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 18, 2026 •

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

commit: 030a71d

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

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

| `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Wait until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`) |
| `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel active turn (`agent_id?`, `include_background?`) |
| `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Branch session (`turn_index?`), undo from `turn_id`, compact context, or spawn read-only side-chat (`{ agent_id }`) |
| `POST /api/v1/sessions/{session_id}/agents/{agent_id}:close` | `agent_close` | Close and remove a `btw` side-chat agent (`40939` if not closable) |

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 new KAP capability

This public core KAP endpoint is observable by external HTTP agents, but the commit adds no .changeset file. If released as-is, the CLI changelog will omit the new capability, so add an @moonshot-ai/kimi-code changeset announcing the endpoint and how to use it.

AGENTS.md reference: AGENTS.md:L90-L91

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from f8dc1f6 to 93ceab0 Compare November 18, 2026 10:10
@wbxl2000
wbxl2000 force-pushed the docs/kap-v1-reference branch from 7703ee6 to 1bea34d Compare November 18, 2026 10:10

@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: 93ceab02c3

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

async removeById(agentId: string): Promise<void> {
this.cancelledAgentIds.add(agentId);
try {
const inflight = this.creating.get(agentId);

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 Serialize close against late agent restoration

When a dormant persisted BTW agent is being lazily restored concurrently, getOrRestoreAgent can read its metadata and then start create() immediately after this one-time creating lookup. removeById then sees no current roster entry, clears cancelledAgentIds, and returns successfully; the delayed create no longer observes cancellation and re-registers the supposedly closed agent, so the API reports { closed: true } while the agent remains live. Serialize creation and removal for the ID, or retain/recheck the cancellation marker until no late creation can enter.

AGENTS.md reference: AGENTS.md:L137-L137

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from 93ceab0 to e3eaf6d Compare November 18, 2026 12:16
@wbxl2000
wbxl2000 force-pushed the docs/kap-v1-reference branch from 1bea34d to 2aaf4f5 Compare November 18, 2026 12:16
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from e3eaf6d to 7ea55aa Compare November 18, 2026 12:47
@wbxl2000
wbxl2000 force-pushed the docs/kap-v1-reference branch from 2aaf4f5 to 2202f65 Compare November 18, 2026 12:47
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from 7ea55aa to eae5840 Compare November 18, 2026 14:16
@wbxl2000
wbxl2000 force-pushed the docs/kap-v1-reference branch from 2202f65 to 4929e0d Compare November 18, 2026 14:16
Base automatically changed from docs/kap-v1-reference to main November 18, 2026 15:21
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from eae5840 to 1c858f4 Compare November 18, 2026 15:33

@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: 1c858f458c

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

if (this.disposed) {
throw new Error2(ErrorCodes.SESSION_STALE, `session ${this.ctx.sessionId} metadata is disposed`);
}
if (this.data.agents?.[agentId] === undefined) return;

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 Retry metadata deletion after a failed write

When the backing-store write in applyUpdate fails transiently, it has already assigned the agent-less object to this.data; a caller retrying :close therefore returns here without persisting anything, removes the live agent, and receives { closed: true } while the on-disk registration remains. After the session is reloaded, that supposedly closed agent can be restored again. Roll back the in-memory patch on write failure or refresh/retry the deletion instead of treating the in-memory absence as success.

AGENTS.md reference: AGENTS.md:L135-L137

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from 1c858f4 to 030a71d Compare November 19, 2026 14:01
@wbxl2000 wbxl2000 changed the title feat(kap-server): add POST /sessions/{id}/agents/{id}:close for btw agents feat(btw): add agent close endpoint, side-chat stop button, and close confirmation Nov 19, 2026

@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: 030a71d38a

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

removedKeys.push(key);
}
}
removePendingCloses(removedKeys);

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 closes across session archiving

When a close is queued because the daemon is offline or authentication is unavailable and the user archives that session before the retry succeeds, onSessionsArchivedLocally calls forgetSession, which reaches this call and deletes the durable pending-close record while cancelling its retry. Archiving drains the live scopes but retains agent metadata, so restoring the session can lazily restore the BTW agent the user already closed; keep the tombstone until the close succeeds, or discard it only after permanent deletion or a not-found response.

AGENTS.md reference: AGENTS.md:L111-L115

Useful? React with 👍 / 👎.

Comment on lines +496 to +500
!isServerErrorCode &&
err.code !== 401 &&
err.code !== 429 &&
err.code !== SERVER_AUTH_UNAUTHORIZED_CODE
) {

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 Retry close requests after session lock conflicts

When another client currently holds the session, this endpoint can return SESSION_OCCUPIED (40931), but this broad permanent-client-error branch clears the retry and removes the persisted close request. Because the tab and local conversation were already evicted, the user sees the side chat as closed while its agent remains registered, and releasing the other client's lock never retries the cleanup; keep 40931 in the retryable set.

AGENTS.md reference: AGENTS.md:L115-L116

Useful? React with 👍 / 👎.

Comment on lines +91 to +94
hasActivity: (agentId) =>
client.sideChatRunningOf(agentId) ||
client.sideChatSendingOf(agentId) ||
client.sideChatTurnsOf(agentId).length > 0,

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 Include unsent drafts in the close guard

When an idle side-chat tab has text or attachments in its composer but no submitted turns, this predicate reports no activity, so closing the tab skips the confirmation. evictSideChatAgent then clears the sidechat:${agentId} composer snapshot and input history, silently discarding the unsent draft; include the current or persisted composer draft in the guard before allowing an unconfirmed close.

AGENTS.md reference: AGENTS.md:L210-L212

Useful? React with 👍 / 👎.

Comment on lines +602 to +605
if (!sideChatRunningOf(agentId) && !sideChatSendingOf(agentId)) return false;
try {
const result = await api.cancelSession(parent, { agentId });
return result.cancelled;

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 Serialize interruption with an in-flight side-chat submit

When the stop button is pressed while sideChatSendingOf is true but submitPrompt has not yet been admitted by the server, this cancellation request can arrive first and return cancelled: false; the pending submission can then complete and start the turn after the user asked to stop it. Abort the submission locally or arrange a second cancellation after that submission settles so the newly added stop control reliably covers the sending state it advertises.

AGENTS.md reference: AGENTS.md:L114-L115

Useful? React with 👍 / 👎.

@@ -0,0 +1,6 @@
---
"kimi-code-app": patch
"@moonshot-ai/kimi-code": patch

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个不加

@wbxl2000
wbxl2000 merged commit f9ee8bb into main Nov 20, 2026
19 checks passed
@wbxl2000
wbxl2000 deleted the feat/kap-agent-close branch November 20, 2026 04:55
RealKai42 added a commit that referenced this pull request Nov 20, 2026
main added POST /api/v1/sessions/{session_id}/agents/{agent_id}:close and
the agent_close capability (#5047), which it recorded in the API
snapshot that this branch replaces. The refreshed OpenAPI document and
contract summary list the two changes, both non-breaking. The contract
digest is updated with the host API level kept at 1, as #5047 kept it.
The KAP and ACP capability table lists agent_close as KAP-only, since
ACP sessions have no side-channel agents.
RealKai42 added a commit that referenced this pull request Nov 20, 2026
…5138)

* test: enforce protected first-turn smoke across four layers

* test: demonstrate a missing protected KAP smoke in CI

* test: restore the protected KAP smoke after the gate experiment

* test: record KAP checkpoints and replay them in the client

* test: recover a released conversation across KAP process boundaries

* test: verify protocol contracts and history performance budgets

* test: consolidate layered test infrastructure into testkit

Move the pieces that the TUI, KAP subprocess, recording and schema
tests each built for themselves into @moonshot-ai/testkit:

- TestProcess starts child processes, drains their output, waits for a
  ready line and kills the process tree. Every child preloads the
  network guard, which appends violations to a log that survives a
  forced kill and also covers Node grandchildren.
- kimiCliCommand, kimiCliEnv and osHomeEnv give the CLI one offline
  environment: Kimi services point at a .test host the guard blocks,
  with stubs for the two optional config endpoints.
- KapClient holds the session operations that the in-process
  KapHarness and the new KapProcess subprocess driver share.
- KapRecorder, readKapRecording and replayKapRecording give producers
  and consumers one recording format. The normalizer keeps one token
  per value across keys and can keep time fields parseable.
- expectGolden and expectTextGolden list every difference, accept CRLF
  checkouts and refuse to write in CI.
- The contract summary turns the KAP OpenAPI and AsyncAPI documents
  into one reviewable line per field, including constraints, and
  classifies changes as breaking, non-breaking or unclassified. The
  schema JSON is no longer hidden as generated in diffs.
- The fake model can split responses at random byte boundaries, with a
  seed per lane, to catch clients that depend on tidy chunks.
- testkitAgentFixtures lets engine tests drive the real provider
  request path through the testkit model; the built-in mock API refuses
  to run on such an agent.

* ci: enforce every L0 kind and keep new tests on the testkit

- tests/protected.yaml declares smoke, regression and contract L0
  entries with their runner, and the projects that need a smoke. A PR
  still has to satisfy the IDs and smoke projects of its base revision,
  and Playwright entries must be smoke.
- The test shards upload Vitest blob reports. The new "L0 protected
  tests" job merges them, checks every Vitest L0 entry, and decides its
  exit code from L0 results only.
- scripts/checks/test-doubles.mjs freezes the legacy model doubles at
  their current use per file, so new tests script models through the
  testkit.
- An optional Desktop E2E workflow runs the selected journeys on pull
  requests, all journeys on main, and the quarantined ones nightly.
- CODEOWNERS lists three owners for the gate files.

* test: check the KAP contract in one place

The route snapshot, the HOST_API_LEVEL digest and the scenario schema
golden all described the same REST and WebSocket surface, each with its
own refresh step. packages/kap-server/test/apiSurface.test.ts now runs
all three against the committed documents in packages/kap-server/schema:

- openapi.json, asyncapi.json and contract.txt are the reviewed
  contract. The test compares them with the live server and lists each
  change as breaking, non-breaking or unclassified; `pnpm qa:refresh
  schema` rewrites them. The route table is part of these documents, so
  the separate snapshot is gone, and contract.txt replaces it as the
  contract tripwire.
- The HOST_API_LEVEL pin hashes the same documents through the testkit's
  canonical form, so the golden and the pin agree on what is wording.
  Message titles now count as wording, like descriptions. That changes
  the pinned digest once; the API level stays 1.
- Debug routes stay outside the contract and are listed explicitly, and
  GET / still answers 404.

The canonical form now treats patternProperties keys as names, as the
old digest did.

* ci: record L0 results per shard instead of merging blob reports

The "L0 protected tests" job failed on its first CI run. Vitest 4.1.4's
--mergeReports crashed while restoring the module graph of the full run
(TypeError: Cannot read properties of undefined (reading 'importers')),
before any reporter saw a result. The gate needs test results, not the
module graph.

Each test shard now records its results through
scripts/vitest-l0-gate.mjs, and the gate job checks the recorded files
with Node, so Vitest no longer merges anything. Paths are recorded
relative to the repository and resolved against it, so the check no
longer depends on the working directory. A shard that leaves no result
file still makes its protected tests count as missing.

* test: run mutation testing on the changed lines of a pull request

pnpm qa:mutation mutates the committed changes since the fork point with
origin/main (or --base) in each package's src directory, and runs the
related Vitest tests of that package through Stryker. It works in a
throwaway git worktree with dependencies installed offline, so the
working tree is never touched. Surviving and uncovered mutants go to
.tmp/mutation/summary.md, with an HTML report per package. Static
mutants rerun a whole package suite, so they are skipped unless
--include-static is given.

The Mutation testing workflow runs it on pull requests that change
package sources and adds the summary to the job summary. It is
informational, not a required check. A package whose related tests
already fail under Stryker's single worker thread is listed with those
tests instead of being mutated.

Its first runs showed that the contract tests did not cover a change to
WebSocket operations or messages alone, the "example" keyword, or shapes
that differ only in wording; the tests now cover them.

Stryker 9.6.1 keeps Babel 7, which the workspace already uses. Adding it
to the root importer also makes pnpm re-resolve two optional peers of
the root's own dependencies in the lockfile.

* test: run the subprocess journeys on the built CLI as well

TESTKIT_CLI_BUILD=dist makes kimiCliCommand run the published bundle,
apps/kimi-code/dist/main.mjs, with plain Node: no tsx and no dev-server
switch. The TUI and KAP subprocess fixtures pick it up unchanged. The
CI build job, which already builds everything, now runs the TUI
journeys and the cold-recovery scenario on the bundle after its smoke
test, so a packaging mistake fails there rather than after a release.

TestProcess.start refuses an entry file that does not exist, so a
missing build fails at once instead of as a timeout.

* test: keep Desktop E2E runs offline and free of host settings

The Desktop fixture copied the whole host environment except KIMI_*
variables, so model keys and proxy settings reached the app, and
nothing noticed when the app went online. It now starts from the
testkit's testEnv(), keeping the production defaults for the search
worker and the read model, and points Kimi services at the test host.

The Electron main process, including the embedded KAP server, now
preloads the testkit network guard. A connection to anything but
loopback is blocked and fails the test at teardown. The first run
showed that every launch fetched the models.dev directory, so the
fixture answers that request with 404 and the app falls back to its
built-in snapshot, as it does offline. Requests from the renderer are
not covered.

TestProcess and the Desktop fixture share networkGuardEnv() for the
guard's environment, and the testkit exports the preload path.

* test: restart a KAP subprocess on its port and reconnect a live client

KapProcess.restart() stops the CLI server, cleanly or with a crash, and
starts a new process on the same data directory and port while keeping
the client object. The origin stays the same. The --json token is
ephemeral by design, so server.token becomes the new process's token.

A new app-core scenario keeps the product's DaemonEventSocket open while
the server is killed and restarted. The socket reconnects by itself,
loads the same history again and follows the next turn to its end. It
runs in qa:layers, so Layered QA also covers it on macOS and Windows.

* test: list contract defaults and harden the mutation script

The contract summary now records each field's default, so a changed
default shows up in contract.txt, the file reviewers check as the KAP
contract tripwire. A default that appears, changes or disappears is
classified as unclassified: clients that omit the field get the new
behavior, and a person has to judge whether that breaks them.
contract.txt gains 45 defaults; the JSON documents and the API level
digest are unchanged.

The mutation script:
- reports a package whose Vitest tests do not import the changed files
  as untested instead of failing (for example pi-tui, whose tests run
  on node:test);
- no longer mutates test files that live under src;
- keeps file names with spaces, quotes or non-ASCII letters, and turns
  off user diff settings that could widen the changed ranges;
- removes its checkout on SIGTERM and SIGHUP as well as SIGINT, writes
  the summary before cleaning up, and reports a failed cleanup instead
  of hiding the results;
- installs into the checkout from the repository's own pnpm store.

* test: answer terminal queries in the TUI harness and add a real PTY smoke

- VirtualTerminal.onReply() passes on what the emulated terminal
  answers, such as device attributes and the cursor position. The TUI
  harness forwards it to the CLI as a real terminal would, instead of
  letting the CLI's queries time out.
- terminalFixturesWith({ columns, rows }) sets the terminal size,
  press() knows the navigation and editing keys, and type() returns
  once the typed text is on screen.
- A real pseudo-terminal smoke runs the CLI under the system script
  command on macOS and Linux, finishes a first turn and exits. The same
  shell then prints the terminal modes, so a CLI that leaves the
  terminal raw fails the test.

* test: record several KAP streams and replay mutated recordings

Recording format 2 holds named streams, one per client connection and
agent, with one normalizer across them, so the same ID gets the same
token in every stream. KapRecorder.watch() adds a stream, also in the
middle of a turn, and checkpoint() records every stream at once.
replayKapRecording() replays one stream.

mutateKapRecording() changes the frames of one checkpoint with
dropFrames(), duplicateFrames() or insertUnknownFrame(), and each of
them fails when it matches nothing.

The first-turn recording adds a second client that subscribes while
the model is held. The app-core replay now filters frame types like the
production socket and checks that:
- the late client reaches the same final view as the first one;
- repeating any recorded frame leaves every view unchanged;
- an unknown frame type is ignored.

* test: compare KAP and ACP through a table of shared behaviors

The capability ledger now lists the behaviors both protocols share:
answering a first turn, cancelling a running turn and rejecting a file
write. The parity test runs each one on KAP and on ACP, translates the
endings into one vocabulary (KAP "interrupted" and ACP "cancelled" both
mean cancelled), and checks both against the scenario's expected
outcome, so the two cannot agree on the same mistake.

A known divergence goes into "divergences" with its reason; its test
then asserts that the divergence is still there and fails once both
protocols meet the expectation. Every capability either protocol
advertises must belong to a scenario or carry a reasoned exemption, and
a guard test fails when the advertised set and the table drift apart.

* test: capture released session corpora and widen the history perf trigger

pnpm qa:capture-released <version> downloads the published CLI from
npm, checks it against the registry integrity, installs it without
install scripts and runs one offline turn against a loopback testkit
provider. It then writes a new tests/scenarios/fixtures/released-<version>
corpus with placeholders for the temporary paths, a manifest of digests
and a README. A run for 2.6.3 reproduced the committed corpus: the same
files and the same sequence of wire events.

Cold recovery now runs for every released corpus, and a new test checks
that each corpus matches its manifest: no unlisted, missing or changed
file, and a writer that matches the directory. A corpus is never
rewritten; a new writer version gets its own directory.

Layered QA also runs when the chat rendering it measures changes, and
nightly history-performance results are kept for 90 days so that a slow
drift across versions stays visible.

* ci: give every quarantined Desktop journey an owner and an expiry date

tests/quarantine.yaml lists the nine Desktop journeys tagged
@quarantine with their reason, owner, start date and expiry date.
scripts/checks/quarantine.mjs runs in pnpm lint and fails when:
- a journey is tagged but not listed, or listed but not found;
- an entry has expired;
- an expiry date is more than 60 days after the commit date;
- a protected L0 or smoke journey is quarantined.

Dates are compared with the date of the commit under test rather than
the day of the run, so the check gives the same result for a commit
whenever it runs, while new work cannot land on an expired quarantine.

* fix(kap-server): report :wait settled only after the session is on disk

: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, so the cold-recovery scenario had to poll
wire.jsonl before it crashed the process.

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 an idle reply. The KAP guide
states the guarantee. A new test slows down the disk write of the turn
end and checks that the record is on disk when :wait returns. The
cold-recovery scenario now crashes right after the idle wait and no
longer polls the wire; its WebSocket and REST consistency checks before
the crash are left to the protected KAP first-turn smoke.

* test: register the #4950 regression and four contract tests as L0

Register as L0:
- the compaction test that retries after a context overflow that follows
  an LLM retry (#4950), verified to fail with the fix reverted;
- the KAP contract golden;
- the first-turn recording on the server side and its app-core replay;
- cold recovery.

Cold recovery is now one test that walks every released corpus, so
capturing a new corpus does not need another ID.

The gate self-tests no longer assume that the manifest holds only smoke
entries, and they now check that a regression entry which passed only on
retry is rejected.

CODEOWNERS adds the three dedicated test files. fullCompaction.test.ts and
apiSurface.test.ts are left out because many authors change them often.

* test: wait for the session wire before crashing and move the :wait fix out

The :wait durability fix moves to its own pull request (#5162), so this
branch keeps only test infrastructure. Its kap-server change, the KAP
guide sentence and the slow-disk test are removed here.

Until that fix lands, :wait can reply before the finished turn reaches
the disk. Cold recovery therefore again waits for the continued turn's
turn.ended record in the session wire before it kills the process, and
the server restart test waits for the first turn the same way. The L0
entry and the test guide no longer mention the :wait guarantee.

* test: share the golden comparison and the baseline ratchet

The new-code duplication check reported two clones in this branch.
expectGolden and expectTextGolden repeated the refresh handling and the
read of the committed file, which now live in one helper. The
test-double check repeated how the oxlint ratchet compares, refuses to
raise and rewrites its baseline; ratchet.mjs now exports that as
ratchetBaseline, both checks call it, and a test covers each outcome.

* chore: update the Nix pnpm dependency hash

* test: compile the client modules before the conversation event tests

On Windows the first test in conversation-events.test.ts also paid for
compiling the whole client module graph: about 3.8 seconds of its
5 second budget. When a run went over, the unfinished send of that test
reached the next test's shared API mock and failed it too. A beforeAll
hook now imports the client once, so each test's timeout covers only
its own work.

* test: record the agent close endpoint in the KAP contract

main added POST /api/v1/sessions/{session_id}/agents/{agent_id}:close and
the agent_close capability (#5047), which it recorded in the API
snapshot that this branch replaces. The refreshed OpenAPI document and
contract summary list the two changes, both non-breaking. The contract
digest is updated with the host API level kept at 1, as #5047 kept it.
The KAP and ACP capability table lists agent_close as KAP-only, since
ACP sessions have no side-channel agents.

* test: quarantine the Desktop relaunch layout journey

The journey that restores panel tabs, sidebar layout, pins and window
size after a relaunch fails only on the CI macOS runner: the window
comes back at the default 1440x900 instead of 1180x820. It passes
locally and already failed before the network guard was added. It is
tagged @quarantine and registered with an owner and an expiry date, so
the nightly quarantine run keeps running it.

* ci: run the Desktop E2E journeys in four shards

The journeys ran in one Playwright worker on one macOS machine and took
about 23 minutes. A plan job still picks the journeys as before and now
splits them into up to four shards on separate machines, never more
shards than changed spec files; each shard also runs the first-turn
smoke that the other projects depend on. Going by the last run's time
for each test, the slowest shard needs about 7 minutes. A result job
reports every shard under the previous check name, so the check can be
made required later without renaming it.

* ci: check that fan-in jobs collect every result

The L0 gate and the Desktop E2E result job turn several jobs into one
check. If one stopped waiting for a job, stopped running after a failure
or stopped reading a result, a failing job could leave the check green,
because GitHub reports a skipped job as passed. The guards now read the
registered fan-in jobs from registry.json and fail when a collected job
is missing from needs, when the job is not run after failures, when the
Desktop result job does not read a result, or when a new job in that
workflow is left out of it.

* ci: time out the test, L0 and build jobs

These jobs had no timeout, so a hung run kept its runner for six hours.
The test shards and the build job now stop after 20 minutes and the L0
gate after 10, several times their usual run time of about 5, 3.5 and
0.6 minutes.

* test: record the context item segment field in the KAP contract

main added an optional segment field ("reply", "thinking" or
"tool_call") to the context item responses (#5175) and recorded it in
the API snapshot that this branch replaces. The refreshed OpenAPI
document and contract summary list the three new outputs, all
non-breaking, and the contract digest is updated with the host API
level kept at 1, as #5175 kept it.

* ci: run desktop journeys on demand and stop mutation testing from killing the runner

Desktop E2E now runs on a pull request only when it changes the journeys
or carries the desktop-e2e label, in up to five shards. Every run takes
five of the organization's macOS machines, so running it on every pull
request that touches desktop or engine code would queue everything else
behind it. main still runs every journey on each push and every night,
and a failure there opens or updates one tracking issue that closes itself
once main passes again.

Mutation testing runs only on pull requests with the mutation label, with a
30-minute budget. It no longer mutates files that start or stop processes:
a mutant that drops the PID guard in killProcessTree made the guard's own
test send SIGKILL to the test runner's process group, or to every process
of the user, which is why every run on this pull request ended with the
runner losing contact. Stryker now runs in its own process group, and the
processes it leaks are killed during and after the run.

* test(desktop): assert the approved command's output inside its output panel

The bash card highlights its command, so in `echo first-approved >
first.txt && cat first.txt` the word first-approved is a span of its own,
next to the same word in the output panel. Once highlighting finished, the
transcript-wide exact-text locator matched both and failed in strict mode;
it only passed when the assertion ran before the highlighter. It failed on
CI that way, and waiting for the highlighted token first reproduces it on
every run. The assertion now looks inside the output panel.

* ci: keep the desktop journeys at four shards

The organization runs at most five macOS jobs at once, and every push also
starts the L0 smoke gate. Four shards plus the smoke gate fill the five
machines exactly; with five shards one of them always queued behind it.
The five-shard run took 15.3 minutes from start to finish against 12.9 with
four, with shards waiting up to 6.2 minutes for a machine.

* build(nix): update the pnpm dependency hash after merging main

* test(cli): wait for the turn to finish before the terminal tests exit

The TUI keeps a turn in its streaming phase after the answer is on
screen, until the agent loop reports that it is idle. The terminal
tests sent /exit as soon as the answer appeared, so on a busy machine
the TUI refused it ("Cannot /exit while streaming") and the CLI never
closed. The L0 first turn, the session helper tests and the PTY test
failed this way on CI. Holding the model stream after the answer shows
the window on every run: the answer is visible, /exit is refused, and
the "Worked for ... done" summary only appears once the turn has ended.
The tests now wait for that summary before they close the CLI.

* test: record the session continue action in the KAP contract

main added POST /api/v1/sessions/{session_id}:continue, advertised as
the session_continue capability, with error code 40940
TURN_NOT_CONTINUABLE (#5048). Continuing starts model work, so the
action can also answer with the sign-in errors 40110, 40111 and 40113;
the session actions share one OpenAPI projection, so the six existing
actions list those four responses as well. The refreshed OpenAPI
document and contract summary record 146 changes, all non-breaking, and
the contract digest is updated with the host API level kept at 1, as
#5048 kept it. The capability ledger lists session_continue as KAP-only,
since ACP has no request to continue a turn.

* test(desktop): quarantine the composer drafts and models journey

After main's #5048 came in, the journey failed once on CI, while it
passed in the two runs before and twice locally. The trace shows the
app itself presenting the model menu again: after choosing Off and
pressing Escape the menu starts closing, then shows again with no
further input and stays open past the 15-second timeout. That is a race
in the product rather than in the test, so the journey is quarantined
with an owner and an expiry while its cause is investigated, and the
nightly run keeps running it without retries.
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
app-core exposes KimiWebApi.closeAgent with the 40401 code and hostRouting;
app-client adds the side-chat close guard, the cancel/pending-close state
machine, btw-tab persistence destruction and the panel skip flag;
SideChatPanel gains stop/Esc, Composer a working override, and the desktop
PanelTabs routes requestClose through the guard with closeConfirm copy
(MoonshotAI#5047). app-client 173 pass, app-core daemon-client 89 pass, root checks
green.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Port upstream 13d363e. The fork already carried the hosts services,
the stdio RPC transport and the session aggregation; the 2.7.0 remerge
had dropped the server-transport half, so restore it:

- start.ts serves the v1 API over a unix socket (startUnixRpcServer,
  0600 socket, auth implied off), builds ManagedIdleExit for a
  --managed-by daemon, drains idle sessions for if_idle shutdowns,
  registers the /api/v1/hosts/{id}/proxy REST and WebSocket routes,
  publishes event.host.changed through the broadcaster (10 ms
  throttle), and closes the RPC listener, notify timer, idle-exit
  timer and host bridges. Fork adaptations: keep the
  skipInstanceRegistry branch and the hosts option name; the socket
  branch takes precedence.
- POST /api/v1/shutdown accepts if_idle=true and answers ok:false
  while a client or a session is still live. The querystring is a
  strictObject because the fork's request-boundary gate rejects strip
  schemas.
- registerApiV1Routes threads drainIdleSessions into the shutdown
  route and mounts hosts:import-providers when managedBy is
  ensure-daemon.
- /config and the config-changed publisher serialize the hosts section
  through IConfigRegistry/applySectionToToml, so hosts fields keep
  their TOML snake_case names.
- The CLI forwards --socket/--managed-by, reports a unix: address and
  prints neither banner nor browser in socket mode. The orphaned
  deprecated-server.ts and its notice keys are deleted; both
  kimi-command docs describe `kimi server` as the browser-less runner.
- modelCatalog shares the provider write queue with host imports
  (services/providerWrites.ts), so host copies and provider edits
  serialize on one chain.
- Schema goldens refreshed (proxy routes, if_idle, event.host.changed)
  and the apiSurface snapshot plus HOST_CONTRACT digest updated. The
  refresh also picked up the {agent_id}:close route that landed in
  MoonshotAI#5047 without regenerating the goldens.

Tests: hosts 36 pass/17 skip (win32 unix-socket cases), host-free
kap-server suites 84 pass (config 32, sessionIdleReaper 7, shutdown 4,
apiSurface 4, snapshot 1, hosts 36); ws suites 140 pass;
boot/openapi/registry/meta/publicApi 56 pass; kimi web CLI 88
pass/1 skip. Typecheck clean for kap-server and apps/kimi-code.
check:no-comments, strict-request-bodies, locale and prose gates pass;
lint 0 errors. Pre-existing and unrelated: hostAggregation's
"within five seconds" case times out because HOST_PROJECTS_TIMEOUT_MS
equals bun's default per-test timeout.
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