Skip to content
337 linesCodeBlameRaw
1import { ArrowUpRight, CreditCard } from "lucide-react";
2import { Link, data } from "react-router";
3
4import { MICROS_PER_DOLLAR, type UsageSlice } from "@g1t/contracts";
5
6import type { Route } from "./+types/usage";
7import { foldTasks, planStatus, usageTask } from "../../lib/billing";
8import { page } from "../../lib/meta";
9import { ButtonLink } from "../../components/ui";
10import { billing } from "../../lib/services.server";
11import { getViewer, roleIn, unwrap } from "../../lib/session.server";
12
13const PERIODS = {
14 month: "This month",
15 "7d": "Last 7 days",
16 "30d": "Last 30 days",
17 "90d": "Last 90 days",
18} as const;
19type Period = keyof typeof PERIODS;
20
21/** What each kind of agent work is called, and its colour. */
22const task = usageTask;
23
24function start(period: Period, now = new Date()): Date {
25 if (period === "month") return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
26 const days = Number(period.replace("d", ""));
27 const day = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
28 return new Date(day.getTime() - (days - 1) * 86_400_000);
29}
30
31export function meta({ params, ...args }: Route.MetaArgs) {
32 return page(args, { title: `Usage · ${params.owner} · g1t` });
33}
34
35export async function loader({ params, context, request }: Route.LoaderArgs) {
36 const viewer = getViewer(context);
37 if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 });
38 const asked = new URL(request.url).searchParams.get("period");
39 const period: Period = asked && asked in PERIODS ? (asked as Period) : "month";
40 const since = start(period);
41 const [usage, account, features, entitlements] = await Promise.all([
42 billing.usage(params.owner, viewer, since.toISOString()),
43 billing.account(params.owner, viewer),
44 billing.features(params.owner, viewer).catch(() => null),
45 billing.entitlements(params.owner).catch(() => null),
46 ]);
47 const plan = features?.ok ? (features.value.find((state) => state.plan.feature === "plan") ?? null) : null;
48 // A comped workspace is charged nothing, so it has no credit to run down.
49 const comped = planStatus(plan, entitlements).kind === "comped";
50 return { period, since: since.toISOString(), usage: unwrap(usage), account: unwrap(account), comped };
51}
52
53function dollars(micros: number, digits = 2): string {
54 return `$${(micros / MICROS_PER_DOLLAR).toFixed(digits)}`;
55}
56
57function Stat({ label, value, note }: { label: string; value: string; note?: string }) {
58 return (
59 <div className="rounded-2xl bg-surface p-5 ring-1 ring-line">
60 <p className="text-sm text-muted">{label}</p>
61 <p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums">{value}</p>
62 {note && <p className="mt-1 text-xs text-faint">{note}</p>}
63 </div>
64 );
65}
66
67/** Spend per day, stacked by kind of work. */
68function Chart({ since, slices }: { since: string; slices: UsageSlice[] }) {
69 const first = new Date(since);
70 const today = new Date();
71 const days: string[] = [];
72 for (let day = first; day <= today; day = new Date(day.getTime() + 86_400_000)) {
73 days.push(day.toISOString().slice(0, 10));
74 }
75 const byDay = new Map<string, { task: string; micros: number }[]>();
76 for (const slice of slices) {
77 const [day, kind] = slice.key.split("/");
78 byDay.set(day!, [...(byDay.get(day!) ?? []), { task: kind ?? "other", micros: slice.micros }]);
79 }
80 const totals = days.map((day) => (byDay.get(day) ?? []).reduce((sum, part) => sum + part.micros, 0));
81 const max = Math.max(...totals, 1);
82 const height = 160;
83 const width = 100 / days.length;
84 return (
85 <div>
86 <div className="relative" style={{ height }}>
87 {/* Gridlines at a quarter, a half and three quarters of the highest day. */}
88 {[0.25, 0.5, 0.75, 1].map((at) => (
89 <div key={at} className="absolute inset-x-0 border-t border-line/60" style={{ bottom: `${at * 100}%` }}>
90 <span className="absolute -top-2.5 right-0 bg-surface pl-1 font-mono text-[0.625rem] text-faint">
91 {dollars(max * at)}
92 </span>
93 </div>
94 ))}
95 <div className="absolute inset-0 flex items-end gap-px pr-12">
96 {days.map((day, index) => {
97 const parts = byDay.get(day) ?? [];
98 return (
99 <div
100 key={day}
101 className="group relative flex h-full flex-col justify-end"
102 style={{ width: `${width}%` }}
103 title={`${day}: ${dollars(totals[index]!)}`}
104 >
105 {parts.map((part) => (
106 <div
107 key={part.task}
108 className="w-full first:rounded-t-sm"
109 style={{ height: `${(part.micros / max) * 100}%`, background: task(part.task).color }}
110 />
111 ))}
112 <div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 hidden -translate-x-1/2 rounded-md bg-raised px-2 py-1 text-xs whitespace-nowrap ring-1 ring-line-strong group-hover:block">
113 <span className="text-muted">{day}</span> {dollars(totals[index]!)}
114 </div>
115 </div>
116 );
117 })}
118 </div>
119 </div>
120 <div className="mt-2 flex justify-between pr-12 font-mono text-[0.625rem] text-faint">
121 <span>{days[0]}</span>
122 <span>{days[days.length - 1]}</span>
123 </div>
124 </div>
125 );
126}
127
128function Breakdown({
129 title,
130 slices,
131 total,
132 label,
133 link,
134 color,
135}: {
136 title: string;
137 slices: UsageSlice[];
138 total: number;
139 label?: (key: string) => string;
140 link?: (key: string) => string | null;
141 color?: (key: string) => string;
142}) {
143 return (
144 <section className="rounded-2xl bg-surface p-5 ring-1 ring-line">
145 <h3 className="text-sm font-medium">{title}</h3>
146 {slices.length === 0 ? (
147 <p className="mt-4 text-sm text-faint">Nothing in this period.</p>
148 ) : (
149 <ul className="mt-4 space-y-3">
150 {slices.map((slice) => {
151 const to = link?.(slice.key);
152 const name = label ? label(slice.key) : slice.key;
153 return (
154 <li key={slice.key}>
155 <div className="flex items-baseline justify-between gap-3 text-sm">
156 <span className="min-w-0 truncate">
157 {to ? (
158 <Link to={to} className="hover:underline">
159 {name}
160 </Link>
161 ) : (
162 name
163 )}
164 </span>
165 <span className="shrink-0 font-mono text-xs tabular-nums">
166 {dollars(slice.micros)} <span className="text-faint">· {slice.runs} {slice.runs === 1 ? "run" : "runs"}</span>
167 </span>
168 </div>
169 <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-raised">
170 <div
171 className="h-full rounded-full"
172 style={{
173 width: `${total ? (slice.micros / total) * 100 : 0}%`,
174 background: color?.(slice.key) ?? "var(--color-merged)",
175 }}
176 />
177 </div>
178 </li>
179 );
180 })}
181 </ul>
182 )}
183 </section>
184 );
185}
186
187export default function UsagePage({ loaderData, params }: Route.ComponentProps) {
188 const { period, since, usage, account, comped } = loaderData;
189 const byTask = foldTasks(usage.byTask);
190 const base = `/${params.owner}`;
191 const days = Math.max(1, Math.ceil((Date.now() - new Date(since).getTime()) / 86_400_000));
192 // While g1t is free nothing is charged, so usage is measured at cost
193 // and credit is not drawn down.
194 // With a discount (100% for g1t's own), usage is shown at its price, with
195 // the discount beside it, so a workspace that pays nothing still sees
196 // what it would pay.
197 const atCost = usage.free;
198 const discount = usage.discountMicros ?? 0;
199 const atPrice = !atCost && (usage.discountPercent ?? 0) > 0;
200 const price = usage.spentMicros + (usage.coveredMicros ?? 0) + discount;
201 const total = atCost ? usage.usedMicros : atPrice ? price : usage.spentMicros;
202 const perDay = atCost ? 0 : total / days;
203 const runway = perDay > 0 ? Math.floor(account.balanceMicros / perDay) : null;
204 return (
205 <div className="space-y-8">
206 <div className="flex flex-wrap items-end justify-end gap-4">
207 <nav className="flex rounded-lg bg-surface p-1 ring-1 ring-line">
208 {(Object.keys(PERIODS) as Period[]).map((key) => (
209 <Link
210 key={key}
211 to={`?period=${key}`}
212 preventScrollReset
213 className={`rounded-md px-3 py-1.5 text-sm transition-colors ${
214 key === period ? "bg-raised text-fg" : "text-muted hover:text-fg"
215 }`}
216 >
217 {PERIODS[key]}
218 </Link>
219 ))}
220 </nav>
221 </div>
222
223 <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
224 {atCost ? (
225 <Stat label="Used" value={dollars(total)} note="At cost. Nothing is charged while g1t is being built out." />
226 ) : atPrice ? (
227 <Stat
228 label="Usage at price"
229 value={dollars(price)}
230 note={`Discount (${usage.discountPercent}%) −${dollars(discount)}; charged ${dollars(usage.spentMicros)}`}
231 />
232 ) : (
233 <Stat
234 label="Spent"
235 value={dollars(usage.spentMicros)}
236 note={
237 (usage.coveredMicros ?? 0) > 0
238 ? `Of ${dollars(usage.spentMicros + (usage.coveredMicros ?? 0))} at price: ${dollars(usage.coveredMicros ?? 0)} of it was not charged (the included usage, the trial, a pool, or a free period)`
239 : usage.providerMicros > 0
240 ? `Plus about ${dollars(usage.providerMicros)} billed by your own model provider`
241 : `${dollars(usage.costMicros)} of it the model provider's`
242 }
243 />
244 )}
245 <Stat label="Agent runs" value={String(usage.runs)} note={PERIODS[period]} />
246 <Stat
247 label="Average run"
248 value={usage.runs ? dollars(total / usage.runs, 3) : "—"}
249 note="Making a change, reviewing, revising…"
250 />
251 {comped ? (
252 // A 100% discount charges nothing: no credit to run down.
253 <div className="rounded-2xl bg-surface p-5 ring-1 ring-line">
254 <p className="text-sm text-muted">Discount</p>
255 <p className="mt-2 text-3xl font-semibold tracking-tight text-accent">100%</p>
256 <p className="mt-1 text-xs text-faint">Usage is shown at its price; g1t takes all of it off, so nothing is charged.</p>
257 </div>
258 ) : (
259 <div className="rounded-2xl bg-surface p-5 ring-1 ring-line">
260 <p className="flex items-center justify-between text-sm text-muted">
261 Credit left
262 {!usage.free && (
263 <Link to={`${base}/-/billing`} className="text-xs text-accent hover:underline">
264 Add credit
265 </Link>
266 )}
267 </p>
268 <p className={`mt-2 text-3xl font-semibold tracking-tight tabular-nums ${account.balanceMicros <= 0 ? "text-warn" : ""}`}>
269 {dollars(account.balanceMicros)}
270 </p>
271 <p className="mt-1 text-xs text-faint">
272 {usage.free
273 ? "Not drawn down while g1t is free."
274 : runway == null
275 ? "Nothing spent in this period."
276 : `About ${runway} ${runway === 1 ? "day" : "days"} at this rate.`}
277 </p>
278 </div>
279 )}
280 </div>
281
282 <section className="rounded-2xl bg-surface p-5 ring-1 ring-line">
283 <div className="flex flex-wrap items-baseline justify-between gap-3">
284 <h3 className="text-sm font-medium">{atCost ? "Usage per day" : "Spend per day"}</h3>
285 <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
286 {byTask.map((slice) => (
287 <li key={slice.key} className="flex items-center gap-1.5">
288 <span className="size-2 rounded-sm" style={{ background: task(slice.key).color }} />
289 {task(slice.key).label}
290 </li>
291 ))}
292 </ul>
293 </div>
294 <div className="mt-6">
295 <Chart since={since} slices={usage.byDay} />
296 </div>
297 </section>
298
299 <div className="grid gap-4 lg:grid-cols-2">
300 <Breakdown
301 title="By kind of work"
302 slices={byTask}
303 total={total}
304 label={(key) => task(key).label}
305 color={(key) => task(key).color}
306 />
307 <Breakdown title="By repository" slices={usage.byRepo} total={total} link={(key) => `/${key}`} />
308 <Breakdown
309 title="Pull requests that cost most"
310 slices={usage.byPull}
311 total={usage.byPull[0]?.micros ?? 0}
312 // Planning runs belong to a repository, not a pull request.
313 label={(key) => (key.endsWith("#0") ? `${key.slice(0, -2)} · planning` : key)}
314 link={(key) => {
315 const [repo, number] = key.split("#");
316 if (!repo) return null;
317 return number && number !== "0" ? `/${repo}/pull/${number}` : `/${repo}/plans`;
318 }}
319 />
320 <Breakdown title="By model" slices={usage.byModel} total={total} color={() => "var(--color-info)"} />
321 </div>
322
323 <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-surface px-5 py-4 text-sm ring-1 ring-line">
324 <span className="flex items-center gap-2 text-muted">
325 <CreditCard size={15} />
326 {usage.addedMicros > 0
327 ? `${dollars(usage.addedMicros)} of credit added in this period.`
328 : "Every charge and payment is on the workspace's statement."}
329 </span>
330 <ButtonLink to={`${base}/-/billing`} variant="quiet">
331 Statement and credit
332 <ArrowUpRight size={14} />
333 </ButtonLink>
334 </div>
335 </div>
336 );
337}