Repository navigation
feat: add the context usage view and session context inspection routes - #5058
Conversation
…st the provider request
…l-call-inspector # Conflicts: # packages/kap-server/src/routes/registerApiV1Routes.ts # packages/kap-server/test/__snapshots__/apiSurface.snapshot.test.ts.snap
# Conflicts: # packages/kap-server/test/apiSurface.snapshot.test.ts
🦋 Changeset detectedLatest commit: 2867553 The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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' }; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
commit: |
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| watch( | ||
| [ctxCardOpen, sessionId, () => status.value?.ctxUsed, () => running.value], | ||
| ([open], [wasOpen]) => { |
There was a problem hiding this comment.
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 👍 / 👎.
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| () => props.item.id, | ||
| () => props.item.role, | ||
| () => props.item.chars, | ||
| () => props.item.preview, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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'), |
There was a problem hiding this comment.
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 👍 / 👎.
| if (observedContextBySession.value[sessionId]) { | ||
| tasks.push(refreshContext(sessionId, options)); | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| registerContextRoutes( | ||
| apiV1 as unknown as Parameters<typeof registerContextRoutes>[0], | ||
| core, | ||
| ); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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}`, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| 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) }; |
There was a problem hiding this comment.
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 👍 / 👎.
| const scale = estimatedTotal > 0 ? used / estimatedTotal : 0; | ||
| const allocate = (estimate: number): number => Math.round(estimate * scale); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| items: [ | ||
| ...allNonToolItems.filter( | ||
| (item) => item.role === 'system' && selectedRoles.has(item.role), | ||
| ), | ||
| ...(selectedRoles.has('definition') ? toolItems : []), |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
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 和会话状态驱动,没有定时轮询。概念
IAgentLoopService.previewRequestContent()返回{ systemPrompt, tools, messages },不发请求,没有副作用system/tool-<i>/message-<i>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预览和真实请求是两条代码路径,按同样的步骤处理同一份持久化消息。对照测试用 scripted provider 截获真实请求,要求 system prompt 和工具完全相同、预览的消息正好是 provider 收到的消息的前缀。媒体解析会读取或上传文件,所以预览不做这一步,图片以引用的形式出现。
关键决策
loop.history()history()是给聊天界面用的展示视图:会把工具备注拆出正文、删掉失败 turn 里没有结果的工具调用,和模型收到的不一致阅读指南
packages/agent-core-v2/src/agent/loop/loopService.ts的previewRequestContent():预览怎么算,可以对照同文件corePolicy()里的 resolver 链看。packages/agent-core-v2/test/agent/loop/coreLoopService.test.ts的previews the request content…:对照测试如何把预览钉在真实请求上。packages/kap-server/src/routes/context.ts:三个路由如何把预览整理成摘要、条目和详情,包括按估算比例分摊实测总量、系统提示词按一级标题分段、角色筛选和分页。packages/app-components/src/composer/ContextSummaryBody.vue与packages/app-client/src/stores/sessionInfo.ts:摘要组件,以及右侧栏上下文的观察、刷新和去重。apps/desktop/src/renderer/inspector/:详情面板的筛选、分页、刷新,条目详情和复制。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 意见,逐条回复见各线程):
definition,并按工具个数计数;只替换媒体块里的长数据,audio_url也算媒体。tokens和状态计数保持一致;预览不调用会写入会话的prepareForRequest();HOST_API_LEVEL留给维护者决定。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的界面GET /api/v1/sessions/{session_id}/context/summary、/context/items、/context/items/{item_id}HOST_CONTRACTHOST_API_LEVEL保持1IAgentLoopService接口previewRequestContent()现有接口、turn 请求的处理流程和默认值都没有变化:
previewRequestContent()只读,不改动持久化消息,也不在请求链里;mediaPolicy.ts只是导出了已有的hideReadMediaFile。请维护者确认:
HOST_API_LEVEL。新增的都是只读接口,旧远程主机缺少它们只影响开启了上下文用量的面板;提升级别会让所有旧远程主机必须先升级才能连接。panelComponents.ts的 ratchet 基线从 8 调到 9,原因见「从 code-app 移植」。契约消费方:本仓的桌面端与
kimi web界面使用这三个接口。上一版服务端没有这些接口,新客户端在旧服务端上读取上下文会得到 404;旧客户端不受影响。受影响模块与测试覆盖:
coreLoopService.test.ts的对照测试覆盖带耗时和备注的工具结果、工具运行期间插入的消息、执行失败的工具结果、不支持图片时隐藏ReadMediaFile、空文本块和没有结果的工具调用。把预览分别改坏三种方式(去掉投影、去掉隐藏ReadMediaFile、只在真实请求链里新增一个改写消息的 resolver),这个测试都会失败。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:通过。packages/app-*与桌面端渲染进程测试):574 个文件,8261 个用例通过,1 个跳过。loop测试(含对照测试)在改用 token 计数之前跑过并通过;之后的提交没有改动 agent-core-v2。pnpm test全量:1527 个文件中 6 个失败。其中 4 个单独重跑通过(并发负载下的超时);另外 2 个(node-sdk的serves suggestFiles…、agent-core-v2tool.test.ts的三个子 agent 截止时间用例)在干净的 main 上以相同方式失败,与本 PR 无关。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.