Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Restore the 30-day bot token heatmap (#660)

Gustavo Yeda3bf1154ae2
diff --git a/src/daemon/src/telemetry/dailyTokenUsage.test.ts b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
index 727978eb3..bda2200d7 100644
--- a/src/daemon/src/telemetry/dailyTokenUsage.test.ts
+++ b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
@@ -92,27 +92,28 @@ describe("DailyTokenUsageStore", () => {
]);
});
- it("keeps only today and the previous six UTC days", async () => {
+ it("exposes 30 UTC days while retaining two recovery days", async () => {
const root = mkdtempSync(join(tmpdir(), "alook-token-retention-"));
roots.push(root);
- let now = new Date("2026-08-20T12:00:00Z");
+ let now = new Date("2026-07-27T12:00:00Z");
const store = new DailyTokenUsageStore(root, () => now, "UTC");
- for (let day = 0; day < 9; day += 1) {
+ for (let day = 0; day < 33; day += 1) {
await store.record("bot", delta(day, day, day));
now = new Date(now.getTime() + 86_400_000);
}
now = new Date("2026-08-28T12:00:00Z");
const snapshots = await store.snapshots("bot");
- expect(snapshots).toHaveLength(7);
- expect(snapshots.map((snapshot) => snapshot.day)).toEqual([
- "2026-08-22",
- "2026-08-23",
- "2026-08-24",
- "2026-08-25",
- "2026-08-26",
- "2026-08-27",
- "2026-08-28",
- ]);
+ expect(snapshots).toHaveLength(30);
+ expect(snapshots.at(0)?.day).toBe("2026-07-30");
+ expect(snapshots.at(-1)?.day).toBe("2026-08-28");
+
+ const persisted = JSON.parse(readFileSync(
+ join(root, ".telemetry", "daily-token-usage.json"),
+ "utf8",
+ )) as { bots: Record<string, Array<{ day: string }>> };
+ expect(persisted.bots.bot).toHaveLength(32);
+ expect(persisted.bots.bot?.at(0)?.day).toBe("2026-07-28");
+ expect(persisted.bots.bot?.at(-1)?.day).toBe("2026-08-28");
});
it("persists retention pruning even when a quiet bot only reconnects", async () => {
@@ -122,7 +123,7 @@ describe("DailyTokenUsageStore", () => {
const store = new DailyTokenUsageStore(root, () => now, "UTC");
await store.record("bot", delta(1, 1, 1));
- now = new Date("2026-08-29T12:00:00Z");
+ now = new Date("2026-09-21T12:00:00Z");
expect(await store.snapshots("bot")).toEqual([]);
const persisted = JSON.parse(readFileSync(
@@ -190,11 +191,11 @@ describe("DailyTokenUsageStore", () => {
it("follows a live computer-timezone change without deleting the prior day's totals", async () => {
const root = mkdtempSync(join(tmpdir(), "alook-token-timezone-change-"));
roots.push(root);
- let now = new Date("2026-08-22T16:00:01Z");
+ let now = new Date("2026-07-31T16:00:01Z");
let timeZone = "Asia/Shanghai";
const store = new DailyTokenUsageStore(root, () => now, () => timeZone);
- for (let day = 23; day <= 30; day += 1) {
- now = new Date(`2026-08-${String(day - 1).padStart(2, "0")}T16:00:01Z`);
+ for (let day = 1; day <= 30; day += 1) {
+ now = new Date(new Date("2026-07-31T16:00:01Z").getTime() + (day - 1) * 86_400_000);
await store.record("bot", delta(day, 2, 3));
}
@@ -205,15 +206,9 @@ describe("DailyTokenUsageStore", () => {
const window = await store.usageWindow("bot");
expect(window.usageDay).toBe("2026-08-29");
expect(window.usageTimeZone).toBe("America/Los_Angeles");
- expect(window.snapshots.map((snapshot) => snapshot.day)).toEqual([
- "2026-08-23",
- "2026-08-24",
- "2026-08-25",
- "2026-08-26",
- "2026-08-27",
- "2026-08-28",
- "2026-08-29",
- ]);
+ expect(window.snapshots).toHaveLength(29);
+ expect(window.snapshots.at(0)?.day).toBe("2026-08-01");
+ expect(window.snapshots.at(-1)?.day).toBe("2026-08-29");
expect(window.snapshots.at(-1)?.metrics).toEqual({ input: 34, output: 3, cache: 7 });
const persisted = JSON.parse(readFileSync(
join(root, ".telemetry", "daily-token-usage.json"),
@@ -225,12 +220,12 @@ describe("DailyTokenUsageStore", () => {
it("retains two recovery days across an exact UTC+14 to UTC-12 switch", async () => {
const root = mkdtempSync(join(tmpdir(), "alook-token-extreme-timezone-change-"));
roots.push(root);
- let now = new Date("2026-08-21T10:30:00Z");
+ let now = new Date("2026-07-29T10:30:00Z");
let timeZone = "Pacific/Kiritimati";
const store = new DailyTokenUsageStore(root, () => now, () => timeZone);
- for (let localDay = 22; localDay <= 30; localDay += 1) {
- now = new Date(`2026-08-${String(localDay - 1).padStart(2, "0")}T10:30:00Z`);
- await store.record("bot", delta(localDay, 2, 3));
+ for (let offset = 0; offset < 32; offset += 1) {
+ now = new Date(new Date("2026-07-29T10:30:00Z").getTime() + offset * 86_400_000);
+ await store.record("bot", delta(offset, 2, 3));
}
now = new Date("2026-08-29T10:30:00Z");
@@ -239,29 +234,15 @@ describe("DailyTokenUsageStore", () => {
const window = await store.usageWindow("bot");
expect(window.usageDay).toBe("2026-08-28");
expect(window.usageTimeZone).toBe("Etc/GMT+12");
- expect(window.snapshots.map((snapshot) => snapshot.day)).toEqual([
- "2026-08-22",
- "2026-08-23",
- "2026-08-24",
- "2026-08-25",
- "2026-08-26",
- "2026-08-27",
- "2026-08-28",
- ]);
+ expect(window.snapshots).toHaveLength(30);
+ expect(window.snapshots.at(0)?.day).toBe("2026-07-30");
+ expect(window.snapshots.at(-1)?.day).toBe("2026-08-28");
const persisted = JSON.parse(readFileSync(
join(root, ".telemetry", "daily-token-usage.json"),
"utf8",
)) as { bots: Record<string, Array<{ day: string }>> };
- expect(persisted.bots.bot?.map((snapshot) => snapshot.day)).toEqual([
- "2026-08-22",
- "2026-08-23",
- "2026-08-24",
- "2026-08-25",
- "2026-08-26",
- "2026-08-27",
- "2026-08-28",
- "2026-08-29",
- "2026-08-30",
- ]);
+ expect(persisted.bots.bot).toHaveLength(32);
+ expect(persisted.bots.bot?.at(0)?.day).toBe("2026-07-30");
+ expect(persisted.bots.bot?.at(-1)?.day).toBe("2026-08-30");
});
});
diff --git a/src/daemon/src/telemetry/dailyTokenUsage.ts b/src/daemon/src/telemetry/dailyTokenUsage.ts
index a71bb6743..c5717bfd2 100644
--- a/src/daemon/src/telemetry/dailyTokenUsage.ts
+++ b/src/daemon/src/telemetry/dailyTokenUsage.ts
@@ -4,6 +4,10 @@ import { randomUUID } from "node:crypto";
import type { TokenUsageDelta } from "@alook/agent-driver";
import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared";
+const TOKEN_USAGE_WINDOW_DAYS = 30;
+const TOKEN_USAGE_RECOVERY_DAYS = 2;
+const TOKEN_USAGE_RETENTION_DAYS = TOKEN_USAGE_WINDOW_DAYS + TOKEN_USAGE_RECOVERY_DAYS;
+
export type DailyUsageMetric = number | null;
export interface DailyUsageSnapshot {
@@ -23,11 +27,11 @@ type UsageFile = {
function oldestRetainedDay(at: Date, timeZone: string): string {
const today = dayKeyInTimeZone(at, timeZone);
- return calendarDayKeyDaysAgo(today, 8);
+ return calendarDayKeyDaysAgo(today, TOKEN_USAGE_RETENTION_DAYS - 1);
}
function oldestVisibleDay(today: string): string {
- return calendarDayKeyDaysAgo(today, 6);
+ return calendarDayKeyDaysAgo(today, TOKEN_USAGE_WINDOW_DAYS - 1);
}
function isMetric(value: unknown): value is DailyUsageMetric {
diff --git a/src/shared/src/provider-telemetry.ts b/src/shared/src/provider-telemetry.ts
index 47657ec2b..b93902bf5 100644
--- a/src/shared/src/provider-telemetry.ts
+++ b/src/shared/src/provider-telemetry.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+export const DAILY_TOKEN_USAGE_WINDOW_DAYS = 30;
+
const safeToken = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const boundedText = z.string().min(1).refine(
(value) => new TextEncoder().encode(value).length <= 64,
diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.ts
index 7b100215e..856f9693a 100644
--- a/src/shared/src/schemas.test.ts
+++ b/src/shared/src/schemas.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest"
import {
CommunityBotCreateRequestSchema,
CommunityBotPatchRequestSchema,
+ AgentActivityMessageSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
CreateWorkspaceRequestSchema,
@@ -11,6 +12,12 @@ import {
CommunityAgentNapRequestSchema,
} from "./schemas"
+const usageSnapshot = (index: number) => ({
+ botId: "bot_1",
+ day: `2026-08-${String(index + 1).padStart(2, "0")}`,
+ metrics: { input: index, output: 0, cache: null },
+})
+
function validCreatePayload(image?: string) {
return {
name: "MyBot",
@@ -28,6 +35,22 @@ describe("CommunityAgentNapRequestSchema", () => {
})
})
+describe("AgentActivityMessageSchema", () => {
+ it("accepts 30 daily snapshots and rejects 31", () => {
+ const frame = {
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: Array.from({ length: 30 }, (_, index) => usageSnapshot(index)),
+ }
+ expect(AgentActivityMessageSchema.safeParse(frame).success).toBe(true)
+ expect(AgentActivityMessageSchema.safeParse({
+ ...frame,
+ dailyUsage: [...frame.dailyUsage, usageSnapshot(30)],
+ }).success).toBe(false)
+ })
+})
+
describe("BotImageUrlSchema (via CommunityBotCreateRequestSchema)", () => {
it("accepts an https URL", () => {
const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("https://cdn.example.com/a.png"))
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index b81c0b252..3138c1b18 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -3,6 +3,7 @@ import { IssueStatus, TASK_TYPES } from "./constants";
import { sanitizeSlug } from "./utils/slug";
import { DiagnosticReportIdSchema } from "./diagnostics-contract";
import {
+ DAILY_TOKEN_USAGE_WINDOW_DAYS,
DailyUsageSnapshotSchema,
ProviderQuotaSnapshotSchema,
} from "./provider-telemetry";
@@ -1031,7 +1032,7 @@ export const AgentActivityMessageSchema = z.object({
state: z.enum(["idle", "starting", "running", "stopping"]),
usageTimeZone: z.string().min(1).max(128).optional(),
usageDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
- dailyUsage: z.array(DailyUsageSnapshotSchema).max(7).optional(),
+ dailyUsage: z.array(DailyUsageSnapshotSchema).max(DAILY_TOKEN_USAGE_WINDOW_DAYS).optional(),
quota: ProviderQuotaSnapshotSchema.optional(),
});
export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index e0620fda9..4efe0fde3 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -252,7 +252,7 @@ describe("GET /api/community/bots — heatmap activity", () => {
expect((await res.json()) as { bots: unknown[] }).toEqual({ bots: [] })
})
- it("returns seven oldest-to-newest usage days with nullable metrics and capability", async () => {
+ it("returns 30 oldest-to-newest usage days with nullable metrics and capability", async () => {
const today = new Date().toISOString().slice(0, 10)
mockListBotsForOwner.mockResolvedValue([
{ id: "bot_claude", runtime: "claude" },
@@ -284,7 +284,7 @@ describe("GET /api/community/bots — heatmap activity", () => {
}
const supported = body.bots.find((bot) => bot.id === "bot_pi")!
expect(supported.usage.capability).toBe("supported")
- expect(supported.usage.days).toHaveLength(7)
+ expect(supported.usage.days).toHaveLength(30)
expect(supported.usage.days.at(-1)).toEqual({
day: today,
period: "in_progress",
@@ -310,17 +310,12 @@ describe("GET /api/community/bots — heatmap activity", () => {
)
})
- it("uses the daemon computer timezone for the seven-day token window", () => {
+ it("uses the daemon computer timezone for the 30-day token window", () => {
const now = new Date("2026-08-29T16:00:01Z")
- expect(tokenUsageDayWindow(now, "Asia/Shanghai")).toEqual([
- "2026-08-24",
- "2026-08-25",
- "2026-08-26",
- "2026-08-27",
- "2026-08-28",
- "2026-08-29",
- "2026-08-30",
- ])
+ const shanghaiDays = tokenUsageDayWindow(now, "Asia/Shanghai")
+ expect(shanghaiDays).toHaveLength(30)
+ expect(shanghaiDays.at(0)).toBe("2026-08-01")
+ expect(shanghaiDays.at(-1)).toBe("2026-08-30")
expect(tokenUsageDayWindow(now, "America/Los_Angeles").at(-1)).toBe("2026-08-29")
expect(tokenUsageDayWindow(now, "not/a-time-zone").at(-1)).toBe("2026-08-29")
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 725f7955b..ef38edbc8 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -3,6 +3,7 @@ import {
queries,
CommunityBotCreateRequestSchema,
COMMUNITY_BOT_LIMIT_PER_OWNER,
+ DAILY_TOKEN_USAGE_WINDOW_DAYS,
calendarDayKeyDaysAgo,
dayKeyInTimeZone,
utcDayKey,
@@ -23,8 +24,8 @@ export function tokenUsageDayWindow(now: Date, timeZone: string | null | undefin
} catch { }
}
return Array.from(
- { length: 7 },
- (_, index) => calendarDayKeyDaysAgo(today, 6 - index),
+ { length: DAILY_TOKEN_USAGE_WINDOW_DAYS },
+ (_, index) => calendarDayKeyDaysAgo(today, DAILY_TOKEN_USAGE_WINDOW_DAYS - 1 - index),
)
}
@@ -42,7 +43,7 @@ export const GET = withAuth(async (_req, ctx) => {
sinceDay,
)
const now = new Date()
- const usageSinceDay = utcDayKeyDaysAgo(now, 7)
+ const usageSinceDay = utcDayKeyDaysAgo(now, DAILY_TOKEN_USAGE_WINDOW_DAYS)
const usageByBot = await queries.communityBot.getBotDailyTokenUsageForOwner(
db,
ctx.userId,
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
index 4bdad8938..b6d20faa3 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.test.ts
+++ b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
@@ -21,15 +21,9 @@ vi.mock("@/components/provider-logo", () => ({
ProviderLogo: (props: unknown) => React.createElement("provider", props as Record<string, unknown>),
}))
vi.mock("./bot-token-usage-chart", () => ({
- usageDayPresentation: (day: NonNullable<BotSummary["usage"]>["days"][number]) => ({
- knownTotal: Object.values(day.metrics).reduce(
- (sum, metric) => sum + (metric ?? 0),
- 0,
- ),
- }),
- BotTokenUsageChart: (props: unknown) => {
+ BotTokenUsageHeatmap: (props: unknown) => {
mocks.usage(props)
- return React.createElement("usage-chart", props as Record<string, unknown>)
+ return React.createElement("usage-heatmap", props as Record<string, unknown>)
},
}))
vi.mock("./bot-quota-summary", () => ({
@@ -129,7 +123,7 @@ describe("renderBotMachineGroup", () => {
expect(renderer.root.findAllByProps({ className: "flex items-start justify-between gap-3" }))
.toHaveLength(1)
expect(renderer.root.findAllByProps({
- className: "flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end",
+ className: "flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5",
})).toHaveLength(1)
expect(renderer.root.findAllByProps({ className: "basis-full sm:ml-auto sm:basis-auto" }))
.toHaveLength(0)
@@ -183,7 +177,7 @@ describe("renderBotMachineGroup", () => {
.toHaveLength(1)
})
- it("projects bot-owned usage on one machine scale and machine-scoped quota once", () => {
+ it("projects bot-owned fixed-scale heatmaps and machine-scoped quota once", () => {
const usage = {
capability: "supported" as const,
days: [{
@@ -241,15 +235,14 @@ describe("renderBotMachineGroup", () => {
expect(mocks.usage).toHaveBeenNthCalledWith(1, {
botId: "smaller",
usage,
- scaleMaxTokens: 100,
+ className: "self-center",
})
expect(mocks.usage).toHaveBeenNthCalledWith(2, {
botId: "larger",
usage: largerUsage,
- scaleMaxTokens: 100,
+ className: "self-center",
})
- expect(renderer.root.findAllByProps({ className: "basis-full sm:ml-auto sm:basis-auto" }))
- .toHaveLength(2)
+ expect(renderer.root.findAllByType("usage-heatmap")).toHaveLength(2)
expect(mocks.quota).toHaveBeenCalledTimes(1)
expect(mocks.quota).toHaveBeenCalledWith({
machineId: "mac1",
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsx
index 3a923d78f..5a4b881e6 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx
+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx
@@ -13,7 +13,7 @@ import {
import { formatAwakeDuration } from "@/lib/community/format-time"
import { tid } from "@/lib/community/testids"
import { MachineQuotaSummary } from "./bot-quota-summary"
-import { BotTokenUsageChart, usageDayPresentation } from "./bot-token-usage-chart"
+import { BotTokenUsageHeatmap } from "./bot-token-usage-chart"
import type { BotListController, BotMachineGroup } from "./bot-list-types"
export function renderBotMachineGroup(
@@ -23,11 +23,6 @@ export function renderBotMachineGroup(
const machineOnline = isPresenceOnline(machine?.status)
const collapsed = controller.collapsedMachines.has(machineId)
const label = controller.machineName(machineId)
- const usageScaleMax = Math.max(0, ...bots.flatMap((bot) => (
- bot.usage?.capability === "supported"
- ? bot.usage.days.map((day) => usageDayPresentation(day).knownTotal)
- : []
- )))
return (
<div
key={machineId}
@@ -90,8 +85,8 @@ export function renderBotMachineGroup(
<Card key={bot.id} className="flex flex-col gap-3 p-4">
<div className="flex items-start justify-between gap-3">
<AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />
- <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end">
- <div className="flex min-w-0 flex-1 flex-col gap-1 sm:min-w-55">
+ <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5">
+ <div className="flex min-w-55 flex-1 flex-col gap-1">
<div className="flex items-center gap-2">
<span className="truncate text-[15px] font-medium text-foreground">
{bot.name}
@@ -156,13 +151,11 @@ export function renderBotMachineGroup(
</span>
</div>
{bot.usage?.capability === "supported" && (
- <div className="basis-full sm:ml-auto sm:basis-auto">
- <BotTokenUsageChart
- botId={bot.id}
- usage={bot.usage}
- scaleMaxTokens={usageScaleMax}
- />
- </div>
+ <BotTokenUsageHeatmap
+ botId={bot.id}
+ usage={bot.usage}
+ className="self-center"
+ />
)}
</div>
<DropdownMenu>
diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.test.ts b/src/web/src/components/community/bots/bot-token-usage-chart.test.ts
index 68f715844..d1ece2b58 100644
--- a/src/web/src/components/community/bots/bot-token-usage-chart.test.ts
+++ b/src/web/src/components/community/bots/bot-token-usage-chart.test.ts
@@ -5,25 +5,19 @@ import type { BotTokenUsage, BotUsageDay } from "@/hooks/community/use-bots"
vi.mock("@/components/ui/tooltip", () => ({
Tooltip: ({ children }: React.PropsWithChildren) => React.createElement(React.Fragment, null, children),
- TooltipTrigger: ({ render }: { render: React.ReactElement }) => React.cloneElement(render),
+ TooltipTrigger: ({ render }: { render: React.ReactElement }) =>
+ React.cloneElement(render, { "data-cell": true }),
TooltipContent: ({ children }: React.PropsWithChildren) =>
React.createElement("tooltip-content", null, children),
}))
-vi.mock("@/components/ui/popover", () => ({
- Popover: ({ children }: React.PropsWithChildren) => React.createElement(React.Fragment, null, children),
- PopoverTrigger: ({ render }: { render: React.ReactElement }) => React.cloneElement(render),
- PopoverContent: ({ children, className }: React.PropsWithChildren<{ className?: string }>) =>
- React.createElement("popover-content", { className }, children),
-}))
import {
- BotTokenUsageChart,
- normalizedBarHeight,
+ BotTokenUsageHeatmap,
+ tokenHeatBucket,
usageDayPresentation,
} from "./bot-token-usage-chart"
const unavailable = null
-const complete = (tokens: number) => tokens
function usageDay(
day: string,
@@ -33,21 +27,19 @@ function usageDay(
return { day, period, metrics }
}
-const sevenDays = (last: BotUsageDay): BotUsageDay[] => [
- usageDay("2026-08-23", { input: complete(5), output: complete(5), cache: complete(0) }),
- usageDay("2026-08-24", { input: complete(10), output: complete(10), cache: complete(0) }),
- usageDay("2026-08-25", { input: unavailable, output: unavailable, cache: unavailable }),
- usageDay("2026-08-26", { input: complete(20), output: complete(10), cache: unavailable }),
- usageDay("2026-08-27", { input: complete(0), output: complete(0), cache: complete(0) }),
- usageDay("2026-08-28", { input: complete(40), output: complete(40), cache: complete(20) }),
- last,
-]
+function thirtyDays(overrides: Partial<Record<number, BotUsageDay["metrics"]>> = {}): BotUsageDay[] {
+ return Array.from({ length: 30 }, (_, index) => usageDay(
+ `2026-08-${String(index + 1).padStart(2, "0")}`,
+ overrides[index + 1] ?? { input: unavailable, output: unavailable, cache: unavailable },
+ index === 29 ? "in_progress" : "closed",
+ ))
+}
function render(usage?: BotTokenUsage) {
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(
- React.createElement(BotTokenUsageChart, { botId: "bot_1", usage }),
+ React.createElement(BotTokenUsageHeatmap, { botId: "bot_1", usage }),
)
})
return renderer
@@ -57,101 +49,94 @@ function text(node: TestRenderer.ReactTestInstance): string {
return node.children.map((child) => typeof child === "string" ? child : text(child)).join(" ")
}
-describe("usage chart normalization", () => {
- it("keeps exact zero and unavailable distinct without projecting coverage labels", () => {
- expect(usageDayPresentation(usageDay("2026-08-29", {
- input: complete(0), output: complete(0), cache: complete(0),
+describe("daily token heat presentation", () => {
+ it("sums every known metric while preserving exact zero and unavailable", () => {
+ expect(usageDayPresentation(usageDay("2026-08-30", {
+ input: 0, output: 0, cache: 0,
}))).toEqual({ knownTotal: 0, unavailable: false })
- expect(usageDayPresentation(usageDay("2026-08-29", {
- input: complete(12), output: complete(3), cache: unavailable,
+ expect(usageDayPresentation(usageDay("2026-08-30", {
+ input: 12, output: 3, cache: unavailable,
}))).toEqual({ knownTotal: 15, unavailable: false })
- expect(usageDayPresentation(usageDay("2026-08-29", {
+ expect(usageDayPresentation(usageDay("2026-08-30", {
input: unavailable, output: unavailable, cache: unavailable,
}))).toEqual({ knownTotal: 0, unavailable: true })
})
- it("normalizes all-zero, one-nonzero, and extreme differences to the seven-day maximum", () => {
- expect(normalizedBarHeight(0, 0)).toBe(0)
- expect(normalizedBarHeight(0, 900)).toBe(0)
- expect(normalizedBarHeight(900, 900)).toBe(100)
- expect(normalizedBarHeight(1, 1_000_000)).toBeCloseTo(0.0001, 8)
+ it("uses the four fixed token bands with an empty zero state", () => {
+ const bucket = (knownTotal: number, unavailable = false) =>
+ tokenHeatBucket({ knownTotal, unavailable })
+
+ expect(bucket(0)).toBe(0)
+ expect(bucket(1)).toBe(1)
+ expect(bucket(9_999_999)).toBe(1)
+ expect(bucket(10_000_000)).toBe(2)
+ expect(bucket(99_999_999)).toBe(2)
+ expect(bucket(100_000_000)).toBe(3)
+ expect(bucket(499_999_999)).toBe(3)
+ expect(bucket(500_000_000)).toBe(4)
+ expect(bucket(900_000_000)).toBe(4)
+ expect(bucket(500_000_000, true)).toBe(0)
})
})
-describe("BotTokenUsageChart", () => {
- it("renders seven keyboard/tap targets oldest-to-newest without a persistent x-axis", () => {
+describe("BotTokenUsageHeatmap", () => {
+ it("renders the original 30-cell 3-by-10 shell oldest to newest", () => {
const usage: BotTokenUsage = {
capability: "supported",
- days: sevenDays(usageDay(
- "2026-08-29",
- { input: complete(8), output: complete(2), cache: complete(0) },
- "in_progress",
- )),
+ days: thirtyDays({
+ 27: { input: 1, output: 0, cache: 0 },
+ 28: { input: 10_000_000, output: 0, cache: 0 },
+ 29: { input: 100_000_000, output: 0, cache: 0 },
+ 30: { input: 500_000_000, output: 0, cache: 0 },
+ }),
}
const renderer = render(usage)
- const targets = renderer.root.findAll((node) => (
- node.props.role === "listitem" && node.props["data-testid"]
- ))
- expect(targets).toHaveLength(7)
- expect(targets[0]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-23")
- expect(targets[6]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-29")
- expect(targets[6]!.props["aria-label"]).toContain("Input 8")
- expect(targets[6]!.props["aria-label"]).toContain("Output 2")
- expect(renderer.root.findAll((node) => String(node.props.className).includes("h-10.5")))
- .not.toHaveLength(0)
- const desktopTargetText = targets.map(text).join(" ")
- expect(desktopTargetText).not.toContain("8/23")
- expect(desktopTargetText).not.toContain("Today")
- expect(text(renderer.root)).not.toContain("Tokens")
+ const heatmap = renderer.root.findByProps({
+ "data-testid": "community-bot-usage-bot_1",
+ })
+ expect(heatmap.props.className).toContain("grid-flow-col")
+ expect(heatmap.props.className).toContain("grid-template-rows:repeat(3")
+ expect(heatmap.props["aria-label"]).toContain("610,000,001 known tokens total")
+
+ const cells = renderer.root.findAllByProps({ "data-cell": true })
+ expect(cells).toHaveLength(30)
+ expect(cells[0]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-01")
+ expect(cells[29]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-30")
+ expect(cells.every((cell) => String(cell.props.className).includes("size-3 rounded-[2px]")))
+ .toBe(true)
+ expect(cells[0]!.props.className).toContain("bg-muted-foreground/15")
+ expect(cells[26]!.props.className).toContain("bg-status-online/30")
+ expect(cells[27]!.props.className).toContain("bg-status-online/55")
+ expect(cells[28]!.props.className).toContain("bg-status-online/80")
+ expect(cells[29]!.props.className.split(/\s+/)).toContain("bg-status-online")
+ expect(renderer.root.findAll((node) => node.props.style?.height !== undefined)).toHaveLength(0)
+ expect(renderer.root.findAll((node) => node.props["aria-pressed"] !== undefined)).toHaveLength(0)
})
- it("shares one proportional seven-day scale without coverage annotations or background pipes", () => {
+ it("shows the date and all three token totals for every day", () => {
const usage: BotTokenUsage = {
capability: "supported",
- days: sevenDays(usageDay(
- "2026-08-29",
- { input: complete(50), output: complete(0), cache: complete(0) },
- "in_progress",
- )),
+ days: thirtyDays({
+ 30: { input: 8, output: 2, cache: unavailable },
+ }),
}
const renderer = render(usage)
- const heightNodes = renderer.root.findAll((node) => typeof node.props.style?.height === "string")
- expect(heightNodes.map((node) => node.props.style.height)).toContain("100%")
- expect(heightNodes.map((node) => node.props.style.height)).toContain("50%")
- expect(renderer.root.findAll((node) => String(node.props.className).includes("ring-inset")))
- .toHaveLength(0)
+ const today = renderer.root.findByProps({
+ "data-testid": "community-bot-usage-day-bot_1-2026-08-30",
+ })
+ expect(today.props["aria-label"]).toContain("Aug 30")
+ expect(today.props["aria-label"]).toContain("Input 8")
+ expect(today.props["aria-label"]).toContain("Output 2")
+ expect(today.props["aria-label"]).toContain("Cache Unavailable")
+ expect(text(renderer.root)).toContain("Input 8")
+ expect(text(renderer.root)).toContain("Output 2")
+ expect(text(renderer.root)).toContain("Cache Unavailable")
})
- it("groups seven mobile days into a four-column selector with one pressed 44px target", () => {
- const usage: BotTokenUsage = {
- capability: "supported",
- days: sevenDays(usageDay(
- "2026-08-29",
- { input: complete(8), output: complete(2), cache: complete(0) },
- "in_progress",
- )),
- }
- const renderer = render(usage)
- const mobileTargets = renderer.root.findAll((node) => node.props["aria-pressed"] !== undefined)
- expect(mobileTargets).toHaveLength(7)
- expect(mobileTargets.filter((node) => node.props["aria-pressed"])).toHaveLength(1)
- expect(mobileTargets[6]!.props["aria-pressed"]).toBe(true)
- expect(mobileTargets.every((node) => String(node.props.className).includes("h-11"))).toBe(true)
- expect(String(mobileTargets[0]!.parent?.props.className)).toContain("grid-cols-4")
-
- act(() => mobileTargets[2]!.props.onClick())
- const updatedTargets = renderer.root.findAll((node) => node.props["aria-pressed"] !== undefined)
- expect(updatedTargets[2]!.props["aria-pressed"]).toBe(true)
- expect(updatedTargets.filter((node) => node.props["aria-pressed"])).toHaveLength(1)
- })
-
- it("omits missing and unsupported usage without reserving a chart slot", () => {
- const unsupported = render({ capability: "unsupported", days: [] })
- expect(unsupported.toJSON()).toBeNull()
-
- const unknown = render()
- expect(unknown.toJSON()).toBeNull()
+ it("omits missing and unsupported usage without reserving a heatmap slot", () => {
+ expect(render({ capability: "unsupported", days: [] }).toJSON()).toBeNull()
+ expect(render().toJSON()).toBeNull()
})
})
diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.tsx b/src/web/src/components/community/bots/bot-token-usage-chart.tsx
index 8b8988c2f..d92685054 100644
--- a/src/web/src/components/community/bots/bot-token-usage-chart.tsx
+++ b/src/web/src/components/community/bots/bot-token-usage-chart.tsx
@@ -1,11 +1,5 @@
"use client"
-import { useState } from "react"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
import {
Tooltip,
TooltipContent,
@@ -21,43 +15,35 @@ const DAY_FMT = new Intl.DateTimeFormat(undefined, {
day: "numeric",
timeZone: "UTC",
})
-const AXIS_DAY_FMT = new Intl.DateTimeFormat(undefined, {
- month: "numeric",
- day: "numeric",
- timeZone: "UTC",
-})
+
+const BUCKET_CLASSES = [
+ "bg-muted-foreground/15",
+ "bg-status-online/30",
+ "bg-status-online/55",
+ "bg-status-online/80",
+ "bg-status-online",
+] as const
type MetricKey = "input" | "output" | "cache"
const METRICS: Array<{
key: MetricKey
label: string
- className: string
}> = [
- { key: "input", label: "Input", className: "bg-foreground/75" },
- { key: "output", label: "Output", className: "bg-muted-foreground/75" },
- { key: "cache", label: "Cache", className: "bg-foreground/25" },
+ { key: "input", label: "Input" },
+ { key: "output", label: "Output" },
+ { key: "cache", label: "Cache" },
]
function parseUtcDay(day: string): Date {
return new Date(`${day}T00:00:00.000Z`)
}
-function dayLabel(day: BotUsageDay): string {
- if (day.period === "in_progress") return "Today"
- const parsed = parseUtcDay(day.day)
- return Number.isNaN(parsed.getTime()) ? day.day : AXIS_DAY_FMT.format(parsed)
-}
-
function fullDayLabel(day: BotUsageDay): string {
const parsed = parseUtcDay(day.day)
return Number.isNaN(parsed.getTime()) ? day.day : DAY_FMT.format(parsed)
}
-function metricTokens(metric: DailyUsageMetric): number | null {
- return metric
-}
-
function metricLabel(metric: DailyUsageMetric): string {
if (metric === null) return "Unavailable"
return TOKEN_FMT.format(metric)
@@ -69,22 +55,21 @@ export type UsageDayPresentation = {
}
export function usageDayPresentation(day: BotUsageDay): UsageDayPresentation {
- const metrics = Object.values(day.metrics)
- const known = metrics.flatMap((metric) => {
- const tokens = metricTokens(metric)
- return tokens === null ? [] : [tokens]
- })
- const knownTotal = known.reduce((sum, tokens) => sum + tokens, 0)
- const unavailable = known.length === 0
+ const known = Object.values(day.metrics).filter(
+ (metric): metric is number => metric !== null,
+ )
return {
- knownTotal,
- unavailable,
+ knownTotal: known.reduce((sum, tokens) => sum + tokens, 0),
+ unavailable: known.length === 0,
}
}
-export function normalizedBarHeight(total: number, maxTotal: number): number {
- if (total <= 0 || maxTotal <= 0) return 0
- return (total / maxTotal) * 100
+export function tokenHeatBucket(presentation: UsageDayPresentation): number {
+ if (presentation.unavailable || presentation.knownTotal <= 0) return 0
+ if (presentation.knownTotal < 10_000_000) return 1
+ if (presentation.knownTotal < 100_000_000) return 2
+ if (presentation.knownTotal < 500_000_000) return 3
+ return 4
}
function accessibleDayLabel(day: BotUsageDay): string {
@@ -110,133 +95,51 @@ function UsageDayDetail({ day }: { day: BotUsageDay }) {
)
}
-function UsageBar({
- day,
- presentation,
- maxKnownTotal,
-}: {
- day: BotUsageDay
- presentation: UsageDayPresentation
- maxKnownTotal: number
-}) {
- const totalHeight = normalizedBarHeight(presentation.knownTotal, maxKnownTotal)
- return (
- <span className="relative flex min-h-0 w-full flex-1 items-end justify-center">
- <span
- className="flex w-3 flex-col-reverse overflow-hidden rounded-sm"
- style={{ height: `${totalHeight}%` }}
- >
- {METRICS.map((metric) => {
- const tokens = metricTokens(day.metrics[metric.key])
- if (!tokens || presentation.knownTotal === 0) return null
- return (
- <span
- key={metric.key}
- className={["w-full", metric.className].join(" ")}
- style={{ flexGrow: tokens }}
- />
- )
- })}
- </span>
- </span>
- )
-}
-
-export function BotTokenUsageChart({
+export function BotTokenUsageHeatmap({
botId,
usage,
- scaleMaxTokens,
+ className,
}: {
botId: string
usage?: BotTokenUsage
- scaleMaxTokens?: number
+ className?: string
}) {
- const [mobileOpen, setMobileOpen] = useState(false)
- const [mobileDayIndex, setMobileDayIndex] = useState(6)
if (!usage || usage.capability !== "supported") return null
- const presentations = usage.days.map(usageDayPresentation)
- const maxKnownTotal = scaleMaxTokens
- ?? Math.max(0, ...presentations.map((day) => day.knownTotal))
+ const total = usage.days.reduce(
+ (sum, day) => sum + usageDayPresentation(day).knownTotal,
+ 0,
+ )
return (
- <section
- aria-label="Token usage over the last 7 days"
+ <div
+ role="img"
+ aria-label={`Token usage over the last 30 days: ${TOKEN_FMT.format(total)} known tokens total`}
data-testid={tid.botUsage(botId)}
- className="h-10.5 w-32 max-w-full"
+ className={[
+ "grid w-fit grid-flow-col gap-[3px] [grid-template-rows:repeat(3,minmax(0,1fr))]",
+ className ?? "",
+ ].join(" ")}
>
- <div className="relative grid h-full min-h-0 grid-cols-7 gap-1" role="list">
- {usage.days.map((day, index) => {
- const presentation = presentations[index]!
- return (
- <Tooltip key={day.day}>
- <TooltipTrigger
- render={
- <button
- type="button"
- role="listitem"
- aria-label={accessibleDayLabel(day)}
- data-testid={tid.botUsageDay(botId, day.day)}
- className="group hidden min-w-0 flex-col items-center gap-1 rounded-sm focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:flex"
- >
- <UsageBar day={day} presentation={presentation} maxKnownTotal={maxKnownTotal} />
- </button>
- }
- />
- <TooltipContent className="items-start">
- <UsageDayDetail day={day} />
- </TooltipContent>
- </Tooltip>
- )
- })}
- {usage.days.map((day, index) => (
- <div
- key={`mobile-${day.day}`}
- role="listitem"
- aria-label={accessibleDayLabel(day)}
- className="group flex min-w-0 flex-col items-center gap-1 sm:hidden"
- >
- <UsageBar day={day} presentation={presentations[index]!} maxKnownTotal={maxKnownTotal} />
- </div>
- ))}
- <Popover open={mobileOpen} onOpenChange={setMobileOpen}>
- <PopoverTrigger
- render={
- <button
- type="button"
- aria-label="Open token usage details"
- aria-expanded={mobileOpen}
- className="absolute inset-0 z-10 min-h-11 rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:hidden"
- />
- }
- />
- <PopoverContent
- side="bottom"
- align="end"
- className="max-h-[calc(100vh-2rem)] w-72 max-w-[calc(100vw-1rem)] overflow-y-auto p-3 thin-scrollbar sm:hidden"
- >
- <div className="flex flex-col gap-3">
- <div className="text-xs text-foreground">
- <UsageDayDetail day={usage.days[mobileDayIndex] ?? usage.days.at(-1)!} />
- </div>
- <div className="grid grid-cols-4 gap-2 border-t border-border/60 pt-2">
- {usage.days.map((day, index) => (
- <button
- key={day.day}
- type="button"
- data-testid={tid.botUsageDay(botId, day.day)}
- aria-pressed={index === mobileDayIndex}
- onClick={() => setMobileDayIndex(index)}
- className="flex h-11 min-w-11 items-center justify-center rounded-md px-1 text-center text-xs text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none aria-pressed:bg-accent aria-pressed:font-semibold aria-pressed:text-foreground"
- >
- <span>{dayLabel(day)}</span>
- </button>
- ))}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- </section>
+ {usage.days.map((day) => {
+ const bucket = tokenHeatBucket(usageDayPresentation(day))
+ return (
+ <Tooltip key={day.day}>
+ <TooltipTrigger
+ render={
+ <span
+ aria-label={accessibleDayLabel(day)}
+ data-testid={tid.botUsageDay(botId, day.day)}
+ className={["size-3 rounded-[2px]", BUCKET_CLASSES[bucket]].join(" ")}
+ />
+ }
+ />
+ <TooltipContent className="items-start">
+ <UsageDayDetail day={day} />
+ </TooltipContent>
+ </Tooltip>
+ )
+ })}
+ </div>
)
}
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 5489c1fe1..a9b2fc6c2 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -46,7 +46,7 @@ export type BotSummary = {
// Sparse — only days with activity; oldest→newest; [] for a brand-new bot.
// The heatmap builds the full 30-day calendar and fills from this by day-key.
dailyActivity: BotActivityDay[]
- // Owner-only seven-day provider telemetry. Older optimistic mutation payloads
+ // Owner-only 30-day provider telemetry. Older optimistic mutation payloads
// can omit it until the bots query refetches, which renders the unknown-state
// placeholder instead of inventing zero usage.
usage?: BotTokenUsage
diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
index 31c56c348..170f55fa8 100644
--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
@@ -45,15 +45,23 @@ async function postAsAlice(path: string, body?: unknown): Promise<Response> {
})
}
-const days = [
- { day: "2026-08-23", period: "closed", metrics: { input: 1200, output: 400, cache: 2000 } },
- { day: "2026-08-24", period: "closed", metrics: { input: 800, output: 200, cache: 1000 } },
- { day: "2026-08-25", period: "closed", metrics: { input: null, output: null, cache: null } },
- { day: "2026-08-26", period: "closed", metrics: { input: 700, output: 300, cache: null } },
- { day: "2026-08-27", period: "closed", metrics: { input: 0, output: 0, cache: 0 } },
- { day: "2026-08-28", period: "closed", metrics: { input: 4000, output: 1200, cache: 6400 } },
- { day: "2026-08-29", period: "in_progress", metrics: { input: 1800, output: 650, cache: 2400 } },
-] as const
+const dayOverrides: Record<string, { input: number | null; output: number | null; cache: number | null }> = {
+ "2026-08-24": { input: 0, output: 0, cache: 0 },
+ "2026-08-25": { input: null, output: null, cache: null },
+ "2026-08-26": { input: 6_000_000, output: 3_000_000, cache: null },
+ "2026-08-27": { input: 8_000_000, output: 2_000_000, cache: 0 },
+ "2026-08-28": { input: 70_000_000, output: 30_000_000, cache: 0 },
+ "2026-08-29": { input: 300_000_000, output: 100_000_000, cache: 100_000_000 },
+}
+
+const days = Array.from({ length: 30 }, (_, index) => {
+ const day = `2026-08-${String(index + 1).padStart(2, "0")}`
+ return {
+ day,
+ period: index === 29 ? "in_progress" as const : "closed" as const,
+ metrics: dayOverrides[day] ?? { input: null, output: null, cache: null },
+ }
+})
const smallerDays = days.map((day) => ({
...day,
@@ -213,7 +221,7 @@ async function expectNoHorizontalOverflow(page: Page) {
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
}
-test("My Bots renders seven-day usage and replace-all quota across responsive themes", async ({ asUser }, testInfo) => {
+test("My Bots restores the 30-day token heatmap across PC and mobile", async ({ asUser }, testInfo) => {
const { page } = await asUser("alice", { hasTouch: true })
await page.route("**/api/community/bots", async (route) => {
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ bots }) })
@@ -226,12 +234,21 @@ test("My Bots renders seven-day usage and replace-all quota across responsive th
await gotoAfterUserWsAuth(page, "/c/me/bots")
const usage = page.getByTestId(tid.botUsage("bot_codex"))
+ const dayCells = usage.locator(`[data-testid^="${tid.botUsageDay("bot_codex", "")}"]`)
await expect(usage).toBeVisible()
- await expect(usage.getByRole("listitem")).toHaveCount(7)
- await expect(usage).not.toContainText("8/23")
- await expect(usage).not.toContainText("Today")
- await expect(usage).not.toContainText("Tokens")
+ await expect(dayCells).toHaveCount(30)
+ await expect(usage).toHaveAttribute("aria-label", /Token usage over the last 30 days/)
await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)
+ await expect.poll(async () => (await usage.boundingBox())?.width ?? 0).toBe(147)
+ const cellGeometry = await dayCells.evaluateAll((elements) => elements.map((element) => {
+ const box = element.getBoundingClientRect()
+ return { width: box.width, height: box.height, x: Math.round(box.x), y: Math.round(box.y) }
+ }))
+ expect(cellGeometry.every((box) => box.width === 12 && box.height === 12)).toBe(true)
+ expect(new Set(cellGeometry.map((box) => box.x)).size).toBe(10)
+ expect(new Set(cellGeometry.map((box) => box.y)).size).toBe(3)
+ await expect(usage.locator('[style*="height"]')).toHaveCount(0)
+ await expect(page.getByRole("button", { name: "Open token usage details" })).toHaveCount(0)
const botCard = usage.locator('xpath=ancestor::*[@data-slot="card"]')
await expect.poll(async () => (await botCard.boundingBox())?.height ?? 0)
.toBeLessThanOrEqual(80)
@@ -241,38 +258,41 @@ test("My Bots renders seven-day usage and replace-all quota across responsive th
])
expect(usageBox).not.toBeNull()
expect(botMetaBox).not.toBeNull()
- expect(Math.abs(
- usageBox!.y + usageBox!.height - (botMetaBox!.y + botMetaBox!.height),
- )).toBeLessThanOrEqual(3)
- await expect(page.getByTestId(tid.botUsage("bot_pi")).getByRole("listitem")).toHaveCount(7)
+ expect(usageBox!.x).toBeGreaterThan(botMetaBox!.x + botMetaBox!.width)
+ await expect(page.locator(
+ `[data-testid^="${tid.botUsageDay("bot_pi", "")}"]`,
+ )).toHaveCount(30)
await expect(page.getByText("Token usage not supported")).toHaveCount(0)
- const claudeUsage = page.getByTestId(tid.botUsage("bot_claude"))
- await expect(claudeUsage.getByRole("listitem")).toHaveCount(7)
+ await expect(page.locator(
+ `[data-testid^="${tid.botUsageDay("bot_claude", "")}"]`,
+ )).toHaveCount(30)
const quota = page.getByTestId(tid.machineQuota(machine.id))
await expect(quota).toHaveCount(1)
await expect(quota).toContainText("Quota · Spark · 18% left · 3 limits")
- const largestDayBar = page
- .getByTestId(tid.botUsageDay("bot_codex", "2026-08-28"))
- .locator('[style*="height"]')
- const smallerDayBar = page
- .getByTestId(tid.botUsageDay("bot_small", "2026-08-28"))
- .locator('[style*="height"]')
- await expect(largestDayBar).toHaveAttribute("style", /height: 100%/)
- await expect(smallerDayBar).toHaveAttribute("style", /height: 10%/)
- await expect(
- page.getByTestId(tid.botUsageDay("bot_claude", "2026-08-28")).locator('[style*="height"]'),
- ).toHaveAttribute("style", /height: 50%/)
+ await expect(page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-24")))
+ .toHaveClass(/bg-muted-foreground\/15/)
+ await expect(page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-26")))
+ .toHaveClass(/bg-status-online\/30/)
+ await expect(page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-27")))
+ .toHaveClass(/bg-status-online\/55/)
+ await expect(page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-28")))
+ .toHaveClass(/bg-status-online\/80/)
+ expect((await page.getByTestId(
+ tid.botUsageDay("bot_codex", "2026-08-29"),
+ ).getAttribute("class"))?.split(/\s+/)).toContain("bg-status-online")
const usageDay = page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-26"))
+ await expectNoHorizontalOverflow(page)
+ await attachScreenshot(page, testInfo, "my-bots-token-heatmap-pc")
await usageDay.hover()
const tooltip = page.locator('[data-slot="tooltip-content"]:visible')
- await expect(tooltip).toContainText("Input700")
- await expect(tooltip).toContainText("Output300")
+ await expect(tooltip).toContainText("Aug 26")
+ await expect(tooltip).toContainText("Input6,000,000")
+ await expect(tooltip).toContainText("Output3,000,000")
await expect(tooltip).toContainText("CacheUnavailable")
- await usageDay.focus()
- await expect(page.getByText("Input", { exact: true }).last()).toBeVisible()
- await page.keyboard.press("Escape")
+ await expect(tooltip).toHaveCSS("opacity", "1")
+ await attachScreenshot(page, testInfo, "my-bots-token-heatmap-pc-hover")
await expect(quota).toHaveAttribute("aria-expanded", "false")
await quota.click()
@@ -289,84 +309,61 @@ test("My Bots renders seven-day usage and replace-all quota across responsive th
await expect(quotaDetail).toContainText("gpt-5.3-codex-spark")
await expect(quotaDetail).toHaveCSS("opacity", "1")
- await expectNoHorizontalOverflow(page)
- await attachScreenshot(page, testInfo, "my-bots-telemetry-pc-light")
await quota.click()
await expect(quota).toHaveAttribute("aria-expanded", "false")
await expect(quotaDetail).toBeHidden()
- await page.emulateMedia({ colorScheme: "dark" })
- await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(true)
- await page.waitForTimeout(300)
- await attachScreenshot(page, testInfo, "my-bots-telemetry-pc-dark")
+ await page.mouse.move(1, 1)
await page.setViewportSize({ width: 639, height: 844 })
- await page.emulateMedia({ colorScheme: "light" })
- await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(false)
await page.waitForTimeout(300)
await expectNoHorizontalOverflow(page)
await expect(usage).toBeVisible()
- await expect(usage.getByRole("listitem")).toHaveCount(7)
- const mobileUsageTrigger = usage.getByRole("button", { name: "Open token usage details" })
- const mobileUsageBox = await mobileUsageTrigger.boundingBox()
- expect(mobileUsageBox?.height).toBeGreaterThanOrEqual(44)
- expect(mobileUsageBox?.width).toBeGreaterThanOrEqual(44)
- await mobileUsageTrigger.tap()
- const mobileUsageDetail = page.locator('[data-slot="popover-content"]:visible')
- await expect.poll(async () => (await mobileUsageDetail.boundingBox())?.height ?? 0)
- .toBeLessThanOrEqual(260)
- const mobileDayTargets = page.locator(
- `[data-testid^="${tid.botUsageDay("bot_codex", "")}"]:visible`,
- )
- await expect(mobileDayTargets).toHaveCount(7)
- await expect.poll(async () => {
- const boxes = await mobileDayTargets.evaluateAll((elements) => elements.map((element) => {
- const box = element.getBoundingClientRect()
- return { width: box.width, height: box.height }
- }))
- return boxes.every((box) => box.width >= 44 && box.height >= 44)
- }).toBe(true)
- const mobileDayBoxes = await mobileDayTargets.evaluateAll((elements) => elements.map((element) => {
- const box = element.getBoundingClientRect()
- return { width: box.width, height: box.height, y: Math.round(box.y) }
- }))
- expect(new Set(mobileDayBoxes.map((box) => box.y)).size).toBeLessThanOrEqual(2)
- await expect(page.locator(
- `[data-testid^="${tid.botUsageDay("bot_codex", "")}"][aria-pressed="true"]:visible`,
- )).toHaveCount(1)
- const mobileUsageDay = page.locator(
- `[data-testid="${tid.botUsageDay("bot_codex", "2026-08-26")}"]:visible`,
+ await expect(dayCells).toHaveCount(30)
+ await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)
+ await expect.poll(async () => (await usage.boundingBox())?.width ?? 0).toBe(147)
+ const [narrowBoundaryUsageBox, narrowBoundaryMetaBox] = await Promise.all([
+ usage.boundingBox(),
+ botCard.getByTestId(tid.botCardModel).boundingBox(),
+ ])
+ expect(narrowBoundaryUsageBox).not.toBeNull()
+ expect(narrowBoundaryMetaBox).not.toBeNull()
+ const narrowBoundaryBoxesOverlap = !(
+ narrowBoundaryUsageBox!.x + narrowBoundaryUsageBox!.width <= narrowBoundaryMetaBox!.x
+ || narrowBoundaryMetaBox!.x + narrowBoundaryMetaBox!.width <= narrowBoundaryUsageBox!.x
+ || narrowBoundaryUsageBox!.y + narrowBoundaryUsageBox!.height <= narrowBoundaryMetaBox!.y
+ || narrowBoundaryMetaBox!.y + narrowBoundaryMetaBox!.height <= narrowBoundaryUsageBox!.y
)
- await expect.poll(async () => (await mobileUsageDay.boundingBox())?.height ?? 0)
- .toBeGreaterThanOrEqual(44)
- await expect.poll(async () => (await mobileUsageDay.boundingBox())?.width ?? 0)
- .toBeGreaterThanOrEqual(44)
- await mobileUsageDay.tap()
- await expect(mobileUsageDay).toHaveAttribute("aria-pressed", "true")
- await expect(mobileUsageDetail).toContainText("Input700")
- await expect(mobileUsageDetail).toContainText("Output300")
- await expect(mobileUsageDetail).toContainText("CacheUnavailable")
- const mobileQuotaBox = await quota.boundingBox()
- expect(mobileQuotaBox?.height).toBeGreaterThanOrEqual(44)
- expect(mobileQuotaBox?.width).toBeGreaterThanOrEqual(44)
- await mobileUsageTrigger.tap()
- await expect(mobileUsageTrigger).toHaveAttribute("aria-expanded", "false")
- await expect(page.locator('[data-slot="popover-content"]:visible')).toHaveCount(0)
- await attachScreenshot(page, testInfo, "my-bots-telemetry-mobile-light")
- await page.emulateMedia({ colorScheme: "dark" })
- await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(true)
+ expect(narrowBoundaryBoxesOverlap).toBe(false)
+
+ await page.setViewportSize({ width: 390, height: 844 })
await page.waitForTimeout(300)
await expectNoHorizontalOverflow(page)
- await attachScreenshot(page, testInfo, "my-bots-telemetry-mobile-dark")
+ await expect(usage).toBeVisible()
+ await expect(dayCells).toHaveCount(30)
+ await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)
+ await expect.poll(async () => (await usage.boundingBox())?.width ?? 0).toBe(147)
+ const [mobileUsageBox, mobileMetaBox] = await Promise.all([
+ usage.boundingBox(),
+ botCard.getByTestId(tid.botCardModel).boundingBox(),
+ ])
+ expect(mobileUsageBox).not.toBeNull()
+ expect(mobileMetaBox).not.toBeNull()
+ expect(mobileUsageBox!.y).toBeGreaterThan(mobileMetaBox!.y + mobileMetaBox!.height)
+ await attachScreenshot(page, testInfo, "my-bots-token-heatmap-mobile")
+ await usageDay.hover()
+ await expect(tooltip).toContainText("Aug 26")
+ await expect(tooltip).toContainText("Input6,000,000")
+ await expect(tooltip).toContainText("Output3,000,000")
+ await expect(tooltip).toContainText("CacheUnavailable")
+ await expect(tooltip).toHaveCSS("opacity", "1")
+ await attachScreenshot(page, testInfo, "my-bots-token-heatmap-mobile-hover")
await page.setViewportSize({ width: 640, height: 844 })
- await expect(mobileUsageTrigger).toBeHidden()
- await expect(page.locator(
- `[data-testid^="${tid.botUsageDay("bot_codex", "")}"]:visible`,
- )).toHaveCount(7)
+ await expect(dayCells).toHaveCount(30)
await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)
const desktopBoundaryDay = page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-26"))
await desktopBoundaryDay.hover()
- await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Input700")
+ await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Input6,000,000")
})
test("My Bots renders Pi usage through real D1 and the unmocked bots API", async ({ asUser }, testInfo) => {
@@ -408,8 +405,8 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async
const timeZone = "Asia/Shanghai"
const today = dayKeyInTimeZone(new Date(), timeZone)
const expectedDays = Array.from(
- { length: 7 },
- (_, index) => calendarDayKeyDaysAgo(today, 6 - index),
+ { length: 30 },
+ (_, index) => calendarDayKeyDaysAgo(today, 29 - index),
)
const updatedAt = new Date().toISOString()
executeLocalD1([
@@ -467,7 +464,7 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async
expect(apiBot?.usage.days.at(-1)).toEqual({
day: today,
period: "in_progress",
- metrics: { input: 106, output: 16, cache: 1006 },
+ metrics: { input: 129, output: 39, cache: 1029 },
})
const apiEvidencePath = testInfo.outputPath("real-pi-bots-api-response.json")
writeFileSync(apiEvidencePath, `${JSON.stringify(apiBot, null, 2)}\n`)
@@ -483,12 +480,10 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async
const usage = page.getByTestId(tid.botUsage(botId))
await expect(usage).toBeVisible()
- await expect(usage.getByRole("listitem")).toHaveCount(7)
- await usage.getByRole("button", { name: "Open token usage details" }).tap()
const visibleDayTargets = page.locator(
`[data-testid^="${tid.botUsageDay(botId, "")}"]:visible`,
)
- await expect(visibleDayTargets).toHaveCount(7)
+ await expect(visibleDayTargets).toHaveCount(30)
const visibleDayTestIds = await visibleDayTargets.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("data-testid")),
)
@@ -496,15 +491,18 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async
const todayTarget = page.locator(
`[data-testid="${tid.botUsageDay(botId, today)}"]:visible`,
)
- await expect(todayTarget).toHaveText("Today")
- await expect(page.locator('[data-slot="popover-content"]:visible')).toContainText("Input106")
+ await expect(todayTarget).toHaveAttribute("aria-label", /Input 129/)
+ await todayTarget.hover()
+ await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Input129")
+ await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Output39")
+ await expect(page.locator('[data-slot="tooltip-content"]:visible')).toContainText("Cache1,029")
const browserEvidencePath = testInfo.outputPath("real-pi-browser-observation.json")
writeFileSync(browserEvidencePath, `${JSON.stringify({
route: "/c/me/bots",
botId,
visibleDayTestIds,
today,
- todayText: await todayTarget.textContent(),
+ todayLabel: await todayTarget.getAttribute("aria-label"),
}, null, 2)}\n`)
await testInfo.attach("real-pi-browser-observation.json", { path: browserEvidencePath })
await attachScreenshot(page, testInfo, "real-pi-d1-local-today")
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index ac9535bf1..38e400af1 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -342,6 +342,40 @@ describe("WebSocketDurableObject", () => {
expect(statements[2]!.values).toMatchObject({ 0: "bot_1", 2: 12, 3: 7, 4: null })
})
+ it("accepts all 30 unique machine-local usage days", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ const usageTimeZone = "Asia/Shanghai"
+ const usageDay = dayKeyInTimeZone(new Date(), usageTimeZone)
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ usageTimeZone,
+ usageDay,
+ dailyUsage: Array.from({ length: 30 }, (_, offset) => ({
+ botId: "bot_1",
+ day: calendarDayKeyDaysAgo(usageDay, offset),
+ metrics: { input: offset, output: 1, cache: 2 },
+ })),
+ }))
+
+ expect(mockD1Batch).toHaveBeenCalledOnce()
+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string }>
+ expect(statements.filter((statement) => (
+ statement.sql.includes("INSERT INTO community_bot_daily_token_usage")
+ ))).toHaveLength(30)
+ })
+
it("advances the computer-local usage day without creating an empty usage row", async () => {
const { durable, store } = createDO()
store.set("community-machine-identity", {
@@ -437,7 +471,7 @@ describe("WebSocketDurableObject", () => {
const prune = statements.find((statement) => statement.sql.includes("DELETE FROM community_bot_daily_token_usage"))
expect(prune?.values).toMatchObject({
0: "bot_1",
- 1: "2026-08-22",
+ 1: "2026-07-30",
2: "bot_1",
3: "cm_1",
})
@@ -490,7 +524,7 @@ describe("WebSocketDurableObject", () => {
]],
["an out-of-window day", (day: string) => [{
botId: "bot_1",
- day: calendarDayKeyDaysAgo(day, 7),
+ day: calendarDayKeyDaysAgo(day, 30),
metrics: { input: 3, output: 1, cache: 2 },
}]],
["a different bot id", (day: string) => [{
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.ts
index 868dc5225..0d7a2bdb6 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts
@@ -1,5 +1,6 @@
import {
AgentActivityMessageSchema,
+ DAILY_TOKEN_USAGE_WINDOW_DAYS,
DailyUsageSnapshotSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
@@ -33,6 +34,8 @@ import {
} from "./provider-telemetry-persistence"
const IDLE_RESET_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000
+const TOKEN_USAGE_RECOVERY_DAYS = 2
+const TOKEN_USAGE_RETENTION_DAYS = DAILY_TOKEN_USAGE_WINDOW_DAYS + TOKEN_USAGE_RECOVERY_DAYS
/**
* Telemetry handlers are deliberately independent first-match branches. Each
@@ -65,7 +68,10 @@ export async function handleActivityFrame(
const { agentId, state } = activityParse.data
const raw = parsed as Record<string, unknown>
const now = new Date()
- const legacyAllowedDays = new Set(Array.from({ length: 7 }, (_, offset) => utcDayKeyDaysAgo(now, offset)))
+ const legacyAllowedDays = new Set(Array.from(
+ { length: DAILY_TOKEN_USAGE_WINDOW_DAYS },
+ (_, offset) => utcDayKeyDaysAgo(now, offset),
+ ))
const rawUsageTimeZone = raw.usageTimeZone
const rawUsageDay = raw.usageDay
const hasUsageCalendarMetadata = rawUsageTimeZone !== undefined || rawUsageDay !== undefined
@@ -97,7 +103,7 @@ export async function handleActivityFrame(
}
const allowedUsageDays = validUsageCalendar
? new Set(Array.from(
- { length: 7 },
+ { length: DAILY_TOKEN_USAGE_WINDOW_DAYS },
(_, offset) => calendarDayKeyDaysAgo(validUsageCalendar.day, offset),
))
: hasUsageCalendarMetadata
@@ -105,7 +111,7 @@ export async function handleActivityFrame(
: legacyAllowedDays
const usageParse = raw.dailyUsage === undefined
? null
- : DailyUsageSnapshotSchema.array().max(7).safeParse(raw.dailyUsage)
+ : DailyUsageSnapshotSchema.array().max(DAILY_TOKEN_USAGE_WINDOW_DAYS).safeParse(raw.dailyUsage)
const parsedUsage = usageParse?.success ? usageParse.data : undefined
const usageDays = parsedUsage ? new Set(parsedUsage.map((snapshot) => snapshot.day)) : null
const validUsage = state === "idle"
@@ -203,14 +209,14 @@ export async function handleActivityFrame(
context.env.DB,
identity.machineId,
agentId,
- calendarDayKeyDaysAgo(validUsageCalendar.day, 8),
+ calendarDayKeyDaysAgo(validUsageCalendar.day, TOKEN_USAGE_RETENTION_DAYS - 1),
))
} else if (validUsage && validUsage.length > 0) {
statements.push(prepareUsagePrune(
context.env.DB,
identity.machineId,
agentId,
- utcDayKeyDaysAgo(now, 8),
+ utcDayKeyDaysAgo(now, TOKEN_USAGE_RETENTION_DAYS - 1),
))
}
if (quota) statements.push(prepareQuotaReplace(context.env.DB, identity, quota, nowIso))