g1t/apps/web/app/components/agents.tsx

495 lines19,690 bytesCodeBlame
1/**
2 * Agents at work, wherever they show: the project's Agents page, the
3 * workspace's fleet, a pull request's Agent panel and the pull request
4 * list. Stopping and messaging a run go through the project's
5 * `agents.json` resource route, so every place behaves the same.
6 */
7import { Bot, CircleSlash, Clock, Coins, Gauge, Loader2, MessageSquare, OctagonX, Square, TriangleAlert } from "lucide-react";
8import { type ReactNode, useEffect, useMemo, useState } from "react";
9import { Link, useFetcher, useRevalidator } from "react-router";
10
11import {
12 type AgentRun,
13 type AgentRunStatus,
14 type Confidence,
15 type RunKind,
16 RUN_KIND_LABEL,
17 type Stage,
18 isActiveRun,
19 isAgentKind,
20 takesMessages,
21} from "@g1t/contracts";
22
23import { RunAudit } from "./audit";
24import { STAGE_LABEL, StageDots } from "./lifecycle";
25import { Avatar, TimeAgo } from "./ui";
26import {
27 AlertDialog,
28 AlertDialogAction,
29 AlertDialogCancel,
30 AlertDialogContent,
31 AlertDialogDescription,
32 AlertDialogFooter,
33 AlertDialogHeader,
34 AlertDialogTitle,
35 AlertDialogTrigger,
36} from "./ui/alert-dialog";
37import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
38
39/** How often a page with something running asks again. */
40export const LIVE_MS = 4000;
41
42/** Revalidates the page every few seconds while `live`, as the merge queue does. */
43export function useLiveRefresh(live: boolean) {
44 const revalidator = useRevalidator();
45 useEffect(() => {
46 if (!live) return;
47 const timer = setInterval(() => {
48 if (document.visibilityState === "visible" && revalidator.state === "idle") revalidator.revalidate();
49 }, LIVE_MS);
50 return () => clearInterval(timer);
51 }, [live, revalidator]);
52}
53
54export function formatCost(usd: number | null | undefined): string | null {
55 if (usd == null) return null;
56 if (usd > 0 && usd < 0.01) return "<$0.01";
57 return `$${usd.toFixed(2)}`;
58}
59
60function span(ms: number): string {
61 const seconds = Math.max(0, Math.floor(ms / 1000));
62 const hours = Math.floor(seconds / 3600);
63 const minutes = Math.floor((seconds % 3600) / 60);
64 if (hours > 0) return `${hours}h ${minutes}m`;
65 if (minutes > 0) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
66 return `${seconds}s`;
67}
68
69/** How long a run has gone on, ticking while it runs. */
70export function Elapsed({ from, to }: { from: string; to?: string | null }) {
71 const [now, setNow] = useState(() => Date.now());
72 useEffect(() => {
73 if (to) return;
74 const timer = setInterval(() => setNow(Date.now()), 1000);
75 return () => clearInterval(timer);
76 }, [to]);
77 const end = to ? new Date(to).getTime() : now;
78 return (
79 <span suppressHydrationWarning className="tabular-nums">
80 {span(end - new Date(from).getTime())}
81 </span>
82 );
83}
84
85const STATUS: Record<AgentRunStatus, { label: string; tone: string; icon: ReactNode }> = {
86 queued: { label: "Starting", tone: "text-muted border-line", icon: <Clock size={12} /> },
87 running: {
88 label: "Running",
89 tone: "text-merged border-merged/40 bg-merged/10",
90 icon: <Loader2 size={12} className="animate-spin" />,
91 },
92 succeeded: { label: "Done", tone: "text-accent border-accent/40 bg-accent/10", icon: <Bot size={12} /> },
93 failed: { label: "Failed", tone: "text-danger border-danger/40 bg-danger/10", icon: <TriangleAlert size={12} /> },
94 stopped: { label: "Stopped", tone: "text-warn border-warn/40 bg-warn/10", icon: <OctagonX size={12} /> },
95};
96
97export function RunStatusBadge({ status }: { status: AgentRunStatus }) {
98 const { label, tone, icon } = STATUS[status];
99 return (
100 <span className={`inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs ${tone}`}>
101 {icon}
102 {label}
103 </span>
104 );
105}
106
107export function KindLabel({ kind }: { kind: RunKind }) {
108 return (
109 <span className="rounded border border-line px-1.5 py-px font-mono text-[0.6875rem] text-muted">
110 {RUN_KIND_LABEL[kind].toLowerCase()}
111 </span>
112 );
113}
114
115/** Where a project's agent actions are posted. */
116function actionUrl(run: AgentRun): string {
117 return `/${run.repo.namespace}/${run.repo.name}/agents.json`;
118}
119
120type ActionResult = { ok: boolean; notice?: string; error?: string } | undefined;
121
122/** Stop a run, after saying what that does. */
123export function StopRun({ run, compact }: { run: AgentRun; compact?: boolean }) {
124 const fetcher = useFetcher<ActionResult>();
125 const busy = fetcher.state !== "idle";
126 const onPull = run.number != null && isAgentKind(run.kind);
127 return (
128 <>
129 <AlertDialog>
130 <AlertDialogTrigger
131 disabled={busy}
132 className="inline-flex items-center gap-1.5 rounded-md border border-line px-2.5 py-1 text-xs text-muted transition-colors hover:border-danger/50 hover:text-danger disabled:opacity-50"
133 >
134 <Square size={11} />
135 {busy ? "Stopping…" : compact ? "Stop" : "Stop run"}
136 </AlertDialogTrigger>
137 <AlertDialogContent>
138 <AlertDialogHeader>
139 <AlertDialogTitle>Stop this {RUN_KIND_LABEL[run.kind].toLowerCase()} run?</AlertDialogTitle>
140 <AlertDialogDescription>
141 Its sandbox is shut down at once and nothing more is pushed.
142 {onPull &&
143 ` g1t stops seeing #${run.number} through and leaves it for a person; what the agent already pushed stays on it.`}
144 </AlertDialogDescription>
145 </AlertDialogHeader>
146 <AlertDialogFooter>
147 <AlertDialogCancel>Keep it running</AlertDialogCancel>
148 <AlertDialogAction
149 onClick={() => fetcher.submit({ intent: "stop", run: run.id }, { method: "post", action: actionUrl(run) })}
150 >
151 Stop
152 </AlertDialogAction>
153 </AlertDialogFooter>
154 </AlertDialogContent>
155 </AlertDialog>
156 {fetcher.data?.error && <span className="text-xs text-danger">{fetcher.data.error}</span>}
157 </>
158 );
159}
160
161/** Send the agent on a run's pull request a message. */
162export function MessageRun({ run }: { run: AgentRun }) {
163 const fetcher = useFetcher<ActionResult>();
164 const [open, setOpen] = useState(false);
165 const live = takesMessages(run.kind) && isActiveRun(run.status);
166 if (run.number == null) return null;
167 return (
168 <Dialog open={open} onOpenChange={setOpen}>
169 <DialogTrigger className="inline-flex items-center gap-1.5 rounded-md border border-line px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg">
170 <MessageSquare size={11} />
171 Message
172 </DialogTrigger>
173 <DialogContent>
174 <DialogHeader>
175 <DialogTitle>Message the agent on #{run.number}</DialogTitle>
176 <DialogDescription>
177 {live
178 ? "It reads this at its next step, between tool calls, without starting over."
179 : "This run does not read messages while it works. Your message waits on the pull request and is given to the agent's next run there."}
180 </DialogDescription>
181 </DialogHeader>
182 <fetcher.Form method="post" action={actionUrl(run)} className="space-y-3">
183 <input type="hidden" name="intent" value="message" />
184 <input type="hidden" name="number" value={run.number} />
185 <textarea
186 name="body"
187 required
188 rows={4}
189 autoComplete="off"
190 data-1p-ignore
191 placeholder="Keep the old flag working too…"
192 className="w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none placeholder:text-faint focus:border-accent-dim"
193 />
194 {fetcher.data?.error && <p className="text-sm text-danger">{fetcher.data.error}</p>}
195 {fetcher.data?.ok && fetcher.data.notice && <p className="text-sm text-accent">{fetcher.data.notice}</p>}
196 <div className="flex justify-end">
197 <button
198 type="submit"
199 disabled={fetcher.state !== "idle"}
200 className="inline-flex items-center gap-2 rounded-md bg-fg px-3.5 py-2 text-sm font-medium text-bg hover:bg-white disabled:opacity-50"
201 >
202 {fetcher.state !== "idle" ? "Sending…" : "Send"}
203 </button>
204 </div>
205 </fetcher.Form>
206 </DialogContent>
207 </Dialog>
208 );
209}
210
211/** What a run is on, as a link: its pull request, or the plan it writes. */
212function RunTarget({ run, showRepo }: { run: AgentRun; showRepo?: boolean }) {
213 const base = `/${run.repo.namespace}/${run.repo.name}`;
214 const repo = showRepo ? (
215 <Link to={base} className="font-mono text-xs text-faint hover:text-muted">
216 {run.repo.namespace}/{run.repo.name}
217 </Link>
218 ) : null;
219 if (run.number != null) {
220 return (
221 <span className="flex min-w-0 flex-wrap items-baseline gap-x-2">
222 {repo}
223 <Link to={`${base}/pull/${run.number}`} prefetch="intent" className="min-w-0 truncate font-medium hover:text-accent">
224 {run.title ?? "Pull request"} <span className="font-normal text-faint">#{run.number}</span>
225 </Link>
226 </span>
227 );
228 }
229 return (
230 <span className="flex min-w-0 flex-wrap items-baseline gap-x-2">
231 {repo}
232 <Link to={`${base}/plans`} className="min-w-0 truncate font-medium hover:text-accent">
233 {run.title ?? "A plan"}
234 </Link>
235 </span>
236 );
237}
238
239/** One run, live or finished, with what can be done about it. */
240export function RunCard({ run, member, showRepo }: { run: AgentRun; member: boolean; showRepo?: boolean }) {
241 const base = `/${run.repo.namespace}/${run.repo.name}`;
242 const active = isActiveRun(run.status);
243 const cost = formatCost(run.costUsd);
244 return (
245 <li
246 className={`rounded-xl border bg-surface p-4 transition-colors hover:border-line-strong ${
247 active ? "border-merged/30" : "border-line"
248 }`}
249 >
250 <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
251 <Avatar name={run.agent} size={22} />
252 <span className="text-sm font-medium">{run.agent}</span>
253 <KindLabel kind={run.kind} />
254 <span className="min-w-0 grow">
255 <RunTarget run={run} showRepo={showRepo} />
256 </span>
257 <RunStatusBadge status={run.status} />
258 </div>
259 {run.step && (
260 <p className={`mt-2.5 truncate font-mono text-xs ${active ? "text-fg/85" : "text-muted"}`} title={run.step}>
261 {active && <span className="mr-1.5 inline-block size-1.5 animate-pulse rounded-full bg-merged align-middle" />}
262 {run.step}
263 </p>
264 )}
265 {run.status === "failed" && run.error && <p className="mt-1.5 text-xs text-danger">{run.error}</p>}
266 <div className="mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted">
267 <span className="flex items-center gap-1">
268 <Clock size={12} />
269 {run.startedAt || active ? <Elapsed from={run.startedAt ?? run.createdAt} to={run.finishedAt} /> : "—"}
270 </span>
271 {cost && (
272 <span className="flex items-center gap-1" title={active ? "So far, as the harness reports it" : "As the harness reported it"}>
273 <Coins size={12} />
274 {cost}
275 {active && " so far"}
276 </span>
277 )}
278 {run.model && <span className="font-mono">{run.model}</span>}
279 {run.startedBy && <span>started by {run.startedBy}</span>}
280 <span>
281 <TimeAgo at={run.createdAt} />
282 </span>
283 <span className="grow" />
284 <Link to={`${base}/agents/runs/${run.id}`} className="hover:text-fg">
285 {run.stepCount} {run.stepCount === 1 ? "step" : "steps"}
286 </Link>
287 {run.number != null && (
288 <Link to={`${base}/sessions/${run.number}`} className="hover:text-fg">
289 Session
290 </Link>
291 )}
292 {member && active && <MessageRun run={run} />}
293 {member && active && <StopRun run={run} compact />}
294 </div>
295 </li>
296 );
297}
298
299/** The runs that are on now, newest first, then the rest. */
300export function splitRuns(runs: AgentRun[]): { live: AgentRun[]; done: AgentRun[] } {
301 return {
302 live: runs.filter((run) => isActiveRun(run.status)),
303 done: runs.filter((run) => !isActiveRun(run.status)),
304 };
305}
306
307type Live = { runs: AgentRun[]; member: boolean };
308
309/**
310 * The runs of a project, fetched from its `agents.json`, every few seconds
311 * while any is running. For pages whose own loader does not have them.
312 */
313export function useRuns(owner: string, repo: string, query: Record<string, string>): Live | null {
314 const fetcher = useFetcher<Live>();
315 const search = new URLSearchParams(query).toString();
316 const url = `/${owner}/${repo}/agents.json?${search}`;
317 const { load } = fetcher;
318 useEffect(() => {
319 load(url);
320 }, [load, url]);
321 const live = fetcher.data?.runs.some((run) => isActiveRun(run.status)) ?? false;
322 useEffect(() => {
323 if (!live) return;
324 const timer = setInterval(() => {
325 if (document.visibilityState === "visible") load(url);
326 }, LIVE_MS);
327 return () => clearInterval(timer);
328 }, [live, load, url]);
329 return fetcher.data ?? null;
330}
331
332/** "Agent confidence: Low — tests not added, 3 revisions", and what the agent said it was unsure of. */
333export function ConfidenceLine({ confidence }: { confidence: Confidence }) {
334 const tone = confidence.level === "low" ? "text-danger" : confidence.level === "medium" ? "text-warn" : "text-accent";
335 const level = { low: "Low", medium: "Medium", high: "High" }[confidence.level];
336 return (
337 <div className="mt-3 text-xs leading-5">
338 <p className="flex items-start gap-2">
339 <Gauge size={13} className={`mt-1 shrink-0 ${tone}`} />
340 <span className="min-w-0">
341 <span className="text-muted">Agent confidence: </span>
342 <span className={`font-medium ${tone}`}>{level}</span>
343 {confidence.reasons.length > 0 && <span className="text-fg-soft"> — {confidence.reasons.join(", ")}</span>}
344 </span>
345 </p>
346 {confidence.uncertainAbout.length > 0 && (
347 <p className="mt-0.5 pl-[1.3125rem] text-muted">Unsure about: {confidence.uncertainAbout.join("; ")}</p>
348 )}
349 </div>
350 );
351}
352
353/**
354 * The agent on a pull request, near the top of its page: who is working
355 * on it, at what stage, what it is doing this minute, for how long and at
356 * what cost, with its session, and Stop and Message for members.
357 */
358export function AgentPanel({
359 owner,
360 repo,
361 number,
362 stage,
363 confidence,
364}: {
365 owner: string;
366 repo: string;
367 number: number;
368 stage?: Stage | null;
369 /** How sure g1t is of the change, once the agent has finished it. */
370 confidence?: Confidence | null;
371}) {
372 const data = useRuns(owner, repo, { number: String(number), limit: "5" });
373 const runs = data?.runs ?? [];
374 const member = data?.member ?? false;
375 const current = runs.find((run) => isActiveRun(run.status)) ?? runs[0];
376 if (!current) return null;
377 const active = isActiveRun(current.status);
378 const base = `/${owner}/${repo}`;
379 const cost = formatCost(current.costUsd);
380 const spent = formatCost(runs.reduce((sum, run) => sum + (run.costUsd ?? 0), 0) || null);
381 return (
382 <section
383 aria-label="Agent"
384 className={`mt-4 rounded-2xl bg-surface p-4 ring-1 ${active ? "ring-merged/40" : "ring-line"}`}
385 >
386 <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
387 <Avatar name={current.agent} size={24} />
388 <p className="text-sm">
389 <span className="font-medium">{current.agent}</span>{" "}
390 {current.startedBy && current.startedBy !== current.agent && (
391 <span className="text-muted">
392 on behalf of <span className="text-fg">{current.startedBy}</span>{" "}
393 </span>
394 )}
395 <span className="text-muted">
396 {active
397 ? `is ${RUN_KIND_LABEL[current.kind].toLowerCase()}`
398 : `${current.status === "succeeded" ? "finished" : current.status} its ${RUN_KIND_LABEL[current.kind].toLowerCase()} run`}
399 </span>
400 </p>
401 {stage && (
402 <span className="flex items-center gap-2 text-xs text-muted">
403 <StageDots stage={stage} />
404 {STAGE_LABEL[stage]}
405 </span>
406 )}
407 <span className="grow" />
408 <RunStatusBadge status={current.status} />
409 </div>
410 {current.step && (
411 <p className="mt-3 truncate rounded-lg bg-bg px-3 py-2 font-mono text-xs text-fg/85 ring-1 ring-line" title={current.step}>
412 {active && <span className="mr-2 inline-block size-1.5 animate-pulse rounded-full bg-merged align-middle" />}
413 {current.step}
414 </p>
415 )}
416 {confidence && <ConfidenceLine confidence={confidence} />}
417 <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted">
418 <span className="flex items-center gap-1">
419 <Clock size={12} />
420 <Elapsed from={current.startedAt ?? current.createdAt} to={current.finishedAt} />
421 </span>
422 {cost && (
423 <span className="flex items-center gap-1">
424 <Coins size={12} />
425 {cost}
426 {active ? " so far" : ""}
427 {runs.length > 1 && spent && ` · ${spent} over ${runs.length} runs`}
428 </span>
429 )}
430 {current.model && <span className="font-mono">{current.model}</span>}
431 <span className="grow" />
432 <Link to={`${base}/agents/runs/${current.id}`} className="hover:text-fg">
433 Run
434 </Link>
435 <Link to={`${base}/sessions/${number}`} className="hover:text-fg">
436 Session
437 </Link>
438 {member && active && <MessageRun run={current} />}
439 {member && active && <StopRun run={current} />}
440 </div>
441 {member && <RunAudit owner={owner} repo={repo} runIds={runs.map((run) => run.id)} live={active} />}
442 </section>
443 );
444}
445
446/** A small "agent working" mark for a row of the pull request list. */
447export function AgentBadge({ run }: { run: AgentRun | undefined }) {
448 if (!run) return null;
449 return (
450 <span
451 title={run.step ?? undefined}
452 className="inline-flex shrink-0 items-center gap-1 rounded-full border border-merged/40 bg-merged/10 px-2 py-0.5 text-xs text-merged"
453 >
454 <Loader2 size={11} className="animate-spin" />
455 {RUN_KIND_LABEL[run.kind]}
456 </span>
457 );
458}
459
460/** The active run on each pull request of a project, by number. */
461export function useActiveRuns(owner: string, repo: string): Map<number, AgentRun> {
462 const data = useRuns(owner, repo, { active: "1", limit: "100" });
463 return useMemo(() => {
464 const byNumber = new Map<number, AgentRun>();
465 for (const run of data?.runs ?? []) {
466 if (run.number != null && !byNumber.has(run.number)) byNumber.set(run.number, run);
467 }
468 return byNumber;
469 }, [data]);
470}
471
472/** Nothing running, said plainly. */
473export function Idle({ children }: { children: ReactNode }) {
474 return (
475 <p className="flex items-center gap-2 rounded-xl border border-dashed border-line px-4 py-6 text-sm text-muted">
476 <CircleSlash size={15} className="text-faint" />
477 {children}
478 </p>
479 );
480}
481
482/**
483 * What the agent on a pull request is doing this minute, as one line, for
484 * an issue's sidebar: which agent picked the issue up, and where it is.
485 */
486export function AgentStepLine({ owner, repo, number }: { owner: string; repo: string; number: number }) {
487 const data = useRuns(owner, repo, { number: String(number), active: "1", limit: "1" });
488 const run = data?.runs[0];
489 if (!run?.step) return null;
490 return (
491 <span className="mt-0.5 block truncate font-mono text-[0.6875rem] text-faint" title={run.step}>
492 {RUN_KIND_LABEL[run.kind]}: {run.step}
493 </span>
494 );
495}