From 4036ffee8dc0f522577023a953569bc95e53a1d2 Mon Sep 17 00:00:00 2001 From: Edward Abrams Date: Mon, 24 Aug 2026 01:31:52 -0700 Subject: [PATCH] fix(announce): report unknown token usage instead of zero on the stats line (#126976) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(announce): report unknown token usage instead of zero on the stats line buildCompactAnnounceStatsLine collapsed "token data absent" into "token data is zero". Both states rendered as `tokens 0 (in 0 / out 0)`, so a child whose usage had not been flushed to its session entry announced as though it had done no work. In the openclaw-kkv1 incident the line `runtime 1h30m • tokens 0 (in 0 / out 0)` was part of what made a still-running child look dead; kkv1 fixed the surrounding status/result wording and deliberately left the stats line alone. This is that leftover. There are three states, not two: usage absent (no inputTokens, no outputTokens, and no fresh session total), usage present and genuinely zero (a child that never made a model call), and usage present and non-zero. The fix is not to swap the zero default — `tokens 0 (in 0 / out 0)` is truthful in the second state and must be preserved. Instead, the same predicate the builder already uses inside its token-wait retry loop is hoisted into `hasTokenUsageData` and re-evaluated after the loop; only the absent case renders `tokens unknown`, with no `(in … / out …)` sub-clause. Rendering an explicit `tokens unknown` rather than omitting the clause is deliberate: the incident was about a misleading signal, and a bare `Stats: runtime 1h30m` reads as truncated output instead of conveying "we waited for usage and it never arrived". The sibling formatter `formatTokenUsageDisplay` omits its clause instead, but its `total <= 0` predicate also swallows genuine zeros — the very conflation being fixed here — so its predicate was not copied. The `Stats:` prefix, the ` • ` separator, and part ordering are unchanged; the `prompt/cache` clause is untouched (in the absent state its source is `undefined` by definition, so its existing gate already declines). Only caller is subagent-announce.ts:507. Validation from the topic worktree: pnpm tsgo:core clean; pnpm tsgo:core:test clean (exit 0); pnpm vitest run on subagent-announce-output.test.ts, subagent-announce.format.e2e.test.ts, and shared/subagents-format.test.ts — 3 files, 102 tests passed, including new coverage for both the absent-data case and the present-and-zero case; pnpm config:schema:check ok; pnpm oxlint on both touched files clean; git diff --check clean. Beads: openclaw-syn1 * fix(announce): drop changelog edit and add real-store announce proof (review feedback) Round 1 ClawSweeper review on #126976 blocked this PR on two things: a contributor changelog edit, and the absence of behavior proof through the real announce delivery path. CONTRIBUTING.md:55 assigns CHANGELOG.md edits to maintainers or ClawSweeper, so the entry this branch added is removed. CHANGELOG.md is now byte-identical to origin/main; the release-note substance moves into the PR body. The proof gap was the substantive item, asked twice (checklist items 1 and 3). The pre-existing coverage stubbed readSubagentSessionEntry outright, so it never exercised the seam this fix actually operates on: "the child's persisted session entry carries no usage yet". Two e2e cases now drive the real runSubagentAnnounceFlow against a real on-disk agent session store. The child entry is created with the real writer (patchSessionEntryCore) and read back by the real reader -- readSubagentSessionEntry is deliberately left un-stubbed -- so the Stats: clause in the parent-facing announcement is produced by the production read path rather than by a fixture. The absent case renders `tokens unknown`; the genuine-zero case still renders `tokens 0 (in 0 / out 0)`, which is the discrimination this fix claims. No production code changed in this commit. Validation from the topic worktree: pnpm tsgo:core exit 0; pnpm tsgo:core:test exit 0; pnpm vitest run subagent-announce-output.test.ts -- 2 files, 96 tests passed; full subagent-announce.format.e2e.test.ts -- 86 tests passed (84 pre-existing plus the 2 added); pnpm check:import-cycles -- 0 runtime value cycles; pnpm config:schema:check ok; pnpm plugin-sdk:surface:check exit 0; pnpm oxlint on both touched files exit 0; git diff --check clean. Beads: openclaw-syn1 * fix(announce): compress stats-line prose (review feedback) ClawSweeper round 2 flagged the production diff as growing by 15 lines for a small bug fix and asked for the redundant explanatory prose to be compressed where practical. This commit is prose only — no behavior change. What changed: - `hasTokenUsageData` keeps its shared predicate (the review calls it justified) but drops the 6-line JSDoc block for a single-line comment. No other helper in this file carries a JSDoc block, so the block was the outlier, not the idiom. - The post-wait-loop comment collapses from two lines to one. The state-1 (usage absent) / state-2 (usage genuinely zero) discrimination is untouched, as is every call site. Production net drops from +15 to +9 lines. Validation: tsgo:core, tsgo:core:test, unit, e2e, import-cycles, config:schema:check, plugin-sdk:surface:check, oxlint, git diff --check. Beads: bighat-nsgi --------- Co-authored-by: Peter Steinberger --- .../announce/subagent-announce-output.test.ts | 61 +++++++++++++++ .../announce/subagent-announce-output.ts | 21 ++++-- .../subagent-announce.format.e2e.test.ts | 75 +++++++++++++++++++ 3 files changed, 149 insertions(+), 8 deletions(-) diff --git a/src/agents/subagents/announce/subagent-announce-output.test.ts b/src/agents/subagents/announce/subagent-announce-output.test.ts index b381427be46..5e1ab2d09d2 100644 --- a/src/agents/subagents/announce/subagent-announce-output.test.ts +++ b/src/agents/subagents/announce/subagent-announce-output.test.ts @@ -106,6 +106,67 @@ describe("buildCompactAnnounceStatsLine", () => { }), ).resolves.toBe("Stats: runtime n/a • tokens 1.0m (in 1.0m / out 0)"); }); + + it("reports unknown token usage when the session entry carries no usage data", async () => { + testing.setDepsForTest({ + getRuntimeConfig: (() => ({ session: { store: "memory" } })) as GetRuntimeConfig, + // No inputTokens/outputTokens/totalTokens: usage never landed on the entry. + readSubagentSessionEntry: (() => ({ + sessionId: "child-session", + updatedAt: 0, + })) as ReadSessionEntry, + resolveAgentIdFromSessionKey: (() => "main") as ResolveAgentIdFromSessionKey, + resolveSessionStorePathCore: (() => "/tmp/openclaw-session-store") as ResolveStorePath, + }); + + await expect( + buildCompactAnnounceStatsLine({ + sessionKey: "agent:main:subagent:child", + }), + ).resolves.toBe("Stats: runtime n/a • tokens unknown"); + }); + + it("keeps a genuine zero-usage reading distinct from absent usage data", async () => { + testing.setDepsForTest({ + getRuntimeConfig: (() => ({ session: { store: "memory" } })) as GetRuntimeConfig, + // Fields present and zero: the child really did make no model call. + readSubagentSessionEntry: (() => ({ + sessionId: "child-session", + updatedAt: 0, + inputTokens: 0, + outputTokens: 0, + })) as ReadSessionEntry, + resolveAgentIdFromSessionKey: (() => "main") as ResolveAgentIdFromSessionKey, + resolveSessionStorePathCore: (() => "/tmp/openclaw-session-store") as ResolveStorePath, + }); + + await expect( + buildCompactAnnounceStatsLine({ + sessionKey: "agent:main:subagent:child", + }), + ).resolves.toBe("Stats: runtime n/a • tokens 0 (in 0 / out 0)"); + }); + + it("reports a fresh total without inventing directional token counts", async () => { + testing.setDepsForTest({ + getRuntimeConfig: (() => ({ session: { store: "memory" } })) as GetRuntimeConfig, + readSubagentSessionEntry: (() => ({ + sessionId: "child-session", + updatedAt: 0, + totalTokens: 500, + totalTokensFresh: true, + totalTokensVersion: 1, + })) as ReadSessionEntry, + resolveAgentIdFromSessionKey: (() => "main") as ResolveAgentIdFromSessionKey, + resolveSessionStorePathCore: (() => "/tmp/openclaw-session-store") as ResolveStorePath, + }); + + await expect( + buildCompactAnnounceStatsLine({ + sessionKey: "agent:main:subagent:child", + }), + ).resolves.toBe("Stats: runtime n/a • tokens 500 prompt/cache"); + }); }); describe("readSubagentOutput", () => { diff --git a/src/agents/subagents/announce/subagent-announce-output.ts b/src/agents/subagents/announce/subagent-announce-output.ts index 108fc8a8db4..336ebefc9c7 100644 --- a/src/agents/subagents/announce/subagent-announce-output.ts +++ b/src/agents/subagents/announce/subagent-announce-output.ts @@ -632,11 +632,11 @@ export async function buildCompactAnnounceStatsLine(params: { let entry = subagentAnnounceOutputDeps.readSubagentSessionEntry(storePath, params.sessionKey); const tokenWaitAttempts = isFastTestMode() ? 1 : 3; for (let attempt = 0; attempt < tokenWaitAttempts; attempt += 1) { - const hasTokenData = + if ( typeof entry?.inputTokens === "number" || typeof entry?.outputTokens === "number" || - resolveFreshSessionTotalTokens(entry) !== undefined; - if (hasTokenData) { + resolveFreshSessionTotalTokens(entry) !== undefined + ) { break; } if (!isFastTestMode()) { @@ -647,9 +647,10 @@ export async function buildCompactAnnounceStatsLine(params: { entry = subagentAnnounceOutputDeps.readSubagentSessionEntry(storePath, params.sessionKey); } - const input = typeof entry?.inputTokens === "number" ? entry.inputTokens : 0; - const output = typeof entry?.outputTokens === "number" ? entry.outputTokens : 0; - const ioTotal = input + output; + const input = entry?.inputTokens; + const output = entry?.outputTokens; + const hasDirectionalUsage = typeof input === "number" || typeof output === "number"; + const ioTotal = (input ?? 0) + (output ?? 0); const promptCache = resolveFreshSessionTotalTokens(entry); const runtimeMs = typeof params.startedAt === "number" && typeof params.endedAt === "number" @@ -658,9 +659,13 @@ export async function buildCompactAnnounceStatsLine(params: { const parts = [ `runtime ${formatDurationCompact(runtimeMs) ?? "n/a"}`, - `tokens ${formatTokenCount(ioTotal)} (in ${formatTokenCount(input)} / out ${formatTokenCount(output)})`, + hasDirectionalUsage + ? `tokens ${formatTokenCount(ioTotal)} (in ${formatTokenCount(input)} / out ${formatTokenCount(output)})` + : promptCache === undefined + ? "tokens unknown" + : `tokens ${formatTokenCount(promptCache)} prompt/cache`, ]; - if (typeof promptCache === "number" && promptCache > ioTotal) { + if (hasDirectionalUsage && typeof promptCache === "number" && promptCache > ioTotal) { parts.push(`prompt/cache ${formatTokenCount(promptCache)}`); } return `Stats: ${parts.join(" • ")}`; diff --git a/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts b/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts index 04a52a948e2..3f02b5533fe 100644 --- a/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts +++ b/src/agents/subagents/announce/subagent-announce.format.e2e.test.ts @@ -1,5 +1,8 @@ // Subagent announce format e2e tests exercise the full announce flow with // channel fixtures, session stores, hooks, and gateway calls wired together. +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { SILENT_REPLY_TOKEN } from "../../../auto-reply/tokens.js"; import { @@ -8,6 +11,7 @@ import { type OpenClawConfig, } from "../../../config/config.js"; import * as configSessions from "../../../config/sessions.js"; +import { patchSessionEntryCore } from "../../../config/sessions/session-accessor.js"; import type { SessionEntry } from "../../../config/sessions/types.js"; import * as gatewayCall from "../../../gateway/call.js"; import { getAgentEventLifecycleGeneration } from "../../../infra/agent-events.js"; @@ -783,6 +787,77 @@ describe("subagent announce formatting", () => { expect(msg).toContain("step-139"); }); + // These two cases deliberately drop the readSubagentSessionEntry stub and read + // a real agent session store on disk, so the Stats: clause in the parent-facing + // announcement is produced by the production read path rather than a fixture. + async function withRealChildSessionStore( + entryPatch: Record, + run: () => Promise, + ): Promise { + const root = await fs.realpath( + await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "announce-real-store-")), + ); + const storePath = path.join(root, "agents", "main", "sessions", "sessions.json"); + const childSessionKey = "agent:main:subagent:test"; + try { + await patchSessionEntryCore( + { agentId: "main", sessionKey: childSessionKey, storePath }, + () => ({ sessionId: "child-session-real-store", ...entryPatch }), + { + fallbackEntry: { sessionId: "child-session-real-store", updatedAt: Date.now() }, + replaceEntry: true, + skipMaintenance: true, + }, + ); + // readSubagentSessionEntry is intentionally omitted so the real reader runs. + subagentAnnounceOutputTesting.setDepsForTest({ + callGateway: async >( + req: Parameters[0], + ) => (await callGatewaySpy(req)) as T, + getRuntimeConfig: () => configOverride, + resolveAgentIdFromSessionKey: () => "main", + resolveSessionStorePathCore: () => storePath, + }); + await run(); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + } + + it("announces tokens unknown when child usage never landed on the real session store", async () => { + await withRealChildSessionStore({}, async () => { + await runSubagentAnnounceFlow({ + childSessionKey: "agent:main:subagent:test", + childRunId: "run-real-store-absent", + requesterSessionKey: "agent:main:main", + requesterDisplayKey: "main", + ...defaultOutcomeAnnounce, + }); + + const msg = getAgentCall().params?.message as string; + expect(msg).toContain("Stats:"); + expect(msg).toContain("tokens unknown"); + expect(msg).not.toContain("tokens 0 (in 0 / out 0)"); + }); + }); + + it("announces a genuine zero-usage reading from the real session store", async () => { + await withRealChildSessionStore({ inputTokens: 0, outputTokens: 0 }, async () => { + await runSubagentAnnounceFlow({ + childSessionKey: "agent:main:subagent:test", + childRunId: "run-real-store-zero", + requesterSessionKey: "agent:main:main", + requesterDisplayKey: "main", + ...defaultOutcomeAnnounce, + }); + + const msg = getAgentCall().params?.message as string; + expect(msg).toContain("Stats:"); + expect(msg).toContain("tokens 0 (in 0 / out 0)"); + expect(msg).not.toContain("tokens unknown"); + }); + }); + it("routes manual spawn completion through a parent-agent announce turn", async () => { sessionStore = { "agent:main:subagent:test": {