Skip to content
1,618 linesCodeBlameRaw
1import {
2 Bot,
3 ChevronRight,
4 FileDiff,
5 GitBranch,
6 GitCommitHorizontal,
7 CircleCheck,
8 CircleSlash,
9 GitMerge,
10 Layers,
11 Scale,
12 GitPullRequestArrow,
13 Hand,
14 Loader,
15 Radar,
16 MessageSquare,
17 ArrowUpRight,
18 MessagesSquare,
19 Rocket,
20 StickyNote,
21 User,
22 Users,
23 Wrench,
24} from "lucide-react";
25import { Suspense, useState } from "react";
26import { Await, Form, Link, redirect } from "react-router";
27
28import {
29 type Capability,
30 type Comment,
31 type Comparison,
32 type Deployment,
33 type Job,
34 type LiveApp,
35 type Pull,
36 type RepoPath,
37 type SessionEntry,
38 type Viewer,
39 pullComparison,
40 workOwner,
41} from "@g1t/contracts";
42
43import type { Route } from "./+types/pull";
44import { highlightFirstFiles } from "../../lib/highlight.server";
45import { excerpt, page } from "../../lib/meta";
46import { openedBy } from "../../lib/opened-by";
47import { cloneUrl, useAddresses } from "../../lib/addresses";
48import { DiffView } from "../../components/diff-view";
49import { DetailsDisclosure, detailsSummary } from "../../components/details-disclosure";
50import { BaseBranch } from "../../components/base-branch";
51import { LabelChip, LabelsBox, MilestoneBox } from "../../components/labels";
52import { Markdown } from "../../components/markdown";
53import {
54 ButtonLink,
55 CopyLine,
56 EmptyState,
57 ErrorText,
58 SubmitButton,
59 Textarea,
60 TimeAgo,
61} from "../../components/ui";
62import { Avatar } from "../../components/ui/avatar";
63import { Card } from "../../components/ui/card";
64import { CheckboxOption } from "../../components/ui/checkbox";
65import { Hint } from "../../components/ui/hint";
66import { TabStrip } from "../../components/ui/tab-strip";
67import { DecisionList, IntegrationFailure, SessionLine } from "../../components/coordination";
68import { resolutionOf, standingFailure } from "../../lib/coordination";
69import { WorkflowStatuses } from "../../components/actions";
70import { AddCiPrompt } from "../../components/add-ci";
71import { AttemptsBox } from "../../components/attempts";
72import { type Attempt, attemptReview, otherAttempts, sharedPaths, splitOverlaps } from "../../lib/attempts";
73import {
74 CommentForm,
75 CommentList,
76 IssueIcon,
77 PeoplePicker,
78 PersonLink,
79 PullState,
80 TimelineItem,
81 verdicts,
82} from "../../components/work";
83import { ChecksSection, ConflictsSection, MergeabilityRow, runIdOf } from "../../components/merge-box";
84import { ViolationList } from "../../components/rules";
85import { PullCodeOwnersPanel, TeamReviewer } from "../../components/codeowners";
86import { notFound } from "../../lib/not-found.server";
87import { actions, deployments, identity, inbox, repos, work } from "../../lib/services.server";
88import { commitChecksFor } from "../../lib/commit-checks.server";
89import { CommitChecksBadge } from "../../components/commit-checks";
90import { DeployLink } from "../../components/deploy";
91import { assertSameOrigin, getViewer, requireUser } from "../../lib/session.server";
92import { accessTo, refusal, repoFor } from "../../lib/access.server";
93import { SubscriptionBox } from "../../components/notifications";
94import { useRefreshWhile } from "../../lib/refresh";
95import { repoPages } from "../../lib/repo-live";
96import { useRepoLive } from "../../lib/use-repo-live";
97
98const EMPTY_COMPARISON: Comparison = { base: null, head: "", files: [], truncated: false };
99const TABS = ["conversation", "session", "changes"] as const;
100type Tab = (typeof TABS)[number];
101
102export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
103 const pull = loaderData?.pull;
104 const title = pull ? `${pull.title} · Pull request #${pull.number} · ` : "";
105 const state = { draft: "Draft", open: "Open", merged: "Merged", closed: "Closed" }[pull?.status ?? "open"];
106 const body = excerpt(pull?.body);
107 const opener = pull ? openedBy(pull) : null;
108 return page(args, {
109 title: `${title}${params.owner}/${params.repo} · g1t`,
110 description: pull
111 ? `${state} pull request #${pull.number} on ${params.owner}/${params.repo} by ${opener!.name}${opener!.requestedBy ? `, requested by ${opener!.requestedBy}` : ""}.${body ? ` ${body}` : ""}`
112 : null,
113 // The card shows the title and the state.
114 version: pull ? [pull.title, pull.status] : undefined,
115 type: "article",
116 });
117}
118
119export async function loader({ params, context, request }: Route.LoaderArgs) {
120 const viewer = getViewer(context);
121 const path = { namespace: params.owner, name: params.repo };
122 const number = Number(params.number);
123 const asked = new URL(request.url).searchParams.get("tab");
124 const tab: Tab = TABS.find((name) => name === asked) ?? "conversation";
125
126 // Members of the workspace pick reviewers and assignees from its people;
127 // what the viewer may do here goes by their role on the repository.
128 const member = (viewer?.workspaces ?? []).some(
129 (membership) => membership.slug === params.owner,
130 );
131 // Everything starts at once. Only what the viewer's role decides waits
132 // for the repository, which the layout is looking up in this request too
133 // (lib/access.server.ts), and only what the pull request decides waits
134 // for it.
135 const ref = { workspace: params.owner, slug: params.repo };
136 const access = accessTo(context, params);
137 const pullFound = work.getPull(path, number, viewer);
138 // Its labels and milestone, with the repository's to choose from.
139 const labelsFound = work.listLabels(path, viewer);
140 const milestonesFound = work.listMilestones(path, viewer);
141 labelsFound.catch(() => null);
142 milestonesFound.catch(() => null);
143 const [{ can }, found, repo, settings, members, session, deployed, subscription, teamList, decisions, harnessSessions] = await Promise.all([
144 access,
145 pullFound,
146 repos.get(path, viewer),
147 work.getSettings(path, viewer),
148 // A member picks reviewers and assignees from the workspace's people.
149 member ? identity.listMembers(params.owner, viewer) : null,
150 tab === "session" ? work.readSession(path, number, viewer) : null,
151 // Its preview, for people with a role here: beside the rest, not after.
152 access.then(({ insider }) => (insider ? deployments.list(ref, viewer).catch(() => null) : null)),
153 // Whether the viewer hears of it, for the sidebar's Notifications.
154 viewer
155 ? repoFor(context, params).then((found) =>
156 found.ok ? inbox.subscription(viewer, { repoId: found.value.id, number }).catch(() => null) : null,
157 )
158 : null,
159 // A member asks the workspace's teams to review, and mentions them.
160 member ? identity.listTeams(viewer, params.owner).catch(() => null) : null,
161 // Its decision records: what the merge queue found when it was combined
162 // with others, and the reasons kept on it (decisions.rs).
163 tab !== "changes" ? work.listDecisions(path, number, viewer).catch(() => null) : null,
164 // The harness sessions working on it, for the Session tab.
165 tab === "session" ? work.listWorkSessions(path, viewer, { pull: number }).catch(() => null) : null,
166 ]);
167 if (!found.ok) {
168 // Issues and pull requests share numbers; this one may be an issue.
169 const issue = await work.getIssue(path, number, viewer);
170 if (issue.ok) throw redirect(`/${params.owner}/${params.repo}/issues/${number}`);
171 throw notFound("pull");
172 }
173 const { pull } = found.value;
174 const range = pullComparison(pull);
175 // The jobs of each workflow run on its head, to list checks job by job.
176 // Read as the viewer: a run they cannot see is listed by its status alone.
177 // Streamed: the checks show by status first, then job by job.
178 // A closed or merged one lists its head's checks too, to read only.
179 const runIds = [...new Set((found.value.statuses ?? []).map(runIdOf).filter((id) => id != null))].slice(0, 10);
180 const workflowJobs =
181 tab === "conversation" && pull.status !== "draft" && runIds.length > 0
182 ? Promise.all(runIds.map((id) => actions.run(path, viewer, id).catch(() => null))).then((runs) => {
183 const jobs: Record<string, Job[]> = {};
184 for (const run of runs) if (run?.ok) jobs[run.value.run.id] = run.value.jobs;
185 return jobs;
186 })
187 .catch(() => ({}) as Record<string, Job[]>)
188 : Promise.resolve({} as Record<string, Job[]>);
189 // No checks at all on an open pull request: whether that is because the
190 // repository has no workflows, to offer a starter one.
191 const unchecked =
192 tab === "conversation" &&
193 pull.status === "open" &&
194 (found.value.statuses ?? []).length === 0 &&
195 (found.value.requiredChecks ?? []).length === 0;
196 const [comparison, noChecks] = await Promise.all([
197 // The first screens of it highlighted here, so their colours do not pop in.
198 tab === "changes"
199 ? repos
200 .compare(range.repoId, viewer, range.base, range.head, range.baseBranch)
201 .then(async (found) => (found.ok ? { ok: true as const, value: await highlightFirstFiles(found.value) } : found))
202 : null,
203 unchecked
204 ? actions
205 .workflows(path, viewer)
206 .then((found) => found.ok && found.value.length === 0)
207 .catch(() => false)
208 : false,
209 ]);
210 // Every pull request for its issue, to compare: streamed, and read only
211 // when there is more than this one.
212 const attempts =
213 tab === "conversation" && pull.issue != null && (found.value.issue?.pullCount ?? 0) > 1
214 ? attemptsFor(path, viewer, pull, found.value.comments).catch(() => [] as Attempt[])
215 : null;
216 const [labels, milestones] = await Promise.all([labelsFound, milestonesFound]);
217 const repoDefault = repo.ok ? repo.value.defaultBranch : "main";
218 // The default branch's protection covers pull requests into it only.
219 const protectedBase = (pull.base ?? repoDefault) === repoDefault;
220 return {
221 ...found.value,
222 // Every check on its head, as the commit's own list shows them: streamed.
223 headChecks: commitChecksFor(path, viewer, [pull.headCommit]),
224 labels: labels.ok ? labels.value : [],
225 milestones: milestones.ok ? milestones.value : [],
226 // Labelling and milestones: Triage and up; its author, its labels.
227 canTriage: can.triage,
228 // Making labels needs Write; applying them, Triage.
229 canMakeLabels: can.manage_labels,
230 // The branch it merges into: Write and up.
231 canChangeBase: can.push,
232 workflowJobs,
233 attempts,
234 tab,
235 session: session?.ok ? session.value : [],
236 decisions: decisions?.ok ? decisions.value : [],
237 harnessSessions: harnessSessions?.ok ? harnessSessions.value : [],
238 // An empty comparison if it could not be made.
239 comparison: comparison && (comparison.ok ? comparison.value : EMPTY_COMPARISON),
240 viewer,
241 // Write and up can merge.
242 canMerge: can.merge,
243 // Triage and up manage anyone's pull request; its author, their own,
244 // and whoever asked g1t for one, that one.
245 canManage: can.triage || (viewer != null && viewer.id === workOwner(pull).id),
246 // Maintain and up edit and delete anyone's comments; everyone, their own.
247 canModerate: can.manage_settings,
248 // A catch-up is pushed as the viewer: a fork takes pushes only from
249 // whoever it is for (who asked g1t for it, or its author), a branch
250 // from anyone who can push.
251 canUpdate: pull.fork ? viewer?.id === workOwner(pull).id : can.push,
252 subscription,
253 members: members?.ok ? members.value.map((person) => person.username) : [],
254 // `workspace/slug` and name of each team the viewer can see.
255 teams: teamList?.ok ? teamList.value.map((team) => ({ ref: `${team.workspace}/${team.slug}`, name: team.name })) : [],
256 // What the rules of the branch it merges into ask, as they stack; the
257 // default branch's settings where the rules are not known.
258 requireUpToDate: found.value.rules ? found.value.rules.strict : protectedBase && settings.ok && settings.value.requireUpToDate,
259 mergeQueue: found.value.rules ? found.value.rules.merge_queue : protectedBase && settings.ok && settings.value.mergeQueue,
260 requiredApprovals: found.value.rules
261 ? found.value.rules.required_approvals
262 : protectedBase && settings.ok
263 ? settings.value.requiredApprovals
264 : 0,
265 canIgnoreChecks: found.value.rules ? found.value.rules.allow_bypass_on_merge : !settings.ok || settings.value.allowIgnoringChecks,
266 noChecks,
267 // Who may open the pull request that adds CI: anyone who can push.
268 canAddCi: can.push,
269 // Who may choose the required checks.
270 canProtect: can.manage_protection,
271 defaultBranch: repo.ok ? repo.value.defaultBranch : "main",
272 ...deploymentOf(deployed?.ok ? deployed.value : null, number),
273 };
274}
275
276/**
277 * This pull request and the latest few others for its issue, each with its
278 * head's checks and where its review stands, this one first.
279 */
280async function attemptsFor(path: RepoPath, viewer: Viewer, pull: Pull, comments: Comment[]): Promise<Attempt[]> {
281 const found = await work.getIssue(path, pull.issue!, viewer);
282 if (!found.ok) return [];
283 const others = otherAttempts(found.value.pulls, pull.number).flatMap(
284 (number) => found.value.pulls.find((other) => other.number === number) ?? [],
285 );
286 const [details, checks] = await Promise.all([
287 Promise.all(others.map((other) => work.getPull(path, other.number, viewer).catch(() => null))),
288 commitChecksFor(path, viewer, [pull.headCommit, ...others.map((other) => other.headCommit)]),
289 ]);
290 const attempt = (one: Pull, said: Comment[], current: boolean): Attempt => ({
291 number: one.number,
292 title: one.title,
293 status: one.status,
294 supersededBy: one.supersededBy,
295 author: openedBy(one).name,
296 headCommit: one.headCommit,
297 files: one.files,
298 updatedAt: one.updatedAt,
299 current,
300 shared: current ? [] : sharedPaths(one.files, pull.files),
301 checks: (one.headCommit && checks?.[one.headCommit]) || null,
302 review: attemptReview(said, one.reviewers),
303 });
304 return [
305 attempt(pull, comments, true),
306 ...others.map((other, index) => {
307 const detail = details[index];
308 return attempt(other, detail?.ok ? detail.value.comments : [], false);
309 }),
310 ];
311}
312
313/**
314 * Where this pull request is live: its preview (or its latest build, while
315 * one is going or after one failed).
316 */
317function deploymentOf(
318 list: { deployments: Deployment[]; live: LiveApp[] } | null,
319 number: number,
320): { preview: LiveApp | null; build: Deployment | null } {
321 const preview = list?.live.find((app) => app.kind === "preview" && app.number === number) ?? null;
322 const build = list?.deployments.find((d) => d.kind === "preview" && d.number === number) ?? null;
323 return { preview, build };
324}
325const PULL_NEEDS: Record<string, Capability> = {
326 "rerun-workflow": "run",
327 "rerun-failed": "run",
328 merge: "merge",
329 unqueue: "merge",
330 milestone: "triage",
331 base: "push",
332};
333
334export async function action({ request, params, context }: Route.ActionArgs) {
335 assertSameOrigin(request);
336 const user = requireUser(context, request);
337 const form = await request.formData();
338 const path = { namespace: params.owner, name: params.repo };
339 const number = Number(params.number);
340 const action = form.get("action");
341 // What each form needs beyond reading; work checks the rest.
342 const needed = typeof action === "string" ? PULL_NEEDS[action] : undefined;
343 const refused = needed ? await refusal(context, params, needed) : null;
344 if (refused) return { error: refused, action: String(action) };
345 const verdict = form.get("verdict");
346 const line = Number(form.get("line"));
347 /** Names ticked in a people picker, plus those typed beside it. */
348 const picked = (field: string) => [
349 ...form.getAll(field).map(String),
350 // `@acme/backend` is asked as `acme/backend`.
351 ...String(form.get("others") ?? "").split(/[\s,]+/).map((name) => name.replace(/^@/, "")),
352 ];
353 // Its labels, milestone and base, from the sidebar's menus and the header.
354 if (action === "labels") {
355 const set = await work.setLabels(user, path, number, form.getAll("label").map(String));
356 return set.ok ? null : { error: set.error.message, action };
357 }
358 if (action === "milestone" || action === "base") {
359 const changed = await work.updatePull(
360 user,
361 path,
362 number,
363 action === "milestone"
364 ? { milestone: Number(form.get("milestone")) || 0 }
365 : { base: String(form.get("base") ?? "") },
366 );
367 return changed.ok ? null : { error: changed.error.message, action };
368 }
369 // Catching up: merged and pushed in seconds when the two sides changed
370 // different files. When they changed the same files, the merge is left
371 // to whoever works on the branch.
372 if (action === "update") {
373 const caught = await work.catchUpPull(user, path, number);
374 if (!caught.ok) return { action, error: caught.error.message };
375 const update = caught.value;
376 if (update.outcome === "needs_agent") {
377 return {
378 action,
379 error: "It and its base changed some of the same files, so it can't be caught up here. Merge the base into the branch where you work on it, then push.",
380 };
381 }
382 return {
383 action,
384 updated: { commit: update.commit, already: update.outcome === "up_to_date", at: Date.now() },
385 };
386 }
387 // A workflow run's failed jobs, run again. Who may is the actions service's call.
388 if (action === "rerun-workflow") {
389 const rerun = await actions.rerun(user, path, String(form.get("run") ?? ""), true);
390 return rerun.ok ? null : { error: rerun.error.message, action };
391 }
392 // Every failed run on its head, run again: Mission control's quick action.
393 if (action === "rerun-failed") {
394 const found = await work.getPull(path, number, user);
395 if (!found.ok) return { error: found.error.message, action };
396 const failed = [
397 ...new Set(
398 (found.value.statuses ?? [])
399 .filter((status) => status.state === "failure" || status.state === "error")
400 .map(runIdOf)
401 .filter((id) => id != null),
402 ),
403 ];
404 if (failed.length === 0) return { error: "No workflow run failed on its latest commit.", action };
405 const reruns = await Promise.all(failed.map((id) => actions.rerun(user, path, id, true)));
406 const refused = reruns.find((rerun) => !rerun.ok);
407 return refused && !refused.ok ? { error: refused.error.message, action } : null;
408 }
409 // A comment's own text, changed or taken away: its author's to do, or a
410 // maintainer's, which work checks.
411 if (action === "edit-comment" || action === "delete-comment") {
412 const id = String(form.get("comment") ?? "");
413 const changed =
414 action === "edit-comment"
415 ? await work.editComment(user, path, id, String(form.get("body") ?? ""))
416 : await work.deleteComment(user, path, id);
417 return changed.ok ? null : { error: changed.error.message, action, comment: id };
418 }
419 const result =
420 action === "merge"
421 ? await work.mergePull(user, path, number, {
422 keepIssueOpen: form.get("keepIssueOpen") === "on",
423 ignoreChecks: form.get("ignoreChecks") === "on",
424 bypassRules: form.get("bypassRules") === "on",
425 })
426 : action === "unqueue"
427 ? await work.removeFromQueue(user, path, number)
428 : action === "close"
429 ? await work.closePull(user, path, number)
430 : action === "reopen"
431 ? await work.reopenPull(user, path, number)
432 : action === "draft"
433 ? await work.convertPullToDraft(user, path, number)
434 : action === "reviewers"
435 ? await work.updatePull(user, path, number, { reviewers: picked("reviewer") })
436 : action === "assign"
437 ? await work.updatePull(user, path, number, { assignees: picked("assignee") })
438 : action === "comment"
439 ? await work.addComment(user, path, number, {
440 body: String(form.get("body") ?? ""),
441 path: String(form.get("path") ?? "") || undefined,
442 line: line > 0 ? line : undefined,
443 verdict:
444 verdict === "approve" || verdict === "request_changes" ? verdict : undefined,
445 })
446 : await work.readyPull(user, path, number, String(form.get("summary") ?? ""));
447 return result.ok ? null : { error: result.error.message, action };
448}
449
450/** How many, beside a tab's name, when there are any. */
451function TabCount({ n }: { n: number }) {
452 if (n <= 0) return null;
453 return (
454 <span className="rounded-full bg-raised px-1.5 py-px text-xs tabular-nums text-muted ring-1 ring-line">
455 {n.toLocaleString("en-US")}
456 </span>
457 );
458}
459
460function TabLink({
461 to,
462 active,
463 children,
464}: {
465 to: string;
466 active: boolean;
467 children: React.ReactNode;
468}) {
469 return (
470 <Link
471 to={to}
472 preventScrollReset
473 aria-current={active ? "page" : undefined}
474 className={
475 "-mb-px flex min-h-11 items-center gap-2 border-b-2 px-2.5 pb-2.5 text-sm whitespace-nowrap transition-colors sm:min-h-0 sm:px-3 [&>svg]:hidden sm:[&>svg]:block " +
476 (active
477 ? "border-accent font-medium text-fg"
478 : "border-transparent text-muted hover:text-fg")
479 }
480 >
481 {children}
482 </Link>
483 );
484}
485
486/** One step of the session, on the timeline's rail. */
487function Entry({ entry, agent }: { entry: SessionEntry; agent: string }) {
488 const isTool = entry.kind === "tool_call" || entry.kind === "tool_result";
489 const Icon =
490 entry.kind === "prompt"
491 ? User
492 : entry.kind === "note"
493 ? StickyNote
494 : isTool
495 ? Wrench
496 : Bot;
497 return (
498 <li className="relative pl-10">
499 <span
500 className={`absolute top-0.5 left-0 flex size-7 items-center justify-center rounded-full border bg-bg ${
501 entry.kind === "prompt"
502 ? "border-accent/50 text-accent"
503 : "border-line text-faint"
504 }`}
505 >
506 <Icon size={14} />
507 </span>
508 {isTool ? (
509 <Card asChild radius="lg" className="group">
510 <details>
511 <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-1.5 text-sm">
512 <ChevronRight
513 size={14}
514 className="text-faint transition-transform group-open:rotate-90"
515 />
516 <span className="font-mono text-xs text-accent">
517 {entry.tool ?? "tool"}
518 </span>
519 <span className="truncate font-mono text-xs text-muted">
520 {entry.kind === "tool_result" ? "→ " : ""}
521 {entry.text.split("\n")[0]}
522 </span>
523 </summary>
524 <pre className="overflow-x-auto border-t border-line p-3 font-mono text-xs whitespace-pre-wrap text-muted">
525 <code>{entry.text}</code>
526 </pre>
527 </details>
528 </Card>
529 ) : (
530 <div>
531 <p className="text-xs font-medium text-faint">
532 {entry.kind === "prompt"
533 ? "Prompt"
534 : entry.kind === "note"
535 ? "Note"
536 : agent}
537 </p>
538 {entry.kind === "message" ? (
539 <div className="mt-1">
540 <Markdown source={entry.text} />
541 </div>
542 ) : entry.kind === "prompt" ? (
543 <Card className="mt-1.5 max-h-128 overflow-y-auto p-4">
544 <Markdown source={entry.text} />
545 </Card>
546 ) : (
547 <p className="mt-1 text-[0.9375rem] leading-relaxed wrap-break-word whitespace-pre-wrap">
548 {entry.text}
549 </p>
550 )}
551 </div>
552 )}
553 {entry.commit && (
554 <p className="mt-1.5 flex items-center gap-1 font-mono text-xs text-faint">
555 <GitCommitHorizontal size={12} />
556 {entry.commit.slice(0, 7)}
557 </p>
558 )}
559 </li>
560 );
561}
562
563/** The box at the foot of the conversation saying what stands before a merge. */
564function StatusBox({ children }: { children: React.ReactNode }) {
565 return (
566 <div className="flex gap-3">
567 <span className="hidden w-8 shrink-0 sm:block" />
568 <section className="min-w-0 grow divide-y divide-line overflow-hidden rounded-xl border border-line-strong bg-surface">
569 {children}
570 </section>
571 </div>
572 );
573}
574
575function StatusRow({
576 icon,
577 title,
578 children,
579}: {
580 icon: React.ReactNode;
581 title: string;
582 children?: React.ReactNode;
583}) {
584 return (
585 <div className="flex gap-3 px-4 py-3 text-sm">
586 <span className="mt-0.5 shrink-0">{icon}</span>
587 <div className="min-w-0">
588 <p className="font-medium">{title}</p>
589 {children && <div className="mt-0.5 text-muted">{children}</div>}
590 </div>
591 </div>
592 );
593}
594
595export default function PullPage({ loaderData, actionData, params }: Route.ComponentProps) {
596 const {
597 pull,
598 issue,
599 comments,
600 checks,
601 overlaps,
602 behind,
603 lifecycle,
604 statuses = [],
605 requiredChecks = [],
606 noChecks,
607 canAddCi,
608 canProtect,
609 mergeable = "unknown",
610 conflicts = [],
611 earlierChecks = [],
612 workflowJobs,
613 attempts,
614 preview,
615 build,
616 landing,
617 stalled,
618 requireUpToDate,
619 mergeQueue,
620 requiredApprovals,
621 canIgnoreChecks,
622 canUpdate,
623 members,
624 teams,
625 codeOwners,
626 rules,
627 tab,
628 session,
629 decisions,
630 harnessSessions,
631 comparison,
632 viewer,
633 canMerge,
634 canManage,
635 canModerate,
636 defaultBranch: repoDefault,
637 } = loaderData;
638 // The branch it merges into: what every line below names.
639 const defaultBranch = pull.base ?? repoDefault;
640 const base = `/${params.owner}/${params.repo}`;
641 const here = `${base}/pull/${pull.number}`;
642 // g1t, on a pull request it made: the person who asked for it is a line below.
643 const opener = openedBy(pull);
644 const checksSection = (jobs: Record<string, Job[]>, loading = false) => (
645 <ChecksSection
646 run={checks}
647 required={requiredChecks}
648 statuses={statuses}
649 jobs={jobs}
650 pull={pull}
651 base={base}
652 earlier={earlierChecks}
653 canRerunWorkflows={canMerge}
654 settingsUrl={canProtect ? `${base}/settings/branches` : null}
655 conflicting={mergeable === "conflicting" && !noChecks}
656 error={actionData?.action === "rerun-failed" || actionData?.action === "rerun-workflow" ? actionData.error : null}
657 loading={loading}
658 />
659 );
660 // A closed or merged pull request's checks, as they ended: to read, with
661 // nothing to re-run and nothing that holds a merge.
662 const settledChecks = (jobs: Record<string, Job[]>, loading = false) => (
663 <ChecksSection
664 run={null}
665 required={[]}
666 statuses={statuses}
667 jobs={jobs}
668 pull={pull}
669 base={base}
670 earlier={[]}
671 canRerunWorkflows={false}
672 settled
673 loading={loading}
674 />
675 );
676 const addresses = useAddresses();
677 const remote = pull.fork
678 ? cloneUrl(addresses, `${pull.fork.namespace}/${pull.fork.name}`)
679 : cloneUrl(addresses, `${params.owner}/${params.repo}`);
680 const active = pull.status === "draft" || pull.status === "open";
681
682 // Follow a draft being worked on, or checks in progress, without a manual reload.
683 const working = pull.status === "draft";
684 const checking = statuses.some((status) => status.state === "pending");
685 const reviews = verdicts(comments);
686 // What stands between this pull request and a merge, if anything: a
687 // required check that has not passed, or the merge queue taking it out.
688 const unchecked = requiredChecks.some((check) => check.state !== "success") || checks?.status === "failed";
689 const requiredFailed = requiredChecks.some((check) => check.state === "failure") || checks?.status === "failed";
690 // Pull requests for other issues changing the same files will conflict;
691 // ones for the same issue are alternatives, and expected to: those are
692 // compared under their own heading.
693 const { collisions } = splitOverlaps(overlaps, pull.issue);
694 // A combination with it that failed in the merge queue and has not passed since.
695 const failure = active ? standingFailure(decisions, pull.number) : null;
696 const answered = failure ? resolutionOf(decisions, failure).fix : null;
697 const review = {
698 changesUrl: here + "?tab=changes",
699 // Nobody reviews their own pull request, nor one g1t made for them.
700 canJudge: active && viewer != null && viewer.id !== workOwner(pull).id,
701 };
702 // Everyone whose review was asked for, then anyone who reviewed unasked.
703 const reviewerNames = [
704 ...new Set([...pull.reviewers, ...reviews.map(({ reviewer }) => reviewer)]),
705 ];
706 const teamReviewers = pull.teamReviewers ?? [];
707 // Teams to ask: the workspace's, and any asked already.
708 const teamChoices = [
709 ...teams,
710 ...teamReviewers.filter((ref) => !teams.some((team) => team.ref === ref)).map((ref) => ({ ref, name: ref })),
711 ];
712 // Branch protection wants code owners' approval it does not have yet.
713 const ownersMissing = codeOwners?.required && codeOwners.missing ? codeOwners.missing : null;
714 // A catch-up: the click shows at once; the answer says whether it is done.
715 const catchUp = actionData?.action === "update" ? actionData : null;
716 const caughtUp = catchUp && "updated" in catchUp ? catchUp.updated : null;
717 // Pushed already: followed until the pull request's head is the merge,
718 // so its checks show starting again, for a minute at most.
719 const settling =
720 caughtUp != null && !caughtUp.already && pull.headCommit !== caughtUp.commit && Date.now() - caughtUp.at < 60_000;
721 // It is moving on its own (the merge queue, auto-merge), so the page will change.
722 const moving =
723 lifecycle != null && lifecycle.stage !== "ready" && lifecycle.stage !== "needs_you";
724 // Whether it merges cleanly is being worked out, so the box will change.
725 const probing = active && mergeable === "checking";
726 const conflicting = active && mergeable === "conflicting";
727 useRefreshWhile(working || checking || settling || moving || landing || probing);
728 // New commits, checks, reviews and comments, and its merge or close, as
729 // they happen: the timeline grows where the reader is, and one reading
730 // at its end follows it.
731 useRepoLive({ match: repoPages.pull(pull.number, { branch: pull.branch, sha: pull.headCommit }), followBottom: true });
732 // The rules of its base it does not meet: checks show in their own
733 // section, so the rest stop the button here. Someone a ruleset lets
734 // bypass it may tick a box and merge past them.
735 const [bypassing, setBypassing] = useState(false);
736 const rulesUnmet = (rules?.unmet ?? []).filter((violation) => violation.rule !== "required_status_checks");
737 const rulesBypassable = rules?.bypassable ?? [];
738 // Why the merge button cannot be pressed, if it cannot.
739 const mergeBlocked = conflicting
740 ? "Resolve the conflicts first."
741 : probing
742 ? "Waiting to find out whether it merges cleanly."
743 : behind && requireUpToDate
744 ? `The rules for ${defaultBranch} require it to be up to date first.`
745 : unchecked && !canIgnoreChecks
746 ? `The checks ${defaultBranch} requires have to pass first.`
747 : rulesUnmet.length > 0
748 ? rulesUnmet[0]!.message
749 : rulesBypassable.length > 0 && !bypassing
750 ? `Rules for ${defaultBranch} are not met. You may bypass them.`
751 : ownersMissing
752 ? "Code owners have to approve first."
753 : null;
754
755 return (
756 // The changes get the whole width; people and settings are a tab away.
757 <div>
758 {/* The title and the tabs run the full width; what is happening on
759 the pull request sits at the top of Conversation. */}
760 <header>
761 <h2 className="text-xl font-semibold tracking-tight text-balance wrap-break-word sm:text-2xl">
762 {pull.title} <span className="font-normal text-faint">#{pull.number}</span>
763 </h2>
764 <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-muted">
765 <PullState status={pull.status} />
766 <span className="flex items-center gap-2">
767 <Avatar
768 name={(pull.status === "merged" && pull.mergedBy) || opener.name}
769 size={18}
770 />
771 <span>
772 <PersonLink
773 name={(pull.status === "merged" && pull.mergedBy) || opener.name}
774 className="font-medium text-fg hover:underline"
775 />{" "}
776 {pull.status === "merged" ? "merged" : "wants to merge"}
777 {pull.branch && (
778 <>
779 {" "}
780 <span className="font-mono text-fg">{pull.branch}</span>
781 </>
782 )}{" "}
783 into{" "}
784 <BaseBranch
785 base={defaultBranch}
786 head={pull.fork ? null : pull.branch}
787 canChange={loaderData.canChangeBase && active}
788 branchesUrl={`${base}/branches.json`}
789 />
790 </span>
791 </span>
792 {(pull.labels ?? []).map((name) => (
793 <LabelChip key={name} name={name} color={loaderData.labels.find((label) => label.name === name)?.color} />
794 ))}
795 {opener.requestedBy && (
796 <span className="text-xs">
797 requested by{" "}
798 <PersonLink name={opener.requestedBy} className="font-medium text-fg-soft hover:underline" />
799 </span>
800 )}
801 {/* A pull request from a branch was made by its author, not an agent;
802 one g1t made already says so. */}
803 {!pull.branch && !opener.requestedBy && (
804 <span className="flex items-center gap-1.5 font-mono text-xs">
805 <Bot size={14} />
806 {pull.agent}
807 {pull.runtime === "hosted" && <span className="text-faint">on g1t</span>}
808 </span>
809 )}
810 </div>
811
812 {reviews.length > 0 && (
813 <p className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
814 {reviews.map(({ reviewer, verdict }) => (
815 <span
816 key={reviewer}
817 className={`flex items-center gap-1.5 ${
818 verdict === "approve" ? "text-success" : "text-danger"
819 }`}
820 >
821 {verdict === "approve" ? <CircleCheck size={15} /> : <CircleSlash size={15} />}
822 {verdict === "approve" ? "Approved by" : "Changes requested by"}{" "}
823 <span className="font-medium">{reviewer}</span>
824 </span>
825 ))}
826 </p>
827 )}
828
829 <TabStrip label="Pull request" className="mt-6 items-end gap-1 border-b border-line">
830 <TabLink to={here} active={tab === "conversation"}>
831 <MessageSquare size={15} />
832 Conversation
833 <TabCount n={comments.length} />
834 </TabLink>
835 <TabLink to={here + "?tab=session"} active={tab === "session"}>
836 <MessagesSquare size={15} />
837 Session
838 </TabLink>
839 <TabLink to={here + "?tab=changes"} active={tab === "changes"}>
840 <FileDiff size={15} />
841 Files changed
842 <TabCount n={pull.files.length} />
843 </TabLink>
844 {pull.files.length > 0 && (
845 <span className="ml-auto hidden pb-2.5 font-mono text-xs sm:inline">
846 <span className="text-success">+{pull.files.reduce((sum, file) => sum + file.additions, 0).toLocaleString("en-US")}</span>{" "}
847 <span className="text-danger">−{pull.files.reduce((sum, file) => sum + file.deletions, 0).toLocaleString("en-US")}</span>
848 </span>
849 )}
850 </TabStrip>
851 </header>
852 <div className={`mt-6 grid gap-6 lg:gap-8 ${tab === "changes" ? "" : "lg:grid-cols-[1fr_19rem]"}`}>
853 <div className="min-w-0">
854 {/* What is happening on it now: its issue, how it ended, the other
855 attempts at its issue, and what else touches the same files. On the
856 conversation, so the tabs sit right under the title. */}
857 {tab === "conversation" && (
858 <div>
859 {issue && (
860 <Link
861 to={`${base}/issues/${issue.number}`}
862 className="mt-4 flex items-center gap-2.5 rounded-xl border border-line bg-surface px-4 py-2.5 text-sm transition-colors hover:border-line-strong"
863 >
864 <IssueIcon issue={issue} />
865 <span className="text-muted">
866 {pull.status === "merged" && issue.resolvedBy === pull.number
867 ? "Resolved"
868 : "For issue"}
869 </span>
870 <span className="truncate font-medium">{issue.title}</span>
871 <span className="text-faint">#{issue.number}</span>
872 {issue.pullCount > 1 && (
873 <span className="ml-auto shrink-0 text-xs text-faint">
874 1 of {issue.pullCount} pull requests
875 </span>
876 )}
877 </Link>
878 )}
879 {pull.status === "merged" && (
880 <p className="mt-4 flex items-center gap-2.5 rounded-xl border border-merged/40 bg-merged/5 px-4 py-2.5 text-sm">
881 <GitMerge size={16} className="shrink-0 text-merged" />
882 <span>
883 Merged into <span className="font-mono">{defaultBranch}</span> by{" "}
884 <span className="font-medium">{pull.mergedBy}</span>{" "}
885 {/* Not an account: the repository's settings said to merge it. */}
886 {pull.mergedBy === "g1t" && "automatically, once it was ready, "}
887 {pull.mergedAt && <TimeAgo at={pull.mergedAt} />}
888 {pull.headCommit && (
889 <span className="font-mono text-muted"> · {pull.headCommit.slice(0, 7)}</span>
890 )}
891 </span>
892 </p>
893 )}
894 {pull.supersededBy != null && (
895 <Card asChild className="mt-4 px-4 py-2.5 text-sm text-muted">
896 <p>
897 Closed because{" "}
898 <Link
899 to={`${base}/pull/${pull.supersededBy}`}
900 className="font-medium text-fg hover:underline"
901 >
902 #{pull.supersededBy}
903 </Link>{" "}
904 was merged for this issue instead.
905 </p>
906 </Card>
907 )}
908 {attempts && pull.issue != null && <AttemptsBox attempts={attempts} issue={pull.issue} base={base} />}
909 {collisions.length > 0 && active && (
910 <Card className="mt-4 px-4 py-3 text-sm">
911 <p className="flex items-center gap-2.5 font-medium">
912 <Radar size={16} className="shrink-0 text-info" />
913 Other work is changing the same files
914 </p>
915 <ul className="mt-2 space-y-1.5">
916 {collisions.map((other) => (
917 <li key={other.number} className="flex flex-wrap items-baseline gap-x-2 text-muted">
918 <Link
919 to={`${base}/pull/${other.number}`}
920 className="font-medium text-fg hover:underline"
921 >
922 {other.title} <span className="font-normal text-faint">#{other.number}</span>
923 </Link>
924 <span className="font-mono text-xs">{other.paths.join(", ")}</span>
925 </li>
926 ))}
927 </ul>
928 <p className="mt-2 text-xs text-faint">
929 Whichever merges second will have to catch up, and may conflict.
930 </p>
931 </Card>
932 )}
933 </div>
934 )}
935 <div className="mt-5">
936 {comparison ? (
937 <DiffView
938 comparison={comparison}
939 review={{
940 comments: comments.filter((comment) => comment.path),
941 canComment: Boolean(viewer),
942 }}
943 />
944 ) : tab === "session" ? (
945 <div className="space-y-8">
946 {harnessSessions.length > 0 && (
947 <section aria-label="Harness sessions">
948 <h3 className="text-sm font-medium">Sessions on it</h3>
949 <Card asChild divided className="mt-3">
950 <ul>
951 {harnessSessions.map((one) => (
952 <li key={one.id} className="px-4 py-3">
953 <SessionLine session={one} base={base} showWhere={false} />
954 </li>
955 ))}
956 </ul>
957 </Card>
958 </section>
959 )}
960 {decisions.length > 0 && (
961 <section aria-label="Decisions">
962 <h3 className="text-sm font-medium">Decisions</h3>
963 <p className="mt-1 text-xs text-muted">
964 Why it is the way it is, each with how sure it is: claimed by whoever recorded it, tested by a check or the merge queue, approved by a person.
965 </p>
966 <div className="mt-3">
967 <DecisionList decisions={decisions} base={base} />
968 </div>
969 </section>
970 )}
971 <section aria-label="What happened">
972 {(harnessSessions.length > 0 || decisions.length > 0) && <h3 className="mb-3 text-sm font-medium">What happened</h3>}
973 {session.length === 0 ? (
974 <EmptyState title="Nothing recorded yet">
975 A coding agent's prompts, reasoning and tool calls appear here once
976 it records them, through the g1t plugin, a harness session or record_session.
977 </EmptyState>
978 ) : (
979 <ol className="relative space-y-5 before:absolute before:top-2 before:bottom-2 before:left-3.25 before:w-px before:bg-line">
980 {session.map((entry) => (
981 <Entry key={entry.seq} entry={entry} agent={pull.agent} />
982 ))}
983 </ol>
984 )}
985 </section>
986 </div>
987 ) : (
988 <div className="space-y-4">
989 <TimelineItem
990 author={opener.name}
991 at={pull.createdAt}
992 action={
993 <span>
994 opened this pull request
995 {opener.requestedBy ? (
996 <>
997 {" "}
998 for{" "}
999 <PersonLink name={opener.requestedBy} className="font-medium text-fg-soft hover:underline" />
1000 </>
1001 ) : !pull.branch && (
1002 <>
1003 {" "}
1004 with <span className="font-mono text-xs">{pull.agent}</span>
1005 </>
1006 )}
1007 </span>
1008 }
1009 >
1010 {pull.body ? (
1011 <Markdown source={pull.body} repo={{ namespace: params.owner, name: params.repo }} />
1012 ) : (
1013 <p className="text-sm text-muted">
1014 {working
1015 ? "No description yet. It is written when the pull request is marked ready for review."
1016 : "No description."}
1017 </p>
1018 )}
1019 {canManage && pull.status === "open" && (
1020 <details className="mt-3 border-t border-line pt-3 text-sm">
1021 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
1022 Edit description
1023 </summary>
1024 <Form method="post" className="mt-3 space-y-2">
1025 <input type="hidden" name="action" value="describe" />
1026 <Textarea
1027 name="summary"
1028 rows={6}
1029 placeholder="What changed and why"
1030 defaultValue={pull.body ?? ""}
1031 />
1032 <SubmitButton match={{ action: "describe" }} pending="Saving…">
1033 Save
1034 </SubmitButton>
1035 </Form>
1036 </details>
1037 )}
1038 </TimelineItem>
1039
1040 <CommentList
1041 comments={comments}
1042 review={review}
1043 base={base}
1044 viewerId={viewer?.id ?? null}
1045 canModerate={canModerate}
1046 failed={actionData && "comment" in actionData ? { comment: String(actionData.comment), error: actionData.error } : null}
1047 />
1048
1049 {(preview || build) && <DeploymentCard preview={preview} build={build} base={base} />}
1050
1051 {pull.status === "draft" && (
1052 <StatusBox>
1053 <StatusRow icon={<Loader size={16} className="text-faint" />} title="This is a draft">
1054 It is still being worked on. It can be reviewed and merged once it is
1055 marked ready.
1056 </StatusRow>
1057 {canManage && (
1058 <Form method="post" className="space-y-2 px-4 py-3">
1059 <input type="hidden" name="action" value="ready" />
1060 <Textarea name="summary" rows={3} placeholder="What changed and why" />
1061 <SubmitButton match={{ action: "ready" }} pending="Marking ready…">
1062 Mark ready for review
1063 </SubmitButton>
1064 </Form>
1065 )}
1066 </StatusBox>
1067 )}
1068
1069 {codeOwners && active && (
1070 <div className="flex gap-3">
1071 <span className="hidden w-8 shrink-0 sm:block" />
1072 <div className="min-w-0 grow">
1073 <PullCodeOwnersPanel
1074 owners={codeOwners}
1075 base={base}
1076 branch={defaultBranch}
1077 errorsHref={canProtect ? `${base}/settings/branches#codeowners` : `${base}/blob/${encodeURIComponent(defaultBranch)}/${codeOwners.path}`}
1078 />
1079 </div>
1080 </div>
1081 )}
1082
1083 {(pull.status === "merged" || pull.status === "closed") && statuses.length > 0 && (
1084 <StatusBox>
1085 <Suspense fallback={settledChecks({}, true)}>
1086 <Await resolve={workflowJobs}>{(jobs) => settledChecks(jobs)}</Await>
1087 </Suspense>
1088 </StatusBox>
1089 )}
1090
1091 {failure && (
1092 <div className="flex gap-3">
1093 <span className="hidden w-8 shrink-0 sm:block" />
1094 <IntegrationFailure className="min-w-0 grow" failure={failure} base={base} branch={defaultBranch} fixed={answered} />
1095 </div>
1096 )}
1097
1098 {pull.status === "open" && (
1099 <StatusBox>
1100 {/* Checks by status at once; job by job when the runs are read. */}
1101 <Suspense fallback={checksSection({}, true)}>
1102 <Await resolve={workflowJobs}>{(jobs) => checksSection(jobs)}</Await>
1103 </Suspense>
1104 {noChecks && <AddCiPrompt owner={params.owner} repo={params.repo} canAdd={canAddCi} compact />}
1105 <StatusRow
1106 icon={
1107 reviews.some(({ verdict }) => verdict === "request_changes") ? (
1108 <CircleSlash size={16} className="text-danger" />
1109 ) : reviews.length > 0 ? (
1110 <CircleCheck size={16} className="text-success" />
1111 ) : (
1112 <MessageSquare size={16} className="text-faint" />
1113 )
1114 }
1115 title={
1116 reviews.length === 0
1117 ? "No reviews yet"
1118 : reviews
1119 .map(
1120 ({ reviewer, verdict }) =>
1121 `${verdict === "approve" ? "Approved by" : "Changes requested by"} ${reviewer}`,
1122 )
1123 .join(" · ")
1124 }
1125 >
1126 {requiredApprovals > 0 &&
1127 `This repository requires ${requiredApprovals} approving ${
1128 requiredApprovals === 1 ? "review" : "reviews"
1129 } before merging.`}
1130 </StatusRow>
1131 {codeOwners?.required && (
1132 <StatusRow
1133 icon={
1134 ownersMissing ? (
1135 <CircleSlash size={16} className="text-warn" />
1136 ) : (
1137 <CircleCheck size={16} className="text-success" />
1138 )
1139 }
1140 title={ownersMissing ? "Waiting for code owners" : "Code owners approved"}
1141 >
1142 {ownersMissing ?? `Every file it changes has its owners' approval.`}{" "}
1143 {ownersMissing && "This repository requires their review before merging."}
1144 </StatusRow>
1145 )}
1146 {landing ? (
1147 <StatusRow
1148 icon={<Loader size={16} className="animate-spin text-accent" />}
1149 title="Merging"
1150 >
1151 {defaultBranch} has moved, so it is being brought up to date first. It
1152 lands as soon as that is done.
1153 </StatusRow>
1154 ) : conflicting ? (
1155 <ConflictsSection
1156 conflicts={conflicts}
1157 pull={pull}
1158 owner={params.owner}
1159 repo={params.repo}
1160 defaultBranch={defaultBranch}
1161 changesUrl={here + "?tab=changes"}
1162 error={catchUp && "error" in catchUp ? catchUp.error : null}
1163 />
1164 ) : probing ? (
1165 <MergeabilityRow mergeable={mergeable} defaultBranch={defaultBranch} />
1166 ) : behind ? (
1167 <StatusRow
1168 icon={<GitPullRequestArrow size={16} className="text-info" />}
1169 title={`${defaultBranch} has moved since this was made`}
1170 >
1171 {mergeable === "clean" && "It has no conflicts with it. "}
1172 {requireUpToDate
1173 ? "This repository requires pull requests to be up to date, so it has to catch up before it can merge."
1174 : "That does not stop it merging: it is brought up to date as part of the merge."}
1175 {canUpdate && (
1176 <Form method="post" className="mt-2">
1177 <input type="hidden" name="action" value="update" />
1178 <SubmitButton variant="outline" match={{ action: "update" }} pending={`Merging ${defaultBranch} in…`}>
1179 Catch up with {defaultBranch} now
1180 </SubmitButton>
1181 </Form>
1182 )}
1183 {catchUp && "error" in catchUp && <ErrorText>{catchUp.error}</ErrorText>}
1184 </StatusRow>
1185 ) : (
1186 (pull.headCommit || (catchUp && "error" in catchUp)) && (
1187 <StatusRow
1188 icon={<CircleCheck size={16} className="text-success" />}
1189 title={
1190 caughtUp && !caughtUp.already
1191 ? `Brought up to date with ${defaultBranch}`
1192 : `Up to date with ${defaultBranch}`
1193 }
1194 >
1195 {caughtUp && !caughtUp.already && (
1196 <>
1197 Merged <span className="font-mono">{defaultBranch}</span> in as{" "}
1198 <span className="font-mono text-fg">{caughtUp.commit.slice(0, 7)}</span>. Its checks run
1199 again on the new commit.
1200 </>
1201 )}
1202 {/* A catch-up refused or failed after the pull request stopped being behind. */}
1203 {catchUp && "error" in catchUp && <ErrorText>{catchUp.error}</ErrorText>}
1204 </StatusRow>
1205 )
1206 )}
1207 {active && rules && (rulesUnmet.length > 0 || rulesBypassable.length > 0 || rules.evaluate.length > 0) && (
1208 <StatusRow
1209 icon={
1210 <Scale
1211 size={16}
1212 className={rulesUnmet.length > 0 ? "text-danger" : rulesBypassable.length > 0 ? "text-warn" : "text-info"}
1213 />
1214 }
1215 title={
1216 rulesUnmet.length > 0
1217 ? `Rules for ${defaultBranch} are not met yet`
1218 : rulesBypassable.length > 0
1219 ? `You may bypass the rules for ${defaultBranch}`
1220 : "Rulesets being evaluated would refuse this merge"
1221 }
1222 >
1223 <div className="mt-2 space-y-3">
1224 {rulesUnmet.length > 0 && <ViolationList violations={rulesUnmet} />}
1225 {rulesBypassable.length > 0 && (
1226 <div>
1227 <p className="mb-1.5 text-xs text-muted">Not met, but a ruleset lets you bypass it:</p>
1228 <ViolationList violations={rulesBypassable} tone="warn" />
1229 </div>
1230 )}
1231 {rules.evaluate.length > 0 && (
1232 <div>
1233 <p className="mb-1.5 text-xs text-muted">Rulesets in evaluate would refuse it for this; nothing is held up:</p>
1234 <ViolationList violations={rules.evaluate} tone="info" />
1235 </div>
1236 )}
1237 {canProtect && (
1238 <Link
1239 to={`${base}/settings/rules?branch=${encodeURIComponent(defaultBranch)}`}
1240 className="inline-block text-xs text-muted underline underline-offset-2 hover:text-fg"
1241 >
1242 See every rule for {defaultBranch}
1243 </Link>
1244 )}
1245 </div>
1246 </StatusRow>
1247 )}
1248 {stalled && !lifecycle && (
1249 <StatusRow icon={<Hand size={16} className="text-warn" />} title="Needs you">
1250 {stalled}
1251 </StatusRow>
1252 )}
1253 {canMerge && lifecycle?.stage === "queued" && (
1254 <Form method="post" className="flex flex-wrap items-center gap-3 px-4 py-3">
1255 <ButtonLink to={`${base}/queue`}>
1256 <Layers size={15} />
1257 See the queue
1258 </ButtonLink>
1259 <SubmitButton variant="outline" name="action" value="unqueue" pending="Removing…">
1260 Remove from the queue
1261 </SubmitButton>
1262 </Form>
1263 )}
1264 {canMerge && !landing && lifecycle?.stage !== "queued" && (
1265 <Form method="post" className="space-y-3 px-4 py-3">
1266 {issue?.state === "open" && (
1267 <CheckboxOption
1268 name="keepIssueOpen"
1269 label={`Keep #${issue.number} open. This is only part of the work.`}
1270 labelClassName="text-xs text-muted"
1271 />
1272 )}
1273 {unchecked && canIgnoreChecks && (
1274 <CheckboxOption
1275 name="ignoreChecks"
1276 label={`Bypass the required checks: merge although ${requiredFailed ? "one failed" : "they have not all passed"}.`}
1277 labelClassName="text-xs text-muted"
1278 />
1279 )}
1280 {rulesBypassable.length > 0 && rulesUnmet.length === 0 && (
1281 <CheckboxOption
1282 name="bypassRules"
1283 checked={bypassing}
1284 onCheckedChange={(checked) => setBypassing(checked === true)}
1285 label={`Bypass the rules for ${defaultBranch}: merge although they are not met. It is recorded.`}
1286 labelClassName="text-xs text-muted"
1287 />
1288 )}
1289 <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:gap-3 *:w-full sm:*:w-auto [&_button]:min-h-11 [&_button]:w-full [&_button]:justify-center sm:[&_button]:min-h-0 sm:[&_button]:w-auto">
1290 <Hint label={mergeBlocked} disabled={mergeBlocked != null}>
1291 <SubmitButton
1292 variant="accent"
1293 name="action"
1294 value="merge"
1295 disabled={mergeBlocked != null}
1296 pending={mergeQueue ? "Adding to the queue…" : "Merging…"}
1297 >
1298 {mergeQueue ? <Layers size={15} /> : <GitMerge size={15} />}
1299 {mergeQueue ? "Add to the merge queue" : `Merge into ${defaultBranch}`}
1300 </SubmitButton>
1301 </Hint>
1302 <span className={`text-xs ${mergeBlocked ? "text-danger" : "text-muted"}`}>
1303 {mergeBlocked ?? (mergeQueue
1304 ? `Tested together with everything ahead of it, then lands on ${defaultBranch}.`
1305 : issue?.state === "open"
1306 ? `Closes issue #${issue.number}, and any other pull requests still open for it.`
1307 : `Lands its commits on ${defaultBranch}.`)}
1308 </span>
1309 </div>
1310 {actionData?.action === "merge" && (
1311 <ErrorText>{actionData.error}</ErrorText>
1312 )}
1313 </Form>
1314 )}
1315 </StatusBox>
1316 )}
1317
1318 <CommentForm
1319 author={viewer?.username ?? null}
1320 resetKey={comments.length}
1321 review={review}
1322 handles={teams.map((team) => `@${team.ref}`)}
1323 />
1324 {canManage && (active || pull.status === "closed") && (
1325 <Form method="post" className="flex flex-wrap justify-end gap-2">
1326 {pull.status === "open" && (
1327 <SubmitButton variant="outline" name="action" value="draft" pending="Converting…">
1328 Convert to draft
1329 </SubmitButton>
1330 )}
1331 {active ? (
1332 <SubmitButton variant="outline" name="action" value="close" pending="Closing…">
1333 Close pull request
1334 </SubmitButton>
1335 ) : (
1336 <SubmitButton variant="outline" name="action" value="reopen" pending="Reopening…">
1337 Reopen pull request
1338 </SubmitButton>
1339 )}
1340 </Form>
1341 )}
1342 {actionData &&
1343 !["merge", "comment", "rerun-failed", "rerun-workflow", "update", "reviewers", "assign", "edit-comment", "delete-comment"].includes(
1344 String(actionData.action),
1345 ) && <ErrorText>{actionData.error}</ErrorText>}
1346 </div>
1347 )}
1348 {actionData?.action === "comment" && (
1349 <div className="mt-2">
1350 <ErrorText>{actionData.error}</ErrorText>
1351 </div>
1352 )}
1353 </div>
1354 </div>
1355
1356 <DetailsDisclosure
1357 className={tab === "changes" ? "hidden" : "order-first lg:order-0"}
1358 summary={detailsSummary([
1359 [reviewerNames.length + teamReviewers.length, "reviewer", "reviewers"],
1360 [pull.assignees.length, "assignee", "assignees"],
1361 [(pull.labels ?? []).length, "label", "labels"],
1362 ])}
1363 >
1364 {/* Other than a draft, a pull request shows its checks in full in the conversation. */}
1365 {pull.status === "draft" && <WorkflowStatuses statuses={statuses} />}
1366 <section>
1367 <h3 className="text-sm font-medium">Reviewers</h3>
1368 <ul className="mt-2 space-y-1.5 text-sm">
1369 {reviewerNames.map((name) => {
1370 const verdict = reviews.find(({ reviewer }) => reviewer === name)?.verdict;
1371 return (
1372 <li key={name} className="flex items-center gap-2 px-1">
1373 <Avatar name={name} size={20} />
1374 <span className="grow truncate font-mono text-xs">
1375 <PersonLink name={name} className="hover:underline" />
1376 </span>
1377 {verdict === "approve" ? (
1378 <span className="flex items-center gap-1 text-xs text-success">
1379 <CircleCheck size={13} /> Approved
1380 </span>
1381 ) : verdict === "request_changes" ? (
1382 <span className="flex items-center gap-1 text-xs text-danger">
1383 <CircleSlash size={13} /> Changes requested
1384 </span>
1385 ) : (
1386 <span className="text-xs text-faint">Review requested</span>
1387 )}
1388 </li>
1389 );
1390 })}
1391 {teamReviewers.map((team) => (
1392 <TeamReviewer key={team} team={team} />
1393 ))}
1394 {reviewerNames.length === 0 && teamReviewers.length === 0 && (
1395 <li className="px-1 text-xs text-faint">No reviews requested yet.</li>
1396 )}
1397 </ul>
1398 {pull.status === "open" && canManage && (
1399 <div className="mt-3 space-y-2">
1400 <details>
1401 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
1402 {teamChoices.length > 0 ? "Request review from people or teams" : "Request review from people"}
1403 </summary>
1404 <Form method="post" className="mt-2 space-y-2" key={[...pull.reviewers, ...teamReviewers].join()}>
1405 <input type="hidden" name="action" value="reviewers" />
1406 <PeoplePicker
1407 name="reviewer"
1408 members={members.filter((name) => name !== workOwner(pull).username)}
1409 chosen={pull.reviewers}
1410 placeholder="Other usernames or teams (acme/backend)"
1411 />
1412 {teamChoices.length > 0 && (
1413 <div className="space-y-1.5 border-t border-line pt-2">
1414 <p className="text-xs text-faint">Teams</p>
1415 {teamChoices.map((team) => (
1416 <CheckboxOption
1417 key={team.ref}
1418 name="reviewer"
1419 value={team.ref}
1420 defaultChecked={teamReviewers.includes(team.ref)}
1421 className="items-center"
1422 labelClassName="flex min-w-0 items-center gap-2"
1423 label={
1424 <>
1425 <Users size={14} className="shrink-0 text-faint" />
1426 <span className="truncate font-mono text-xs">@{team.ref}</span>
1427 </>
1428 }
1429 />
1430 ))}
1431 </div>
1432 )}
1433 <SubmitButton variant="outline" match={{ action: "reviewers" }} pending="Saving…">
1434 Save reviewers
1435 </SubmitButton>
1436 </Form>
1437 </details>
1438 </div>
1439 )}
1440 {actionData?.action === "reviewers" && (
1441 <ErrorText>{actionData?.error}</ErrorText>
1442 )}
1443 </section>
1444
1445 <section>
1446 <h3 className="text-sm font-medium">Assignees</h3>
1447 <ul className="mt-2 space-y-1.5 text-sm">
1448 {pull.assignees.map((name) => (
1449 <li key={name} className="flex items-center gap-2 px-1">
1450 <Avatar name={name} size={20} />
1451 <span className="grow truncate font-mono text-xs">
1452 <PersonLink name={name} className="hover:underline" />
1453 </span>
1454 </li>
1455 ))}
1456 {pull.assignees.length === 0 && (
1457 <li className="px-1 text-xs text-faint">No one yet.</li>
1458 )}
1459 </ul>
1460 {viewer && canManage && active && (
1461 <div className="mt-3 space-y-2">
1462 {!pull.assignees.includes(viewer.username) && (
1463 <Form method="post">
1464 <input type="hidden" name="action" value="assign" />
1465 {pull.assignees.map((name) => (
1466 <input key={name} type="hidden" name="assignee" value={name} />
1467 ))}
1468 <input type="hidden" name="assignee" value={viewer.username} />
1469 <div className="*:w-full">
1470 <SubmitButton variant="outline" name="who" value="self" pending="Assigning…">
1471 Assign yourself
1472 </SubmitButton>
1473 </div>
1474 </Form>
1475 )}
1476 <details>
1477 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
1478 Assign people
1479 </summary>
1480 <Form method="post" className="mt-2 space-y-2" key={pull.assignees.join()}>
1481 <input type="hidden" name="action" value="assign" />
1482 <PeoplePicker name="assignee" members={members} chosen={pull.assignees} />
1483 <SubmitButton variant="outline" name="who" value="picked" pending="Saving…">
1484 Save assignees
1485 </SubmitButton>
1486 </Form>
1487 </details>
1488 </div>
1489 )}
1490 {actionData?.action === "assign" && <ErrorText>{actionData.error}</ErrorText>}
1491 </section>
1492
1493 <LabelsBox
1494 labels={loaderData.labels}
1495 chosen={pull.labels ?? []}
1496 canEdit={canManage && active}
1497 canCreate={loaderData.canMakeLabels}
1498 manageUrl={loaderData.canMakeLabels ? `${base}/labels` : undefined}
1499 />
1500 <MilestoneBox
1501 milestones={loaderData.milestones}
1502 current={pull.milestone}
1503 canEdit={loaderData.canTriage}
1504 base={base}
1505 />
1506
1507 <section>
1508 <h3 className="text-sm font-medium">Working copy</h3>
1509 {pull.branch ? (
1510 <>
1511 <p className="mt-1 text-xs text-muted">
1512 <GitBranch size={13} className="mr-1 inline align-[-2px]" />
1513 Branch <span className="font-mono text-fg">{pull.branch}</span> of this
1514 repository. Pushes to it show up here.
1515 </p>
1516 <div className="mt-2">
1517 <CopyLine text={`git clone -b ${pull.branch} ${remote}`} />
1518 </div>
1519 </>
1520 ) : (
1521 <>
1522 <p className="mt-1 text-xs text-muted">
1523 This fork belongs to the pull request. Pushes to it show up here.
1524 </p>
1525 <div className="mt-2">
1526 <CopyLine text={`git clone ${remote}`} />
1527 </div>
1528 </>
1529 )}
1530 <p className="mt-3 flex items-center gap-1.5 font-mono text-xs text-faint">
1531 <GitCommitHorizontal size={13} />
1532 {pull.headCommit ? (
1533 <Link to={`${base}/commit/${pull.headCommit}`} className="hover:text-fg">
1534 {pull.headCommit.slice(0, 12)}
1535 </Link>
1536 ) : (
1537 "no commits pushed yet"
1538 )}
1539 {pull.headCommit && <CommitChecksBadge checks={loaderData.headChecks} sha={pull.headCommit} className="size-5" />}
1540 </p>
1541 </section>
1542 {loaderData.viewer && (
1543 <SubscriptionBox action={`${base}/notifications`} number={pull.number} kind="pull" subscription={loaderData.subscription} />
1544 )}
1545 </DetailsDisclosure>
1546 </div>
1547 </div>
1548 );
1549}
1550
1551/** Where the pull request's change is live, as GitHub shows a deployment. */
1552function DeploymentCard({
1553 preview,
1554 build,
1555 base,
1556}: {
1557 preview: LiveApp | null;
1558 build: Deployment | null;
1559 base: string;
1560}) {
1561 const building = build?.status === "queued" || build?.status === "building";
1562 const failed = build?.status === "failed";
1563 return (
1564 <Card asChild className="ml-12 overflow-hidden">
1565 <section>
1566 <div className="flex flex-wrap items-center gap-3 px-4 py-3">
1567 <span
1568 className={`flex size-8 shrink-0 items-center justify-center rounded-full ring-1 ${
1569 failed ? "text-danger ring-danger/40" : building ? "text-warn ring-warn/40" : "text-success ring-success/40"
1570 }`}
1571 >
1572 {building ? <Loader size={15} className="animate-spin" /> : <Rocket size={15} />}
1573 </span>
1574 <div className="min-w-0 grow">
1575 <p className="text-sm font-medium">
1576 {building
1577 ? preview
1578 ? "Deploying the latest push. The last preview is still live."
1579 : "Deploying a preview"
1580 : failed
1581 ? "The preview failed to deploy"
1582 : "This branch is live"}
1583 </p>
1584 {preview ? (
1585 <DeployLink href={preview.url} className="mt-0.5 block truncate font-mono text-xs text-muted hover:text-accent">
1586 {preview.url.replace(/^https?:[/][/]/, "")}
1587 </DeployLink>
1588 ) : (
1589 build?.error && <p className="mt-0.5 truncate text-xs text-muted">{build.error}</p>
1590 )}
1591 </div>
1592 <div className="flex shrink-0 items-center gap-2">
1593 {build && (
1594 <Link to={`${base}/deployments/${build.id}`} className="text-xs text-muted hover:text-fg">
1595 {failed ? "See why" : "Build log"}
1596 </Link>
1597 )}
1598 {preview && (
1599 <DeployLink
1600 href={preview.url}
1601 className="inline-flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-bg hover:opacity-90"
1602 >
1603 Visit preview
1604 <ArrowUpRight size={13} />
1605 </DeployLink>
1606 )}
1607 </div>
1608 </div>
1609 {preview && (
1610 <p className="border-t border-line px-4 py-2 text-xs text-faint">
1611 <span className="font-mono">{preview.commit.slice(0, 7)}</span> · deployed <TimeAgo at={preview.deployedAt} />
1612 {preview.branch && ` · from ${preview.branch}`}
1613 </p>
1614 )}
1615 </section>
1616 </Card>
1617 );
1618}