Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion site/src/components/DateRangePicker/DateRangePicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ type DateRangePickerProps = {
* rounded up to the next hour (if it falls on today) or to the start of
* the following day.
*/
function toBoundary(from: Date, to: Date, now: Date): DateRangeValue {
export function toBoundary(from: Date, to: Date, now: Date): DateRangeValue {
const currentTime = dayjs(now);
const start = dayjs(from).startOf("day").toDate();
const end = dayjs(to).isSame(currentTime, "day")
Expand Down
128 changes: 128 additions & 0 deletions site/src/pages/AISettingsPage/SpendPage/SpendPage.period.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { afterAll, beforeAll, expect, it, vi } from "vitest";
import { appliedWindowToDateRange, firstDayWithinRetention } from "./SpendPage";

// Local days run ahead of the UTC calendar the server uses in a
// positive-offset zone, which is where the retention mapping has its edges.
beforeAll(() => {
vi.stubEnv("TZ", "Asia/Tokyo");
});

afterAll(() => {
vi.unstubAllEnvs();
});

// Noon on March 12 in Asia/Tokyo.
const now = new Date("2026-03-12T03:00:00Z");

const clampedToRetention = (cutoff: Date, period_end: string) => ({
period_start: cutoff.toISOString(),
period_end,
retention_start: cutoff.toISOString(),
});

it("maps a UTC budget period onto the same local calendar days", () => {
expect(
appliedWindowToDateRange(
{
period_start: "2026-03-01T00:00:00Z",
period_end: "2026-04-01T00:00:00Z",
},
now,
),
).toEqual({
startDate: new Date(2026, 2, 1),
endDate: new Date(2026, 3, 1),
});
});

it("starts at the first local midnight after a mid-day retention cutoff", () => {
expect(
appliedWindowToDateRange(
clampedToRetention(
new Date("2026-02-14T15:32:10Z"),
"2026-03-01T00:00:00Z",
),
now,
),
).toEqual({
startDate: new Date(2026, 1, 16),
endDate: new Date(2026, 2, 1),
});
});

it("treats a retention cutoff at UTC midnight as a cutoff", () => {
expect(
appliedWindowToDateRange(
clampedToRetention(
new Date("2026-02-15T00:00:00Z"),
"2026-03-01T00:00:00Z",
),
now,
),
).toMatchObject({ startDate: new Date(2026, 1, 16) });
});

it("keeps a budget start whose local midnight precedes the cutoff inside retention", () => {
expect(
appliedWindowToDateRange(
{
period_start: "2026-02-01T00:00:00Z",
period_end: "2026-03-01T00:00:00Z",
retention_start: "2026-01-31T23:30:00Z",
},
now,
),
).toMatchObject({ startDate: new Date(2026, 1, 2) });
});

it("shows the first selectable day when no whole day of the window remains", () => {
// 08:30 on April 1 in Asia/Tokyo, still March 31 in UTC, with the cutoff
// at 23:00 the evening before.
const lateNow = new Date("2026-03-31T23:30:00Z");
expect(
appliedWindowToDateRange(
clampedToRetention(
new Date("2026-03-31T14:00:00Z"),
"2026-04-01T00:00:00Z",
),
lateNow,
),
).toEqual({
startDate: new Date(2026, 3, 1),
endDate: new Date(2026, 3, 1, 9),
});
});

it("offers no range when retention is shorter than a day", () => {
const cutoff = new Date(now.getTime() - 60 * 60 * 1000);
expect(
appliedWindowToDateRange(
clampedToRetention(cutoff, "2026-04-01T00:00:00Z"),
now,
),
).toBeUndefined();
});

it("offers no range while the period's first local day is still tomorrow", () => {
// 19:00 on September 30 in America/Los_Angeles, already October 1 in UTC,
// so the server has moved on to the October budget period.
vi.stubEnv("TZ", "America/Los_Angeles");
expect(
appliedWindowToDateRange(
{
period_start: "2026-10-01T00:00:00Z",
period_end: "2026-11-01T00:00:00Z",
},
new Date("2026-10-01T02:00:00Z"),
),
).toBeUndefined();
vi.stubEnv("TZ", "Asia/Tokyo");
});

it("bounds the picker at the first local midnight after the retention cutoff", () => {
const cutoff = new Date(2026, 1, 14, 15, 32, 10);
expect(firstDayWithinRetention(cutoff)).toEqual(new Date(2026, 1, 15));
expect(firstDayWithinRetention(new Date(2026, 1, 14))).toEqual(
new Date(2026, 1, 14),
);
});
151 changes: 151 additions & 0 deletions site/src/pages/AISettingsPage/SpendPage/SpendPage.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import dayjs from "dayjs";
import { screen, spyOn, userEvent, within } from "storybook/test";
import { reactRouterParameters } from "storybook-addon-remix-react-router";
import { API } from "#/api/api";
import type { OrganizationAISpendUser } from "#/api/typesGenerated";
import {
MockOrganization,
MockOrganization2,
MockOrganizationAISpendReport,
MockOrganizationAISpendUser,
MockUserMember,
} from "#/testHelpers/entities";
import {
withAuthProvider,
withDashboardProvider,
} from "#/testHelpers/storybook";
import SpendPage from "./SpendPage";

const fixedNow = dayjs("2026-03-12T12:00:00Z");
// Mix single and collapsed badges across both pages.
const mockSpendUsers: OrganizationAISpendUser[] = Array.from(
{ length: 12 },
(_, i) => ({
...MockOrganizationAISpendUser,
user_id: `user-${i + 1}`,
username: `user${String(i + 1).padStart(2, "0")}`,
name: `User ${i + 1}`,
cost_micros: (12 - i) * 1_000_000,
providers: i % 3 === 0 ? ["anthropic", "openai"] : ["anthropic"],
clients: i % 2 === 1 ? ["Claude Code", "Cursor"] : ["Claude Code"],
models: i % 3 === 0 ? ["claude-opus-4-6", "gpt-5.4"] : ["claude-opus-4-6"],
}),
);

const routing = { path: "/ai/settings/spend", useStoryElement: true };

// Story parameters deep-merge into the meta's, so a story cannot drop a range
// the meta sets.
const explicitRange = reactRouterParameters({
location: {
path: "/ai/settings/spend",
searchParams: {
startDate: "2026-02-10T00:00:00.000Z",
endDate: "2026-03-12T00:00:00.000Z",
},
},
routing,
});

const meta = {
title: "pages/AISettingsPage/SpendPage/SpendPage",
component: SpendPage,
decorators: [withAuthProvider, withDashboardProvider],
args: { now: fixedNow.toDate() },
parameters: {
user: MockUserMember,
features: ["aibridge"],
reactRouter: reactRouterParameters({
location: { path: "/ai/settings/spend" },
routing,
}),
},
beforeEach: () => {
spyOn(API, "getOrganizations").mockResolvedValue([
MockOrganization,
MockOrganization2,
]);
spyOn(API, "checkAuthorization").mockResolvedValue({
[MockOrganization.id]: true,
[MockOrganization2.id]: true,
});
spyOn(API, "getOrganizationAISpendUsers").mockImplementation(
async (_organizationId, params) => ({
...MockOrganizationAISpendReport,
period_start: params.period_start ?? "2026-03-01T00:00:00.000Z",
period_end: params.period_end ?? "2026-04-01T00:00:00.000Z",
count: mockSpendUsers.length,
totals: { cost_micros: 78_000_000, unpriced_usage_count: 0 },
users: mockSpendUsers.slice(
params.offset ?? 0,
(params.offset ?? 0) + (params.limit ?? 10),
),
}),
);
},
} satisfies Meta<typeof SpendPage>;
export default meta;
type Story = StoryObj<typeof SpendPage>;

export const FirstPage: Story = {
parameters: { reactRouter: explicitRange },
play: async ({ canvasElement }) => {
await within(canvasElement).findByRole("table", { name: "Spend by user" });
},
};

export const BudgetPeriod: Story = {
play: async ({ canvasElement }) => {
await within(canvasElement).findByRole("table", { name: "Spend by user" });
},
};

// Without a URL range the server narrows the budget period to retention, and
// the endpoint rejects any explicit start before that cutoff.
export const RetentionLimitedPicker: Story = {
beforeEach: () => {
const retentionStart = fixedNow.subtract(10, "day").toISOString();
spyOn(API, "getOrganizationAISpendUsers").mockResolvedValue({
...MockOrganizationAISpendReport,
period_start: retentionStart,
period_end: "2026-04-01T00:00:00.000Z",
retention_start: retentionStart,
count: mockSpendUsers.length,
users: mockSpendUsers.slice(0, 10),
});
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByRole("table", { name: "Spend by user" });
await userEvent.click(canvas.getByRole("button", { name: /Mar 3, 2026/ }));
await screen.findByRole("button", { name: "Apply" });
},
};

// Less than a day of retention leaves no whole day for the picker to select,
// so the report keeps the server's default window and the picker stays off.
export const SubDayRetention: Story = {
beforeEach: () => {
spyOn(API, "getOrganizationAISpendUsers").mockResolvedValue({
...MockOrganizationAISpendReport,
period_start: fixedNow.subtract(1, "hour").toISOString(),
period_end: fixedNow.add(1, "hour").startOf("hour").toISOString(),
retention_start: fixedNow.subtract(1, "hour").toISOString(),
count: mockSpendUsers.length,
users: mockSpendUsers.slice(0, 10),
});
},
play: async ({ canvasElement }) => {
await within(canvasElement).findByRole("table", { name: "Spend by user" });
},
};

export const SecondPage: Story = {
parameters: { reactRouter: explicitRange },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await canvas.findByRole("table", { name: "Spend by user" });
await userEvent.click(canvas.getByRole("button", { name: "Next page" }));
},
};
Loading
Loading