g1t/apps/web/app/routes/repo/attempt.tsx

345 lines11,330 bytesCodeBlame
1import {
2 Bot,
3 ChevronRight,
4 FileDiff,
5 GitCommitHorizontal,
6 MessagesSquare,
7 Rocket,
8 StickyNote,
9 User,
10 Wrench,
11} from "lucide-react";
12import { useEffect } from "react";
13import { Form, Link, useRevalidator } from "react-router";
14
15import type { Comparison, SessionEntry } from "@g1t/contracts";
16
17import type { Route } from "./+types/attempt";
18import { DiffView } from "../../components/diff-view";
19import { Markdown } from "../../components/markdown";
20import {
21 Button,
22 CopyLine,
23 EmptyState,
24 ErrorText,
25 Status,
26 Textarea,
27 TimeAgo,
28} from "../../components/ui";
29import { repos, work } from "../../lib/services.server";
30import {
31 assertSameOrigin,
32 getViewer,
33 requireUser,
34 unwrap,
35} from "../../lib/session.server";
36
37const REFRESH_MS = 4000;
38const EMPTY_COMPARISON: Comparison = { base: null, head: "", files: [], truncated: false };
39
40export function meta({ loaderData }: Route.MetaArgs) {
41 return [
42 {
43 title: loaderData
44 ? `Attempt ${loaderData.attempt.number} · ${loaderData.intent.title} · g1t`
45 : "g1t",
46 },
47 ];
48}
49
50export async function loader({ params, context, request }: Route.LoaderArgs) {
51 const viewer = getViewer(context);
52 const [found, session] = await Promise.all([
53 work.getAttempt(params.id, viewer),
54 work.readSession(params.id, viewer),
55 ]);
56 const detail = unwrap(found);
57 const repo = await repos.getById(detail.attempt.repoId, viewer);
58 const showChanges = new URL(request.url).searchParams.get("tab") === "changes";
59 const comparison = showChanges
60 ? await repos.compare(
61 detail.attempt.forkRepoId,
62 viewer,
63 detail.attempt.landedBase,
64 )
65 : null;
66 return {
67 ...detail,
68 // Null on the session tab; an empty comparison if it could not be made.
69 comparison: comparison && (comparison.ok ? comparison.value : EMPTY_COMPARISON),
70 session: unwrap(session),
71 viewer,
72 // Members of the repository's workspace can land an attempt.
73 canShip:
74 repo.ok &&
75 (viewer?.workspaces ?? []).some(
76 (membership) => membership.slug === repo.value.namespace,
77 ),
78 defaultBranch: repo.ok ? repo.value.defaultBranch : "main",
79 };
80}
81
82export async function action({ request, params, context }: Route.ActionArgs) {
83 assertSameOrigin(request);
84 const user = requireUser(context, request);
85 const form = await request.formData();
86 const action = form.get("action");
87 const result =
88 action === "ship"
89 ? await work.shipAttempt(user, params.id)
90 : action === "abandon"
91 ? await work.abandonAttempt(user, params.id)
92 : await work.submitAttempt(
93 user,
94 params.id,
95 String(form.get("summary") ?? ""),
96 );
97 return result.ok ? null : { error: result.error.message };
98}
99
100/** One step of the session, on the timeline's rail. */
101function TabLink({
102 to,
103 active,
104 children,
105}: {
106 to: string;
107 active: boolean;
108 children: React.ReactNode;
109}) {
110 return (
111 <Link
112 to={to}
113 preventScrollReset
114 className={
115 "-mb-px flex items-center gap-2 border-b-2 px-1 pb-2.5 text-sm transition-colors " +
116 (active
117 ? "border-accent font-medium text-fg"
118 : "border-transparent text-muted hover:text-fg")
119 }
120 >
121 {children}
122 </Link>
123 );
124}
125
126function Entry({ entry, agent }: { entry: SessionEntry; agent: string }) {
127 const isTool = entry.kind === "tool_call" || entry.kind === "tool_result";
128 const Icon =
129 entry.kind === "prompt"
130 ? User
131 : entry.kind === "note"
132 ? StickyNote
133 : isTool
134 ? Wrench
135 : Bot;
136 return (
137 <li className="relative pl-10">
138 <span
139 className={`absolute top-0.5 left-0 flex size-7 items-center justify-center rounded-full border bg-bg ${
140 entry.kind === "prompt"
141 ? "border-accent/50 text-accent"
142 : "border-line text-faint"
143 }`}
144 >
145 <Icon size={14} />
146 </span>
147 {isTool ? (
148 <details className="group rounded-lg border border-line bg-surface">
149 <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-1.5 text-sm">
150 <ChevronRight
151 size={14}
152 className="text-faint transition-transform group-open:rotate-90"
153 />
154 <span className="font-mono text-xs text-accent">
155 {entry.tool ?? "tool"}
156 </span>
157 <span className="truncate font-mono text-xs text-muted">
158 {entry.kind === "tool_result" ? "→ " : ""}
159 {entry.text.split("\n")[0]}
160 </span>
161 </summary>
162 <pre className="overflow-x-auto border-t border-line p-3 font-mono text-xs whitespace-pre-wrap text-muted">
163 {entry.text}
164 </pre>
165 </details>
166 ) : (
167 <div>
168 <p className="text-xs font-medium text-faint">
169 {entry.kind === "prompt"
170 ? "Prompt"
171 : entry.kind === "note"
172 ? "Note"
173 : agent}
174 </p>
175 {entry.kind === "message" ? (
176 <div className="mt-1">
177 <Markdown source={entry.text} />
178 </div>
179 ) : (
180 <p
181 className={`mt-1 text-[0.9375rem] leading-relaxed wrap-break-word whitespace-pre-wrap ${
182 entry.kind === "prompt" ? "font-medium" : ""
183 }`}
184 >
185 {entry.text}
186 </p>
187 )}
188 </div>
189 )}
190 {entry.commit && (
191 <p className="mt-1.5 flex items-center gap-1 font-mono text-xs text-faint">
192 <GitCommitHorizontal size={12} />
193 {entry.commit.slice(0, 7)}
194 </p>
195 )}
196 </li>
197 );
198}
199
200export default function AttemptPage({
201 loaderData,
202 actionData,
203 params,
204}: Route.ComponentProps) {
205 const { attempt, intent, session, viewer, canShip, defaultBranch, comparison } =
206 loaderData;
207 const base = `/${params.owner}/${params.repo}`;
208 const here = base + "/attempts/" + attempt.id;
209 const remote = `https://g1t.sh/${attempt.fork.namespace}/${attempt.fork.name}.git`;
210 const mine = viewer?.id === attempt.startedBy.id;
211 const active = attempt.status === "working" || attempt.status === "submitted";
212
213 // Follow a running attempt without a manual reload.
214 const revalidator = useRevalidator();
215 const working = attempt.status === "working";
216 useEffect(() => {
217 if (!working) return;
218 const timer = setInterval(() => {
219 if (document.visibilityState === "visible") revalidator.revalidate();
220 }, REFRESH_MS);
221 return () => clearInterval(timer);
222 }, [working, revalidator]);
223
224 return (
225 <div className="grid gap-8 lg:grid-cols-[1fr_19rem]">
226 <div className="min-w-0">
227 <p className="text-sm text-muted">
228 <Link
229 to={`${base}/intents/${intent.number}`}
230 className="hover:text-fg hover:underline"
231 >
232 {intent.title} <span className="text-faint">#{intent.number}</span>
233 </Link>
234 </p>
235 <div className="mt-1 flex flex-wrap items-center gap-3">
236 <h2 className="text-2xl font-semibold tracking-tight">
237 Attempt {attempt.number}
238 </h2>
239 <span className="flex items-center gap-1.5 font-mono text-sm text-muted">
240 <Bot size={15} />
241 {attempt.agent}
242 </span>
243 <Status value={attempt.status} />
244 </div>
245 <p className="mt-2 text-sm text-muted">
246 Started by{" "}
247 <span className="font-medium text-fg">{attempt.startedBy.username}</span>{" "}
248 <TimeAgo at={attempt.createdAt} />
249 </p>
250
251 {attempt.summary && (
252 <section className="mt-6 rounded-xl border border-line bg-surface p-5">
253 <h3 className="text-xs font-medium tracking-wide text-faint uppercase">
254 Summary
255 </h3>
256 <div className="mt-2">
257 <Markdown source={attempt.summary} />
258 </div>
259 </section>
260 )}
261
262 <nav className="mt-10 flex gap-6 border-b border-line">
263 <TabLink to={here} active={!comparison}>
264 <MessagesSquare size={15} />
265 Session
266 </TabLink>
267 <TabLink to={here + "?tab=changes"} active={Boolean(comparison)}>
268 <FileDiff size={15} />
269 Changes
270 </TabLink>
271 </nav>
272 <div className="mt-5">
273 {comparison ? (
274 <DiffView comparison={comparison} />
275 ) : session.length === 0 ? (
276 <EmptyState title="Nothing recorded yet">
277 The agent's prompts, reasoning and tool calls appear here as it
278 works.
279 </EmptyState>
280 ) : (
281 <ol className="relative space-y-5 before:absolute before:top-2 before:bottom-2 before:left-3.25 before:w-px before:bg-line">
282 {session.map((entry) => (
283 <Entry key={entry.seq} entry={entry} agent={attempt.agent} />
284 ))}
285 </ol>
286 )}
287 </div>
288 </div>
289
290 <aside className="space-y-6">
291 {canShip && active && intent.status === "open" && (
292 <section className="rounded-xl border border-accent/30 bg-accent/5 p-4">
293 <h3 className="text-sm font-medium">Ship this attempt</h3>
294 <p className="mt-1 text-xs text-muted">
295 Lands its commits on {defaultBranch} and closes the intent.
296 </p>
297 <Form method="post" className="mt-3 *:w-full">
298 <Button variant="accent" type="submit" name="action" value="ship">
299 <Rocket size={15} />
300 Ship to {defaultBranch}
301 </Button>
302 </Form>
303 {!(mine && active) && <ErrorText>{actionData?.error}</ErrorText>}
304 </section>
305 )}
306 <section>
307 <h3 className="text-sm font-medium">Working copy</h3>
308 <p className="mt-1 text-xs text-muted">
309 This fork belongs to the attempt. Pushes to it show up here.
310 </p>
311 <div className="mt-2">
312 <CopyLine text={`git clone ${remote}`} />
313 </div>
314 <p className="mt-3 flex items-center gap-1.5 font-mono text-xs text-faint">
315 <GitCommitHorizontal size={13} />
316 {attempt.headCommit?.slice(0, 12) ?? "no commits pushed yet"}
317 </p>
318 </section>
319
320 {mine && active && (
321 <section className="rounded-xl border border-line bg-surface p-4">
322 <h3 className="text-sm font-medium">
323 {attempt.status === "submitted" ? "Update summary" : "Submit"}
324 </h3>
325 <Form method="post" className="mt-3 space-y-2">
326 <Textarea
327 name="summary"
328 rows={4}
329 placeholder="What changed and why"
330 defaultValue={attempt.summary ?? ""}
331 />
332 <div className="flex gap-2">
333 <Button type="submit">Submit attempt</Button>
334 <Button variant="quiet" type="submit" name="action" value="abandon">
335 Abandon
336 </Button>
337 </div>
338 </Form>
339 <ErrorText>{actionData?.error}</ErrorText>
340 </section>
341 )}
342 </aside>
343 </div>
344 );
345}