Skip to content

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

644 lines26,855 bytesCodeBlame
1import { env } from "cloudflare:workers";
2import { Bot, ExternalLink, GitCommitHorizontal, GitMerge, Play, Sparkles } from "lucide-react";
3import { useEffect } from "react";
4import { Form, Link, redirect, useNavigation, useRevalidator } from "react-router";
5
6import { type Pull, PROVIDERS } from "@g1t/contracts";
7
8import type { Route } from "./+types/issue";
9import { excerpt, page } from "../../lib/meta";
10import { Markdown } from "../../components/markdown";
11import { AgentStepLine } from "../../components/agents";
12import {
13 Avatar,
14 Button,
15 CopyLine,
16 EmptyState,
17 ComputeNote,
18 ErrorText,
19 Input,
20 Textarea,
21 TimeAgo,
22} from "../../components/ui";
23import { CheckboxOption } from "../../components/ui/checkbox";
24import { CheckBadge } from "../../components/checks";
25import {
26 Assignee,
27 AssigneeStack,
28 ChangeSize,
29 CommentForm,
30 CommentList,
31 PeoplePicker,
32 IssueState,
33 Label,
34 PersonLink,
35 PullIcon,
36 plainText,
37} from "../../components/work";
38import { notFound } from "../../lib/not-found.server";
39import { openedBy } from "../../lib/opened-by";
40import { computeNoteFor } from "../../lib/compute.server";
41import { identity, integrations, work } from "../../lib/services.server";
42import { assertSameOrigin, getViewer, requireUser, roleIn } from "../../lib/session.server";
43import { accessTo, refusal } from "../../lib/access.server";
44
45const REFRESH_MS = 4000;
46
47export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
48 const issue = loaderData?.issue;
49 const title = issue ? `${issue.title} · Issue #${issue.number} · ` : "";
50 const state = issue?.state === "open" ? "Open" : issue?.reason === "not_planned" ? "Closed as not planned" : "Closed";
51 const body = excerpt(issue?.body);
52 return page(args, {
53 title: `${title}${params.owner}/${params.repo} · g1t`,
54 description: issue
55 ? `${state} issue #${issue.number} on ${params.owner}/${params.repo}, opened by ${issue.author.username}.${body ? ` ${body}` : ""}`
56 : null,
57 // The card shows the title and the state.
58 version: issue ? [issue.title, issue.state, issue.reason] : undefined,
59 type: "article",
60 });
61}
62
63export async function loader({ params, context }: Route.LoaderArgs) {
64 const viewer = getViewer(context);
65 const path = { namespace: params.owner, name: params.repo };
66 const number = Number(params.number);
67 // At once: only the plan's note waits for the viewer's role. Putting an
68 // agent on it needs Write: Read cannot spend compute.
69 const access = accessTo(context, params);
70 const [{ can }, found, labels, agentsEnabled, members, links, computeNote] = await Promise.all([
71 access,
72 work.getIssue(path, number, viewer),
73 work.listLabels(path, viewer),
74 env.RUNNER.enabled(viewer, path),
75 // A member picks assignees from the workspace's people.
76 roleIn(viewer, params.owner) ? identity.listMembers(params.owner, viewer) : null,
77 // What it is tied to outside g1t. Shown only once the issue is known visible.
78 integrations.links(path, number).catch(() => []),
79 // Before a member assigns g1t: whether the workspace's plan lets it start.
80 access.then(({ can }) => (can.run ? computeNoteFor(params.owner, "agent") : null)),
81 ]);
82 if (!found.ok) {
83 // Issues and pull requests share numbers; this one may be a pull request.
84 const pull = await work.getPull(path, number, viewer);
85 if (pull.ok) throw redirect(`/${params.owner}/${params.repo}/pull/${number}`);
86 throw notFound("issue");
87 }
88 const { issue } = found.value;
89 return {
90 ...found.value,
91 viewer,
92 labels: labels.ok ? labels.value : [],
93 agentsEnabled,
94 computeNote,
95 links,
96 members: members?.ok ? members.value.map((member) => member.username) : [],
97 // The author can close and reopen their own issue; Triage and up, anyone's.
98 canManage: viewer != null && (viewer.id === issue.author.id || can.triage),
99 can,
100 };
101}
102
103export async function action({ request, params, context }: Route.ActionArgs) {
104 assertSameOrigin(request);
105 const user = requireUser(context, request);
106 const form = await request.formData();
107 const path = { namespace: params.owner, name: params.repo };
108 const number = Number(params.number);
109 // What each form needs; closing your own issue is checked by work.
110 const needed = form.get("action") === "run-hosted" ? "run" : form.get("action") === "assign" || form.get("action") === "labels" ? "triage" : null;
111 const refused = needed ? await refusal(context, params, needed) : null;
112 if (refused) return { error: refused, action: String(form.get("action")) };
113
114 switch (form.get("action")) {
115 case "run-hosted": {
116 const result = await env.RUNNER.run(user, path, number, {
117 instructions: String(form.get("instructions") ?? ""),
118 });
119 return result.ok ? null : { error: result.error.message, action: "run-hosted" };
120 }
121 case "open-pull": {
122 const result = await work.openPull(user, path, {
123 issue: number,
124 agent: String(form.get("agent") ?? ""),
125 runtime: "external",
126 });
127 if (!result.ok) return { error: result.error.message };
128 throw redirect(`/${params.owner}/${params.repo}/pull/${result.value.number}`);
129 }
130 case "comment": {
131 const result = await work.addComment(user, path, number, {
132 body: String(form.get("body") ?? ""),
133 });
134 return result.ok ? null : { error: result.error.message };
135 }
136 case "assign": {
137 const result = await work.updateIssue(user, path, number, {
138 assignees: [
139 ...form.getAll("assignee").map(String),
140 ...String(form.get("others") ?? "").split(/[\s,]+/),
141 ],
142 });
143 return result.ok ? null : { error: result.error.message };
144 }
145 case "labels": {
146 const result = await work.updateIssue(user, path, number, {
147 labels: [
148 ...form.getAll("label").map(String),
149 ...String(form.get("labels") ?? "").split(","),
150 ],
151 });
152 return result.ok ? null : { error: result.error.message };
153 }
154 case "reopen": {
155 const result = await work.reopenIssue(user, path, number);
156 return result.ok ? null : { error: result.error.message };
157 }
158 default: {
159 const result = await work.closeIssue(
160 user,
161 path,
162 number,
163 form.get("action") === "close-not-planned" ? "not_planned" : "completed",
164 );
165 return result.ok ? null : { error: result.error.message };
166 }
167 }
168}
169
170/** What became of a pull request, in a few words. */
171function outcome(pull: Pull): string {
172 if (pull.status === "merged") return `Merged by ${pull.mergedBy ?? "someone"}`;
173 if (pull.supersededBy != null) return `Closed · #${pull.supersededBy} was merged instead`;
174 if (pull.status === "closed") return "Closed without merging";
175 if (pull.status === "draft") return "Draft · in progress";
176 return "Ready for review";
177}
178
179function PullRow({ pull, base }: { pull: Pull; base: string }) {
180 const merged = pull.status === "merged";
181 const opener = openedBy(pull);
182 return (
183 <li>
184 <Link
185 to={`${base}/pull/${pull.number}`}
186 className={`block rounded-xl border p-4 transition-colors ${
187 merged
188 ? "border-merged/40 bg-merged/5 hover:border-merged/70"
189 : "border-line bg-surface hover:border-line-strong"
190 } ${pull.status === "closed" ? "opacity-70" : ""}`}
191 >
192 <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
193 <PullIcon status={pull.status} />
194 <span className="font-medium">
195 {pull.title} <span className="font-normal text-faint">#{pull.number}</span>
196 </span>
197 {pull.status === "draft" && (
198 <span className="size-1.5 animate-pulse rounded-full bg-accent" />
199 )}
200 <span className="ml-auto flex items-center gap-3 text-xs text-faint">
201 <ChangeSize files={pull.files} />
202 <CheckBadge status={pull.checkStatus} />
203 <span className="flex items-center gap-1 font-mono">
204 <GitCommitHorizontal size={13} />
205 {pull.headCommit?.slice(0, 7) ?? "no commits"}
206 </span>
207 <TimeAgo at={pull.updatedAt} />
208 </span>
209 </div>
210 <p className="mt-1.5 flex flex-wrap items-center gap-x-2 text-xs text-muted">
211 <span className={merged ? "font-medium text-merged" : ""}>{outcome(pull)}</span>
212 <span className="text-faint">·</span>
213 <span className="flex items-center gap-1 font-mono">
214 <Bot size={12} />
215 {pull.agent}
216 </span>
217 {opener.requestedBy ? (
218 <span className="text-faint">· requested by {opener.requestedBy}</span>
219 ) : (
220 <>
221 {pull.runtime === "hosted" && <span className="text-faint">on g1t</span>}
222 <span className="text-faint">· opened by {opener.name}</span>
223 </>
224 )}
225 </p>
226 {pull.body && (
227 <p className="mt-2 line-clamp-2 text-sm text-muted">{plainText(pull.body)}</p>
228 )}
229 </Link>
230 </li>
231 );
232}
233
234export default function IssuePage({ loaderData, actionData, params }: Route.ComponentProps) {
235 const { issue, pulls, comments, viewer, labels, agentsEnabled, members, canManage, can } = loaderData;
236
237 // Follow agents at work without a manual reload.
238 const revalidator = useRevalidator();
239 const navigation = useNavigation();
240 const running = pulls.some(
241 (pull) =>
242 pull.status === "draft" ||
243 pull.checkStatus === "queued" ||
244 pull.checkStatus === "running",
245 );
246 // The pull request g1t's agent has in progress for this issue, if any.
247 const assigned = [...pulls]
248 .reverse()
249 .find(
250 (pull) =>
251 pull.agent === "g1t" &&
252 pull.runtime === "hosted" &&
253 (pull.status === "draft" || pull.status === "open"),
254 );
255 useEffect(() => {
256 if (!running && !assigned) return;
257 const timer = setInterval(() => {
258 if (document.visibilityState === "visible") revalidator.revalidate();
259 }, REFRESH_MS);
260 return () => clearInterval(timer);
261 }, [running, assigned, revalidator]);
262
263 const starting = navigation.formData?.get("action") === "run-hosted";
264 const base = `/${params.owner}/${params.repo}`;
265 const open = issue.state === "open";
266 const reference = `${params.owner}/${params.repo}#${issue.number}`;
267 const resolver = pulls.find((pull) => pull.number === issue.resolvedBy);
268 // The merged pull request first, then the ones still in play, then the rest.
269 const rank = { merged: 0, open: 1, draft: 2, closed: 3 } as const;
270 const ordered = [...pulls].sort(
271 (a, b) => rank[a.status] - rank[b.status] || a.number - b.number,
272 );
273
274 return (
275 <div className="grid gap-8 lg:grid-cols-[1fr_19rem]">
276 <div className="min-w-0">
277 <h2 className="text-2xl font-semibold tracking-tight text-balance">
278 {issue.title} <span className="font-normal text-faint">#{issue.number}</span>
279 </h2>
280 <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-muted">
281 <IssueState issue={issue} />
282 <span className="flex items-center gap-2">
283 <Avatar name={issue.author.username} size={18} />
284 <span>
285 <PersonLink name={issue.author.username} className="font-medium text-fg hover:underline" /> opened this{" "}
286 <TimeAgo at={issue.createdAt} />
287 </span>
288 </span>
289 {issue.labels.map((name) => (
290 <Label key={name} name={name} />
291 ))}
292 {open && issue.agent && <Assignee agent={issue.agent} />}
293 </div>
294
295 {issue.resolvedBy != null && (
296 <Link
297 to={`${base}/pull/${issue.resolvedBy}`}
298 className="mt-5 flex items-center gap-3 rounded-xl border border-merged/40 bg-merged/5 px-4 py-3 text-sm transition-colors hover:border-merged/70"
299 >
300 <GitMerge size={18} className="shrink-0 text-merged" />
301 <span>
302 Resolved by{" "}
303 <span className="font-medium">
304 {resolver?.title ?? "pull request"} #{issue.resolvedBy}
305 </span>
306 {resolver?.mergedBy && (
307 <span className="text-muted">
308 , merged by {resolver.mergedBy}{" "}
309 {resolver.mergedAt && <TimeAgo at={resolver.mergedAt} />}
310 </span>
311 )}
312 </span>
313 </Link>
314 )}
315
316 {issue.body && (
317 <div className="mt-5 rounded-xl border border-line bg-surface p-5">
318 <Markdown source={issue.body} repo={{ namespace: params.owner, name: params.repo }} />
319 </div>
320 )}
321
322 <div className="mt-10 flex items-baseline justify-between">
323 <h3 className="font-semibold tracking-tight">Pull requests</h3>
324 <p className="text-sm text-muted">
325 {pulls.length === 0
326 ? "None yet"
327 : `${pulls.length} for this issue${
328 pulls.some((pull) => pull.status === "merged") ? "" : ", none merged"
329 }`}
330 </p>
331 </div>
332 <div className="mt-3">
333 {pulls.length === 0 ? (
334 <EmptyState title="Nobody has worked on this yet">
335 Put g1t on it, or point your own agent at{" "}
336 <code className="font-mono">{reference}</code>.
337 </EmptyState>
338 ) : (
339 <ol className="space-y-3">
340 {ordered.map((pull) => (
341 <PullRow key={pull.id} pull={pull} base={base} />
342 ))}
343 </ol>
344 )}
345 </div>
346
347 <h3 className="mt-10 font-semibold tracking-tight">Discussion</h3>
348 <div className="mt-3">
349 <div className="space-y-4">
350 <CommentList comments={comments} base={base} />
351 <CommentForm author={viewer?.username ?? null} resetKey={comments.length} />
352 {canManage && (
353 <Form method="post" className="flex flex-wrap justify-end gap-2">
354 {open ? (
355 <>
356 <Button variant="quiet" type="submit" name="action" value="close-not-planned">
357 Close as not planned
358 </Button>
359 <Button variant="quiet" type="submit" name="action" value="close-completed">
360 Close issue
361 </Button>
362 </>
363 ) : (
364 <Button variant="quiet" type="submit" name="action" value="reopen">
365 Reopen issue
366 </Button>
367 )}
368 </Form>
369 )}
370 </div>
371 </div>
372 <div className="mt-2">
373 {!(actionData && "action" in actionData) && <ErrorText>{actionData?.error}</ErrorText>}
374 </div>
375 </div>
376
377 <aside className="space-y-6">
378 {loaderData.links.length > 0 && (
379 <section>
380 <h3 className="text-sm font-medium">From outside g1t</h3>
381 <ul className="mt-2 space-y-1.5 text-sm">
382 {loaderData.links.map((link) => (
383 <li key={`${link.connectionId}-${link.key}`}>
384 <a
385 href={link.url}
386 target="_blank"
387 rel="noreferrer"
388 className="group flex items-center gap-2 rounded-lg border border-line px-2.5 py-2 transition-colors hover:border-line-strong"
389 >
390 <span className="min-w-0 grow">
391 <span className="block truncate font-medium">
392 {PROVIDERS[link.provider].label} <span className="font-mono text-muted">{link.key}</span>
393 </span>
394 <span className="block text-xs text-faint">
395 {link.count > 1 ? `Seen ${link.count} times, last ` : "Linked "}
396 <TimeAgo at={link.count > 1 ? link.lastSeen : link.firstSeen} />
397 </span>
398 </span>
399 <ExternalLink size={13} className="shrink-0 text-faint group-hover:text-fg" />
400 </a>
401 </li>
402 ))}
403 </ul>
404 </section>
405 )}
406 <section>
407 <h3 className="text-sm font-medium">Assignees</h3>
408 <ul className="mt-2 space-y-1.5 text-sm">
409 {open && assigned && (
410 <li>
411 <Link
412 to={`${base}/pull/${assigned.number}`}
413 className="flex items-center gap-2 rounded-lg border border-accent/30 bg-accent/5 px-2.5 py-2 transition-colors hover:border-accent/60"
414 >
415 <Sparkles size={15} className="shrink-0 text-accent" />
416 <span className="min-w-0 grow">
417 <span className="block font-mono text-xs font-medium">g1t</span>
418 <span className="block truncate text-xs text-muted">
419 {assigned.status === "draft"
420 ? "Making the change"
421 : "Seeing it through checks and review"}{" "}
422 · #{assigned.number}
423 </span>
424 <AgentStepLine owner={params.owner} repo={params.repo} number={assigned.number} />
425 </span>
426 <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-accent" />
427 </Link>
428 </li>
429 )}
430 {issue.assignees.map((name) => (
431 <li key={name} className="flex items-center gap-2 px-1">
432 <Avatar name={name} size={20} />
433 <span className="grow truncate font-mono text-xs">{name}</span>
434 </li>
435 ))}
436 {open && issue.queued && !assigned && (
437 <li className="flex items-center gap-2 rounded-lg border border-line bg-surface px-2.5 py-2">
438 <Sparkles size={15} className="shrink-0 text-faint" />
439 <span className="min-w-0 grow">
440 <span className="block font-mono text-xs font-medium">g1t</span>
441 <span className="block text-xs text-muted">
442 {issue.blockedBy.length > 0
443 ? "Queued. Starts when what this depends on has merged."
444 : "Queued. Starts as soon as there is room."}
445 </span>
446 </span>
447 </li>
448 )}
449 {!open && resolver && resolver.agent === "g1t" && (
450 <li>
451 <Link
452 to={`${base}/pull/${resolver.number}`}
453 className="flex items-center gap-2 rounded-lg border border-line bg-surface px-2.5 py-2 transition-colors hover:border-line-strong"
454 >
455 <Sparkles size={15} className="shrink-0 text-merged" />
456 <span className="min-w-0 grow">
457 <span className="block font-mono text-xs font-medium">g1t</span>
458 <span className="block truncate text-xs text-muted">
459 Resolved it with #{resolver.number}
460 </span>
461 </span>
462 </Link>
463 </li>
464 )}
465 {issue.assignees.length === 0 &&
466 !(open && (assigned || issue.queued)) &&
467 !(!open && resolver?.agent === "g1t") && (
468 <li className="px-1 text-xs text-faint">No one yet.</li>
469 )}
470 </ul>
471 {issue.blockedBy.length > 0 && (
472 <p className="mt-3 text-xs text-muted">
473 Depends on{" "}
474 {issue.blockedBy.map((number, index) => (
475 <span key={number}>
476 {index > 0 && ", "}
477 <Link
478 to={`${base}/issues/${number}`}
479 className="font-medium text-fg hover:underline"
480 >
481 #{number}
482 </Link>
483 </span>
484 ))}
485 {open ? ", which has to merge first." : "."}
486 </p>
487 )}
488
489 {open && agentsEnabled && can.run && !assigned && !issue.queued && (
490 <Form method="post" className="mt-3 space-y-2">
491 <input type="hidden" name="action" value="run-hosted" />
492 <div className="*:w-full">
493 <Button variant="accent" type="submit" disabled={starting}>
494 <Sparkles size={14} />
495 {starting ? "Starting a sandbox…" : "Assign to g1t"}
496 </Button>
497 </div>
498 <details>
499 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
500 Add guidance for this run
501 </summary>
502 <div className="mt-2">
503 <Textarea
504 name="instructions"
505 rows={2}
506 placeholder="On top of the issue's description"
507 />
508 </div>
509 </details>
510 <p className="text-xs text-muted">
511 It opens a pull request and sees it through checks, a review by another
512 agent and fixes. You get it back ready to merge.
513 </p>
514 <ComputeNote note={loaderData.computeNote} />
515 {actionData && "action" in actionData && actionData.action === "run-hosted" && (
516 <ErrorText>{actionData.error}</ErrorText>
517 )}
518 </Form>
519 )}
520
521 {open && !agentsEnabled && can.run && !assigned && !issue.queued && (
522 // Where g1t's agent would be, and what makes it appear.
523 <div className="mt-3 rounded-lg border border-dashed border-line p-3 text-sm">
524 <p className="flex items-center gap-1.5 font-medium">
525 <Sparkles size={14} className="text-accent" />
526 g1t
527 </p>
528 <p className="mt-1 text-xs text-muted">
529 Connect a model provider and g1t can take this issue: it opens a pull request and sees it
530 through checks, review and fixes. Agents run on a paid workspace, or on the free trial.
531 </p>
532 <Link
533 to={`/${params.owner}/-/integrations`}
534 className="mt-2 inline-block text-xs text-accent hover:underline"
535 >
536 Connect a model
537 </Link>
538 </div>
539 )}
540
541 {viewer && can.triage && open && (
542 <div className="mt-3 space-y-2">
543 {!issue.assignees.includes(viewer.username) && (
544 <Form method="post">
545 <input type="hidden" name="action" value="assign" />
546 {issue.assignees.map((name) => (
547 <input key={name} type="hidden" name="assignee" value={name} />
548 ))}
549 <input type="hidden" name="assignee" value={viewer.username} />
550 <div className="*:w-full">
551 <Button variant="quiet" type="submit">
552 Assign yourself
553 </Button>
554 </div>
555 </Form>
556 )}
557 <details className="group">
558 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
559 Assign people
560 </summary>
561 <Form method="post" className="mt-2 space-y-2" key={issue.assignees.join()}>
562 <input type="hidden" name="action" value="assign" />
563 <PeoplePicker name="assignee" members={members} chosen={issue.assignees} />
564 <Button variant="quiet" type="submit">
565 Save assignees
566 </Button>
567 </Form>
568 </details>
569 </div>
570 )}
571 </section>
572
573 {open && (
574 <section className="rounded-xl border border-line bg-surface p-4">
575 <h3 className="text-sm font-medium">Bring your own agent</h3>
576 <p className="mt-1 text-xs text-muted">
577 With g1t connected to your agent, ask it to work on this issue.
578 </p>
579 <div className="mt-3">
580 <CopyLine text={reference} />
581 </div>
582 {viewer ? (
583 <Form method="post" className="mt-4 space-y-2 border-t border-line pt-4">
584 <input type="hidden" name="action" value="open-pull" />
585 <p className="text-xs text-muted">
586 Or open a draft pull request yourself and get a fork to push to.
587 </p>
588 <Input name="agent" placeholder="Who is working, e.g. claude-code" maxLength={60} />
589 <div className="*:w-full">
590 <Button type="submit">Open pull request</Button>
591 </div>
592 <p className="text-xs text-muted">
593 Already pushed a branch?{" "}
594 <Link
595 to={`${base}/pulls/new?issue=${issue.number}`}
596 className="text-fg underline underline-offset-4"
597 >
598 Open a pull request from it
599 </Link>
600 .
601 </p>
602 </Form>
603 ) : (
604 <p className="mt-4 border-t border-line pt-4 text-sm text-muted">
605 <Link to="/login" className="text-fg underline underline-offset-4">
606 Sign in
607 </Link>{" "}
608 to open a pull request.
609 </p>
610 )}
611 </section>
612 )}
613
614 {can.triage && (
615 <details className="group">
616 <summary className="cursor-pointer list-none text-sm font-medium">
617 Labels <span className="text-xs font-normal text-faint group-open:hidden">Edit</span>
618 </summary>
619 <Form method="post" className="mt-3 space-y-3" key={issue.labels.join()}>
620 <input type="hidden" name="action" value="labels" />
621 <div className="flex flex-wrap gap-x-3 gap-y-2">
622 {labels.map((name) => (
623 <CheckboxOption
624 key={name}
625 name="label"
626 value={name}
627 defaultChecked={issue.labels.includes(name)}
628 label={<Label name={name} />}
629 className="items-center gap-1.5"
630 />
631 ))}
632 </div>
633 <Input name="labels" placeholder="New labels, comma separated" />
634 <Button variant="quiet" type="submit">
635 Save labels
636 </Button>
637 </Form>
638 </details>
639 )}
640
641 </aside>
642 </div>
643 );
644}