Skip to content

Commit ff32076

Browse files
authored
feat(ui): add comparative cost analysis (#100432)
* feat(ui): add comparative cost analysis * fix(usage): align cost buckets with request timezone * test(ui): avoid shadowing cost fixture * fix(usage): align session daily timezone buckets * test(usage): include day offset in cache keys * fix(ui): ship translated cost analysis strings * fix(ui): scope cost window analysis * chore(ui): refresh locale metadata * chore(ui): refresh locale metadata
1 parent a905eb4 commit ff32076

76 files changed

Lines changed: 1761 additions & 290 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/reference/api-usage-costs.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ Map of OpenClaw features that can call paid provider APIs, where each reads its
2424
- `/usage cost` prints a local cost summary; `/usage off` disables the footer.
2525
- Gemini CLI note: both `stream-json` and legacy `json` output carry usage under `stats`. OpenClaw normalizes `stats.cached` into `cacheRead` and derives input tokens from `stats.input_tokens - stats.cached` when needed.
2626

27+
**Control UI → Usage** (cross-session analysis)
28+
29+
- Shows transcript-derived token and estimated-cost totals for the selected date range, with breakdowns by provider, model, agent, channel, and token type.
30+
- Compares shorter calendar windows ending on the selected range end date. Missing dates count as zero-usage calendar days; they are not skipped to create a denser window.
31+
- Labels the daily chart scale directly. A `√` badge means square-root compression is keeping low-usage days visible.
32+
- These totals describe the available local session history, not a provider invoice or lifetime billing ledger. The UI warns when pricing is missing for some entries.
33+
2734
**CLI usage windows** (provider quotas, not per-message cost)
2835

2936
- `openclaw status --usage` and `openclaw channels list` show provider **usage windows** as `X% left`.

‎src/gateway/server-methods/usage.cost-usage-cache.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,14 @@ describe("costUsageCache bounded growth", () => {
8686
// oldest-first, never the newest.
8787
const lastStartMs = Date.UTC(2026, 0, 1) + (ITERATIONS - 1) * DAY_MS;
8888
const lastEndMs = lastStartMs + ((ITERATIONS - 1) % 3 === 0 ? DAY_MS : 7 * DAY_MS) - 1;
89-
const lastCacheKey = `agent:__default__:${lastStartMs}-${lastEndMs}`;
89+
const lastCacheKey = `agent:__default__:${lastStartMs}-${lastEndMs}:gateway`;
9090
expect(testApi.costUsageCache.has(lastCacheKey)).toBe(true);
9191

9292
// Tertiary: the oldest entry must have been evicted once the cap was
9393
// exceeded. Pre-fix all 600 entries remain and this fails too.
9494
const firstStartMs = Date.UTC(2026, 0, 1);
9595
const firstEndMs = firstStartMs + DAY_MS - 1;
96-
const firstCacheKey = `agent:__default__:${firstStartMs}-${firstEndMs}`;
96+
const firstCacheKey = `agent:__default__:${firstStartMs}-${firstEndMs}:gateway`;
9797
expect(testApi.costUsageCache.has(firstCacheKey)).toBe(false);
9898
});
9999

@@ -125,7 +125,7 @@ describe("costUsageCache bounded growth", () => {
125125
});
126126
await Promise.resolve();
127127

128-
expect(testApi.costUsageCache.has("agent:__default__:1-2")).toBe(true);
128+
expect(testApi.costUsageCache.has("agent:__default__:1-2:gateway")).toBe(true);
129129
expect(mocks.loadCostUsageSummaryFromCache).toHaveBeenCalledTimes(257);
130130
void inFlight.catch(() => {});
131131
void repeated.catch(() => {});

‎src/gateway/server-methods/usage.sessions-usage.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,18 @@ describe("sessions.usage", () => {
332332
expect(result.totals.totalTokens).toBe(60);
333333
});
334334

335+
it("passes the requested timezone offset to session daily summaries", async () => {
336+
await runSessionsUsage({
337+
...BASE_USAGE_RANGE,
338+
mode: "specific",
339+
utcOffset: "UTC-5",
340+
});
341+
342+
expect(vi.mocked(loadSessionCostSummariesFromCache)).toHaveBeenCalledWith(
343+
expect.objectContaining({ dailyUtcOffsetMinutes: -300 }),
344+
);
345+
});
346+
335347
it("discovers usage for requested disk-only agents not listed in config", async () => {
336348
const respond = await runSessionsUsage({ ...BASE_USAGE_RANGE, agentId: "codex" });
337349

‎src/gateway/server-methods/usage.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,31 @@ describe("gateway usage helpers", () => {
329329
});
330330
});
331331

332+
it("keeps cost usage cache entries scoped by daily timezone offset", async () => {
333+
const config = {} as OpenClawConfig;
334+
335+
await testApi.loadCostUsageSummaryCached({
336+
startMs: 1,
337+
endMs: 2,
338+
dailyUtcOffsetMinutes: 0,
339+
config,
340+
});
341+
await testApi.loadCostUsageSummaryCached({
342+
startMs: 1,
343+
endMs: 2,
344+
dailyUtcOffsetMinutes: -300,
345+
config,
346+
});
347+
await testApi.loadCostUsageSummaryCached({
348+
startMs: 1,
349+
endMs: 2,
350+
dailyUtcOffsetMinutes: 0,
351+
config,
352+
});
353+
354+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledTimes(2);
355+
});
356+
332357
it("passes usage.cost agentId through to the cost summary loader", async () => {
333358
const respond = vi.fn();
334359

@@ -344,6 +369,25 @@ describe("gateway usage helpers", () => {
344369
);
345370
});
346371

372+
it("buckets usage.cost daily rows with the requested UTC offset", async () => {
373+
const respond = vi.fn();
374+
375+
await usageHandlers["usage.cost"]({
376+
respond,
377+
params: {
378+
startDate: "2026-02-01",
379+
endDate: "2026-02-02",
380+
mode: "specific",
381+
utcOffset: "UTC-5",
382+
},
383+
context: { getRuntimeConfig: () => ({}) },
384+
} as unknown as Parameters<(typeof usageHandlers)["usage.cost"]>[0]);
385+
386+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledWith(
387+
expect.objectContaining({ dailyUtcOffsetMinutes: -300 }),
388+
);
389+
});
390+
347391
it("passes usage.cost all-agent scope through to all configured agent loaders", async () => {
348392
const respond = vi.fn();
349393

‎src/gateway/server-methods/usage.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,13 @@ const resolveDateInterpretation = (params: {
236236
return { mode: "utc" };
237237
};
238238

239+
const resolveDayBucketUtcOffsetMinutes = (interpretation: DateInterpretation) =>
240+
interpretation.mode === "gateway"
241+
? undefined
242+
: interpretation.mode === "specific"
243+
? interpretation.utcOffsetMinutes
244+
: 0;
245+
239246
/**
240247
* Parse a date string (YYYY-MM-DD) to start-of-day timestamp based on interpretation mode.
241248
* Returns undefined if invalid.
@@ -742,11 +749,13 @@ function mergeDailyModelRows(
742749
async function loadCostUsageSummaryCached(params: {
743750
startMs: number;
744751
endMs: number;
752+
dailyUtcOffsetMinutes?: number;
745753
config: OpenClawConfig;
746754
agentId?: string;
747755
agentScope?: "all";
748756
}): Promise<CostUsageSummary> {
749-
const cacheKey = `${params.agentScope === "all" ? "all" : `agent:${params.agentId ?? "__default__"}`}:${params.startMs}-${params.endMs}`;
757+
const dailyOffsetKey = params.dailyUtcOffsetMinutes ?? "gateway";
758+
const cacheKey = `${params.agentScope === "all" ? "all" : `agent:${params.agentId ?? "__default__"}`}:${params.startMs}-${params.endMs}:${dailyOffsetKey}`;
750759
const now = Date.now();
751760
const cached = costUsageCache.get(cacheKey);
752761
if (
@@ -771,11 +780,13 @@ async function loadCostUsageSummaryCached(params: {
771780
? loadAllAgentCostUsageSummary({
772781
startMs: params.startMs,
773782
endMs: params.endMs,
783+
dailyUtcOffsetMinutes: params.dailyUtcOffsetMinutes,
774784
config: params.config,
775785
})
776786
: loadCostUsageSummaryFromCache({
777787
startMs: params.startMs,
778788
endMs: params.endMs,
789+
dailyUtcOffsetMinutes: params.dailyUtcOffsetMinutes,
779790
config: params.config,
780791
agentId: params.agentId,
781792
requestRefresh: true,
@@ -816,6 +827,7 @@ async function loadCostUsageSummaryCached(params: {
816827
async function loadAllAgentCostUsageSummary(params: {
817828
startMs: number;
818829
endMs: number;
830+
dailyUtcOffsetMinutes?: number;
819831
config: OpenClawConfig;
820832
}): Promise<CostUsageSummary> {
821833
const agentIds = listAgentsForGateway(params.config).agents.map((agent) =>
@@ -826,6 +838,7 @@ async function loadAllAgentCostUsageSummary(params: {
826838
loadCostUsageSummaryFromCache({
827839
startMs: params.startMs,
828840
endMs: params.endMs,
841+
dailyUtcOffsetMinutes: params.dailyUtcOffsetMinutes,
829842
config: params.config,
830843
agentId,
831844
requestRefresh: true,
@@ -908,6 +921,10 @@ export const usageHandlers: GatewayRequestHandlers = {
908921
respond(true, summary, undefined);
909922
},
910923
"usage.cost": async ({ respond, params, context }) => {
924+
const dateInterpretation = resolveDateInterpretation({
925+
mode: params?.mode,
926+
utcOffset: params?.utcOffset,
927+
});
911928
const dateRange = resolveDateRange({
912929
startDate: params?.startDate,
913930
endDate: params?.endDate,
@@ -927,6 +944,7 @@ export const usageHandlers: GatewayRequestHandlers = {
927944
const summary = await loadCostUsageSummaryCached({
928945
startMs,
929946
endMs,
947+
dailyUtcOffsetMinutes: resolveDayBucketUtcOffsetMinutes(dateInterpretation),
930948
config,
931949
agentId,
932950
agentScope,
@@ -960,6 +978,9 @@ export const usageHandlers: GatewayRequestHandlers = {
960978
}
961979
const config = context.getRuntimeConfig();
962980
const { startMs, endMs } = dateRange.value;
981+
const dailyUtcOffsetMinutes = resolveDayBucketUtcOffsetMinutes(
982+
resolveDateInterpretation({ mode: p.mode, utcOffset: p.utcOffset }),
983+
);
963984
const limit = typeof p.limit === "number" && Number.isFinite(p.limit) ? p.limit : 50;
964985
const includeContextWeight = p.includeContextWeight ?? false;
965986
const specificKey = normalizeOptionalString(p.key) ?? null;
@@ -1227,6 +1248,7 @@ export const usageHandlers: GatewayRequestHandlers = {
12271248
agentId,
12281249
startMs,
12291250
endMs,
1251+
dailyUtcOffsetMinutes,
12301252
}),
12311253
})),
12321254
limit: SESSIONS_USAGE_AGENT_LOAD_CONCURRENCY,

‎src/infra/session-cost-usage.test.ts‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,57 @@ describe("session cost usage", () => {
584584
});
585585
});
586586

587+
it("rebuckets cached session daily fields with the request timezone offset", async () => {
588+
const root = await makeSessionCostRoot("cost-cache-request-offset");
589+
const sessionsDir = path.join(root, "agents", "main", "sessions");
590+
await fs.mkdir(sessionsDir, { recursive: true });
591+
const sessionFile = path.join(sessionsDir, "sess-offset.jsonl");
592+
await fs.writeFile(
593+
sessionFile,
594+
[
595+
{
596+
type: "message",
597+
timestamp: "2026-02-12T00:29:00.000Z",
598+
message: { role: "user", content: "hello" },
599+
},
600+
{
601+
type: "message",
602+
timestamp: "2026-02-12T00:30:00.000Z",
603+
message: {
604+
role: "assistant",
605+
provider: "openai",
606+
model: "gpt-5.5",
607+
usage: { input: 10, output: 5, totalTokens: 15, cost: { total: 0.00001 } },
608+
},
609+
},
610+
]
611+
.map((entry) => JSON.stringify(entry))
612+
.join("\n"),
613+
"utf-8",
614+
);
615+
616+
await withStateDir(root, async () => {
617+
await refreshCostUsageCache({ sessionFiles: [sessionFile] });
618+
const result = await loadSessionCostSummariesFromCache({
619+
sessions: [{ sessionId: "sess-offset", sessionFile }],
620+
agentId: "main",
621+
startMs: Date.UTC(2026, 1, 11, 2),
622+
endMs: Date.UTC(2026, 1, 12, 1, 59, 59, 999),
623+
dailyUtcOffsetMinutes: -120,
624+
});
625+
const summary = requireValue(result.summaries[0], "offset session summary missing");
626+
627+
expect(summary.activityDates).toEqual(["2026-02-11"]);
628+
expect(summary.dailyBreakdown).toEqual([{ date: "2026-02-11", tokens: 15, cost: 0.00001 }]);
629+
expect(summary.dailyMessageCounts?.map((entry) => entry.date)).toEqual(["2026-02-11"]);
630+
expect(summary.dailyLatency?.map((entry) => entry.date)).toEqual(["2026-02-11"]);
631+
expect(summary.dailyModelUsage?.map((entry) => entry.date)).toEqual(["2026-02-11"]);
632+
expect(new Set(summary.utcQuarterHourMessageCounts?.map((entry) => entry.date))).toEqual(
633+
new Set(["2026-02-12"]),
634+
);
635+
});
636+
});
637+
587638
it("ignores compaction checkpoint transcript snapshots in daily totals and discovery", async () => {
588639
const root = await makeSessionCostRoot("cost-checkpoint");
589640
const sessionsDir = path.join(root, "agents", "main", "sessions");
@@ -655,6 +706,38 @@ describe("session cost usage", () => {
655706
});
656707
});
657708

709+
it("buckets daily totals with the request timezone offset", async () => {
710+
const root = await makeSessionCostRoot("cost-offset-bucket");
711+
const sessionsDir = path.join(root, "agents", "main", "sessions");
712+
await fs.mkdir(sessionsDir, { recursive: true });
713+
await fs.writeFile(
714+
path.join(sessionsDir, "sess-offset.jsonl"),
715+
transcriptText("sess-offset", {
716+
type: "message",
717+
timestamp: "2026-02-12T00:30:00.000Z",
718+
message: {
719+
role: "assistant",
720+
usage: { input: 10, output: 5, totalTokens: 15, cost: { total: 0.00001 } },
721+
},
722+
}),
723+
"utf-8",
724+
);
725+
726+
await withStateDir(root, async () => {
727+
const startMs = Date.UTC(2026, 1, 11, 2);
728+
const endMs = Date.UTC(2026, 1, 12, 1, 59, 59, 999);
729+
const summary = await loadCostUsageSummary({
730+
startMs,
731+
endMs,
732+
dailyUtcOffsetMinutes: -120,
733+
});
734+
735+
expect(summary.daily.map((entry) => entry.date)).toEqual(["2026-02-11"]);
736+
expect(summary.daily[0]?.totalTokens).toBe(15);
737+
expect(summary.daily[0]?.totalCost).toBeCloseTo(0.00001, 8);
738+
});
739+
});
740+
658741
it("fills missing days between sparse activity within the requested range", async () => {
659742
const root = await makeSessionCostRoot("cost-sparse");
660743
const sessionsDir = path.join(root, "agents", "main", "sessions");
@@ -1699,6 +1782,49 @@ describe("session cost usage", () => {
16991782
});
17001783
});
17011784

1785+
it("preserves offset-aware synchronous fallback for aggregate-only cache entries", async () => {
1786+
const root = await makeSessionCostRoot("cost-cache-session-sync-offset");
1787+
const sessionsDir = path.join(root, "agents", "main", "sessions");
1788+
await fs.mkdir(sessionsDir, { recursive: true });
1789+
const sessionFile = path.join(sessionsDir, "sess-cache-session-sync-offset.jsonl");
1790+
await fs.writeFile(
1791+
sessionFile,
1792+
JSON.stringify({
1793+
type: "message",
1794+
timestamp: "2026-02-05T00:30:00.000Z",
1795+
message: {
1796+
role: "assistant",
1797+
usage: {
1798+
input: 10,
1799+
output: 20,
1800+
totalTokens: 30,
1801+
cost: { total: 0.03 },
1802+
},
1803+
},
1804+
}),
1805+
"utf-8",
1806+
);
1807+
1808+
await withStateDir(root, async () => {
1809+
await refreshCostUsageCache();
1810+
const summary = await loadSessionCostSummaryFromCache({
1811+
sessionId: "sess-cache-session-sync-offset",
1812+
sessionFile,
1813+
startMs: Date.UTC(2026, 1, 4, 2),
1814+
endMs: Date.UTC(2026, 1, 5, 1, 59, 59, 999),
1815+
dailyUtcOffsetMinutes: -120,
1816+
requestRefresh: false,
1817+
refreshMode: "sync-when-empty",
1818+
});
1819+
1820+
expect(summary.summary?.totalTokens).toBe(30);
1821+
expect(summary.summary?.dailyBreakdown).toEqual([
1822+
{ date: "2026-02-04", tokens: 30, cost: 0.03 },
1823+
]);
1824+
expect(summary.cacheStatus.status).toBe("partial");
1825+
});
1826+
});
1827+
17021828
it("limits session summary refreshes to requested files", async () => {
17031829
const root = await makeSessionCostRoot("cost-cache-session-requested-files");
17041830
const sessionsDir = path.join(root, "agents", "main", "sessions");

0 commit comments

Comments
 (0)