Skip to content

Commit c4aaf3c

Browse files
committed
feat(pr): add GitHub maintainer edit control
1 parent 3f94487 commit c4aaf3c

20 files changed

Lines changed: 459 additions & 12 deletions
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { useAtomRefresh } from "@effect/atom-react";
2+
import type { PullRequestDetail } from "@t3tools/contracts";
3+
import { AsyncResult } from "effect/reactivity";
4+
import { useRef, useState } from "react";
5+
import { View } from "react-native";
6+
7+
import { AppText } from "../../components/ui/AppText";
8+
import { ListToggleRow } from "../../components/ui/ListToggleRow";
9+
import { composerPullRequests } from "../../state/pull-requests";
10+
import { useAtomCommand } from "../../state/use-atom-command";
11+
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
12+
import { usePullRequestPermissions } from "./usePullRequestPermissions";
13+
14+
export function PullRequestMaintainerEdits({
15+
params,
16+
pr,
17+
}: {
18+
params: PullRequestParams;
19+
pr: PullRequestDetail;
20+
}) {
21+
const target = pullRequestTarget(params);
22+
const permissions = usePullRequestPermissions(params, pr);
23+
const update = useAtomCommand(composerPullRequests.update, { reportFailure: false });
24+
const refresh = useAtomRefresh(composerPullRequests.detail(target));
25+
const [value, setValue] = useState(pr.maintainerCanModify ?? false);
26+
const [saving, setSaving] = useState(false);
27+
const [error, setError] = useState(false);
28+
const inFlight = useRef(false);
29+
const save = async (next: boolean) => {
30+
if (!permissions.canEditChangeRequest || inFlight.current) return;
31+
const previous = value;
32+
inFlight.current = true;
33+
setSaving(true);
34+
setError(false);
35+
setValue(next);
36+
const result = await update({
37+
...target,
38+
input: { ...target.input, maintainerCanModify: next },
39+
});
40+
inFlight.current = false;
41+
setSaving(false);
42+
if (AsyncResult.isFailure(result)) {
43+
setValue(previous);
44+
setError(true);
45+
return;
46+
}
47+
refresh();
48+
};
49+
50+
return (
51+
<View className="gap-2 border-t border-border-subtle pt-3">
52+
<ListToggleRow
53+
label="Allow edits from maintainers"
54+
description="Maintainers can push to this branch. If your fork has workflows, this can also give access to its secrets."
55+
value={value}
56+
disabled={!permissions.canEditChangeRequest || saving}
57+
onValueChange={(next) => void save(next)}
58+
/>
59+
{saving ? (
60+
<AppText accessibilityLiveRegion="polite" className="text-xs text-foreground-muted">
61+
Saving…
62+
</AppText>
63+
) : null}
64+
{error ? (
65+
<AppText accessibilityRole="alert" className="text-xs text-danger-foreground">
66+
Could not save maintainer access. Try again.
67+
</AppText>
68+
) : null}
69+
</View>
70+
);
71+
}

‎apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ import {
110110
PullRequestReadStatus,
111111
} from "./PullRequestPresentation";
112112
import { usePullRequestFilesSection } from "./PullRequestFiles";
113+
import { PullRequestMaintainerEdits } from "./PullRequestMaintainerEdits";
113114
import { PullRequestDescription } from "./PullRequestDescription";
114115
import { PullRequestMediaVisibleContext } from "./PullRequestMedia";
115116
import { PullRequestMarkdownRepository } from "./PullRequestMarkdown";
@@ -324,6 +325,15 @@ function PullRequestOverview(props: {
324325
footer={<PullRequestReactions params={props.params} />}
325326
/>
326327
</Animated.View>
328+
{pr.capabilities.edit?.maintainerEdits === true &&
329+
pr.viewerPermissions.maintainerEdits === true &&
330+
pr.maintainerCanModify !== undefined ? (
331+
<PullRequestMaintainerEdits
332+
key={`${pr.url}:${pr.maintainerCanModify}`}
333+
params={props.params}
334+
pr={pr}
335+
/>
336+
) : null}
327337
</View>
328338
);
329339
}

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,68 @@ function hostedChangeRequest(body: string, additions = 1) {
116116
};
117117
}
118118

119+
it.effect("reads and changes maintainer edits through the existing update command", () =>
120+
Effect.gen(function* () {
121+
let enabled = true;
122+
const provider = fakePullRequestProvider(SourceControlProviderKind.make("github"), {
123+
getChangeRequest: () =>
124+
Effect.succeed({ ...hostedChangeRequest("Body"), maintainerCanModify: enabled }),
125+
updateChangeRequest: (input) =>
126+
Effect.sync(() => {
127+
assert.strictEqual(input.title, undefined);
128+
assert.strictEqual(input.body, undefined);
129+
enabled = input.maintainerCanModify!;
130+
}),
131+
});
132+
const service = yield* makeService({
133+
projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })],
134+
providers: [
135+
{
136+
...provider,
137+
capabilities: {
138+
...provider.capabilities,
139+
edit: { changeRequest: true, comment: true, maintainerEdits: true },
140+
},
141+
},
142+
],
143+
});
144+
const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
145+
assert.strictEqual((yield* service.detail(ref)).maintainerCanModify, true);
146+
for (const value of [false, true]) {
147+
yield* service.update({ ...ref, maintainerCanModify: value });
148+
assert.strictEqual((yield* service.detail(ref)).maintainerCanModify, value);
149+
}
150+
}),
151+
);
152+
153+
it.effect("refuses maintainer edits on hosts that do not support them", () =>
154+
Effect.gen(function* () {
155+
let writes = 0;
156+
const service = yield* makeService({
157+
projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })],
158+
providers: [
159+
fakePullRequestProvider(SourceControlProviderKind.make("github"), {
160+
updateChangeRequest: () =>
161+
Effect.sync(() => {
162+
writes += 1;
163+
}),
164+
}),
165+
],
166+
});
167+
const result = yield* service
168+
.update({
169+
projectId: "p1" as ProjectId,
170+
repository: "acme/web",
171+
number: 1,
172+
body: "Body",
173+
maintainerCanModify: false,
174+
})
175+
.pipe(Effect.flip);
176+
assert.strictEqual(result._tag, "PullRequestOperationError");
177+
assert.strictEqual(writes, 0);
178+
}),
179+
);
180+
119181
it.effect("does not wait for an in-flight detail read to display a preview", () =>
120182
Effect.gen(function* () {
121183
const detailStarted = yield* Deferred.make<void>();

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1753,6 +1753,9 @@ export const make = Effect.gen(function* () {
17531753
...(changeRequest.autoMergeMethod === undefined
17541754
? {}
17551755
: { autoMergeMethod: changeRequest.autoMergeMethod }),
1756+
...(changeRequest.maintainerCanModify === undefined
1757+
? {}
1758+
: { maintainerCanModify: changeRequest.maintainerCanModify }),
17561759
...(changeRequest.workflowApprovalsRequired === undefined
17571760
? {}
17581761
: { workflowApprovalsRequired: changeRequest.workflowApprovalsRequired }),
@@ -2134,7 +2137,22 @@ export const make = Effect.gen(function* () {
21342137
}),
21352138
);
21362139
}
2137-
if (input.title === undefined && input.body === undefined) {
2140+
if (
2141+
input.maintainerCanModify !== undefined &&
2142+
project.api.capabilities.edit?.maintainerEdits !== true
2143+
) {
2144+
return Effect.fail(
2145+
new PullRequestOperationError({
2146+
operation: "update",
2147+
detail: "This host does not support maintainer edits.",
2148+
}),
2149+
);
2150+
}
2151+
if (
2152+
input.title === undefined &&
2153+
input.body === undefined &&
2154+
input.maintainerCanModify === undefined
2155+
) {
21382156
return Effect.fail(
21392157
new PullRequestOperationError({
21402158
operation: "update",
@@ -2147,6 +2165,9 @@ export const make = Effect.gen(function* () {
21472165
repository: project.repository,
21482166
host: project.host,
21492167
number: input.number,
2168+
...(input.maintainerCanModify === undefined
2169+
? {}
2170+
: { maintainerCanModify: input.maintainerCanModify }),
21502171
...(input.title === undefined ? {} : { title: input.title }),
21512172
...(input.body === undefined ? {} : { body: input.body }),
21522173
}).pipe(Effect.mapError(toPullRequestError("update")));

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1732,6 +1732,7 @@ export function PullRequestDetailPanel({
17321732
detail={detail}
17331733
activityPending={activityPending}
17341734
checksStale={checksStale}
1735+
canWriteSourceControl={canWriteSourceControl && environmentConnected}
17351736
activityError={activityError}
17361737
pendingFinding={handoff}
17371738
fixFindingLabel={handoffLabels.fixFinding}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import "~/index.css";
2+
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
3+
import { expect, it, vi } from "vite-plus/test";
4+
5+
const mocks = vi.hoisted(() => ({
6+
update: vi.fn<(input: unknown) => Promise<{ _tag: "Success" | "Failure" }>>(),
7+
}));
8+
vi.mock(
9+
import("~/state/pullRequests"),
10+
() => ({ pullRequestEnvironment: { update: {} } }) as never,
11+
);
12+
vi.mock(
13+
import("~/state/use-atom-command"),
14+
() => ({ useAtomCommand: () => mocks.update }) as never,
15+
);
16+
17+
import { render } from "../../../test/render";
18+
import { PullRequestMaintainerEdits } from "./PullRequestMaintainerEdits";
19+
20+
const reference = { projectId: ProjectId.make("project"), repository: "owner/repo", number: 7 };
21+
const environmentId = EnvironmentId.make("environment");
22+
23+
function setup() {
24+
mocks.update.mockReset().mockResolvedValue({ _tag: "Success" });
25+
const onSaved = vi.fn();
26+
const control = (allowed = true) => (
27+
<PullRequestMaintainerEdits
28+
environmentId={environmentId}
29+
reference={reference}
30+
enabled={true}
31+
allowed={allowed}
32+
onSaved={onSaved}
33+
/>
34+
);
35+
return { control, onSaved };
36+
}
37+
38+
it("saves both directions without waiting for a refreshed detail", async () => {
39+
const { control, onSaved } = setup();
40+
await using screen = await render(control());
41+
const checkbox = screen.getByRole("checkbox", { name: "Allow edits from maintainers" });
42+
await checkbox.click();
43+
await expect.element(checkbox).not.toBeChecked();
44+
await vi.waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
45+
await checkbox.click();
46+
await expect.element(checkbox).toBeChecked();
47+
expect(mocks.update.mock.calls.map(([input]) => input)).toEqual([
48+
{ environmentId, input: { ...reference, maintainerCanModify: false } },
49+
{ environmentId, input: { ...reference, maintainerCanModify: true } },
50+
]);
51+
});
52+
53+
it("locks the control while a save is in flight", async () => {
54+
const { control } = setup();
55+
let settle!: (value: { _tag: "Success" }) => void;
56+
const pending = new Promise<{ _tag: "Success" }>((resolve) => {
57+
settle = resolve;
58+
});
59+
mocks.update.mockReturnValue(pending);
60+
await using screen = await render(control());
61+
const checkbox = screen.getByRole("checkbox");
62+
await checkbox.click();
63+
await expect.element(checkbox).toBeDisabled();
64+
await expect.element(screen.getByRole("status")).toHaveTextContent("Saving…");
65+
expect(mocks.update).toHaveBeenCalledTimes(1);
66+
settle({ _tag: "Success" });
67+
await expect.element(checkbox).toBeEnabled();
68+
});
69+
70+
it("restores the last saved value after a failed save and lets the user retry", async () => {
71+
const { control, onSaved } = setup();
72+
await using screen = await render(control());
73+
const checkbox = screen.getByRole("checkbox");
74+
await checkbox.click();
75+
await expect.element(checkbox).not.toBeChecked();
76+
await vi.waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
77+
mocks.update.mockResolvedValueOnce({ _tag: "Failure" });
78+
await checkbox.click();
79+
await expect
80+
.element(screen.getByRole("alert"))
81+
.toHaveTextContent("Could not save maintainer access. Try again.");
82+
await expect.element(checkbox).not.toBeChecked();
83+
expect(onSaved).toHaveBeenCalledTimes(1);
84+
await checkbox.click();
85+
await expect.element(checkbox).toBeChecked();
86+
await expect.element(screen.getByRole("alert")).not.toBeInTheDocument();
87+
});
88+
89+
it("blocks a session without source control write access", async () => {
90+
const { control } = setup();
91+
await using screen = await render(control(false));
92+
await expect.element(screen.getByRole("checkbox")).toBeDisabled();
93+
expect(mocks.update).not.toHaveBeenCalled();
94+
});
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
2+
import { useId, useRef, useState } from "react";
3+
4+
import { pullRequestEnvironment } from "~/state/pullRequests";
5+
import { useAtomCommand } from "~/state/use-atom-command";
6+
import { Checkbox } from "../ui/checkbox";
7+
8+
export function PullRequestMaintainerEdits({
9+
environmentId,
10+
reference,
11+
enabled,
12+
allowed,
13+
onSaved,
14+
}: {
15+
environmentId: EnvironmentId;
16+
reference: PullRequestRef;
17+
enabled: boolean;
18+
allowed: boolean;
19+
onSaved: () => void;
20+
}) {
21+
const id = useId();
22+
const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
23+
const [value, setValue] = useState(enabled);
24+
const [saving, setSaving] = useState(false);
25+
const [error, setError] = useState(false);
26+
const inFlight = useRef(false);
27+
const save = async (next: boolean) => {
28+
if (!allowed || inFlight.current) return;
29+
const previous = value;
30+
inFlight.current = true;
31+
setSaving(true);
32+
setError(false);
33+
setValue(next);
34+
const result = await update({
35+
environmentId,
36+
input: { ...reference, maintainerCanModify: next },
37+
});
38+
inFlight.current = false;
39+
setSaving(false);
40+
if (result._tag === "Failure") {
41+
setValue(previous);
42+
setError(true);
43+
return;
44+
}
45+
onSaved();
46+
};
47+
48+
return (
49+
<div className="mt-4 border-t border-border/60 pt-3">
50+
<div className="flex items-start gap-2.5 text-xs">
51+
<span className="pt-0.5">
52+
<Checkbox
53+
id={id}
54+
checked={value}
55+
disabled={!allowed || saving}
56+
aria-describedby={`${id}-hint`}
57+
onCheckedChange={(next) => void save(next)}
58+
/>
59+
</span>
60+
<div className="min-w-0 space-y-1">
61+
<label htmlFor={id} className="block font-medium text-foreground">
62+
Allow edits from maintainers
63+
</label>
64+
<span id={`${id}-hint`} className="block max-w-sm leading-relaxed text-muted-foreground">
65+
Maintainers can push to this branch. If your fork has workflows, this can also give
66+
access to its secrets.
67+
</span>
68+
</div>
69+
</div>
70+
{saving ? (
71+
<p role="status" className="mt-2 text-xs text-muted-foreground">
72+
Saving…
73+
</p>
74+
) : null}
75+
{error ? (
76+
<p role="alert" className="mt-2 text-xs text-destructive">
77+
Could not save maintainer access. Try again.
78+
</p>
79+
) : null}
80+
</div>
81+
);
82+
}

0 commit comments

Comments
 (0)