Skip to content

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.sh
328 linesCodeBlameRaw
1import { env } from "cloudflare:workers";
2import { GitPullRequest, MessageSquare, Milestone as MilestoneIcon, Plus, Sparkles, Tag } from "lucide-react";
3import { useEffect, useRef } from "react";
4import { Form, Link, useLocation, useRouteLoaderData } from "react-router";
5
6import type { Route } from "./+types/issues";
7import { page } from "../../lib/meta";
8import { ButtonLink, ComputeNote, EmptyState, ErrorText, SubmitButton, TimeAgo } from "../../components/ui";
9import { Badge } from "../../components/ui/badge";
10import { Button } from "../../components/ui/button";
11import { Card } from "../../components/ui/card";
12import { Checkbox } from "../../components/ui/checkbox";
13import { Hint } from "../../components/ui/hint";
14import { mirrorReason, type MirroredRepo } from "../../lib/mirror";
15import {
16 Assignee,
17 AssigneeStack,
18 IssueIcon,
19 StateTabs,
20} from "../../components/work";
21import { FilterMenu, LabelChip, Swatch } from "../../components/labels";
22import { colorsOf, listFilters, withFilter } from "../../lib/labels";
23import { computeNoteFor } from "../../lib/compute.server";
24import { isWaitingMessage } from "../../lib/compute";
25import { work } from "../../lib/services.server";
26import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
27import { accessTo, refusal, requireWritableRepo } from "../../lib/access.server";
28import { repoPages } from "../../lib/repo-live";
29import { useRepoLive } from "../../lib/use-repo-live";
30
31/** As many sandboxes as one request may start. */
32const MAX_ASSIGNED_AT_ONCE = 10;
33
34export function meta({ params, ...args }: Route.MetaArgs) {
35 return page(args, { title: `Issues · ${params.owner}/${params.repo} · g1t` });
36}
37
38export async function loader({ params, context, request }: Route.LoaderArgs) {
39 const viewer = getViewer(context);
40 const path = { namespace: params.owner, name: params.repo };
41 // `?label=bug&milestone=3`, or `label:bug milestone:3` written in `q`.
42 const { state, label, milestone } = listFilters(new URL(request.url).searchParams);
43 // Assigning agents needs Write: Read cannot spend compute. All at once:
44 // only the plan's note waits for the viewer's role.
45 const access = accessTo(context, params);
46 const [{ can }, issues, labels, milestones, agentsEnabled, computeNote] = await Promise.all([
47 access,
48 work.listIssues(path, viewer, { state, label: label || undefined, milestone: milestone ?? undefined }),
49 work.listLabels(path, viewer),
50 work.listMilestones(path, viewer, "open"),
51 env.RUNNER.enabled(viewer, path),
52 // Before a member assigns: whether the workspace's plan lets agents start.
53 access.then(({ can }) => (can.run ? computeNoteFor(params.owner, "agent") : null)),
54 ]);
55 return {
56 issues: unwrap(issues),
57 labels: unwrap(labels),
58 milestones: milestones.ok ? milestones.value : [],
59 state,
60 label,
61 milestone,
62 agentsEnabled: agentsEnabled && can.run,
63 computeNote,
64 } as const;
65}
66
67/** Assigns each selected issue to g1t, one run of its own each. */
68export async function action({ request, params, context }: Route.ActionArgs) {
69 assertSameOrigin(request);
70 const user = requireUser(context, request);
71 await requireWritableRepo(context, params);
72 const path = { namespace: params.owner, name: params.repo };
73 const numbers = (await request.formData())
74 .getAll("issue")
75 .map(Number)
76 .filter((number) => Number.isInteger(number) && number > 0);
77 if (numbers.length === 0) return { error: "Select the issues to assign first." };
78 const denied = await refusal(context, params, "run");
79 if (denied) return { error: denied };
80 if (numbers.length > MAX_ASSIGNED_AT_ONCE) {
81 return { error: `Assign at most ${MAX_ASSIGNED_AT_ONCE} issues at a time.` };
82 }
83 const results = await Promise.all(
84 numbers.map((number) => env.RUNNER.run(user, path, number)),
85 );
86 // Over the workspace's agents-at-once cap, the rest wait in the queue.
87 const waiting = results.filter((result) => !result.ok && isWaitingMessage(result.error.message)).length;
88 const refused = results.find((result) => !result.ok && !isWaitingMessage(result.error.message));
89 const started = results.filter((result) => result.ok).length;
90 return {
91 started,
92 waiting,
93 error:
94 refused && !refused.ok
95 ? `${started} of ${numbers.length} assigned. ${refused.error.message}`
96 : null,
97 };
98}
99
100export default function Issues({ loaderData, actionData, params }: Route.ComponentProps) {
101 const { issues, labels, milestones, state, label, milestone, agentsEnabled } = loaderData;
102 // Issues opened, commented on and closed show as it happens.
103 useRepoLive({ match: repoPages.issues() });
104 const repo = `/${params.owner}/${params.repo}`;
105 const base = `${repo}/issues`;
106 const assignable = agentsEnabled && state === "open" && issues.length > 0;
107 const current = new URLSearchParams(useLocation().search);
108 const colors = colorsOf(labels);
109 const milestoneTitle = milestones.find((m) => m.number === milestone)?.title ?? (milestone ? `#${milestone}` : null);
110 const filtered = [label, milestone].some(Boolean);
111 // The tabs keep the filters; each filter keeps the state and the other.
112 const kept = new URLSearchParams(current);
113 kept.delete("state");
114 kept.delete("q");
115
116 // An archived repository's issues are locked: no new ones.
117 const layout = useRouteLoaderData("routes/repo/layout") as { repo?: MirroredRepo & { archivedAt?: string | null } } | undefined;
118 const archived = Boolean(layout?.repo?.archivedAt);
119 // A mirror takes no new issues until someone takes over: the button says why.
120 const mirrorBlocked = mirrorReason(layout?.repo);
121 // Handed over: the ticks are cleared. Refused: they stay, to try again.
122 const form = useRef<HTMLFormElement>(null);
123 useEffect(() => {
124 if (actionData && !actionData.error) form.current?.reset();
125 }, [actionData]);
126 return (
127 <div>
128 <StateTabs
129 to={base}
130 state={state}
131 query={kept.toString()}
132 action={
133 archived ? undefined : mirrorBlocked ? (
134 <Hint label={mirrorBlocked} disabled>
135 <Button type="button" disabled>
136 <Plus size={15} />
137 New issue
138 </Button>
139 </Hint>
140 ) : (
141 <ButtonLink to={`${base}/new`}>
142 <Plus size={15} />
143 New issue
144 </ButtonLink>
145 )
146 }
147 />
148 <div className="mt-3 flex flex-wrap items-center gap-2">
149 <FilterMenu
150 label="Label"
151 active={label || undefined}
152 clearTo={label ? withFilter(base, current, "label", null) : undefined}
153 searchPlaceholder="Filter labels"
154 emptyText="No label matches."
155 options={labels.map((each) => ({
156 key: each.name,
157 to: withFilter(base, current, "label", each.name),
158 keywords: `${each.name} ${each.description}`,
159 selected: each.name === label,
160 label: (
161 <>
162 <Swatch color={each.color} />
163 <span className="truncate">{each.name}</span>
164 </>
165 ),
166 }))}
167 />
168 <FilterMenu
169 label="Milestone"
170 active={milestoneTitle ?? undefined}
171 clearTo={milestone ? withFilter(base, current, "milestone", null) : undefined}
172 searchPlaceholder="Filter milestones"
173 emptyText="No open milestone matches."
174 options={milestones.map((each) => ({
175 key: String(each.number),
176 to: withFilter(base, current, "milestone", String(each.number)),
177 keywords: `${each.title} ${each.number}`,
178 selected: each.number === milestone,
179 label: <span className="truncate">{each.title}</span>,
180 }))}
181 />
182 {filtered && (
183 <Link to={state === "closed" ? `${base}?state=closed` : base} className="text-xs text-muted hover:text-fg">
184 Clear filters
185 </Link>
186 )}
187 <span className="ml-auto flex items-center gap-1">
188 <Link
189 to={`${repo}/labels`}
190 className="inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 text-sm text-muted transition-colors hover:bg-surface hover:text-fg"
191 >
192 <Tag size={14} />
193 Labels
194 </Link>
195 </span>
196 </div>
197 <Form ref={form} method="post" className="mt-4">
198 {assignable && (
199 <div className="mb-3 flex flex-wrap items-center gap-3 rounded-xl border border-accent/30 bg-accent/5 px-4 py-2.5">
200 <Sparkles size={15} className="shrink-0 text-accent" />
201 <p className="min-w-0 grow text-sm text-muted">
202 Tick the issues to hand over. g1t takes each one in a run of its own,
203 and they all work at once.
204 </p>
205 <Hint label={mirrorBlocked} disabled={mirrorBlocked != null}>
206 <SubmitButton variant="accent" pending="Starting sandboxes…" disabled={mirrorBlocked != null}>
207 Assign to g1t
208 </SubmitButton>
209 </Hint>
210 {loaderData.computeNote && (
211 <div className="basis-full">
212 <ComputeNote note={loaderData.computeNote} />
213 </div>
214 )}
215 </div>
216 )}
217 {actionData?.error ? (
218 <div className="mb-3">
219 <ErrorText>{actionData.error}</ErrorText>
220 </div>
221 ) : (
222 actionData?.started != null && (
223 <p className="mb-3 text-sm text-muted">
224 {actionData.started}{" "}
225 {actionData.started === 1 ? "agent is" : "agents are"} starting. Each
226 issue shows its pull request as it appears.
227 {actionData.waiting
228 ? ` ${actionData.waiting} more ${actionData.waiting === 1 ? "waits" : "wait"} for a free slot and start by themselves.`
229 : ""}
230 </p>
231 )
232 )}
233 {issues.length === 0 ? (
234 <EmptyState
235 title={
236 filtered
237 ? `No ${state} issues match these filters`
238 : state === "open"
239 ? "No open issues"
240 : "No closed issues"
241 }
242 >
243 An issue says what should change: a bug, a feature, a question.
244 Agents and people open pull requests against it.
245 </EmptyState>
246 ) : (
247 <Card asChild tone="plain" divided className="overflow-hidden">
248 <ul>
249 {issues.map((issue) => (
250 <li key={issue.id} className="flex items-start transition-colors hover:bg-surface">
251 {assignable && (
252 <Checkbox
253 name="issue"
254 value={String(issue.number)}
255 // Already being worked on: nothing more to hand over.
256 disabled={issue.agent != null || issue.queued}
257 aria-label={`Select issue #${issue.number}`}
258 className="mt-4 ml-4 disabled:opacity-30"
259 />
260 )}
261 <Link
262 prefetch="intent"
263 to={`${base}/${issue.number}`}
264 className="flex min-w-0 grow items-start gap-3 px-4 py-3"
265 >
266 <span className="mt-0.5">
267 <IssueIcon issue={issue} />
268 </span>
269 <span className="min-w-0 grow">
270 <span className="flex flex-wrap items-center gap-x-2 gap-y-1">
271 <span className="font-medium">{issue.title}</span>
272 {issue.labels.map((name) => (
273 <LabelChip key={name} name={name} color={colors[name]} />
274 ))}
275 {issue.state === "open" && issue.agent && (
276 <Assignee agent={issue.agent} />
277 )}
278 {issue.state === "open" && issue.queued && !issue.agent && (
279 <Badge size="md" className="py-px">
280 queued for g1t
281 {issue.blockedBy.length > 0 &&
282 `, after ${issue.blockedBy.map((number) => `#${number}`).join(", ")}`}
283 </Badge>
284 )}
285 </span>
286 <span className="mt-0.5 block text-xs text-faint">
287 #{issue.number} opened <TimeAgo at={issue.createdAt} /> by{" "}
288 {issue.author.username}
289 {issue.requestedBy && <> for {issue.requestedBy.username}</>}
290 {issue.resolvedBy != null && (
291 <span className="text-merged"> · resolved by #{issue.resolvedBy}</span>
292 )}
293 {issue.milestone && (
294 <span className="inline-flex items-center gap-1">
295 {" "}
296 · <MilestoneIcon size={11} className="inline" /> {issue.milestone.title}
297 </span>
298 )}
299 </span>
300 </span>
301 <span className="mt-0.5 flex shrink-0 items-center gap-3 text-xs text-muted">
302 <AssigneeStack people={issue.assignees} />
303 {issue.pullCount > 0 && (
304 <Hint label={`${issue.pullCount} pull ${issue.pullCount === 1 ? "request" : "requests"}`}>
305 <span className="flex items-center gap-1">
306 <GitPullRequest size={13} />
307 {issue.pullCount}
308 <span className="sr-only">pull {issue.pullCount === 1 ? "request" : "requests"}</span>
309 </span>
310 </Hint>
311 )}
312 {issue.commentCount > 0 && (
313 <span className="flex items-center gap-1">
314 <MessageSquare size={13} />
315 {issue.commentCount}
316 </span>
317 )}
318 </span>
319 </Link>
320 </li>
321 ))}
322 </ul>
323 </Card>
324 )}
325 </Form>
326 </div>
327 );
328}