flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/web/app/routes/workspace/usage.tsx

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