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

644 lines27,110 bytesCodeBlame
1import { env } from "cloudflare:workers";
2import { Bot, ExternalLink, GitCommitHorizontal, GitMerge, Play, Sparkles } from "lucide-react";
3import { Form, Link, redirect, useNavigation } from "react-router";
4
5import { type Pull, PROVIDERS, workOwner } from "@g1t/contracts";
6
7import type { Route } from "./+types/issue";
8import { excerpt, page } from "../../lib/meta";
9import { Markdown } from "../../components/markdown";
10import { AgentStepLine } from "../../components/agents";
11import {
12 Avatar,
13 Button,
14 CopyLine,
15 EmptyState,
16 ComputeNote,
17 ErrorText,
18 Input,
19 Textarea,
20 TimeAgo,
21} from "../../components/ui";
22import { CheckboxOption } from "../../components/ui/checkbox";
23import { CheckBadge } from "../../components/checks";
24import {
25 Assignee,
26 AssigneeStack,
27 ChangeSize,
28 CommentForm,
29 CommentList,
30 PeoplePicker,
31 IssueState,
32 Label,
33 PersonLink,
34 PullIcon,
35 plainText,
36} from "../../components/work";
37import { notFound } from "../../lib/not-found.server";
38import { openedBy } from "../../lib/opened-by";
39import { computeNoteFor } from "../../lib/compute.server";
40import { identity, integrations, work } from "../../lib/services.server";
41import { assertSameOrigin, getViewer, requireUser, roleIn } from "../../lib/session.server";
42import { accessTo, refusal } from "../../lib/access.server";
43import { useRefreshWhile } from "../../lib/refresh";
44
45
46export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
47 const issue = loaderData?.issue;
48 const title = issue ? `${issue.title} · Issue #${issue.number} · ` : "";
49 const state = issue?.state === "open" ? "Open" : issue?.reason === "not_planned" ? "Closed as not planned" : "Closed";
50 const body = excerpt(issue?.body);
51 return page(args, {
52 title: `${title}${params.owner}/${params.repo} · g1t`,
53 description: issue
54 ? `${state} issue #${issue.number} on ${params.owner}/${params.repo}, opened by ${issue.author.username}${issue.requestedBy ? ` for ${issue.requestedBy.username}` : ""}.${body ? ` ${body}` : ""}`
55 : null,
56 // The card shows the title and the state.
57 version: issue ? [issue.title, issue.state, issue.reason] : undefined,
58 type: "article",
59 });
60}
61
62export async function loader({ params, context }: Route.LoaderArgs) {
63 const viewer = getViewer(context);
64 const path = { namespace: params.owner, name: params.repo };
65 const number = Number(params.number);
66 // At once: only the plan's note waits for the viewer's role. Putting an
67 // agent on it needs Write: Read cannot spend compute.
68 const access = accessTo(context, params);
69 const [{ can }, found, labels, agentsEnabled, members, links, computeNote] = await Promise.all([
70 access,
71 work.getIssue(path, number, viewer),
72 work.listLabels(path, viewer),
73 env.RUNNER.enabled(viewer, path),
74 // A member picks assignees from the workspace's people.
75 roleIn(viewer, params.owner) ? identity.listMembers(params.owner, viewer) : null,
76 // What it is tied to outside g1t. Shown only once the issue is known visible.
77 integrations.links(path, number).catch(() => []),
78 // Before a member assigns g1t: whether the workspace's plan lets it start.
79 access.then(({ can }) => (can.run ? computeNoteFor(params.owner, "agent") : null)),
80 ]);
81 if (!found.ok) {
82 // Issues and pull requests share numbers; this one may be a pull request.
83 const pull = await work.getPull(path, number, viewer);
84 if (pull.ok) throw redirect(`/${params.owner}/${params.repo}/pull/${number}`);
85 throw notFound("issue");
86 }
87 const { issue } = found.value;
88 return {
89 ...found.value,
90 viewer,
91 labels: labels.ok ? labels.value : [],
92 agentsEnabled,
93 computeNote,
94 links,
95 members: members?.ok ? members.value.map((member) => member.username) : [],
96 // The author can close and reopen their own issue, and whoever g1t's
97 // agent filed one for, that one; Triage and up, anyone's.
98 canManage: viewer != null && (viewer.id === workOwner(issue).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 navigation = useNavigation();
239 const running = pulls.some(
240 (pull) =>
241 pull.status === "draft" ||
242 pull.checkStatus === "queued" ||
243 pull.checkStatus === "running",
244 );
245 // The pull request g1t's agent has in progress for this issue, if any.
246 const assigned = [...pulls]
247 .reverse()
248 .find(
249 (pull) =>
250 pull.agent === "g1t" &&
251 pull.runtime === "hosted" &&
252 (pull.status === "draft" || pull.status === "open"),
253 );
254 useRefreshWhile(Boolean(running || assigned));
255
256 const starting = navigation.formData?.get("action") === "run-hosted";
257 const base = `/${params.owner}/${params.repo}`;
258 const open = issue.state === "open";
259 const reference = `${params.owner}/${params.repo}#${issue.number}`;
260 const resolver = pulls.find((pull) => pull.number === issue.resolvedBy);
261 // The merged pull request first, then the ones still in play, then the rest.
262 const rank = { merged: 0, open: 1, draft: 2, closed: 3 } as const;
263 const ordered = [...pulls].sort(
264 (a, b) => rank[a.status] - rank[b.status] || a.number - b.number,
265 );
266
267 return (
268 <div className="grid gap-8 lg:grid-cols-[1fr_19rem]">
269 <div className="min-w-0">
270 <h2 className="text-2xl font-semibold tracking-tight text-balance">
271 {issue.title} <span className="font-normal text-faint">#{issue.number}</span>
272 </h2>
273 <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-muted">
274 <IssueState issue={issue} />
275 <span className="flex items-center gap-2">
276 <Avatar name={issue.author.username} size={18} />
277 <span>
278 <PersonLink name={issue.author.username} className="font-medium text-fg hover:underline" /> opened this{" "}
279 {issue.requestedBy && (
280 <>
281 for{" "}
282 <PersonLink name={issue.requestedBy.username} className="font-medium text-fg-soft hover:underline" />{" "}
283 </>
284 )}
285 <TimeAgo at={issue.createdAt} />
286 </span>
287 </span>
288 {issue.labels.map((name) => (
289 <Label key={name} name={name} />
290 ))}
291 {open && issue.agent && <Assignee agent={issue.agent} />}
292 </div>
293
294 {issue.resolvedBy != null && (
295 <Link
296 to={`${base}/pull/${issue.resolvedBy}`}
297 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"
298 >
299 <GitMerge size={18} className="shrink-0 text-merged" />
300 <span>
301 Resolved by{" "}
302 <span className="font-medium">
303 {resolver?.title ?? "pull request"} #{issue.resolvedBy}
304 </span>
305 {resolver?.mergedBy && (
306 <span className="text-muted">
307 , merged by {resolver.mergedBy}{" "}
308 {resolver.mergedAt && <TimeAgo at={resolver.mergedAt} />}
309 </span>
310 )}
311 </span>
312 </Link>
313 )}
314
315 {issue.body && (
316 <div className="mt-5 rounded-xl border border-line bg-surface p-5">
317 <Markdown source={issue.body} repo={{ namespace: params.owner, name: params.repo }} />
318 </div>
319 )}
320
321 <div className="mt-10 flex items-baseline justify-between">
322 <h3 className="font-semibold tracking-tight">Pull requests</h3>
323 <p className="text-sm text-muted">
324 {pulls.length === 0
325 ? "None yet"
326 : `${pulls.length} for this issue${
327 pulls.some((pull) => pull.status === "merged") ? "" : ", none merged"
328 }`}
329 </p>
330 </div>
331 <div className="mt-3">
332 {pulls.length === 0 ? (
333 <EmptyState title="Nobody has worked on this yet">
334 Put g1t on it, or point your own agent at{" "}
335 <code className="font-mono">{reference}</code>.
336 </EmptyState>
337 ) : (
338 <ol className="space-y-3">
339 {ordered.map((pull) => (
340 <PullRow key={pull.id} pull={pull} base={base} />
341 ))}
342 </ol>
343 )}
344 </div>
345
346 <h3 className="mt-10 font-semibold tracking-tight">Discussion</h3>
347 <div className="mt-3">
348 <div className="space-y-4">
349 <CommentList comments={comments} base={base} />
350 <CommentForm author={viewer?.username ?? null} resetKey={comments.length} />
351 {canManage && (
352 <Form method="post" className="flex flex-wrap justify-end gap-2">
353 {open ? (
354 <>
355 <Button variant="quiet" type="submit" name="action" value="close-not-planned">
356 Close as not planned
357 </Button>
358 <Button variant="quiet" type="submit" name="action" value="close-completed">
359 Close issue
360 </Button>
361 </>
362 ) : (
363 <Button variant="quiet" type="submit" name="action" value="reopen">
364 Reopen issue
365 </Button>
366 )}
367 </Form>
368 )}
369 </div>
370 </div>
371 <div className="mt-2">
372 {!(actionData && "action" in actionData) && <ErrorText>{actionData?.error}</ErrorText>}
373 </div>
374 </div>
375
376 <aside className="space-y-6">
377 {loaderData.links.length > 0 && (
378 <section>
379 <h3 className="text-sm font-medium">From outside g1t</h3>
380 <ul className="mt-2 space-y-1.5 text-sm">
381 {loaderData.links.map((link) => (
382 <li key={`${link.connectionId}-${link.key}`}>
383 <a
384 href={link.url}
385 target="_blank"
386 rel="noreferrer"
387 className="group flex items-center gap-2 rounded-lg border border-line px-2.5 py-2 transition-colors hover:border-line-strong"
388 >
389 <span className="min-w-0 grow">
390 <span className="block truncate font-medium">
391 {PROVIDERS[link.provider].label} <span className="font-mono text-muted">{link.key}</span>
392 </span>
393 <span className="block text-xs text-faint">
394 {link.count > 1 ? `Seen ${link.count} times, last ` : "Linked "}
395 <TimeAgo at={link.count > 1 ? link.lastSeen : link.firstSeen} />
396 </span>
397 </span>
398 <ExternalLink size={13} className="shrink-0 text-faint group-hover:text-fg" />
399 </a>
400 </li>
401 ))}
402 </ul>
403 </section>
404 )}
405 <section>
406 <h3 className="text-sm font-medium">Assignees</h3>
407 <ul className="mt-2 space-y-1.5 text-sm">
408 {open && assigned && (
409 <li>
410 <Link
411 to={`${base}/pull/${assigned.number}`}
412 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"
413 >
414 <Sparkles size={15} className="shrink-0 text-accent" />
415 <span className="min-w-0 grow">
416 <span className="block font-mono text-xs font-medium">g1t</span>
417 <span className="block truncate text-xs text-muted">
418 {assigned.status === "draft"
419 ? "Making the change"
420 : "Seeing it through checks and review"}{" "}
421 · #{assigned.number}
422 </span>
423 <AgentStepLine owner={params.owner} repo={params.repo} number={assigned.number} />
424 </span>
425 <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-accent" />
426 </Link>
427 </li>
428 )}
429 {issue.assignees.map((name) => (
430 <li key={name} className="flex items-center gap-2 px-1">
431 <Avatar name={name} size={20} />
432 <span className="grow truncate font-mono text-xs">{name}</span>
433 </li>
434 ))}
435 {open && issue.queued && !assigned && (
436 <li className="flex items-center gap-2 rounded-lg border border-line bg-surface px-2.5 py-2">
437 <Sparkles size={15} className="shrink-0 text-faint" />
438 <span className="min-w-0 grow">
439 <span className="block font-mono text-xs font-medium">g1t</span>
440 <span className="block text-xs text-muted">
441 {issue.blockedBy.length > 0
442 ? "Queued. Starts when what this depends on has merged."
443 : "Queued. Starts as soon as there is room."}
444 </span>
445 </span>
446 </li>
447 )}
448 {!open && resolver && resolver.agent === "g1t" && (
449 <li>
450 <Link
451 to={`${base}/pull/${resolver.number}`}
452 className="flex items-center gap-2 rounded-lg border border-line bg-surface px-2.5 py-2 transition-colors hover:border-line-strong"
453 >
454 <Sparkles size={15} className="shrink-0 text-merged" />
455 <span className="min-w-0 grow">
456 <span className="block font-mono text-xs font-medium">g1t</span>
457 <span className="block truncate text-xs text-muted">
458 Resolved it with #{resolver.number}
459 </span>
460 </span>
461 </Link>
462 </li>
463 )}
464 {issue.assignees.length === 0 &&
465 !(open && (assigned || issue.queued)) &&
466 !(!open && resolver?.agent === "g1t") && (
467 <li className="px-1 text-xs text-faint">No one yet.</li>
468 )}
469 </ul>
470 {issue.blockedBy.length > 0 && (
471 <p className="mt-3 text-xs text-muted">
472 Depends on{" "}
473 {issue.blockedBy.map((number, index) => (
474 <span key={number}>
475 {index > 0 && ", "}
476 <Link
477 to={`${base}/issues/${number}`}
478 className="font-medium text-fg hover:underline"
479 >
480 #{number}
481 </Link>
482 </span>
483 ))}
484 {open ? ", which has to merge first." : "."}
485 </p>
486 )}
487
488 {open && agentsEnabled && can.run && !assigned && !issue.queued && (
489 <Form method="post" className="mt-3 space-y-2">
490 <input type="hidden" name="action" value="run-hosted" />
491 <div className="*:w-full">
492 <Button variant="accent" type="submit" disabled={starting}>
493 <Sparkles size={14} />
494 {starting ? "Starting a sandbox…" : "Assign to g1t"}
495 </Button>
496 </div>
497 <details>
498 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
499 Add guidance for this run
500 </summary>
501 <div className="mt-2">
502 <Textarea
503 name="instructions"
504 rows={2}
505 placeholder="On top of the issue's description"
506 />
507 </div>
508 </details>
509 <p className="text-xs text-muted">
510 It opens a pull request and sees it through checks, a review by another
511 agent and fixes. You get it back ready to merge.
512 </p>
513 <ComputeNote note={loaderData.computeNote} />
514 {actionData && "action" in actionData && actionData.action === "run-hosted" && (
515 <ErrorText>{actionData.error}</ErrorText>
516 )}
517 </Form>
518 )}
519
520 {open && !agentsEnabled && can.run && !assigned && !issue.queued && (
521 // Where g1t's agent would be, and what makes it appear.
522 <div className="mt-3 rounded-lg border border-dashed border-line p-3 text-sm">
523 <p className="flex items-center gap-1.5 font-medium">
524 <Sparkles size={14} className="text-accent" />
525 g1t
526 </p>
527 <p className="mt-1 text-xs text-muted">
528 Connect a model provider and g1t can take this issue: it opens a pull request and sees it
529 through checks, review and fixes. Agents run on a paid workspace, or on the free trial.
530 </p>
531 <Link
532 to={`/${params.owner}/-/integrations`}
533 className="mt-2 inline-block text-xs text-accent hover:underline"
534 >
535 Connect a model
536 </Link>
537 </div>
538 )}
539
540 {viewer && can.triage && open && (
541 <div className="mt-3 space-y-2">
542 {!issue.assignees.includes(viewer.username) && (
543 <Form method="post">
544 <input type="hidden" name="action" value="assign" />
545 {issue.assignees.map((name) => (
546 <input key={name} type="hidden" name="assignee" value={name} />
547 ))}
548 <input type="hidden" name="assignee" value={viewer.username} />
549 <div className="*:w-full">
550 <Button variant="quiet" type="submit">
551 Assign yourself
552 </Button>
553 </div>
554 </Form>
555 )}
556 <details className="group">
557 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
558 Assign people
559 </summary>
560 <Form method="post" className="mt-2 space-y-2" key={issue.assignees.join()}>
561 <input type="hidden" name="action" value="assign" />
562 <PeoplePicker name="assignee" members={members} chosen={issue.assignees} />
563 <Button variant="quiet" type="submit">
564 Save assignees
565 </Button>
566 </Form>
567 </details>
568 </div>
569 )}
570 </section>
571
572 {/* Another way to start the work: not once a pull request is doing it. */}
573 {open && !pulls.some((pull) => pull.status === "open" || pull.status === "draft") && (
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}