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