Skip to content

Commit b995be0

Browse files
committed
fix(review): show admin merge option and group pending replies
1 parent 470ffbc commit b995be0

19 files changed

Lines changed: 528 additions & 172 deletions

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

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { reviewThreadReplyTarget } from "@t3tools/client-runtime/review-editing";
1+
import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions";
2+
import { useRetiredReviewDraftCommentIds } from "./usePullRequestReviewDraft";
3+
import {
4+
reviewThreadReplyTarget,
5+
pendingReviewCommentsFromThreads,
6+
} from "@t3tools/client-runtime/review-editing";
27
import { useAtomRefresh } from "@effect/atom-react";
38
import { useNavigation } from "@react-navigation/native";
49
import { reviewLineRangeLabel } from "@t3tools/client-runtime/review-selection";
@@ -105,6 +110,8 @@ export function PullRequestCommentItem({
105110
badges,
106111
meta,
107112
leadingAction,
113+
onDiscard,
114+
disabled,
108115
onResolve,
109116
onUnresolve,
110117
}: {
@@ -126,13 +133,17 @@ export function PullRequestCommentItem({
126133
meta?: ReactNode;
127134
/** A direct action shown before the reaction and overflow controls. */
128135
leadingAction?: ReactNode;
136+
onDiscard?: (() => void) | undefined;
137+
disabled?: boolean;
129138
onResolve?: (() => void) | undefined;
130139
onUnresolve?: (() => void) | undefined;
131140
}) {
132141
return (
133142
<PullRequestCommentControls
134143
params={params}
135144
comment={comment}
145+
onDiscard={onDiscard}
146+
disabled={disabled}
136147
onResolve={onResolve}
137148
onUnresolve={onUnresolve}
138149
render={({ actions, reactions }) => (
@@ -295,12 +306,22 @@ export function PullRequestThreadCard({
295306
const [uploading, setUploading] = useState(false);
296307
const sendingRef = useRef(false);
297308
const page = loadedPage?.threadId === thread.id ? loadedPage : null;
298-
const comments = useMemo(
299-
() => mergeReviewThreadComments(thread.comments, page?.comments ?? []),
300-
[thread.comments, page?.comments],
301-
);
309+
const pendingActions = usePendingReviewCommentActions(params);
310+
const retiredIds = useRetiredReviewDraftCommentIds(params);
311+
const comments = useMemo(() => {
312+
const retired = new Set(retiredIds);
313+
return mergeReviewThreadComments(thread.comments, page?.comments ?? []).filter(
314+
(comment) => !comment.pendingReviewId || !retired.has(comment.id),
315+
);
316+
}, [thread.comments, page?.comments, retiredIds]);
302317
const nextCursor = page === null ? (thread.nextCommentsCursor ?? null) : page.nextCursor;
303318
const summary = reviewThreadSummary(thread);
319+
const pendingById = new Map(
320+
pendingReviewCommentsFromThreads([{ ...thread, comments }]).map((comment) => [
321+
comment.id,
322+
{ ...comment, headSha: "", code: "" },
323+
]),
324+
);
304325

305326
const send = async () => {
306327
const body = reply.trim();
@@ -417,6 +438,27 @@ export function PullRequestThreadCard({
417438
params={params}
418439
comment={{ ...comment, url: comment.url ?? null }}
419440
badges={comment.pendingReviewId ? <PullRequestPendingBadge /> : null}
441+
disabled={pendingActions.busy}
442+
onDiscard={
443+
comment.pendingReviewId &&
444+
pendingById.has(comment.id) &&
445+
pendingActions.canDiscard
446+
? () =>
447+
Alert.alert(
448+
"Discard this comment?",
449+
"Your other review comments will be kept.",
450+
[
451+
{ text: "Cancel", style: "cancel" },
452+
{
453+
text: "Discard",
454+
style: "destructive",
455+
onPress: () =>
456+
void pendingActions.discard(pendingById.get(comment.id)!),
457+
},
458+
],
459+
)
460+
: undefined
461+
}
420462
leadingAction={
421463
index === 0 && actions.canResolve && !thread.isResolved ? (
422464
<InlineIconAction

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ export function PullRequestCommentControls({
3434
onEdit,
3535
onUnresolve,
3636
onResolve,
37+
onDiscard,
3738
disabled,
3839
render,
3940
}: {
@@ -51,6 +52,7 @@ export function PullRequestCommentControls({
5152
onUnresolve?: (() => void) | undefined;
5253
onResolve?: (() => void) | undefined;
5354
disabled?: boolean;
55+
onDiscard?: (() => void) | undefined;
5456
render?: (slots: { actions: ReactNode; reactions: ReactNode }) => ReactNode;
5557
}) {
5658
const target = pullRequestTarget(params);
@@ -202,6 +204,15 @@ export function PullRequestCommentControls({
202204
]
203205
: []),
204206
...(onEdit || canEdit ? [{ id: "edit", title: "Edit comment" }] : []),
207+
...(onDiscard
208+
? [
209+
{
210+
id: "discard",
211+
title: "Discard comment",
212+
attributes: { destructive: true, disabled: Boolean(disabled) },
213+
},
214+
]
215+
: []),
205216
{
206217
id: "copy-menu",
207218
title: "Copy",
@@ -233,6 +244,7 @@ export function PullRequestCommentControls({
233244
markdown,
234245
);
235246
else if (nativeEvent.event === "unresolve") onUnresolve?.();
247+
else if (nativeEvent.event === "discard") onDiscard?.();
236248
else if (nativeEvent.event === "edit") edit();
237249
else if (nativeEvent.event === "copy") void Clipboard.setStringAsync(markdown);
238250
else if (nativeEvent.event === "copy-link" && comment.url)

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

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,26 @@ export function PullRequestCommentsSheet({
3333
const [status, setStatus] = useState<"resolved" | "unresolved" | "pending">("unresolved");
3434
// Threads come from the optimistic activity projection, so a resolve moves its card between
3535
// tabs and updates every count before the host answers.
36-
const resolved = draft.threads.filter((thread) => thread.isResolved);
37-
const unresolved = draft.threads.filter((thread) => !thread.isResolved);
38-
const counts = countReviewThreads(draft.threads);
36+
const published = draft.threads.filter((thread) =>
37+
thread.comments.some((comment) => !comment.pendingReviewId),
38+
);
39+
const pendingThreads = draft.threads.filter((thread) =>
40+
thread.comments.some((comment) => comment.pendingReviewId),
41+
);
42+
const resolved = published.filter((thread) => thread.isResolved);
43+
const unresolved = published.filter((thread) => !thread.isResolved);
44+
const counts = countReviewThreads(published);
3945
// Removing the last draft also removes its tab; stay on an available status.
4046
const selectedStatus =
4147
status === "pending" && draft.comments.length === 0 ? "unresolved" : status;
4248
if (selectedStatus !== status) setStatus(selectedStatus);
4349
const threads =
44-
selectedStatus === "resolved" ? resolved : selectedStatus === "unresolved" ? unresolved : [];
45-
const pending = selectedStatus === "pending" ? draft.comments : [];
50+
selectedStatus === "resolved"
51+
? resolved
52+
: selectedStatus === "unresolved"
53+
? unresolved
54+
: pendingThreads;
55+
const pending = selectedStatus === "pending" ? draft.ungroupedComments : [];
4656
const options = [
4757
{
4858
value: "unresolved" as const,

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

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,11 @@ export function PullRequestMergeControls(props: {
107107
checks: pr.checks,
108108
baseBehind: pr.baseComparison === "behind" && pr.mergeability === "mergeable",
109109
});
110-
const canBypassRequirements = canAdminMerge && requirementsUnmet;
111110
const confirmationKey = `${target.environmentId}:${pr.projectId}:${pr.repository}:${pr.number}:${pr.headSha ?? ""}:${method ?? ""}`;
112111
const bypass = confirmation?.key === confirmationKey && confirmation.bypass;
113-
const confirmationOpen = confirmation?.key === confirmationKey && canBypassRequirements;
112+
const confirmationOpen = confirmation?.key === confirmationKey && canAdminMerge;
114113
const canConfirmAutoMerge = canAutoMerge && autoAction === "enable-auto-merge";
115-
if (confirmation !== null && (!canBypassRequirements || confirmation.key !== confirmationKey))
114+
if (confirmation !== null && (!canAdminMerge || confirmation.key !== confirmationKey))
116115
setConfirmation(null);
117116
const perform = async (
118117
action: "merge" | "enable-auto-merge" | "disable-auto-merge",
@@ -121,7 +120,7 @@ export function PullRequestMergeControls(props: {
121120
if (
122121
pending.current ||
123122
(action !== "disable-auto-merge" && !method) ||
124-
(action === "merge" ? (adminOverride ? !canBypassRequirements : !canMerge) : !canAutoMerge)
123+
(action === "merge" ? (adminOverride ? !canAdminMerge : !canMerge) : !canAutoMerge)
125124
)
126125
return false;
127126
pending.current = true;
@@ -180,7 +179,7 @@ export function PullRequestMergeControls(props: {
180179
});
181180
};
182181
const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
183-
if (action === "merge" && canBypassRequirements) {
182+
if (action === "merge" && canAdminMerge) {
184183
setConfirmation({ key: confirmationKey, bypass: false });
185184
return;
186185
}
@@ -337,14 +336,16 @@ export function PullRequestMergeControls(props: {
337336
<Text className="text-sm text-foreground-muted">
338337
{bypass
339338
? `Merge #${pr.number} into ${pr.baseBranch} before its requirements are met.`
340-
: canConfirmAutoMerge || pr.autoMergeEnabled
341-
? "Merge requirements have not passed. Auto-merge waits for them to be met."
342-
: "Merge requirements have not passed."}
339+
: requirementsUnmet
340+
? canConfirmAutoMerge || pr.autoMergeEnabled
341+
? "Merge requirements have not passed. Auto-merge waits for them to be met."
342+
: "Merge requirements have not passed."
343+
: `Merge #${pr.number} into ${pr.baseBranch} using ${method}.`}
343344
</Text>
344345
</View>
345346
<Pressable
346347
accessibilityRole="checkbox"
347-
accessibilityLabel="Merge without waiting for requirements to be met (bypass rules)"
348+
accessibilityLabel="Merge with admin permissions"
348349
accessibilityState={{ checked: bypass, disabled: busy }}
349350
disabled={busy}
350351
className="min-h-11 flex-row items-start gap-2 py-2"
@@ -362,7 +363,7 @@ export function PullRequestMergeControls(props: {
362363
) : null}
363364
</View>
364365
<Text className="min-w-0 flex-1 text-sm text-danger-foreground">
365-
Merge without waiting for requirements to be met (bypass rules)
366+
Merge with admin permissions
366367
</Text>
367368
</Pressable>
368369
<View className="flex-row flex-wrap justify-end gap-2">

‎apps/mobile/src/features/pull-requests/pullRequestDiffComments.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import { resolvedReviewCommentsLabel } from "@t3tools/client-runtime/review-editing";
1+
import {
2+
resolvedReviewCommentsLabel,
3+
groupPendingReviewComments,
4+
} from "@t3tools/client-runtime/review-editing";
25
export { reviewPositionLabel } from "@t3tools/client-runtime/review-selection";
36
import {
47
reviewPositionLabel,
@@ -96,7 +99,7 @@ export function annotatePullRequestDiff(
9699
: undefined,
97100
);
98101
}
99-
for (const draft of drafts) {
102+
for (const draft of groupPendingReviewComments(threads, drafts).pendingComments) {
100103
if (draft.headSha !== headSha) continue;
101104
const side =
102105
draft.position.kind === "deleted"

‎apps/mobile/src/features/pull-requests/usePullRequestReviewDraft.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import { useEffect, useMemo } from "react";
3-
import { pendingReviewCommentsFromThreads } from "@t3tools/client-runtime/review-editing";
3+
import {
4+
pendingReviewCommentsFromThreads,
5+
groupPendingReviewComments,
6+
} from "@t3tools/client-runtime/review-editing";
47
import { AppState } from "react-native";
58
import * as Atom from "effect/reactivity/Atom";
69
import * as Schema from "effect/Schema";
@@ -28,6 +31,12 @@ const removedHostComments = Atom.make<Readonly<Record<string, ReadonlyArray<stri
2831
Atom.keepAlive,
2932
);
3033

34+
const NO_RETIRED_COMMENTS: ReadonlyArray<string> = [];
35+
36+
export function useRetiredReviewDraftCommentIds(params: PullRequestParams) {
37+
return useAtomValue(removedHostComments)[pullRequestReviewKey(params)] ?? NO_RETIRED_COMMENTS;
38+
}
39+
3140
/** Keep a successful removal from reappearing in an older activity snapshot. */
3241
export function retireReviewDraftComments(
3342
params: PullRequestParams,
@@ -167,12 +176,11 @@ export function usePullRequestReviewDraft(params: PullRequestParams) {
167176
.map((comment) => ({ ...comment, headSha: detail.data?.headSha ?? "", code: "" }));
168177
return remote.length ? [...local, ...remote] : local;
169178
}, [draft.comments, activity.data?.reviewThreads, detail, retiredIds]);
170-
const threads = useMemo(() => {
171-
return (activity.data?.reviewThreads ?? []).flatMap((thread) => {
172-
const published = thread.comments.filter((comment) => !comment.pendingReviewId);
173-
return published.length ? [{ ...thread, comments: published }] : [];
174-
});
175-
}, [activity.data?.reviewThreads]);
179+
const grouped = useMemo(
180+
() => groupPendingReviewComments(activity.data?.reviewThreads ?? [], comments),
181+
[activity.data?.reviewThreads, comments],
182+
);
183+
const threads = grouped.threads;
176184
const pendingReviewId = comments.find((comment) => comment.hostedComment)?.hostedComment
177185
?.reviewId;
178186
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads review drafts from disk and persists them when AppState leaves active and on unmount
@@ -191,6 +199,7 @@ export function usePullRequestReviewDraft(params: PullRequestParams) {
191199
return {
192200
draft,
193201
comments,
202+
ungroupedComments: grouped.pendingComments,
194203
threads,
195204
activityLoaded: activity.data !== null,
196205
activityError: activity.error,

‎apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { EnvironmentId, ProjectId, ThreadId, type PullRequestCheck } from "@t3tools/contracts";
22
import { DraftId } from "~/composerDraftStore";
3-
import { AsyncResult } from "effect/reactivity";
3+
import { AsyncResult, Atom } from "effect/reactivity";
44
import { expect, it, vi } from "vite-plus/test";
5+
import { page } from "vite-plus/test/browser";
6+
import { pullRequestEnvironment } from "~/state/pullRequests";
57

68
const state = vi.hoisted(() => ({
9+
adminMerge: false,
710
status: "success" as PullRequestCheck["status"],
811
extraStatus: null as PullRequestCheck["status"] | null,
912
mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">,
@@ -47,7 +50,7 @@ const queryData = () => ({
4750
url: null,
4851
})),
4952
capabilities: { actions: ["merge"], mergeMethods: state.mergeMethods },
50-
viewerPermissions: { actions: ["merge"] },
53+
viewerPermissions: { actions: ["merge"], adminMerge: state.adminMerge },
5154
mergeCapabilities: {
5255
merge: state.mergeMethods.includes("merge"),
5356
squash: state.mergeMethods.includes("squash"),
@@ -168,6 +171,7 @@ it("requires a new merge click after passing checks become pending and pass agai
168171
});
169172
expect(dialogs()).toHaveLength(0);
170173
await act(async () => {
174+
state.adminMerge = false;
171175
state.status = "success";
172176
await screen.rerender(render());
173177
});
@@ -177,6 +181,59 @@ it("requires a new merge click after passing checks become pending and pass agai
177181
expect(state.perform).not.toHaveBeenCalled();
178182
});
179183

184+
it("resets admin permission consent after cancellation or lost access", async () => {
185+
using _permission = vi
186+
.spyOn(pullRequestEnvironment.runAction, "permissionAtom")
187+
.mockReturnValue(Atom.make(true));
188+
await using screen = await setup();
189+
state.adminMerge = true;
190+
const row = () => (
191+
<ThreadDetailsPrRow
192+
environmentId={EnvironmentId.make("environment")}
193+
pr={null}
194+
number={1}
195+
status={null}
196+
project={null}
197+
label="Test PR"
198+
openAriaLabel="Open PR"
199+
onOpen={vi.fn()}
200+
/>
201+
);
202+
await screen.rerender(row());
203+
const open = () =>
204+
act(() => {
205+
[...screen.container.querySelectorAll("button")]
206+
.find((button) => button.textContent?.trim() === "Merge")!
207+
.click();
208+
});
209+
const toggle = () =>
210+
act(() => {
211+
document.querySelector<HTMLLabelElement>('label:has([role="checkbox"])')!.click();
212+
});
213+
const cancel = () =>
214+
act(() => {
215+
[...document.querySelectorAll('[role="alertdialog"] button')]
216+
.find((button) => button.textContent?.trim() === "Cancel")!
217+
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
218+
});
219+
const checkbox = () => page.getByRole("checkbox", { name: "Merge with admin permissions" });
220+
await open();
221+
await expect.element(checkbox()).not.toBeChecked();
222+
await toggle();
223+
await expect.element(checkbox()).toBeChecked();
224+
await cancel();
225+
await open();
226+
await expect.element(checkbox()).not.toBeChecked();
227+
await toggle();
228+
state.adminMerge = false;
229+
await screen.rerender(row());
230+
await expect.element(page.getByRole("alertdialog")).not.toBeInTheDocument();
231+
state.adminMerge = true;
232+
await screen.rerender(row());
233+
await open();
234+
await expect.element(checkbox()).not.toBeChecked();
235+
});
236+
180237
async function setup() {
181238
state.perform.mockReset();
182239
state.checkoutError = null;
@@ -188,6 +245,7 @@ async function setup() {
188245
state.addToast.mockReset().mockReturnValue("checkout-toast");
189246
state.updateToast.mockReset();
190247

248+
state.adminMerge = false;
191249
state.status = "success";
192250
state.extraStatus = null;
193251
state.mergeMethods = ["merge"];

0 commit comments

Comments
 (0)