Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): stop double-counting reasoning tokens in context occupancy
JJDonaldb92d3a22a45e
diff --git a/apps/desktop/src/lib/context-usage.ts b/apps/desktop/src/lib/context-usage.tsindex ac4606bc5..169581781 100644--- a/apps/desktop/src/lib/context-usage.ts+++ b/apps/desktop/src/lib/context-usage.ts@@ -25,15 +25,18 @@ export function usageTokenTotal(usage: MessageUsage): number {}/**- * Occupancy of one model request, matching OpenCode's context widget:- * `input + output + reasoning + cache.read + cache.write` on that request.- * Cache reads from earlier tool-loop calls are not occupancy.+ * Occupancy of one model request: `input + output + cache.read + cache.write`+ * on that request. `output` already carries the reasoning tokens — Chat+ * Completions reports `completion_tokens` including `reasoning_tokens`,+ * Responses reports `output_tokens` including `reasoning_tokens`, and Google+ * reports `candidatesTokenCount + thoughtsTokenCount` — so `reasoningTokens`+ * is a subset and must not be added again. Cache reads from earlier tool-loop+ * calls are not occupancy.*/export function contextOccupancyTokens(usage: MessageUsage): number {const occupancy =positiveTokenCount(usage.inputTokens) +positiveTokenCount(usage.outputTokens) +- positiveTokenCount(usage.reasoningTokens) +positiveTokenCount(usage.cacheReadTokens) +positiveTokenCount(usage.cacheWriteTokens);return occupancy > 0 ? occupancy : usageTokenTotal(usage);diff --git a/apps/desktop/test/context-usage.test.mjs b/apps/desktop/test/context-usage.test.mjsindex 1b89d2de9..b5f6c9f9f 100644--- a/apps/desktop/test/context-usage.test.mjs+++ b/apps/desktop/test/context-usage.test.mjs@@ -203,7 +203,7 @@ test("context usage falls back to input and output when total is absent", () =>);});-test("occupancy sums last-request input, output, reasoning, and cache", () => {+test("occupancy sums last-request input, output, and cache, not reasoning twice", () => {const usage = {inputTokens: 10,outputTokens: 5,@@ -212,8 +212,9 @@ test("occupancy sums last-request input, output, reasoning, and cache", () => {reasoningTokens: 3,totalTokens: 15,};- assert.equal(contextOccupancyTokens(usage), 100);- assert.equal(calculateContextUsage(usage, 200).usedTokens, 100);+ // `outputTokens` already includes `reasoningTokens`, so occupancy is 97.+ assert.equal(contextOccupancyTokens(usage), 97);+ assert.equal(calculateContextUsage(usage, 200).usedTokens, 97);assert.equal(usageTokenTotal(usage), 15);});diff --git a/docs/adr/0193-last-request-context-occupancy.md b/docs/adr/0193-last-request-context-occupancy.mdindex 8f48efe8c..fd9361371 100644--- a/docs/adr/0193-last-request-context-occupancy.md+++ b/docs/adr/0193-last-request-context-occupancy.md@@ -1,6 +1,7 @@# ADR 0193: Last-request occupancy in the context inspector-- Status: Accepted+- Status: Accepted (amended 2026-10-11: occupancy no longer adds+ `reasoningTokens`, which the reported output already contains)- Date: 2026-09-09- Deciders: PI-Desktop renderer and UX maintainers- Amends: D103, D184, D244, D347, ADR 0047, ADR 0103, ADR 0184@@ -18,14 +19,17 @@ total after nine tool calls. The numbers were billed correctly and stilllooked like a leak. OpenCode's context widget and compaction check use onlythe last assistant message:-`input + output + reasoning + cache.read + cache.write`+`input + output + cache.read + cache.write`## Decision1. Occupancy, remaining capacity, used/window counts, turn total, providerinput/output/cache/reasoning, and cache hit rate are the newestusage-bearing assistant message (the last model request). Occupancy is- `input + output + reasoning + cacheRead + cacheWrite` on that message.+ `input + output + cacheRead + cacheWrite` on that message: `output` already+ carries the reasoning tokens (Chat Completions `completion_tokens`, Responses+ `output_tokens`, Google `candidatesTokenCount + thoughtsTokenCount`), so+ `reasoningTokens` is a subset and is never added again.2. Completed-turn generation speed and the aggregate tool row still describethe visual turn (every fragment and tool call between the surroundinguser messages).diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1b93197a7..7fd48a937 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1890,7 +1890,8 @@ Single message render — either user (plaintext) or assistant (markdown streamicapacity, used/window counts, turn total, and providerinput/output/cache/reasoning/hit-rate are that turn's newest usage-bearingassistant message (the last model request), using- `input + output + reasoning + cacheRead + cacheWrite` (D355). They are not+ `input + output + cacheRead + cacheWrite` (D355; `output` already carries the+ reasoning tokens, so `reasoningTokens` is never added again). They are notthe sum of every model call in the visual tool-loop. It is hidden until thatusage exists. The trigger keeps a small capacity ring beside thepercentage and omits the redundant `Context` label; the leading figurediff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex e850fba3a..d994f3c91 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -125,7 +125,7 @@ This log freezes previously open questions into concrete decisions.| D244 | Compact context usage summary | **Amend D103 / D184 / ADR 0047: keep the context inspector's remaining-capacity trigger, used/window counts, turn total, completed-turn speed, exact provider values, aggregate tool types/calls/tokens, and checkpoint summary, but render them as a short summary. Remove the per-tool rows, share bars, source badges, explanatory estimate paragraph, and used-capacity meter from the default panel. No protocol, storage, runtime accounting, or model metadata changes.** *(Amended by D347: the trigger moves to the composer toolbar.)* | The prior diagnostic layout made a routine capacity check tall and visually dense. Keeping the aggregate signal while removing drill-down chrome makes the default status surface scannable without changing the underlying usage data. See ADR 0103 and E2E-060d / US-UI-61. || D347 | Composer-docked context usage inspector | **Amend D103 / D184 / D244 / ADR 0047 / ADR 0103: the compact context inspector lives in the composer right toolbar, immediately left of the model × reasoning chip, and always mirrors the newest assistant turn that reported usage. The trigger keeps the remaining-capacity ring and percentage and drops the redundant Context label. The popover heading is remaining tokens plus percentage; rows below share one label/value rhythm separated by spacing, with no inner section rules (D297). Assistant meta keeps the model badge. Renderer only.** | The inspector under the newest answer scrolled out of reach. One composer entry is the single authority for the latest snapshot, and the doubled heading rule is fixed by dropping the extra caption rather than adding hairlines. See ADR 0184 and E2E-060d / US-UI-61. |-| D355 | Last-request occupancy in the context inspector | **Amend D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184: remaining capacity, used/window counts, turn total, and provider input/output/cache/reasoning/hit-rate are the newest usage-bearing assistant message (the last model request). Occupancy is `input + output + reasoning + cacheRead + cacheWrite` on that message. They are not the sum of every model call in the visual tool-loop. Completed-turn speed and the aggregate tool row still describe that visual turn. Renderer only; host turn rollups and Token Insights stay additive billing.** | Summing cache reads across a tool loop put 367k cache read next to a 55k window. OpenCode's context widget uses only the last assistant message. See ADR 0193 and E2E-060d. |+| D355 | Last-request occupancy in the context inspector | **Amend D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184: remaining capacity, used/window counts, turn total, and provider input/output/cache/reasoning/hit-rate are the newest usage-bearing assistant message (the last model request). Occupancy is `input + output + cacheRead + cacheWrite` on that message; `output` already contains the reasoning tokens, so `reasoningTokens` is never added again. They are not the sum of every model call in the visual tool-loop. Completed-turn speed and the aggregate tool row still describe that visual turn. Renderer only; host turn rollups and Token Insights stay additive billing.** | Summing cache reads across a tool loop put 367k cache read next to a 55k window. OpenCode's context widget uses only the last assistant message. See ADR 0193 and E2E-060d. || D356 | Optional subagent thinking override | **Amend ADR 0062 / ADR 0144: subagent frontmatter accepts `thinkingLevel: omit` in addition to inherit and the seven canonical levels. `omit` keeps the agent bookkeeping state at `off` but uses the low-level provider stream so no thinking override is synthesized. Explicit `off` still disables thinking. Model-configuration thinking chips use an accent/inverted-text selected state in both themes. No storage schema or protocol version change. See ADR 0194 and E2E-203.** | Users need inherit, explicit off, and leave-the-provider-default as three distinct choices, and selected thinking chips were unreadable in dark mode. || D348 | macOS sidebar source-list vibrancy | **Amend D304: the main window uses Electron `vibrancy: "sidebar"` instead of `under-window`. `nativeTheme.themeSource` follows the app theme (`system` / `light` / `dark` / plugin base) process-wide. Vibrancy re-applies only when `themeSource` changes; a missing plugin theme falls back to `system`.** | macOS 26 Liquid Glass made `under-window` a light plate that the 40% tint could not keep dark, including when app and OS appearances were both dark. See `04-ux/08-component-spec.md` §1.7 and US-UI-74 / E2E-076. || D243 | Model-aware image attachment transport | **Amend D197 / ADR 0059: Composer file references retain structured kind/name/MIME metadata. Electron main resolves vision from the exact models.dev model record when matched, or the exact pi-ai fallback record (`modalities.input` / `input` includes `image`), then applies an exact binding's explicit `supportsImages` override. It stores image bytes as `attachments/<sha256>`, sends eligible images as transient image blocks, and falls back to a safe `@path` for unknown/non-vision or oversized images. Durable messages store refs and metadata, never base64; the renderer shows an accessible capability status.** | The previous path-only contract made a vision-capable GPT model receive a scratch path instead of image content. Keeping the published capability authoritative by default while allowing an explicit endpoint-local override keeps Composer and transport aligned without mutating shared model metadata (ADR 0101, amended by D266 and D392 / ADR 0218). |@@ -4214,7 +4214,8 @@ D193, and D194.ADR 0184: occupancy, remaining capacity, used/window counts, turn total,and provider cache/input/output/reasoning/hit-rate are the lastusage-bearing assistant message. Occupancy is- `input + output + reasoning + cacheRead + cacheWrite`. Speed and the+ `input + output + cacheRead + cacheWrite`; `output` already contains the+ reasoning tokens, so `reasoningTokens` is never added again. Speed and theaggregate tool row still describe the visual turn.- Renderer only. Host completed-turn rollups and Token Insights stay additivebilling. See ADR 0193 and E2E-060d.diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 56f4ddbfa..1efd8269d 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1299,7 +1299,8 @@ row 而不是在转录本中添加树镶边。报告用量的助手回合(D347)。占用、剩余容量、已用/窗口计数、本轮合计以及模型 input/output/cache/reasoning/命中率取该回合最新一条已报告用量的助手消息(最后一次模型请求),占用为- `input + output + reasoning + cacheRead + cacheWrite`(D355);它们不是+ `input + output + cacheRead + cacheWrite`(D355;`output` 已包含推理令牌,+ 因此不再重复加上 `reasoningTokens`);它们不是视觉工具循环里每一次请求的加总。没有用量时不显示。触发器保留容量圆环和百分比,去掉重复的 `Context` 文字;引导数值(圆弧、百分比、令牌标签、弹层标题、tooltip 与 `aria-label`)跟随diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 4ee165a3a..825f25e9c 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -125,7 +125,7 @@| D423 | 移除子智能体轮次上限 | **修订 D328 / ADR 0062 / ADR 0063 / ADR 0119 / ADR 0126 / ADR 0166 / ADR 0210:`maxTurns` 与 `MAX_SUBAGENT_MAX_TURNS` 从定义类型、frontmatter 解析器及其钳制/非法告警、`UserSubagentRecord` / `UserSubagentInput`、host-core 注册表(记录、输入、frontmatter 解析、文档渲染、`MAX_TURNS_CEILING`)、五个内置文档、`SUBAGENT_PRESETS` 以及子智能体编辑器中移除。委托只在完成、父级调用 `TaskStop`、用户 Stop,或父级终态错误中止它时结束(ADR 0189)。既有文档中的 `maxTurns` / `max-turns` / `max_turns` 现在是无法识别的 frontmatter 键,会像其他未知键一样被忽略:不报错、不告警、不让定义加载失败,也不改写用户文件。`truncated` 从 `SubagentRunStatus`、渲染器 `SubagentOutcome` 联合类型、各语言 `chat.subagentStatus` 目录项以及委托拓扑的警告计数中移除;`timed_out` 保留。不改协议版本、schema 版本或存储。见 ADR 0253、E2E-155 与 E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored。** | 父级看不到委托的实时工作,因此无法给出合理的轮次上限,而 60 / 50 / 40 / 80 这些内置兜底值也没有推导依据。该上限的唯一效果是把委托中途杀死,并以带部分报告的 `truncated` 呈现 —— 用户和父级模型都无法从中恢复。 || D244 | 紧凑的上下文用量摘要 | **修订 D103 / D184 / ADR 0047:保留上下文检查器的剩余容量触发器、已用/窗口计数、回合合计、已完成回合速度、精确的提供商数值、聚合的工具类型/调用数/令牌数以及检查点摘要,但把它们渲染为一段简短摘要。从默认面板中移除逐工具行、占比条、来源徽章、解释性估算段落和已用容量计量条。不改动协议、存储、运行时计费或模型元数据。** *(由 D347 修订:触发器移到输入框工具栏。)* | 之前的诊断式布局让一次例行的容量检查变得又高又密。保留聚合信号、移除下钻装饰,使默认状态界面可以快速浏览,同时不改变底层用量数据。参见 ADR 0103 与 E2E-060d / US-UI-61。 || D347 | 输入框工具栏中的上下文用量检查器 | **修订 D103 / D184 / D244 / ADR 0047 / ADR 0103:紧凑上下文检查器放在输入框右侧工具栏、模型 × 推理芯片左侧,始终对应当前最新一条已报告用量的助手回合。触发器保留剩余容量圆环和百分比,去掉重复的 Context 文字。弹层标题为剩余 tokens + 百分比;下方行用同一套左标签/右数值节奏,只用留白分隔,不画内部分隔线(D297)。答案下方的助理元只保留模型徽章。仅渲染器改动。** | 挂在最新答案下方的检查器会随记录滚出视野。输入框只保留一个入口作为最新快照的权威位置;标题双线通过去掉多余说明文字解决,而不是加分隔线。参见 ADR 0184 与 E2E-060d / US-UI-61。 |-| D355 | 上下文检查器按最后一次请求计算占用 | **修订 D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184:剩余容量、已用/窗口计数、本轮合计,以及模型 input/output/cache/reasoning/命中率,都取最新一条已报告用量的助手消息(最后一次模型请求)。占用为该消息的 `input + output + reasoning + cacheRead + cacheWrite`。它们不是视觉工具循环里每一次请求的加总。已完成回合速度和聚合工具行仍描述该视觉回合。仅渲染器改动;宿主回合汇总和 Token Insights 仍做账单累加。** | 把工具循环里的缓存读取加总后,367k 缓存读取会紧挨着 55k 窗口。OpenCode 的上下文组件只用最后一条助手消息。参见 ADR 0193 与 E2E-060d。 |+| D355 | 上下文检查器按最后一次请求计算占用 | **修订 D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184:剩余容量、已用/窗口计数、本轮合计,以及模型 input/output/cache/reasoning/命中率,都取最新一条已报告用量的助手消息(最后一次模型请求)。占用为该消息的 `input + output + cacheRead + cacheWrite`;`output` 已包含推理令牌,因此不再重复加上 `reasoningTokens`。它们不是视觉工具循环里每一次请求的加总。已完成回合速度和聚合工具行仍描述该视觉回合。仅渲染器改动;宿主回合汇总和 Token Insights 仍做账单累加。** | 把工具循环里的缓存读取加总后,367k 缓存读取会紧挨着 55k 窗口。OpenCode 的上下文组件只用最后一条助手消息。参见 ADR 0193 与 E2E-060d。 || D356 | 可选的子智能体思考覆盖 | **修订 ADR 0062 / ADR 0144:子智能体 frontmatter 在沿用会话和七个规范档位之外接受 `thinkingLevel: omit`。`omit` 把智能体记账状态保持为 `off`,但走低层 provider 流,不合成思考覆盖。显式 `off` 仍关闭思考。模型配置里已选思考芯片在两种主题下使用强调底和反色主文本。不改存储 schema 或协议版本。见 ADR 0194 与 E2E-203。** | 用户需要区分沿用、显式关闭和保留提供商默认;深色主题下已选芯片原先对比不足。 || D348 | macOS 侧边栏改用 source-list vibrancy | **修订 D304:主窗口改用 Electron `vibrancy: "sidebar"`,不再用 `under-window`。`nativeTheme.themeSource` 跟随应用主题(`system` / `light` / `dark` / 插件 base),进程级生效。仅在 `themeSource` 真变时重设 vibrancy;缺失的插件主题回落 `system`。** | macOS 26 Liquid Glass 让 `under-window` 变成浅色底板,40% tint 压不住,即使应用和系统都是深色也一样。见 `04-ux/08-component-spec.md` §1.7 与 US-UI-74 / E2E-076。 || D243 | 模型感知的图片附件传输 | **修订 D197 / ADR 0059:输入框文件引用保留结构化的 kind/name/MIME 元数据。Electron main 在匹配时从精确的 models.dev 模型记录解析视觉能力,否则用精确的 pi-ai 回退记录(`modalities.input` / `input` 含 `image`),将图片字节存为 `attachments/<sha256>`,把符合条件的图片作为瞬态图片块发送,并对未知/非视觉或超大图片回退为安全的 `@path`。持久消息只存引用和元数据,绝不存 base64;渲染器展示可访问的能力状态。** | 之前只走路径的约定让具备视觉能力的 GPT 模型收到的是一个临时路径而不是图片内容。把能力归属放在所选目录来源上,可以避免提供商发现或未知模型 ID 擅自决定传输方式,而路径回退保留了非视觉的文件工具行为(ADR 0101,由 D266 修订)。 |@@ -3550,7 +3550,8 @@ D193 和 D194。- 决策 D355 修订 D103 / D184 / D244 / D347 / ADR 0047 / ADR 0103 / ADR 0184:占用、剩余容量、已用/窗口计数、本轮合计,以及模型缓存/输入/输出/推理/命中率,都取最后一条已报告用量的助手消息。占用为- `input + output + reasoning + cacheRead + cacheWrite`。速度和聚合工具行+ `input + output + cacheRead + cacheWrite`;`output` 已包含推理令牌,因此+ 不再重复加上 `reasoningTokens`。速度和聚合工具行仍描述该视觉回合。- 仅渲染器改动。宿主已完成回合汇总和 Token Insights 仍做账单累加。参见 ADR 0193 与 E2E-060d。