Merge origin/master and renumber additive Speko migrations

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 15:45:59 -05:00
commit bf1ead3772
65 files changed
+5336 -56682

No files matched your search

+86 -2
View File
@@ -28,6 +28,8 @@ const costsApiMocks = vi.hoisted(() => ({
windowSpend: vi.fn(),
quotaWindows: vi.fn(),
}));
const subscriptionsMocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), update: vi.fn(), link: vi.fn() }));
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: subscriptionsMocks }));
vi.mock("../api/budgets", () => ({
budgetsApi: {
@@ -63,6 +65,8 @@ describe("Shared Costs surfaces", () => {
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
const usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
subscriptionsMocks.report.mockResolvedValue({ canRefresh: false, asOf: "2026-10-08T00:00:00Z", accounts: [], monthlyTotals: [], activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0, api: usage, subscription: usage, unknown: usage, unattributedSubscription: usage });
decisionHistoryMock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
container = document.createElement("div");
@@ -92,6 +96,24 @@ describe("Shared Costs surfaces", () => {
expect(container.textContent).toContain("1 unpriced charge");
});
it.each(surfaces)("labels other and unknown billing accurately on the %s surface", async (_name, props) => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true });
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
const report = await subscriptionsMocks.report();
subscriptionsMocks.report.mockResolvedValue({ ...report, unknown: { ...report.unknown,
inputTokens: 100, cachedInputTokens: 40, outputTokens: 10, costCents: "600", eventCount: 3,
} });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(container);
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));
await act(async () => vi.waitFor(() => expect(container.textContent).toContain(
"150 tokens have other or unknown billing types, with $6.00 in recorded charges. They remain in the inference ledger.",
)));
expect(container.textContent).not.toContain("tokens have an unknown billing type");
});
it("renders a focused Budgets section without duplicate Costs chrome or spend queries", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(container);
@@ -212,6 +234,56 @@ describe("Shared Costs surfaces", () => {
queryClient.clear();
});
it("retries failed account discovery without discarding the last subscription report", async () => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
costsApiMocks.summary.mockResolvedValue({ spendCents: 0, budgetCents: 0, pricingComplete: true });
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
const report = await subscriptionsMocks.report();
subscriptionsMocks.report.mockResolvedValue({ ...report, canRefresh: true, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }] });
subscriptionsMocks.refresh.mockRejectedValueOnce(new Error("private connection error")).mockResolvedValue({});
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(container);
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
const retry = () => [...container.querySelectorAll("button")].find(button => button.textContent === "Retry account check");
await act(async () => { await vi.waitFor(() => expect(retry()).toBeDefined()); });
expect(container.textContent).toContain("$20.00/month");
expect(container.textContent).not.toContain("private connection error");
await act(async () => retry()!.click());
await act(async () => { await vi.waitFor(() => expect(retry()).toBeUndefined()); });
expect(subscriptionsMocks.refresh).toHaveBeenCalledTimes(2);
expect(subscriptionsMocks.refresh).toHaveBeenLastCalledWith("company-1");
expect(container.textContent).toContain("$20.00/month");
queryClient.clear();
});
it("keeps monthly subscription fees through date changes and failed background reloads", async () => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 0, pricingComplete: true });
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
const report = await subscriptionsMocks.report();
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "200" } });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(container);
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
const card = (label: string) => [...container.querySelectorAll("div")].find(node => node.textContent === label)?.closest('[data-slot="card"]');
await act(async () => { await vi.waitFor(() => expect(card("Subscriptions")?.textContent).toContain("$20.00/month")); });
expect(card("API spend")?.textContent).toContain("$2.00");
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "300" } });
await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "All Time")!.click());
await act(async () => { await vi.waitFor(() => expect(card("API spend")?.textContent).toContain("$3.00")); });
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
expect(subscriptionsMocks.report).toHaveBeenLastCalledWith("company-1", undefined, undefined);
subscriptionsMocks.report.mockRejectedValue(new Error("private provider failure"));
await act(async () => { await queryClient.invalidateQueries({ queryKey: ["cost-subscriptions"] }); });
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("Showing the last loaded API and subscription usage")); });
expect(card("API spend")?.textContent).toContain("$3.00");
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
expect(container.textContent).not.toContain("private provider failure");
queryClient.clear();
});
it("compares monthly budgets only with month-to-date spend", async () => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
@@ -224,6 +296,8 @@ describe("Shared Costs surfaces", () => {
await act(async () => { await vi.waitFor(() => expect(budgetCard()?.textContent).toContain("20%")); });
expect(budgetCard()?.textContent).toContain("$2.00 of $10.00 this month");
costsApiMocks.summary.mockResolvedValue({ spendCents: 12000, budgetCents: 1000, utilizationPercent: 1200, pricingComplete: true });
const subscriptionReport = await subscriptionsMocks.report();
subscriptionsMocks.report.mockResolvedValue({ ...subscriptionReport, api: { ...subscriptionReport.api, costCents: "12000" } });
await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "All Time")!.click());
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("$120.00")); });
expect(budgetCard()?.textContent).toContain("$10.00");
@@ -281,7 +355,7 @@ describe("Shared Costs surfaces", () => {
expect(notice.querySelector(".text-destructive")).toBeNull();
expect(notice.classList.contains("text-destructive")).toBe(false);
expect(notice.textContent).toContain("1 run is awaiting cost data.");
expect(notice.previousElementSibling?.textContent).toContain("Inference spend");
expect(notice.previousElementSibling?.textContent).toContain("API spend");
expect(container.textContent).toContain("Finance headline totals are USD only");
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 10, pendingRunCount: 0 });
await act(async () => { await queryClient.invalidateQueries(); });
@@ -296,12 +370,17 @@ describe("Shared Costs surfaces", () => {
await vi.waitFor(() => expect(container.contains(notice)).toBe(false));
});
it.each(surfaces)("labels each agent and expanded model independently on the %s page", async (_name, props) => {
it.each(surfaces)("labels each agent, project, and expanded model independently on the %s page", async (_name, props) => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true, estimatedEventCount: 3 });
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
const base = { costCents: 200, inputTokens: 10, cachedInputTokens: 5, outputTokens: 2, apiRunCount: 2, subscriptionRunCount: 0, eventCount: 2 };
costsApiMocks.byProject.mockResolvedValue([
{ ...base, projectId: "estimated-project", projectName: "Estimated project", estimatedEventCount: 2 },
{ ...base, projectId: "mixed-project", projectName: "Mixed project", estimatedEventCount: 1 },
{ ...base, projectId: "reported-project", projectName: "Reported project", estimatedEventCount: 0 },
]);
costsApiMocks.byAgent.mockResolvedValue([
{ ...base, agentId: "codie", agentName: "Codie", estimatedEventCount: 2 },
{ ...base, agentId: "mixed", agentName: "Mixed", estimatedEventCount: 1 },
@@ -326,6 +405,11 @@ describe("Shared Costs surfaces", () => {
expect(card("Mixed").textContent).toContain("Partially estimated");
expect(card("Reported").textContent).not.toMatch(/Estimated|Partially estimated/);
expect(card("Legacy").textContent).not.toMatch(/Estimated|Partially estimated/);
const projectBadge = (name: string) => [...container.querySelectorAll("span")]
.find(element => element.textContent === name)!.parentElement!.querySelector('[data-slot="badge"]');
expect(projectBadge("Estimated project")?.textContent).toBe("Estimated");
expect(projectBadge("Mixed project")?.textContent).toBe("Partially estimated");
expect(projectBadge("Reported project")).toBeNull();
await act(async () => card("Mixed").querySelector<HTMLElement>(".cursor-pointer")!.click());
const breakdown = card("Mixed").querySelector(".border-l")!;
expect(breakdown.textContent).toContain("gpt-6-astra");
+54 -30
View File
@@ -1,6 +1,9 @@
import { DecisionHistory } from "../components/decision-models/DecisionHistory";
import { SubscriptionCostCard, SubscriptionTokenUsage } from "../components/SubscriptionCostCard";
import { subscriptionsApi } from "../api/subscriptions";
import { useSearchParams } from "@/lib/router";
import { CostEstimateLabel } from "../components/CostEstimateLabel";
import { CostAmount } from "../components/CostAmount";
import { CostByUserTable } from "../components/CostByUserTable";
import { AgentIdentity } from "@/components/AgentIdentity";
import { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
@@ -228,6 +231,23 @@ export function Costs({
const reportQueryFrom = ["custom", "mtd", "ytd"].includes(preset) ? from || undefined : undefined;
const reportQueryTo = preset === "custom" ? to || undefined : preset;
const subscriptionKey = ["cost-subscriptions", companyId, reportQueryFrom, reportQueryTo];
const { data: subscriptions, error: subscriptionError } = useQuery({
queryKey: subscriptionKey,
queryFn: () => subscriptionsApi.report(companyId, from || undefined, to || undefined),
enabled: !!selectedCompanyId && customReady && showSummaryChrome,
refetchInterval: 30_000,
});
const invalidateSubscriptions = () => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", companyId] }); };
const discoveryCompany = useRef<string | null>(null);
const discoverSubscriptions = useMutation({ mutationFn: (id: string) => subscriptionsApi.refresh(id),
onSuccess: (_data, id) => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", id] }); } });
useEffect(() => {
if (!selectedCompanyId || !showSummaryChrome || !subscriptions?.canRefresh || discoveryCompany.current === selectedCompanyId) return;
discoveryCompany.current = selectedCompanyId;
discoverSubscriptions.mutate(selectedCompanyId);
}, [selectedCompanyId, showSummaryChrome, subscriptions?.canRefresh, discoverSubscriptions.mutate]);
const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({
queryKey: queryKeys.budgets.overview(companyId),
queryFn: () => budgetsApi.overview(companyId),
@@ -558,12 +578,6 @@ export function Costs({
];
}, [byBiller]);
const inferenceTokenTotal =
(spendData?.byAgent ?? []).reduce(
(sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens,
0,
);
const topFinanceEvents = (financeData?.events ?? []) as FinanceEvent[];
const budgetPolicies = budgetData?.policies ?? [];
const activeBudgetIncidents = budgetData?.activeIncidents ?? [];
@@ -631,13 +645,17 @@ export function Costs({
Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied.
</p>
)}
<div className="grid gap-3 lg:grid-cols-4">
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<MetricTile
label="Inference spend"
value={spendData ? formatCents(spendData.summary.spendCents) : "—"}
subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}
label="API spend"
value={subscriptions ? subscriptions.api.unpricedEventCount === subscriptions.api.eventCount && subscriptions.api.eventCount > 0 ? "—" : formatCents(Number(subscriptions.api.costCents)) : "—"}
subtitle={subscriptions ? <div className="space-y-1">
<CostEstimateLabel eventCount={subscriptions.api.eventCount} estimatedEventCount={subscriptions.api.estimatedEventCount} />
<div><SubscriptionTokenUsage usage={subscriptions.api} /></div>
</div> : subscriptionError ? "API usage is unavailable" : "API usage is loading"}
icon={DollarSign}
/>
<SubscriptionCostCard key={companyId} companyId={companyId} report={subscriptions} error={subscriptionError} onChanged={invalidateSubscriptions} />
<MetricTile
label="Budget"
value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (
@@ -672,6 +690,14 @@ export function Costs({
icon={ArrowUpRight}
/>
</div>
{subscriptions && Number(subscriptions.subscription.costCents) > 0 && <p className="text-sm text-muted-foreground">Subscription accounts also have {formatCents(Number(subscriptions.subscription.costCents))} in recorded usage charges for this period, separate from monthly fees.</p>}
{subscriptions && subscriptions.unknown.eventCount > 0 && <p className="text-sm text-muted-foreground">{formatTokens(subscriptions.unknown.inputTokens + subscriptions.unknown.cachedInputTokens + subscriptions.unknown.outputTokens)} tokens have other or unknown billing types{Number(subscriptions.unknown.costCents) > 0 ? `, with ${formatCents(Number(subscriptions.unknown.costCents))} in recorded charges` : ""}. They remain in the inference ledger.</p>}
{subscriptionError && subscriptions && <p role="status" className="text-sm text-muted-foreground">Showing the last loaded API and subscription usage. Updates will resume automatically.</p>}
{discoverSubscriptions.error && <div role="status" className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<p>Connected accounts could not be checked. Existing subscription estimates are still shown.</p>
{subscriptions?.canRefresh && <Button variant="outline" size="sm" disabled={discoverSubscriptions.isPending}
onClick={() => discoverSubscriptions.mutate(companyId)}>Retry account check</Button>}
</div>}
{spendData?.summary.pricingComplete === false && (
<div role="status" className="space-y-1 text-sm text-muted-foreground">
{spendData.summary.unpricedEventCount > 0 && (
@@ -704,14 +730,16 @@ export function Costs({
{incidentMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again.</p>}
<Tabs value={mainTab} onValueChange={(value) => { setMainTab(value as typeof mainTab); setSearchParams(current => { const next = new URLSearchParams(current); next.set("tab", value); return next; }, { replace: true }); }}>
{!lockTab ? (
<TabsList variant="line" className="justify-start">
<TabsTrigger value="overview">Overview</TabsTrigger>
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
<TabsTrigger value="providers">Providers</TabsTrigger>
<TabsTrigger value="billers">Billers</TabsTrigger>
<TabsTrigger value="finance">Finance</TabsTrigger>
<TabsTrigger value="decisions">Decisions</TabsTrigger>
</TabsList>
<div className="max-w-full overflow-x-auto pb-2">
<TabsList variant="line" className="justify-start">
<TabsTrigger value="overview">Overview</TabsTrigger>
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
<TabsTrigger value="providers">Providers</TabsTrigger>
<TabsTrigger value="billers">Billers</TabsTrigger>
<TabsTrigger value="finance">Finance</TabsTrigger>
<TabsTrigger value="decisions">Decisions</TabsTrigger>
</TabsList>
</div>
) : null}
<TabsContent value="decisions" className="mt-4">{showCustomPrompt ? <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p> : <DecisionHistory companyId={companyId} from={from} to={to} />}</TabsContent>
@@ -756,10 +784,7 @@ export function Costs({
{row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}
</div>
<div className="text-right text-sm tabular-nums">
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
<span>{formatCents(row.costCents)}</span>
<CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
</div>
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
<div className="text-xs text-muted-foreground">
in {formatTokens(row.inputTokens + row.cachedInputTokens)} ({formatTokens(row.cachedInputTokens)} cached) · out {formatTokens(row.outputTokens)}
</div>
@@ -796,13 +821,12 @@ export function Costs({
</div>
</div>
<div className="text-right tabular-nums">
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
<span>
{formatCents(modelRow.costCents)}
<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>
</span>
<CostEstimateLabel eventCount={modelRow.eventCount} estimatedEventCount={modelRow.estimatedEventCount} />
</div>
<CostAmount
costCents={modelRow.costCents}
eventCount={modelRow.eventCount}
estimatedEventCount={modelRow.estimatedEventCount}
suffix={<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>}
/>
<div className="text-muted-foreground">
{formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok
</div>
@@ -841,7 +865,7 @@ export function Costs({
className="flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm"
>
<span className="truncate">{row.projectName ?? row.projectId ?? "Unattributed"}</span>
<span className="font-medium tabular-nums">{formatCents(row.costCents)}</span>
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
</div>
))
)}