g1t/apps/web/app/routes/repo/settings-branches.tsx

209 lines10,962 bytesCodeBlame
1import { ChevronRight, ShieldCheck } from "lucide-react";
2import { Form, Link, useNavigation } from "react-router";
3
4import type { Route } from "./+types/settings-branches";
5import { page } from "../../lib/meta";
6import { AddCiPrompt } from "../../components/add-ci";
7import { RepoSettingsHeading } from "../../components/repo-settings-heading";
8import { RequiredChecksPicker } from "../../components/required-checks";
9import { SettingChoice as Choice, SettingsSection as Section, SettingToggle as Toggle } from "../../components/settings-section";
10import { Button, ErrorText, TimeAgo } from "../../components/ui";
11import { actions, repos, work } from "../../lib/services.server";
12import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
13import { requireCapability, requireInsider } from "../../lib/access.server";
14
15export function meta({ params, ...args }: Route.MetaArgs) {
16 return page(args, { title: `Branches and merging · ${params.owner}/${params.repo} · g1t` });
17}
18
19export async function loader({ params, context }: Route.LoaderArgs) {
20 const viewer = getViewer(context);
21 // Maintain and up; to anyone without a role here the page does not exist.
22 const { access } = await requireInsider(context, params, "manage_protection");
23 const path = { namespace: params.owner, name: params.repo };
24 const [repo, settings, seen, workflows] = await Promise.all([
25 repos.get(path, viewer),
26 work.getSettings(path, viewer),
27 work.seenChecks(path, viewer),
28 actions.workflows(path, viewer),
29 ]);
30 return {
31 repo: unwrap(repo),
32 settings: unwrap(settings),
33 // The names to choose required checks from: what reported lately.
34 seen: seen.ok ? seen.value : [],
35 // Nothing to require until something runs: the page offers to add CI.
36 noChecks: workflows.ok && workflows.value.length === 0 && seen.ok && seen.value.length === 0,
37 canPush: access.can.push,
38 };
39}
40
41/** A whole number from a form field, kept within `min` and `max`. */
42function count(value: FormDataEntryValue | null, min: number, max: number): number {
43 const number = Math.trunc(Number(value));
44 return Number.isFinite(number) ? Math.min(Math.max(number, min), max) : min;
45}
46
47export async function action({ request, params, context }: Route.ActionArgs) {
48 assertSameOrigin(request);
49 const user = requireUser(context, request);
50 await requireCapability(context, params, "manage_protection");
51 const form = await request.formData();
52 const path = { namespace: params.owner, name: params.repo };
53 const on = (name: string) => form.get(name) === "on";
54 // Protection belongs to the repository and how its pull requests are
55 // handled to the work service; the page is one form over both.
56 const repo = await repos.update(user, path, { protected: on("protected") });
57 if (!repo.ok) return { saved: false, error: repo.error.message };
58 const settings = await work.updateSettings(user, path, {
59 autoMerge: on("autoMerge"),
60 requiredChecks: form.getAll("requiredChecks").map(String),
61 requireUpToDate: on("requireUpToDate"),
62 requiredApprovals: count(form.get("requiredApprovals"), 0, 6),
63 countAgentApprovals: on("countAgentApprovals"),
64 allowIgnoringChecks: on("bypassChecks"),
65 agentReview: on("agentReview"),
66 maxRevisions: count(form.get("maxRevisions"), 0, 5),
67 mergeQueue: on("mergeQueue"),
68 holdLowConfidence: on("holdLowConfidence"),
69 });
70 return settings.ok ? { saved: true, error: null } : { saved: false, error: settings.error.message };
71}
72
73export default function BranchSettings({ loaderData, actionData }: Route.ComponentProps) {
74 const { repo, settings, seen, noChecks, canPush } = loaderData;
75 const saving = useNavigation().state === "submitting";
76 const branch = repo.defaultBranch;
77 const base = `/${repo.namespace}/${repo.name}`;
78 const archived = Boolean(repo.archivedAt);
79 return (
80 <>
81 <RepoSettingsHeading base={base} />
82 {/* Its own form, so outside the settings one. */}
83 {noChecks && (
84 <div className="mb-8 max-w-4xl">
85 <AddCiPrompt owner={repo.namespace} repo={repo.name} canAdd={canPush && !archived} />
86 </div>
87 )}
88 <Form method="post" className="max-w-4xl">
89 <fieldset disabled={archived} className="min-w-0 space-y-8">
90 <Section title="Branch protection" about={`Rules for ${branch}, the branch every pull request merges into. They hold for people and agents alike.`}>
91 <Toggle name="protected" on={repo.protected} title={`Require a pull request to change ${branch}`}>
92 Pushing to {branch} is refused, for members and agents alike, and git says why. Changes reach it only by
93 merging a pull request. The first push to an empty repository is still allowed.
94 </Toggle>
95 <RequiredChecksPicker
96 required={settings.requiredChecks ?? []}
97 seen={seen}
98 mergeQueue={settings.mergeQueue}
99 disabled={archived}
100 />
101 <Toggle name="bypassChecks" on={settings.allowIgnoringChecks} title="Allow bypassing required checks">
102 Someone who may merge can tick a box to merge although a required check failed or has not finished, and
103 the pull request says who did. With this off, nobody can, and auto-merge never does.
104 </Toggle>
105 <Toggle
106 name="requireUpToDate"
107 on={settings.requireUpToDate}
108 title="Require branches to be up to date before merging"
109 >
110 With this off, a pull request can be merged after {branch} has moved: g1t brings it up to date as part of
111 merging, and asks you only if there is a conflict it cannot resolve. With it on, it has to catch up first
112 and its required checks pass again on the result, so what lands is exactly what was checked.
113 </Toggle>
114 <Choice
115 name="requiredApprovals"
116 value={settings.requiredApprovals}
117 title="Required approvals"
118 options={[
119 [0, "None"],
120 [1, "1"],
121 [2, "2"],
122 [3, "3"],
123 ]}
124 >
125 How many reviewers must approve before a pull request can merge. A reviewer who has since asked for
126 changes blocks it, and nobody approves their own.
127 </Choice>
128 <Toggle name="countAgentApprovals" on={settings.countAgentApprovals} title="g1t's approval counts">
129 With this off, required approvals have to come from people, and an agent's review is advice.
130 </Toggle>
131 <Toggle name="mergeQueue" on={settings.mergeQueue} title="Merge through a queue">
132 Merging adds a pull request to the queue instead of changing {branch} at once. g1t builds it together with
133 every pull request ahead of it, several combinations at a time, and runs the workflows that run on{" "}
134 <code className="text-fg">merge_group</code> on each. {branch} only ever moves to a combination whose
135 required checks passed. One that fails leaves the queue and goes back to its author.
136 </Toggle>
137 </Section>
138
139 <Section
140 title="g1t"
141 about="What happens to a pull request g1t makes, from the moment it is ready. Its checks are the same workflows, and the rules above hold."
142 >
143 <Toggle name="agentReview" on={settings.agentReview} title="Review by a second agent">
144 A different agent reads each change and posts comments on lines, a summary and a verdict. If it asks for
145 changes, the author is sent back to make them. With this off, review is left to people.
146 </Toggle>
147 <Choice
148 name="maxRevisions"
149 value={settings.maxRevisions}
150 title="Revisions before asking you"
151 options={[
152 [0, "None"],
153 [1, "1"],
154 [2, "2"],
155 [3, "3"],
156 [5, "5"],
157 ]}
158 >
159 How many times an agent is sent back to fix a failed check, with what its jobs printed, or to address a
160 review, before g1t stops and the pull request says it needs you. After that, only a required check that
161 still fails holds it.
162 </Choice>
163 <Toggle name="autoMerge" on={settings.autoMerge} title="Merge automatically when ready">
164 A pull request g1t made lands without anyone pressing merge once every rule above is met, its required
165 checks included. With this off, it waits for a member. Pull requests from people and from other agents
166 always wait.
167 </Toggle>
168 <Toggle
169 name="holdLowConfidence"
170 on={settings.holdLowConfidence}
171 title="Ask a person before merging low-confidence changes"
172 >
173 g1t rates how sure it is of each change an agent finishes, from its required checks, revisions, review,
174 tests, size and guardrails. One it rates low waits for a member to approve it, instead of merging by itself
175 or joining the queue, and shows on Mission control as needing you.
176 </Toggle>
177 <Link
178 to={`${base}/settings/guardrails`}
179 className="group flex items-center gap-3 rounded-xl border border-line p-4 transition-colors hover:border-line-strong hover:bg-surface"
180 >
181 <ShieldCheck size={16} className="shrink-0 text-accent" />
182 <span className="min-w-0 grow">
183 <span className="block text-sm font-medium">Guardrails</span>
184 <span className="mt-0.5 block text-sm text-muted">
185 What agents may reach, run and spend while they work on this repository.
186 </span>
187 </span>
188 <ChevronRight size={16} className="shrink-0 text-faint transition-transform group-hover:translate-x-0.5" />
189 </Link>
190 </Section>
191
192 <div className="sticky bottom-0 -mx-4 flex flex-wrap items-center gap-4 border-t border-line bg-bg/90 px-4 py-4 backdrop-blur">
193 <Button type="submit" disabled={saving || archived}>
194 {saving ? "Saving…" : "Save settings"}
195 </Button>
196 {actionData?.saved && <span className="text-sm text-muted">Saved.</span>}
197 <ErrorText>{actionData?.error}</ErrorText>
198 {settings.updatedBy && settings.updatedAt && !actionData && (
199 <span className="text-xs text-faint">
200 Merge rules last changed by <span className="font-mono">{settings.updatedBy}</span>{" "}
201 <TimeAgo at={settings.updatedAt} />
202 </span>
203 )}
204 </div>
205 </fieldset>
206 </Form>
207 </>
208 );
209}