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