Skip to content

feat: add the context usage view and session context inspection routes - #5058

Merged
wbxl2000 merged 25 commits into
mainfrom
qer/model-call-inspector
Nov 19, 2026
Merged

wbxl2000 merged 25 commits into
mainfrom
qer/model-call-inspector

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

长会话里,用户很难知道上下文已经用了多少、还剩多少、被什么占满,也没法确认模型实际收到了哪些内容(系统提示词、工具定义、工具结果),往往要等到自动压缩或报错才发现问题。

这个 PR 新增「上下文用量」:输入框的上下文圆环小窗和右侧会话信息栏展示上下文的已用、剩余和组成,详情面板按模型实际收到的样子逐条列出内容。服务端新增三个只读接口提供这些数据,返回的内容与 agent 下一次请求发给模型的内容一致。界面先作为实验室功能发布:设置 → 实验室 的「上下文用量」开关,默认关闭;关闭时界面和行为与 main 一致。

两仓合并前,界面部分在 code-app 的 MoonshotAI/kimi-code-app#1374,现已移植到本 PR,那个 PR 会关闭。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路:agent-core-v2 的 Loop 服务新增只读方法 previewRequestContent(),从核心 Loop 的持久化消息出发,按 turn 请求同样的整理步骤(tool-select 塑形 → 对不支持图片的模型隐藏 ReadMediaFile → projector 投影),算出下一次请求的系统提示词、工具和消息。kap-server 的三个路由把它整理成摘要、分页条目和单条详情。一个对照测试跑真实 turn,断言 provider 收到的内容与预览一致;以后请求流程改了而预览没跟上,CI 会直接失败。各类和各条的大小都以 token 计:用引擎的估算服务(ISessionTokenCountingService,自动压缩也用它)估出每一项,再按比例把实测的已用量分给各项,所以各项相加等于圆环上的已用量。客户端在输入框圆环小窗和右侧会话信息栏展示摘要,在详情面板分页列出条目;三个入口都受实验室开关控制。刷新由服务端推送的已用 token 和会话状态驱动,没有定时轮询。

概念

概念 回答什么问题 本 PR 之后
请求预览 下一次请求会给模型发什么 IAgentLoopService.previewRequestContent() 返回 { systemPrompt, tools, messages },不发请求,没有副作用
上下文条目 面板里的一行对应什么 系统提示词、每个工具定义、每条投影后的消息各是一个条目,id 为 system / tool-<i> / message-<i>
上下文摘要 用了多少、还剩多少、被什么占满 第一行是已用百分比和「已用 / 上限」;组成条按整个窗口画,彩色小段是各角色的用量,浅灰是剩余;下方按用量从大到小列出各角色的 token 数和占整个窗口的比例,悬停角色名可看条数
分项大小 每类、每条各占多少 token 估算值按比例分摊实测的已用量,各项相加等于已用量;会话还没有实测值(还没调用过模型)时,直接用估算总和。界面上分项数字前的「~」表示估算,已用量和上限是实测值,不加
「上下文用量」开关 用户能不能看到这些入口 设置 → 实验室 的开关,默认关闭;保存在本机 localStorage,桌面端和 kimi web 各自保存

结构

flowchart TB
  D[核心 Loop 的持久化消息]
  D --> P[previewRequestContent<br/>tool-select → 隐藏 ReadMediaFile → 投影]
  D --> Q[turn 请求的 resolver 链<br/>tool-select → 隐藏 ReadMediaFile → 投影 → 媒体解析]
  Q --> M[provider]
  T{{对照测试}} -. 比较 .-> P
  T -. 比较 .-> M
  P --> R[kap-server context 路由<br/>summary · items · items/:id]
  R --> ring[输入框圆环小窗]
  R --> info[右侧会话信息栏 · 上下文分区]
  R --> panel[详情面板与条目弹窗]
  lab[实验室「上下文用量」开关] -. 开启后显示 .-> ring
  lab -. 开启后显示 .-> info
  lab -. 关闭时关掉标签页 .-> panel
Loading

预览和真实请求是两条代码路径,按同样的步骤处理同一份持久化消息。对照测试用 scripted provider 截获真实请求,要求 system prompt 和工具完全相同、预览的消息正好是 provider 收到的消息的前缀。媒体解析会读取或上传文件,所以预览不做这一步,图片以引用的形式出现。

关键决策

决策 选择 没选 理由
数据源 核心 Loop 的持久化消息,加上与请求相同的整理 loop.history() history() 是给聊天界面用的展示视图:会把工具备注拆出正文、删掉失败 turn 里没有结果的工具调用,和模型收到的不一致
预览还是记录 预览下一次请求 记录上一次实际发出的请求 上一次请求只在内存里,重启后就没有,也不包含之后新增的工具结果
放在哪 Loop 服务 在 kap-server 里自己拼 持久化消息和请求整理都在 Loop 里;放到别处要先暴露私有数据,还会复制一份整理流程
防止走偏 对照测试 让真实请求链和预览共用同一份转换代码 共用代码要改每次请求都走的热路径(resolver 结构和恢复逻辑),风险更高
分项大小 引擎的 token 估算,按比例分摊实测总量 字符数;内置分词器或调用模型服务的计数接口 模型接口只返回整次请求的总数。字符数在中英文之间相差好几倍,粘贴的图片按 base64 长度会被放大上百倍;精确分词要为每家模型单独接入。用本地 80 个会话、约 2.5 万次调用比对,估算按类别汇总后与实测相差在 ±30% 以内,只用来分配比例
上线方式 实验室开关,默认关闭 直接对所有用户开放 先让需要的人手动开启;默认用户看到的界面与 main 一致
开关存在哪 本机 localStorage,和「多标签页的会话列表」一样 服务端 experimental flag 开关只影响客户端界面;三个接口是只读的,不开启的用户不会调用
详情面板自动刷新 重新拉取已加载的范围 回到第一页 回到第一页会清掉「加载更多」的条目、关掉超出第一页的条目弹窗

阅读指南

  1. packages/agent-core-v2/src/agent/loop/loopService.ts 的 previewRequestContent():预览怎么算,可以对照同文件 corePolicy() 里的 resolver 链看。
  2. packages/agent-core-v2/test/agent/loop/coreLoopService.test.ts 的 previews the request content…:对照测试如何把预览钉在真实请求上。
  3. packages/kap-server/src/routes/context.ts:三个路由如何把预览整理成摘要、条目和详情,包括按估算比例分摊实测总量、系统提示词按一级标题分段、角色筛选和分页。
  4. packages/app-components/src/composer/ContextSummaryBody.vue 与 packages/app-client/src/stores/sessionInfo.ts:摘要组件,以及右侧栏上下文的观察、刷新和去重。
  5. apps/desktop/src/renderer/inspector/:详情面板的筛选、分页、刷新,条目详情和复制。
  6. packages/app-core/src/composables/useContextInspector.ts 和各入口的开关判断:Composer.vue 的圆环、SessionInfoPanel.vue 的分区与观察、App.vue 里关闭上下文标签页、SettingsDialog.vue 的实验室开关。

可以略读:contextItems.ts(多角色筛选)、rest-context.ts(schema)、registerApiV1Routes.ts(注册)、mediaPolicy.ts(只是导出已有函数)、两个测试替身、packages/app-core/src/api/ 的接口方法与 hostRouting.ts 的会话路由、面板注册接线(panel*)、i18n 词条、样式 token、API 快照与契约摘要、ratchet 基线和 changeset。

从 code-app 移植:#5079 是不带历史的快照导入,所以界面部分按补丁移植到 apps/desktop 和 packages/app-*,只做了这些适配:

  • apps/web 已不存在,原来同步到 Web 的副本和对应测试不再需要;kimi web 的界面由桌面端渲染进程构建,自动带上这些改动。
  • 上下文标签页改用已有的 list-numbers 图标,不新增图标。
  • sessionInfo.ts 的排队刷新改用 then(reload, reload),合并了重复的加载代码,符合本仓的 promise 规则;行为不变。
  • scripts/checks/baselines/oxlint-ratchet.json 里 panelComponents.ts 的 no-unsafe-assignment 从 8 调到 9:面板表里每个 .vue 组件在 oxlint 看来都是 error 类型,现有 8 个面板都是这条,新增上下文面板必然加 1。

评审跟进(Codex 意见,逐条回复见各线程):

  • 服务端:读取已持久化但不在内存里的子 agent 前先恢复它;条目 id 必须和列表生成的完全一致;动态加载的工具 schema 归为 definition,并按工具个数计数;只替换媒体块里的长数据,audio_url 也算媒体。
  • 客户端:自动刷新走后台读取预算并带会话级取消信号;上下文上限或模型变化时刷新;同一位置换了内容(角色、名称、预览或媒体变化)时弹窗重新读取,只有分摊后的 token 数变化时不重新读取;弹窗翻过已加载范围时先加载下一页;首次读取失败可重试;刷新失败时保留上次数据并提示;圆环小窗可滚动,焦点在圆环上也能用 Escape 关闭;详情弹窗保留焦点框。
  • 没有改并回复了理由:tokens 和状态计数保持一致;预览不调用会写入会话的 prepareForRequest();HOST_API_LEVEL 留给维护者决定。
  • 精简:预览里只有 core 的 Message,服务端改为按类型解析,删掉了兼容其他协议原始格式、实际走不到的分支;每条消息只计算一次,摘要、列表、详情共用这份结果;内容块限定为 text、think、definition、function、media 五种,客户端同步删掉了走不到的 result 渲染。

三个接口的说明来自路由定义,出现在运行中的 /openapi.json。没有更新 packages/kap-server/docs/kap.md:这三个接口供上下文界面使用,不在 packages/kap-server/AGENTS.md 列出的核心会话循环接口之内。

Screenshots / Recordings

以下截自真实运行,上下文相关的截图是开启「上下文用量」后的样子;默认关闭时,输入框圆环和 main 一样只有悬停提示,右侧栏没有上下文分区。

设置 → 实验室 新增「上下文用量」开关,默认关闭(中文、英文):

实验室(中文)

实验室(英文)

上下文摘要,浅色和深色:左边是右侧会话信息栏的上下文分区,右边是点击输入框圆环弹出的小窗。第一行是已用百分比和「已用 / 上限」;组成条按整个窗口画,彩色小段是各角色的用量,浅灰是剩余;下面按用量从大到小列出各角色估算的 token 数(带「~」)和占窗口的比例。

上下文摘要(浅色)

上下文摘要(深色)

详情面板:顶部是用量和组成条,点组成条或图例可以按角色筛选;下面按模型收到的顺序列出系统提示词、工具定义和消息,右侧是每条估算的 token 数(带「~」)。

上下文详情面板

英文界面:

上下文摘要(英文)

上下文详情面板(英文)

Behavior Changes and Affected Users

行为 之前 之后 谁依赖旧行为 退路
桌面端和 kimi web 的界面 输入框圆环只有悬停提示 默认不变;设置 → 实验室 多一个「上下文用量」开关,开启后才出现圆环小窗、右侧栏上下文分区和详情面板 无 关闭开关即回到原样,已打开的上下文标签页会被关闭
开启后的请求量 不适用 右侧栏显示期间,每个 step 大约一次 summary 请求(后台低优先级);圆环小窗和详情面板只在打开时请求 无 关闭开关
GET /api/v1/sessions/{session_id}/context/summary、/context/items、/context/items/{item_id} 不存在 新增的只读接口 无 不需要
通过上述接口读取冷会话 不适用 会话被加载进服务进程 无(新接口) 不需要
客户端可见的 API 契约摘要 HOST_CONTRACT 旧摘要 加入三条路由后的新摘要,HOST_API_LEVEL 保持 1 通过 SSH 连接远程主机的桌面端:远程主机上的旧版 kimi 没有这些接口,开启上下文用量后面板会报错,其他功能照常 在远程主机上升级 kimi
IAgentLoopService 接口 无此方法 新增 previewRequestContent() 自行完整实现该接口的代码需要补上这个方法;仓库内只有两个测试替身,已补上 无

现有接口、turn 请求的处理流程和默认值都没有变化:previewRequestContent() 只读,不改动持久化消息,也不在请求链里;mediaPolicy.ts 只是导出了已有的 hideReadMediaFile。

请维护者确认:

  • 本 PR 没有提升 HOST_API_LEVEL。新增的都是只读接口,旧远程主机缺少它们只影响开启了上下文用量的面板;提升级别会让所有旧远程主机必须先升级才能连接。
  • panelComponents.ts 的 ratchet 基线从 8 调到 9,原因见「从 code-app 移植」。

契约消费方:本仓的桌面端与 kimi web 界面使用这三个接口。上一版服务端没有这些接口,新客户端在旧服务端上读取上下文会得到 404;旧客户端不受影响。

受影响模块与测试覆盖:

  • agent-core-v2 Loop:coreLoopService.test.ts 的对照测试覆盖带耗时和备注的工具结果、工具运行期间插入的消息、执行失败的工具结果、不支持图片时隐藏 ReadMediaFile、空文本块和没有结果的工具调用。把预览分别改坏三种方式(去掉投影、去掉隐藏 ReadMediaFile、只在真实请求链里新增一个改写消息的 resolver),这个测试都会失败。
  • kap-server context 路由:context.test.ts 覆盖恢复会话的系统提示词分段(含每段的 token 数)、动态工具 schema 归为 definition、多角色筛选、模型视角的工具结果与顺序、恢复不在内存里的子 agent、拒绝非列表生成的条目 id、只替换媒体数据、有实测值时各项 token 之和等于实测总量且按估算等比分配、没有实测值时已用量等于估算总和;apiSurface.snapshot.test.ts 覆盖路由快照和契约摘要。
  • 客户端:sessionInfoPanel.test.ts 覆盖右侧栏上下文分区的渲染(已用百分比、「已用 / 上限」、按 token 数排序的各角色及其占窗口比例、角色名的条数提示)、上下文上限未知时只显示 token 数、折叠后标题行显示用量、压缩和查看详情按钮、开关关闭时不渲染也不发起观察、切换模型后刷新、刷新失败时保留旧数据并提示;composerMenuViewportClamp.test.ts 覆盖开关关闭时圆环是静态指示、悬停提示与 main 相同,开启后小窗的定位,以及焦点在圆环上时用 Escape 关闭;contextPanel.test.ts 覆盖自动刷新走后台读取且保留已加载条目和打开的弹窗、同一位置内容变化时重新读取而只有 token 数变化时不重新读取、超过 500 条分批拉取、弹窗翻过已加载范围时加载下一页、首次读取失败重试、切换模型后刷新;formatTokens.test.ts 覆盖占比和估算值(带「~」)的格式;另有 session-info.test.ts、context-copy.test.ts、panel-registry.test.ts、hostRouting.test.ts。

验证结论:以上测试全部通过。用一份真实会话(461 条消息)的副本做了离线比对,接口返回的角色顺序和每条正文,与独立按请求流程算出的结果完全一致。在桌面端开发环境里验证了实验室开关(默认关闭、开启后入口出现、关闭后上下文标签页被关闭)、圆环小窗、右侧栏(浅色和深色)和详情面板的刷新,并核对了各角色的 token 数相加与已用量一致。没有覆盖:媒体解析(只有真正发送请求时才发生)、kimi web 的人工验证、远程主机上的会话。

检查记录
  • pnpm lint:通过(ratchet 基线调整见上)。
  • pnpm exec tsc -p packages/kap-server/tsconfig.json --noEmit、pnpm --filter kimi-code-app run typecheck:通过。
  • 合并最新 main 后,受影响的测试(kap-server 全部、packages/app-* 与桌面端渲染进程测试):574 个文件,8261 个用例通过,1 个跳过。
  • agent-core-v2 的 loop 测试(含对照测试)在改用 token 计数之前跑过并通过;之后的提交没有改动 agent-core-v2。
  • 改用 token 计数之前跑过一次 pnpm test 全量:1527 个文件中 6 个失败。其中 4 个单独重跑通过(并发负载下的超时);另外 2 个(node-sdk 的 serves suggestFiles…、agent-core-v2 tool.test.ts 的三个子 agent 截止时间用例)在干净的 main 上以相同方式失败,与本 PR 无关。

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

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

This PR includes changesets to release 4 packages
Name Type
kimi-code-app Patch
@moonshot-ai/kimi-code Patch
@moonshot-ai/kap-server Patch
@moonshot-ai/agent-core-v2 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-19T12:24:51.684229Z 2867553 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.

@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: 340d3a6174

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +435 to +440
previewRequestContent(): LoopRequestContent {
const capabilities = this.data().modelCapabilities;
const disclosure = this.toolSelect.enabled(capabilities);
const source = this.loop?.state.messages ?? this.journal.snapshot().input.messages ?? [];
const tools = this.toolSelect.requestTools(this.baselineTools(), disclosure, true, source);
const messages = this.toolSelect.shapeHistory(source, disclosure, tools);

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 Reconcile dynamic tools before building the preview

When the MCP/tool registry changes after the previous request—for example, when a dynamically loaded MCP tool is removed—the real createToolSelectResolver first awaits prepareForRequest(), which reconciles the current tool state before calling requestTools() and shapeHistory(). This preview skips that preparation and shapes the stale state directly, so the context endpoints can keep showing a removed tool or schema even though the next model request omits it; make the preview asynchronous and reconcile first, or reuse the resolver path.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving this as is. prepareForRequest() publishes the deferred tool initialization and runs the tool reconcile, and both can append messages to the conversation, so calling it from a GET endpoint would write to the session on every read. The preview reports the current state; once the next request reconciles, the following read shows it (the panels refresh on usage changes).

});

const HOST_CONTRACT = { apiLevel: 1, digest: '69590c90b95ea06c1fc8e4bf9d1fedcac0a66db09c8eb5ead907f68496a19c55' };
const HOST_CONTRACT = { apiLevel: 1, digest: '658677a7434aba409e1b98bcd6b04ca06622c0ed8d3341d8d3ed842a62b4faf7' };

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 Negotiate the new context routes with remote hosts

For a desktop client connecting through the SSH host bridge to a host running the previous release, changing only the contract digest while leaving API level 1 causes checkBootstrapOutput() to accept that old host; the context panel then calls routes that do not exist there and receives a 404. Since these routes are required by the new client feature and are not capability-discovered, bump HOST_API_LEVEL or add explicit feature negotiation so incompatible remote hosts are rejected or the panel is disabled before use.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Keeping API level 1 and leaving the call to maintainers (it is asked in the PR description). The UI that calls these routes now sits behind an off-by-default Lab toggle; against an older remote host only that panel shows a request error and nothing else changes. Bumping the level would force every older remote host to upgrade before it can connect at all.

# Conflicts:
#	docs/en/reference/server-api-sessions.md
#	docs/zh/reference/server-api-sessions.md
#	packages/kap-server/test/apiSurface.snapshot.test.ts
@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@2867553
npx https://pkg.pr.new/@moonshot-ai/kimi-code@2867553

commit: 2867553

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

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

messages: request.messages,
modelAlias,
tokens: {
used: legacyStatus?.contextTokens ?? 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.

P2 Badge Size the preview instead of reusing legacy status

When the session has not made a model call yet, or its profile/tool set changed since the last call, legacyStatus.contextTokens is not the size of request: the status counter is anchored to conversation history and prior measured usage, so a fresh profiled session reports used: 0 even though this preview contains a system prompt and tools. Use the existing ISessionTokenCountingService.requestSize() path, which includes the prompt, tools, and messages, to avoid showing desktop/web clients a stale or materially low usage figure.

AGENTS.md reference: packages/kap-server/AGENTS.md:L3-L3

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving this as is. tokens intentionally mirrors the status counter that also drives the ring percentage, the "used / left" label, and auto-compaction, so every context indicator agrees. requestSize() is a pure estimate and would drift from the measured anchor once a session has made calls. The zero before the first call matches the existing ring; changing it belongs in the token counting service rather than in this endpoint.

Port the context usage UI from code-app: the composer ring card, the session info context section, the details panel, and the Lab toggle that gates them.
@wbxl2000 wbxl2000 changed the title feat(kap-server): add session context inspection routes feat: add the context usage view and session context inspection routes 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: 308206e695

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

"apps/desktop/src/main/browser/browser-view.ts": 1,
"apps/desktop/src/renderer/api/config.ts": 1,
"apps/desktop/src/renderer/components/panel/panelComponents.ts": 8,
"apps/desktop/src/renderer/components/panel/panelComponents.ts": 9,

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 Fix the new violation instead of raising the ratchet

Restore this count to 8 and fix the newly introduced typescript/no-unsafe-assignment violation in panelComponents.ts; increasing the stored baseline to 9 silently permits a new violation and weakens the lint safeguard for future changes, contrary to the repository rule that new code must not increase ratcheted violations.

AGENTS.md reference: AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Raising this one entry is deliberate and was approved for this PR. Every component in this registry is a .vue import that oxlint's type-aware pass resolves as error, so all 8 existing entries already carry this finding, and registering any new panel adds one. Avoiding it would mean bypassing the registry for this panel, which is worse than the frozen count. It is called out under "从 code-app 移植" in the description.

Restore persisted subagents before reading their context, reject item ids the listing never produces, report dynamically loaded tool schemas as definitions, and redact only media payloads in raw details.
Use background reads for automatic refreshes, reload an open item when its slot changes, page through items past the loaded range, add retries for failed first reads, keep the last summary visible with a notice after a failed refresh, let the ring card scroll and close with Escape from the ring, and keep focus rings in the item dialog.
The session info section and the details panel now refresh when the context limit or model changes while the session is idle, and the panel no longer refreshes on unrelated status updates.

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

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

import { ref } from 'vue';
import { STORAGE_KEYS, safeGetJson, safeSetJson } from '../lib/storage';

const contextInspectorEnabled = ref(safeGetJson<boolean>(STORAGE_KEYS.contextInspector) === true);

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 Gate the experiment with the repository flag system

This Lab feature is described as experimental, but its enablement is sourced exclusively from localStorage, so KIMI_CODE_EXPERIMENTAL_*, the [experimental] configuration, and the global experimental flag cannot control it, while an individual browser can enable it independently of server policy. Define and consume the repository-standard experimental flag rather than using a standalone client-only boolean.

AGENTS.md reference: AGENTS.md:L119-L122

Useful? React with 👍 / 👎.

Comment on lines +2500 to +2502
watch(
[ctxCardOpen, sessionId, () => status.value?.ctxUsed, () => running.value],
([open], [wasOpen]) => {

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 Refresh the composer card when the active model changes

Although the earlier refresh issue was fixed in SessionInfoPanel and ContextPanel, this separate composer watcher still omits status.modelId and status.ctxMax. If another connected client changes the model while this card remains open and ctxUsed/running stay unchanged, its live usage header can show the new limit while the stored composition and tool snapshot remain from the old model until the card is closed or another turn runs; include the model and capacity in this refresh trigger.

AGENTS.md reference: AGENTS.md:L109-L115

Useful? React with 👍 / 👎.

Comment on lines +113 to +116
const toolDefinition = computed(() => {
if (props.item.role !== 'definition' || !detail.value) return null;
const raw = asObj(detail.value.raw);
const fn = Object.keys(asObj(raw['function'])).length ? asObj(raw['function']) : raw;

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 Render injected tool-schema messages from their parts

When the selected definition item is a dynamically injected schema message, detail.raw is the enclosing system message ({ role, content, tools }), not a standalone tool definition. This computed value nevertheless returns a truthy definition with no description or parameters, so the parsed tab selects the empty tool-view branch and never renders the populated detail.parts; detect whether raw is actually a standalone schema and otherwise fall back to the parts view.

Useful? React with 👍 / 👎.

Comment on lines +57 to +60
() => props.item.id,
() => props.item.role,
() => props.item.chars,
() => props.item.preview,

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 Reload open details for every context snapshot

If a refreshed item changes only beyond the 240-character preview while keeping the same total length, role, and ID, every value watched here remains unchanged. The parent list advances to the new snapshot, but the open dialog keeps displaying and copying the old raw content; pass a snapshot revision such as captured_at into the dialog and include it in this reload trigger rather than using the lossy summary fields as the change detector.

Useful? React with 👍 / 👎.

The preview only ever holds core messages, so parse them by type instead of probing provider-specific shapes, outline each message once for the summary, list, and detail, and narrow item parts to text, think, definition, function, and media.

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

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


function partChars(part: ContentPart): number {
if (part.type === 'text') return part.text.length;
if (part.type === 'think') return part.think.length;

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 Count encrypted reasoning in context totals

For sessions using Anthropic, OpenAI Responses, or compatible reasoning models, a think part can contain a large encrypted payload that is replayed to the provider, but this branch counts only the visible think text. When summaries are short or empty, the assistant group and total_chars can therefore omit most of the actual context and show misleading composition percentages; include the replayed encrypted payload in the character measurement.

Useful? React with 👍 / 👎.

context: {
type: 'context',
policy: 'singleton',
title: (_payload, t) => t('inspector.title'),

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 context to locale-driven tab refresh

When an open context tab survives a locale change, its title remains in the previous language because usePanelTabs.ts rebuilds titles only for LOCALIZED_TITLE_TYPES, and that set still omits the newly registered context type. Add this type to the locale-refresh set so the new tab updates alongside the other localized tabs.

AGENTS.md reference: AGENTS.md:L108-L108

Useful? React with 👍 / 👎.

Comment on lines +166 to +168
if (observedContextBySession.value[sessionId]) {
tasks.push(refreshContext(sessionId, options));
}

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 Coalesce turn-end context refreshes

When the context sidebar is enabled and a main turn finishes, onMainTurnEnd() already calls sessionInfoStore().refresh(), which now starts this context refresh, while SessionInfoPanel.vue independently calls refreshContext() on the same running-to-idle transition. Since refreshContext() queues a follow-up request when one is in flight rather than deduplicating it, every completed turn issues two sequential context-summary requests; keep only one of these turn-end triggers or coalesce them.

Useful? React with 👍 / 👎.

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

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +142 to +145
registerContextRoutes(
apiV1 as unknown as Parameters<typeof registerContextRoutes>[0],
core,
);

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 context routes to the built-in KAP guide

The three new session-context endpoints are registered as public KAP routes and appear in OpenAPI, but packages/kap-server/docs/kap.md still omits them from its endpoint directory. External agents are directed to the in-binary /api/v1/kap.md guide, so shipped clients cannot discover these endpoints or their query/pagination semantics from the protocol guide; update that guide alongside the route registration.

AGENTS.md reference: packages/kap-server/AGENTS.md:L16-L16

Useful? React with 👍 / 👎.

Segments now sit flush without separators or per-segment rounding, keep only the bar's outer corners, and shrink to a 4px minimum so small groups stay visible without dominating the bar.
Split the measured context size across the system prompt, tool definitions, and messages in proportion to the engine's token estimates, and show the summary as a percentage used, the used and maximum tokens, and per-role token counts and window shares sorted by size.

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

ℹ️ 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 messageItems = sources.outlines.map((outline, index): ContextItemSummary => ({
id: `message-${index}`,

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 Make context item IDs snapshot-stable

When a turn, compaction, or second client changes the context after /context/items returns, a positional ID such as message-3 can refer to a different message because the detail endpoint rebuilds the current preview and indexes its new sources.messages array. The inspector can therefore display or copy content that does not match the item the user selected; tie IDs to stable message identities or require a snapshot revision when fetching details.

AGENTS.md reference: AGENTS.md:L111-L116

Useful? React with 👍 / 👎.

wbxl2000 added a commit that referenced this pull request Nov 19, 2026
wbxl2000 added a commit that referenced this pull request 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: 59cf8b2b10

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +62 to +69
const pages = await Promise.all(starts.map((start) =>
getKimiWebApi().getSessionContextItems(sid, {
roles,
offset: start,
limit: Math.min(MAX_REQUEST_LIMIT, offset + count - start),
}, options),
));
return { ...pages.at(-1)!, items: pages.flatMap((page) => page.items) };

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 Fetch one immutable snapshot before merging pages

When more than 500 items are loaded, a refresh issues several /context/items requests concurrently and concatenates their independently generated previews. If an active turn, compaction, or another client changes the context while those requests run, later pages can use different positional boundaries, producing duplicated or missing rows and a summary that does not describe the merged list. Return pages from a shared snapshot revision, or fetch them through a server operation that holds one immutable preview.

AGENTS.md reference: AGENTS.md:L111-L116

Useful? React with 👍 / 👎.

Comment on lines +249 to +250
const scale = estimatedTotal > 0 ? used / estimatedTotal : 0;
const allocate = (estimate: number): number => Math.round(estimate * scale);

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 the measured total when allocating item tokens

When the measured-to-estimated scale is not an integer, independently rounding every item does not preserve tokens.used; with many small messages the group and item totals can differ substantially from the headline usage, and sufficiently small scaled estimates can all become zero. Allocate the rounding remainder across items after scaling so the reported groups and items sum exactly to the measured total.

Useful? React with 👍 / 👎.

# Conflicts:
#	apps/desktop/src/renderer/components/settings/SettingsDialog.vue
#	packages/app-i18n/src/locales/en/settings.ts
#	packages/app-i18n/src/locales/zh/settings.ts
#	packages/kap-server/test/apiSurface.snapshot.test.ts

@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: 286755389b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +11 to +15
items: [
...allNonToolItems.filter(
(item) => item.role === 'system' && selectedRoles.has(item.role),
),
...(selectedRoles.has('definition') ? toolItems : []),

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 message order when filtering multiple roles

When the context contains a raw system reminder injected after user or assistant messages, selecting system together with another role moves every matching system message to the front because this branch collects them separately before filtering the remaining roles. The inspector then displays a later sequence before earlier messages even though it labels the list as model-request order; filter allNonToolItems in place and special-case only the synthetic prompt/tool prefix.

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

Useful? React with 👍 / 👎.

Comment on lines +438 to +440
const source = this.loop?.state.messages ?? this.journal.snapshot().input.messages ?? [];
const tools = this.toolSelect.requestTools(this.baselineTools(), disclosure, true, source);
const messages = this.toolSelect.shapeHistory(source, disclosure, tools);

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 Include queued inputs in the request preview

When a notification or reminder arrives while a turn is running, it can remain in loop.state.inbox or the live turn's pending items until the loop schedules the next step, but this preview reads only loop.state.messages. The loop state machine subsequently promotes those entries and appends them before generation, so a context refresh during background-task completion or user steering omits content that the next model request will receive; build the preview from the pending-aware request state without consuming the queue.

AGENTS.md reference: AGENTS.md:L111-L116

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 merged commit 638fd94 into main Nov 19, 2026
18 checks passed
@wbxl2000
wbxl2000 deleted the qer/model-call-inspector branch November 19, 2026 12:54
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
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