The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 09:45 UTC
fix(pr): label and reviewer pickers send picks once, when they close (#37733)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 16, 2026 at 11:54 UTC
15271c8d00875d2fb03a71cf8dec778273c19cdd
9 files changed
+351
-116
apps/mobile/src/features/pull-requests/PullRequestLabelsScreen.tsx
+55
-35
@@ -1,15 +1,23 @@
1
import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2
import { LegendList } from "@legendapp/list/react-native";
3
import { useAtomValue } from "@effect/atom-react";
4
-import type { StaticScreenProps } from "@react-navigation/native";
4
+import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
5
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6
+import {
7
+ emptySelection,
8
+ isSelected,
9
+ changeBatches,
10
+ selectionChanges,
11
+ toggleSelection,
12
+} from "@t3tools/client-runtime/pull-request-selection";
13
import type { PullRequestLabelCandidate } from "@t3tools/contracts";
14
import { AsyncResult } from "effect/reactivity";
8
-import { useRef, useState } from "react";
15
+import { useEffect, useState } from "react";
16
import { Platform, View } from "react-native";
17
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
18
import { AppText as Text } from "../../components/ui/AppText";
19
import { Button } from "../../components/ui/Button";
20
+import * as Dialog from "../../components/ui/Dialog";
21
import { EmptyState } from "../../components/ui/EmptyState";
22
import { SelectionRow } from "../../components/ui/SelectionRow";
23
import { composerPullRequests } from "../../state/pull-requests";
@@ -22,6 +30,7 @@ import { usePullRequestConnected } from "./usePullRequestConnected";
30
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
31
32
export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequestParams>) {
33
+ const navigation = useNavigation();
34
const target = pullRequestTarget(route.params);
35
const pr = useEnvironmentQuery(composerPullRequests.detail(target)).data;
36
const canWrite = useAtomValue(
@@ -47,30 +56,46 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequest
56
const result = useEnvironmentQuery(composerPullRequests.labelCandidates(target));
57
const setLabels = useAtomCommand(composerPullRequests.setLabels, { reportFailure: false });
58
const [query, setQuery] = useState("");
50
- const [pending, setPending] = useState<{ readonly name: string; readonly applied: boolean }>();
51
- const [error, setError] = useState<string | null>(null);
52
- const inFlight = useRef(false);
59
+ const [draft, setDraft] = useState(emptySelection<PullRequestLabelCandidate>);
60
const needle = query.trim().toLowerCase();
61
// Host order, not applied-first: re-sorting on toggle would move the row out from under a tap.
62
const candidates = (result.data?.candidates ?? []).filter((candidate) =>
63
`${candidate.name} ${candidate.description ?? ""}`.toLowerCase().includes(needle),
64
);
58
- const toggle = async (candidate: PullRequestLabelCandidate) => {
59
- if (!allowed || inFlight.current) return;
60
- inFlight.current = true;
61
- setPending({ name: candidate.name, applied: !candidate.isApplied });
62
- setError(null);
63
- const response = await setLabels({
64
- ...target,
65
- input: { ...target.input, labels: [candidate.name], applied: !candidate.isApplied },
66
- });
67
- inFlight.current = false;
68
- setPending(undefined);
69
- if (AsyncResult.isFailure(response)) {
70
- const cause = squashAtomCommandFailure(response);
71
- setError(cause instanceof Error ? cause.message : "Couldn't update this label. Try again.");
72
- }
73
- };
65
+ const latest = result.data?.candidates;
66
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
67
+ useEffect(
68
+ () =>
69
+ navigation.addListener("beforeRemove", () => {
70
+ const { add, remove } = selectionChanges(
71
+ draft,
72
+ (name, label) =>
73
+ latest?.find((entry) => entry.name === name)?.isApplied ?? label.isApplied,
74
+ );
75
+ const sendBatch = async (
76
+ labels: ReadonlyArray<PullRequestLabelCandidate>,
77
+ applied: boolean,
78
+ ) => {
79
+ const names = labels.map((label) => label.name);
80
+ const response = await setLabels({
81
+ ...target,
82
+ input: { ...target.input, labels: names, applied },
83
+ });
84
+ if (!AsyncResult.isFailure(response)) return;
85
+ const cause = squashAtomCommandFailure(response);
86
+ Dialog.alert(
87
+ applied ? `Couldn't add ${names.join(", ")}` : `Couldn't remove ${names.join(", ")}`,
88
+ cause instanceof Error ? cause.message : "The provider refused the change.",
89
+ );
90
+ };
91
+ const send = async (labels: ReadonlyArray<PullRequestLabelCandidate>, applied: boolean) => {
92
+ for (const batch of changeBatches(labels)) await sendBatch(batch, applied);
93
+ };
94
+ // Adding first keeps the Labels row from showing empty between the two writes.
95
+ void send(add, true).then(() => send(remove, false));
96
+ }),
97
+ [navigation, draft, latest, setLabels, target],
98
+ );
99
return (
100
<PullRequestSearchSheet
101
title="Labels"
@@ -85,7 +110,7 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequest
110
renderScrollComponent={NativeScrollView}
111
data={candidates}
112
keyExtractor={(candidate) => candidate.name}
88
- extraData={{ pending, allowed, count: candidates.length }}
113
+ extraData={{ draft, allowed, count: candidates.length }}
114
estimatedItemSize={72}
115
recycleItems
116
className="flex-1"
@@ -96,16 +121,9 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequest
121
showsVerticalScrollIndicator={false}
122
contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }}
123
ListHeaderComponent={
99
- readOnlyReason || error ? (
100
- <View className="gap-2 pb-3">
101
- {readOnlyReason ? (
102
- <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
103
- ) : null}
104
- {error ? (
105
- <Text selectable className="text-sm text-danger-foreground">
106
- {error}
107
- </Text>
108
- ) : null}
124
+ readOnlyReason ? (
125
+ <View className="pb-3">
126
+ <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
127
</View>
128
) : undefined
129
}
@@ -114,13 +132,15 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequest
132
title={item.name}
133
{...(item.description ? { subtitle: item.description } : {})}
134
role="checkbox"
117
- // The change shows as soon as it is tapped; a failure puts the host's answer back.
118
- selected={pending?.name === item.name ? pending.applied : item.isApplied}
135
+ // Sent when the sheet closes; a failure puts the host's answer back.
136
+ selected={isSelected(draft, item.name, item.isApplied)}
137
disabled={!allowed}
138
isFirst={index === 0}
139
isLast={index === candidates.length - 1}
140
leading={<PullRequestLabelDot color={pullRequestLabelColor(item.color)} />}
123
- onPress={() => void toggle(item)}
141
+ onPress={() =>
142
+ setDraft((current) => toggleSelection(current, item.name, item, item.isApplied))
143
+ }
144
/>
145
)}
146
ListEmptyComponent={
apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
+73
-19
@@ -12,14 +12,22 @@ import {
12
reviewerCandidateView,
13
type ReviewerTruncation,
14
} from "@t3tools/client-runtime/pull-request-reviewers";
15
+import {
16
+ emptySelection,
17
+ isSelected,
18
+ changeBatches,
19
+ selectionChanges,
20
+ toggleSelection,
21
+} from "@t3tools/client-runtime/pull-request-selection";
22
import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
16
-import { useRef, useState } from "react";
23
+import { useEffect, useRef, useState } from "react";
24
import { Pressable, ScrollView, View } from "react-native";
25
import { NativeScrollView } from "../../native/NativeScrollViewMarker";
26
import { useContentTopInset, useSearchToolbarInset } from "../../components/ui/useBarInset";
27
import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
28
import { EmptyState } from "../../components/ui/EmptyState";
29
import { Button } from "../../components/ui/Button";
30
+import * as Dialog from "../../components/ui/Dialog";
31
import { SymbolView } from "../../components/ui/AppSymbol";
32
import { composerPullRequests } from "../../state/pull-requests";
33
import { useEnvironmentQuery } from "../../state/query";
@@ -68,6 +76,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
76
const [pending, setPending] = useState<string | null>(null);
77
const [error, setError] = useState<string | null>(null);
78
const inFlight = useRef(false);
79
+ const [draft, setDraft] = useState(emptySelection<PullRequestReviewerCandidate>);
80
const debouncedQuery = useDebouncedValue(query.trim(), 250);
81
const searchInput = {
82
loaded: result.data,
@@ -100,6 +109,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
109
animated: false,
110
});
111
};
112
+ // Hosts that cannot list candidates take one typed id at a time.
113
const update = async (
114
candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
115
) => {
@@ -124,13 +134,60 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
134
);
135
return;
136
}
127
- if (hostQuery !== null) searchResult.refresh();
128
- if (!pr?.capabilities.reviewers.listCandidates) {
129
- search("");
130
- detail.refresh();
131
- }
137
+ search("");
138
+ detail.refresh();
139
};
140
const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
141
+ // Loaded rows first: they carry the request state mutations update.
142
+ const latest = [...(result.data?.candidates ?? []), ...(searchResult.data?.candidates ?? [])];
143
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
144
+ useEffect(
145
+ () =>
146
+ navigation.addListener("beforeRemove", () => {
147
+ const { add, remove } = selectionChanges(
148
+ draft,
149
+ (key, person) =>
150
+ latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ??
151
+ person.isRequested,
152
+ );
153
+ const sendBatch = async (
154
+ people: ReadonlyArray<PullRequestReviewerCandidate>,
155
+ requested: boolean,
156
+ ) => {
157
+ const response = await request({
158
+ ...target,
159
+ input: {
160
+ ...target.input,
161
+ reviewers: people.map(({ id, kind }) => ({ id, kind })),
162
+ requested,
163
+ },
164
+ });
165
+ if (!AsyncResult.isFailure(response)) return;
166
+ const cause = squashAtomCommandFailure(response);
167
+ const logins = people.map((person) => person.login).join(", ");
168
+ Dialog.alert(
169
+ requested
170
+ ? `Couldn't request a review from ${logins}`
171
+ : `Couldn't remove the review request from ${logins}`,
172
+ cause instanceof Error ? cause.message : "The provider refused the change.",
173
+ );
174
+ };
175
+ const send = async (
176
+ people: ReadonlyArray<PullRequestReviewerCandidate>,
177
+ requested: boolean,
178
+ ) => {
179
+ for (const batch of changeBatches(people)) await sendBatch(batch, requested);
180
+ };
181
+ // A search result is keyed by what was typed, so the writes do not reach it on their own.
182
+ const refreshSearch =
183
+ hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null;
184
+ // Removing first lets a host that keeps one reviewer take the new one.
185
+ void send(remove, false)
186
+ .then(() => send(add, true))
187
+ .then(() => refreshSearch?.());
188
+ }),
189
+ [navigation, draft, latest, request, target, hostQuery, searchResult.refresh],
190
+ );
191
const reviewerSearch: AppBarSearch | undefined = listCandidates
192
? {
193
mode: "inline",
@@ -155,7 +212,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
212
ref={listRef}
213
data={candidates}
214
keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
158
- extraData={{ allowed, pending }}
215
+ extraData={{ allowed, draft }}
216
estimatedItemSize={64}
217
recycleItems
218
renderScrollComponent={NativeScrollView}
@@ -168,28 +225,27 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
225
<View className="gap-3 px-4 py-4">
226
<Text className="text-xs text-foreground-muted">
227
Tap someone to request a review. Tap a requested reviewer to remove the request.
228
+ Changes are sent when you close this sheet.
229
</Text>
230
{!allowed ? (
231
<Text className="text-xs text-foreground-muted">
232
Requesting reviews requires write access and an open {singular}.
233
</Text>
234
) : null}
177
- {error ? (
178
- <Text selectable className="text-sm text-danger-foreground">
179
- {error}
180
- </Text>
181
- ) : null}
235
</View>
236
}
237
renderItem={({ item }) => {
238
const id = `${item.kind}:${item.id}`;
239
+ const requested = isSelected(draft, id, item.isRequested);
240
return (
241
<Pressable
242
accessibilityRole="button"
189
- accessibilityLabel={`${item.isRequested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`}
190
- accessibilityState={{ disabled: !allowed || pending !== null }}
191
- disabled={!allowed || pending !== null}
192
- onPress={() => void update(item)}
243
+ accessibilityLabel={`${requested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`}
244
+ accessibilityState={{ disabled: !allowed }}
245
+ disabled={!allowed}
246
+ onPress={() =>
247
+ setDraft((current) => toggleSelection(current, id, item, item.isRequested))
248
+ }
249
className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
250
>
251
<PullRequestAvatar actor={item} size={32} />
@@ -202,9 +258,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
258
{item.kind === "team" ? " · Team" : ""}
259
</Text>
260
</View>
205
- {pending === id ? (
206
- <AppActivityIndicator />
207
- ) : item.isRequested ? (
261
+ {requested ? (
262
<View className="flex-row items-center gap-1.5">
263
<Text className="text-xs text-foreground-muted">Requested</Text>
264
<SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx
+1
-9
@@ -32,7 +32,6 @@ export function PullRequestCandidatePicker<T>({
32
truncated,
33
truncatedLabel,
34
candidateKey,
35
- disabled,
35
onSelect,
36
children,
37
}: {
@@ -54,7 +53,6 @@ export function PullRequestCandidatePicker<T>({
53
truncated: boolean;
54
truncatedLabel: string;
55
candidateKey: (candidate: T) => string;
57
- disabled: boolean;
56
onSelect: (candidate: T) => void;
57
children: (candidate: T) => ReactNode;
58
}) {
@@ -123,13 +121,7 @@ export function PullRequestCandidatePicker<T>({
121
</p>
122
) : (
123
candidates.map((candidate, index) => (
126
- <ComboboxItem
127
- key={keys[index]}
128
- hideIndicator
129
- index={index}
130
- value={keys[index]}
131
- disabled={disabled}
132
- >
124
+ <ComboboxItem key={keys[index]} hideIndicator index={index} value={keys[index]}>
125
{children(candidate)}
126
</ComboboxItem>
127
))
apps/web/src/components/pullRequest/PullRequestLabelPicker.tsx
+45
-20
@@ -6,6 +6,13 @@ import { useState } from "react";
6
import { pullRequestEnvironment } from "~/state/pullRequests";
7
import { useEnvironmentQuery } from "~/state/query";
8
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9
+import {
10
+ emptySelection,
11
+ isSelected,
12
+ changeBatches,
13
+ selectionChanges,
14
+ toggleSelection,
15
+} from "@t3tools/client-runtime/pull-request-selection";
16
17
import { toastManager } from "../ui/toast";
18
import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";
@@ -32,6 +39,7 @@ export function PullRequestLabelPicker({
39
}) {
40
const [open, setOpen] = useState(false);
41
const [query, setQuery] = useState("");
42
+ const [draft, setDraft] = useState(emptySelection<PullRequestLabelCandidate>);
43
44
const candidatesQuery = useEnvironmentQuery(
45
open ? pullRequestEnvironment.labelCandidates({ environmentId, input: reference }) : null,
@@ -44,25 +52,39 @@ export function PullRequestLabelPicker({
52
matches(entry, query),
53
);
54
47
- // Each change shows at once and queues behind the one before it on the host.
48
- const toggle = async (candidate: PullRequestLabelCandidate) => {
55
+ const send = async (labels: ReadonlyArray<PullRequestLabelCandidate>, applied: boolean) => {
56
+ for (const batch of changeBatches(labels)) await sendBatch(batch, applied);
57
+ };
58
+ const sendBatch = async (labels: ReadonlyArray<PullRequestLabelCandidate>, applied: boolean) => {
59
+ const names = labels.map((label) => label.name);
60
const result = await setLabels({
61
environmentId,
51
- input: { ...reference, labels: [candidate.name], applied: !candidate.isApplied },
62
+ input: { ...reference, labels: names, applied },
63
+ });
64
+ if (result._tag === "Success") return;
65
+ toastManager.add({
66
+ type: "error",
67
+ title: applied
68
+ ? `Could not put ${names.join(", ")} on`
69
+ : `Could not take ${names.join(", ")} off`,
70
+ description: readableFailure(
71
+ squashAtomCommandFailure(result),
72
+ "The host refused it. Check that you have triage access on this repository.",
73
+ ),
74
});
53
- if (result._tag === "Failure") {
54
- toastManager.add({
55
- type: "error",
56
- title: candidate.isApplied
57
- ? `Could not take ${candidate.name} off`
58
- : `Could not put ${candidate.name} on`,
59
- description: readableFailure(
60
- squashAtomCommandFailure(result),
61
- "The host refused it. Check that you have triage access on this repository.",
62
- ),
63
- });
64
- return;
65
- }
75
+ };
76
+
77
+ const onOpenChange = (nextOpen: boolean) => {
78
+ setOpen(nextOpen);
79
+ if (nextOpen) return;
80
+ const latest = candidatesQuery.data?.candidates ?? [];
81
+ const { add, remove } = selectionChanges(
82
+ draft,
83
+ (name, label) => latest.find((entry) => entry.name === name)?.isApplied ?? label.isApplied,
84
+ );
85
+ setDraft(emptySelection());
86
+ // Adding first keeps the Labels row from showing empty between the two writes.
87
+ void send(add, true).then(() => send(remove, false));
88
};
89
90
return (
@@ -72,7 +94,7 @@ export function PullRequestLabelPicker({
94
allowed={allowed}
95
disabledReason="Changing labels needs triage access on this repository"
96
open={open}
75
- onOpenChange={setOpen}
97
+ onOpenChange={onOpenChange}
98
query={query}
99
onQueryChange={setQuery}
100
searchLabel="Search labels"
@@ -85,8 +107,11 @@ export function PullRequestLabelPicker({
107
truncated={candidatesQuery.data?.truncated === true}
108
truncatedLabel="This repository has more labels than are listed here. Apply the rest on the host."
109
candidateKey={(candidate) => candidate.name}
88
- disabled={false}
89
- onSelect={(candidate) => void toggle(candidate)}
110
+ onSelect={(candidate) =>
111
+ setDraft((current) =>
112
+ toggleSelection(current, candidate.name, candidate, candidate.isApplied),
113
+ )
114
+ }
115
>
116
{(candidate) => {
117
const dot = pullRequestLabelColor(candidate.color);
@@ -103,7 +128,7 @@ export function PullRequestLabelPicker({
128
<span className="text-muted-foreground"> · {candidate.description}</span>
129
) : null}
130
</span>
106
- {candidate.isApplied ? (
131
+ {isSelected(draft, candidate.name, candidate.isApplied) ? (
132
<CheckIcon aria-label="Applied" className="size-3.5 shrink-0" />
133
) : null}
134
</>
apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx
+63
-31
@@ -9,6 +9,13 @@ import {
9
reviewerCandidateView,
10
type ReviewerTruncation,
11
} from "@t3tools/client-runtime/pull-request-reviewers";
12
+import {
13
+ emptySelection,
14
+ isSelected,
15
+ changeBatches,
16
+ selectionChanges,
17
+ toggleSelection,
18
+} from "@t3tools/client-runtime/pull-request-selection";
19
import { CheckIcon, UserPlusIcon } from "lucide-react";
20
import { useState } from "react";
21
@@ -46,7 +53,7 @@ export function PullRequestReviewerPicker({
53
}) {
54
const [open, setOpen] = useState(false);
55
const [query, setQuery] = useState("");
49
- const [pending, setPending] = useState<string | null>(null);
56
+ const [draft, setDraft] = useState(emptySelection<PullRequestReviewerCandidate>);
57
58
const candidatesQuery = useEnvironmentQuery(
59
open ? pullRequestEnvironment.reviewerCandidates({ environmentId, input: reference }) : null,
@@ -72,42 +79,59 @@ export function PullRequestReviewerPicker({
79
search: searchResult,
80
});
81
75
- const toggle = async (candidate: PullRequestReviewerCandidate) => {
76
- if (pending !== null) return;
77
- setPending(candidate.id);
82
+ const send = async (people: ReadonlyArray<PullRequestReviewerCandidate>, requested: boolean) => {
83
+ for (const batch of changeBatches(people)) await sendBatch(batch, requested);
84
+ };
85
+ const sendBatch = async (
86
+ people: ReadonlyArray<PullRequestReviewerCandidate>,
87
+ requested: boolean,
88
+ ) => {
89
const result = await requestReviewers({
90
environmentId,
91
input: {
92
...reference,
82
- reviewers: [{ id: candidate.id, kind: candidate.kind }],
83
- requested: !candidate.isRequested,
93
+ reviewers: people.map(({ id, kind }) => ({ id, kind })),
94
+ requested,
95
},
96
});
86
- setPending(null);
87
- if (result._tag === "Failure") {
88
- toastManager.add({
89
- type: "error",
90
- title: candidate.isRequested
91
- ? `Could not take back the review request to ${candidate.login}`
92
- : `Could not ask ${candidate.login} for a review`,
93
- description: readableFailure(
94
- squashAtomCommandFailure(result),
95
- "The host refused it. Check that you have write access on this repository, and that they still have access to it.",
96
- ),
97
- });
98
- return;
99
- }
100
- // The command reads the loaded list again only for somebody it lacked, and a search result
101
- // is keyed by what was typed, so the one on screen is read here or it keeps the old request.
102
- if (hostQuery !== null) searchResult.refresh();
97
+ if (result._tag === "Success") return;
98
+ const logins = people.map((person) => person.login).join(", ");
99
toastManager.add({
104
- type: "success",
105
- title: candidate.isRequested
106
- ? `Review request to ${candidate.login} taken back`
107
- : `Review requested from ${candidate.login}`,
100
+ type: "error",
101
+ title: requested
102
+ ? `Could not ask ${logins} for a review`
103
+ : `Could not take back the review request to ${logins}`,
104
+ description: readableFailure(
105
+ squashAtomCommandFailure(result),
106
+ "The host refused it. Check that you have write access on this repository, and that they still have access to it.",
107
+ ),
108
});
109
};
110
111
+ const onOpenChange = (nextOpen: boolean) => {
112
+ setOpen(nextOpen);
113
+ if (nextOpen) return;
114
+ // Loaded rows first: they carry the request state mutations update.
115
+ const latest = [
116
+ ...(candidatesQuery.data?.candidates ?? []),
117
+ ...(searchResult.data?.candidates ?? []),
118
+ ];
119
+ const { add, remove } = selectionChanges(
120
+ draft,
121
+ (key, person) =>
122
+ latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ??
123
+ person.isRequested,
124
+ );
125
+ setDraft(emptySelection());
126
+ // A search result is keyed by what was typed, so the writes do not reach it on their own.
127
+ const refreshSearch =
128
+ hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null;
129
+ // Removing first lets a host that keeps one reviewer take the new one.
130
+ void send(remove, false)
131
+ .then(() => send(add, true))
132
+ .then(() => refreshSearch?.());
133
+ };
134
+
135
return (
136
<PullRequestCandidatePicker
137
icon={<UserPlusIcon className="size-3.5" />}
@@ -115,7 +139,7 @@ export function PullRequestReviewerPicker({
139
allowed={allowed}
140
disabledReason="Asking someone to review needs write access on this repository"
141
open={open}
118
- onOpenChange={setOpen}
142
+ onOpenChange={onOpenChange}
143
query={query}
144
onQueryChange={setQuery}
145
searchLabel="Search people with access"
@@ -134,8 +158,16 @@ export function PullRequestReviewerPicker({
158
truncated={truncation !== null}
159
truncatedLabel={truncation === null ? "" : TRUNCATED_LABELS[truncation](searchError)}
160
candidateKey={(candidate) => `${candidate.kind}:${candidate.id}`}
137
- disabled={pending !== null}
138
- onSelect={(candidate) => void toggle(candidate)}
161
+ onSelect={(candidate) =>
162
+ setDraft((current) =>
163
+ toggleSelection(
164
+ current,
165
+ `${candidate.kind}:${candidate.id}`,
166
+ candidate,
167
+ candidate.isRequested,
168
+ ),
169
+ )
170
+ }
171
>
172
{(candidate) => (
173
<>
@@ -143,7 +175,7 @@ export function PullRequestReviewerPicker({
175
{candidate.kind === "team" ? (
176
<span className="shrink-0 text-muted-foreground">team</span>
177
) : null}
146
- {candidate.isRequested ? (
178
+ {isSelected(draft, `${candidate.kind}:${candidate.id}`, candidate.isRequested) ? (
179
<CheckIcon aria-label="Already asked" className="size-3.5 shrink-0" />
180
) : null}
181
</>
packages/client-runtime/package.json
+4
@@ -563,6 +563,10 @@
563
"types": "./src/pullRequestReviewers.ts",
564
"default": "./src/pullRequestReviewers.ts"
565
},
566
+ "./pull-request-selection": {
567
+ "types": "./src/pullRequestSelection.ts",
568
+ "default": "./src/pullRequestSelection.ts"
569
+ },
570
"./provider-clients": {
571
"types": "./src/providerClients.ts",
572
"default": "./src/providerClients.ts"
packages/client-runtime/src/pullRequestSelection.test.ts
new
+48
@@ -0,0 +1,48 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+
3
+import {
4
+ changeBatches,
5
+ emptySelection,
6
+ isSelected,
7
+ selectionChanges,
8
+ toggleSelection,
9
+ type SelectionDraft,
10
+} from "./pullRequestSelection.ts";
11
+
12
+const host = new Set(["bug"]);
13
+const hostSelected = (key: string) => host.has(key);
14
+
15
+function pick(draft: SelectionDraft<string>, key: string) {
16
+ return toggleSelection(draft, key, key, hostSelected(key));
17
+}
18
+
19
+describe("pull request selection draft", () => {
20
+ it("collapses several picks into one add and one remove", () => {
21
+ let draft = emptySelection<string>();
22
+ for (const key of ["docs", "bug", "feature", "chore", "chore"]) draft = pick(draft, key);
23
+ expect(isSelected(draft, "bug", true)).toBe(false);
24
+ expect(isSelected(draft, "docs", false)).toBe(true);
25
+ expect(selectionChanges(draft, hostSelected)).toEqual({
26
+ add: ["docs", "feature"],
27
+ remove: ["bug"],
28
+ });
29
+ });
30
+
31
+ it("sends nothing for a pick toggled back", () => {
32
+ const draft = pick(pick(emptySelection(), "bug"), "bug");
33
+ expect(draft.size).toBe(0);
34
+ expect(selectionChanges(draft, hostSelected)).toEqual({ add: [], remove: [] });
35
+ });
36
+
37
+ it("diffs against the host's state at close, not at the pick", () => {
38
+ const draft = pick(pick(emptySelection(), "docs"), "bug");
39
+ const refreshed = new Set(["docs"]);
40
+ expect(selectionChanges(draft, (key) => refreshed.has(key))).toEqual({ add: [], remove: [] });
41
+ });
42
+
43
+ it("splits a change into writes the contract accepts", () => {
44
+ const labels = Array.from({ length: 26 }, (_, index) => `label-${index}`);
45
+ expect(changeBatches(labels).map((batch) => batch.length)).toEqual([25, 1]);
46
+ expect(changeBatches([])).toEqual([]);
47
+ });
48
+});
packages/client-runtime/src/pullRequestSelection.ts
new
+54
@@ -0,0 +1,54 @@
1
+import { PULL_REQUEST_CHANGE_BATCH_LIMIT } from "@t3tools/contracts";
2
+
3
+/** Picks that differ from the host, keyed by candidate. Nothing is sent until the picker closes. */
4
+export type SelectionDraft<T> = ReadonlyMap<
5
+ string,
6
+ { readonly item: T; readonly selected: boolean }
7
+>;
8
+
9
+export function emptySelection<T>(): SelectionDraft<T> {
10
+ return new Map();
11
+}
12
+
13
+export function isSelected<T>(draft: SelectionDraft<T>, key: string, hostSelected: boolean) {
14
+ return draft.get(key)?.selected ?? hostSelected;
15
+}
16
+
17
+export function toggleSelection<T>(
18
+ draft: SelectionDraft<T>,
19
+ key: string,
20
+ item: T,
21
+ hostSelected: boolean,
22
+): SelectionDraft<T> {
23
+ const next = new Map(draft);
24
+ const selected = !isSelected(draft, key, hostSelected);
25
+ if (selected === hostSelected) next.delete(key);
26
+ else next.set(key, { item, selected });
27
+ return next;
28
+}
29
+
30
+/**
31
+ * What to send on close, diffed against the host's latest state rather than the state when the
32
+ * pick was made, so a refresh while the picker was open does not resend anything.
33
+ */
34
+export function selectionChanges<T>(
35
+ draft: SelectionDraft<T>,
36
+ hostSelected: (key: string, item: T) => boolean,
37
+): { readonly add: ReadonlyArray<T>; readonly remove: ReadonlyArray<T> } {
38
+ const add: T[] = [];
39
+ const remove: T[] = [];
40
+ for (const [key, { item, selected }] of draft) {
41
+ if (selected === hostSelected(key, item)) continue;
42
+ (selected ? add : remove).push(item);
43
+ }
44
+ return { add, remove };
45
+}
46
+
47
+/** Splits a change into writes the contract accepts. */
48
+export function changeBatches<T>(items: ReadonlyArray<T>): ReadonlyArray<ReadonlyArray<T>> {
49
+ const batches: Array<ReadonlyArray<T>> = [];
50
+ for (let start = 0; start < items.length; start += PULL_REQUEST_CHANGE_BATCH_LIMIT) {
51
+ batches.push(items.slice(start, start + PULL_REQUEST_CHANGE_BATCH_LIMIT));
52
+ }
53
+ return batches;
54
+}
packages/contracts/src/pullRequest.ts
+8
-2
@@ -946,18 +946,24 @@ export const PullRequestReactionInput = Schema.Struct({
946
});
947
export type PullRequestReactionInput = typeof PullRequestReactionInput.Type;
948
949
+/** The most labels or reviewers one write may change. */
950
+export const PULL_REQUEST_CHANGE_BATCH_LIMIT = 25;
951
+
952
export const PullRequestReviewerRequestInput = Schema.Struct({
953
...PullRequestRef.fields,
954
reviewers: Schema.Array(
955
Schema.Struct({ id: TrimmedNonEmptyString, kind: PullRequestReviewerKind }),
953
- ).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
956
+ ).check(Schema.isMinLength(1), Schema.isMaxLength(PULL_REQUEST_CHANGE_BATCH_LIMIT)),
957
requested: Schema.Boolean,
958
});
959
export type PullRequestReviewerRequestInput = typeof PullRequestReviewerRequestInput.Type;
960
961
export const PullRequestLabelChangeInput = Schema.Struct({
962
...PullRequestRef.fields,
960
- labels: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
963
+ labels: Schema.Array(TrimmedNonEmptyString).check(
964
+ Schema.isMinLength(1),
965
+ Schema.isMaxLength(PULL_REQUEST_CHANGE_BATCH_LIMIT),
966
+ ),
967
applied: Schema.Boolean,
968
});
969
export type PullRequestLabelChangeInput = typeof PullRequestLabelChangeInput.Type;