Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(runtime): preserve explicit zero cache usage

Linuxdazhao820ad643e50c
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index f9a44f4cb..88ac9744c 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -668,6 +668,12 @@ gateway's total that omits cached input from delaying compaction, while keeping
the total-based guard when bucket details are incomplete. Billing totals remain
unchanged.
+Pi usage conversion retains explicitly supplied finite, nonnegative cache-read
+and cache-write counts, including zero, through physical-request observation,
+history replay and operation deduplication. Missing or invalid cache counts
+remain absent, so consumers can distinguish a known zero from unavailable
+usage. Previously stored missing fields are not backfilled as zero.
+
The calibration still measures the two errors separately — per-character bias
as a scale-free ratio over the guessed tail, and an unanchored residual as a
ratio only for observations taken at a comparable scale (0.5×–2× of the
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index c9d031d8f..2d615cdc2 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1,5 +1,16 @@
# 04. E2E Test Plan
+### E2E-USAGE-explicit-zero-cache
+
+- Complete a controlled Pi request with nonzero input/output and explicit zero
+ cache reads/writes. Observe the request, consume the stream result, and replay
+ its usage: both cache fields remain zero, not absent.
+- Include zero reads with nonzero writes and nonzero reads with zero writes.
+ Replaying the same operation does not double-count any token bucket. Cache
+ counters that are absent, non-finite or negative remain unavailable.
+- Focused runtime coverage: `src/request-usage.test.ts`. Native/live-provider
+ execution is separate from these controlled request-accounting regressions.
+
### E2E-CHAT-output-token-truncation (#2277)
Use the real Desktop runtime and Pi loop with a controlled provider stream
diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.ts
index 5e4594dfd..4d0ba9260 100644
--- a/packages/agent-runtime/src/agent-messages.ts
+++ b/packages/agent-runtime/src/agent-messages.ts
@@ -85,8 +85,8 @@ export function usageFromPi(
return {
inputTokens,
outputTokens,
- ...(cacheReadTokens > 0 ? { cacheReadTokens } : {}),
- ...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),
+ ...(Number.isFinite(usage.cacheRead) && usage.cacheRead >= 0 ? { cacheReadTokens } : {}),
+ ...(Number.isFinite(usage.cacheWrite) && usage.cacheWrite >= 0 ? { cacheWriteTokens } : {}),
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
totalTokens,
usageOrigin: "pi",
diff --git a/packages/agent-runtime/src/request-usage.test.ts b/packages/agent-runtime/src/request-usage.test.ts
index edd1696f0..4dbf42f39 100644
--- a/packages/agent-runtime/src/request-usage.test.ts
+++ b/packages/agent-runtime/src/request-usage.test.ts
@@ -11,6 +11,37 @@ function response(): AssistantMessage {
}
describe("physical request accounting", () => {
+ it.each([[0, 0], [0, 4], [9, 0]])("retains cache read/write %j/%j through accounting and replay", async (cacheRead, cacheWrite) => {
+ const reports: MessageUsage[] = [];
+ const stream = accountModelStream({ id: "physical", provider: "openai" }, () => {
+ const inner = createAssistantMessageEventStream();
+ const message = response();
+ Object.assign(message.usage, { cacheRead, cacheWrite, totalTokens: 15 + cacheRead + cacheWrite });
+ inner.push({ type: "done", reason: "stop", message });
+ inner.end();
+ return inner;
+ }, { onUsage: (usage) => reports.push(usage) });
+ for await (const _event of stream) { /* Consume the actual Pi stream. */ }
+ const replayed = usageFromPi((await stream.result()).usage);
+ expect(reports).toHaveLength(1);
+ for (const usage of [reports[0], replayed, addUsage(reports[0], replayed)]) {
+ expect(usage).toMatchObject({ cacheReadTokens: cacheRead, cacheWriteTokens: cacheWrite,
+ totalTokens: 15 + cacheRead + cacheWrite });
+ }
+ });
+
+ it.each([undefined, NaN, -1])("keeps invalid or absent cache usage unknown: %s", (value) => {
+ const message = response();
+ for (const key of ["cacheRead", "cacheWrite"] as const) {
+ if (value === undefined) Reflect.deleteProperty(message.usage, key);
+ else message.usage[key] = value;
+ }
+ const usage = usageFromPi(message.usage);
+ expect(usage).toBeDefined();
+ expect(usage?.cacheReadTokens).toBeUndefined();
+ expect(usage?.cacheWriteTokens).toBeUndefined();
+ });
+
it("reports once across iteration and result and preserves unknown price through replay", async () => {
const reports: MessageUsage[] = [];
const stream = accountModelStream({ id: "physical", provider: "openai" }, () => {