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": {