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

300 lines12,118 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1import { 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 const perDay = usage.spentMicros / days;
193 const runway = perDay > 0 ? Math.floor(account.balanceMicros / perDay) : null;
194 return (
195 <div className="space-y-8">
A catalogue of model providers, and settings that feel like settings196 <div className="flex flex-wrap items-end justify-end gap-4">
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request197 <nav className="flex rounded-lg bg-surface p-1 ring-1 ring-line">
198 {(Object.keys(PERIODS) as Period[]).map((key) => (
199 <Link
200 key={key}
201 to={`?period=${key}`}
202 preventScrollReset
203 className={`rounded-md px-3 py-1.5 text-sm transition-colors ${
204 key === period ? "bg-raised text-fg" : "text-muted hover:text-fg"
205 }`}
206 >
207 {PERIODS[key]}
208 </Link>
209 ))}
210 </nav>
211 </div>
212
213 <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
Integrations: your own model provider, alerts that open issues, tickets agents read214 <Stat
215 label="Spent"
216 value={dollars(usage.spentMicros)}
217 note={
218 usage.providerMicros > 0
219 ? `Plus about ${dollars(usage.providerMicros)} billed by your own model provider`
220 : `${dollars(usage.costMicros)} of it the model provider's`
221 }
222 />
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request223 <Stat label="Agent runs" value={String(usage.runs)} note={PERIODS[period]} />
224 <Stat
225 label="Average run"
226 value={usage.runs ? dollars(usage.spentMicros / usage.runs, 3) : "—"}
227 note="Making a change, reviewing, revising…"
228 />
229 <div className="rounded-2xl bg-surface p-5 ring-1 ring-line">
230 <p className="flex items-center justify-between text-sm text-muted">
231 Credit left
232 <Link to={`${base}/-/billing`} className="text-xs text-accent hover:underline">
233 Add credit
234 </Link>
235 </p>
236 <p className={`mt-2 text-3xl font-semibold tracking-tight tabular-nums ${account.balanceMicros <= 0 ? "text-warn" : ""}`}>
237 {dollars(account.balanceMicros)}
238 </p>
239 <p className="mt-1 text-xs text-faint">
240 {runway == null ? "Nothing spent in this period." : `About ${runway} ${runway === 1 ? "day" : "days"} at this rate.`}
241 </p>
242 </div>
243 </div>
244
245 <section className="rounded-2xl bg-surface p-5 ring-1 ring-line">
246 <div className="flex flex-wrap items-baseline justify-between gap-3">
247 <h3 className="text-sm font-medium">Spend per day</h3>
248 <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
249 {usage.byTask.map((slice) => (
250 <li key={slice.key} className="flex items-center gap-1.5">
251 <span className="size-2 rounded-sm" style={{ background: task(slice.key).color }} />
252 {task(slice.key).label}
253 </li>
254 ))}
255 </ul>
256 </div>
257 <div className="mt-6">
258 <Chart since={since} slices={usage.byDay} />
259 </div>
260 </section>
261
262 <div className="grid gap-4 lg:grid-cols-2">
263 <Breakdown
264 title="By kind of work"
265 slices={usage.byTask}
266 total={usage.spentMicros}
267 label={(key) => task(key).label}
268 color={(key) => task(key).color}
269 />
270 <Breakdown title="By repository" slices={usage.byRepo} total={usage.spentMicros} link={(key) => `/${key}`} />
271 <Breakdown
272 title="Pull requests that cost most"
273 slices={usage.byPull}
274 total={usage.byPull[0]?.micros ?? 0}
275 // Planning runs belong to a repository, not a pull request.
276 label={(key) => (key.endsWith("#0") ? `${key.slice(0, -2)} · planning` : key)}
277 link={(key) => {
278 const [repo, number] = key.split("#");
279 if (!repo) return null;
280 return number && number !== "0" ? `/${repo}/pull/${number}` : `/${repo}/plans`;
281 }}
282 />
283 <Breakdown title="By model" slices={usage.byModel} total={usage.spentMicros} color={() => "var(--color-info)"} />
284 </div>
285
286 <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">
287 <span className="flex items-center gap-2 text-muted">
288 <CreditCard size={15} />
289 {usage.addedMicros > 0
290 ? `${dollars(usage.addedMicros)} of credit added in this period.`
291 : "Every charge and payment is on the workspace's statement."}
292 </span>
293 <ButtonLink to={`${base}/-/billing`} variant="quiet">
294 Statement and credit
295 <ArrowUpRight size={14} />
296 </ButtonLink>
297 </div>
298 </div>
299 );
300}