@devries-cameron20 / t3code-1 / commits / 22dc1dabc6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(pull-requests): label and author filters search the host (#23924)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 23, 2026 at 16:11 UTC 22dc1dabc6d3b1616d0fa5017268c086a77887bc
37 files changed +1614 -241
apps/mobile/src/Stack.tsx
+16
@@ -34,6 +34,7 @@ import {
34 import { PullRequestFilesSheet } from "./features/pull-requests/PullRequestFiles";
35 import { PullRequestReviewSheet } from "./features/pull-requests/PullRequestReviewSheet";
36 import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequestReviewersScreen";
37 +import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen";
38 import {
39 RenderErrorBoundary,
40 RenderFailureView,
@@ -689,6 +690,21 @@ const RootStackConfig = createWorkspaceStackNavigator({
690 headerBackVisible: false,
691 },
692 }),
693 + PullRequestFilterSearch: createNativeStackScreen({
694 + screen: PullRequestFilterSearchScreen,
695 + // Android pushes it like the branch picker; a formSheet there leaves the list's header
696 + // peeking above it once the keyboard opens.
697 + options:
698 + Platform.OS === "android"
699 + ? { presentation: "card", headerShown: false }
700 + : {
701 + ...DETAIL_HEADER_OPTIONS,
702 + ...HORIZONTAL_FORM_SHEET_OPTIONS,
703 + sheetAllowedDetents: formSheetDetents(0.75),
704 + sheetGrabberVisible: true,
705 + headerBackVisible: false,
706 + },
707 + }),
708 PullRequestDiscussion: createNativeStackScreen({
709 screen: PullRequestDiscussionScreen,
710 options: DETAIL_HEADER_OPTIONS,
apps/mobile/src/components/ui/AppSymbol.tsx
+2
@@ -39,6 +39,7 @@ import IconChevronLeft from "@tabler/icons-react-native/IconChevronLeft";
39 import IconChevronRight from "@tabler/icons-react-native/IconChevronRight";
40 import IconChevronUp from "@tabler/icons-react-native/IconChevronUp";
41 import IconCircle from "@tabler/icons-react-native/IconCircle";
42 +import IconCircleFilled from "@tabler/icons-react-native/IconCircleFilled";
43 import IconCircleCheck from "@tabler/icons-react-native/IconCircleCheck";
44 import IconCircleDashed from "@tabler/icons-react-native/IconCircleDashed";
45 import IconCircleDot from "@tabler/icons-react-native/IconCircleDot";
@@ -176,6 +177,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
177 "checkmark.circle": IconCircleCheck,
178 "checkmark.circle.fill": IconCircleCheck,
179 circle: IconCircle,
180 + "circle.fill": IconCircleFilled,
181 "circle.dashed": IconCircleDashed,
182 "circle.inset.filled": IconCircleDot,
183 "circle.dashed.inset.filled": IconCircleDot,
apps/mobile/src/components/ui/MenuPopup.android.tsx
+12 -7
@@ -8,6 +8,7 @@ import {
8 Text,
9 } from "@expo/ui/jetpack-compose";
10 import { defaultMinSize, padding, size, width } from "@expo/ui/jetpack-compose/modifiers";
11 +import type { MenuAction } from "@react-native-menu/menu";
12 import { Pressable } from "react-native";
13 import { resolveScaledTextRole } from "../../lib/appearancePreferences";
14
@@ -21,6 +22,7 @@ import { isAppSymbolName, SymbolView, type AppSymbolName } from "./AppSymbol";
22 // row's action itself; the row stays the accessible element.
23 function MenuIcon(props: {
24 readonly name: AppSymbolName;
25 + readonly color?: MenuAction["imageColor"];
26 readonly onPress: () => void;
27 readonly destructive?: boolean;
28 readonly disabled?: boolean;
@@ -40,13 +42,15 @@ function MenuIcon(props: {
42 name={props.name}
43 size={iconSize}
44 type="monochrome"
43 - tintColorClassName={
44 - props.disabled
45 - ? "accent-icon-subtle"
46 - : props.destructive
47 - ? "accent-danger-foreground"
48 - : "accent-foreground"
49 - }
45 + {...(typeof props.color === "string" && !props.disabled
46 + ? { tintColor: props.color }
47 + : {
48 + tintColorClassName: props.disabled
49 + ? "accent-icon-subtle"
50 + : props.destructive
51 + ? "accent-danger-foreground"
52 + : "accent-foreground",
53 + })}
54 />
55 </Pressable>
56 </RNHostView>
@@ -96,6 +100,7 @@ export function MenuPopup(props: MenuPopupProps) {
100 <DropdownMenuItem.LeadingIcon>
101 <MenuIcon
102 name={action.image}
103 + color={action.imageColor}
104 onPress={() => props.onPress(action)}
105 destructive={action.attributes?.destructive}
106 disabled={action.attributes?.disabled}
apps/mobile/src/components/ui/SelectionRow.tsx new
+104
@@ -0,0 +1,104 @@
1 +import type { ReactNode } from "react";
2 +import { Platform, Pressable, View } from "react-native";
3 +
4 +import { cn } from "../../lib/cn";
5 +import { SymbolView, type AppSymbolName } from "./AppSymbol";
6 +import { AppText as Text } from "./AppText";
7 +import { NavigationRow } from "./NavigationRow";
8 +
9 +/** A picker row in a grouped list; the first and last rows round the group's corners. */
10 +export function SelectionRow(props: {
11 + readonly icon?: AppSymbolName;
12 + /** Drawn where the icon goes, for marks a symbol can't express (a label's color dot). */
13 + readonly leading?: ReactNode;
14 + readonly onPress: () => void;
15 + readonly disabled?: boolean;
16 + readonly selected: boolean;
17 + /** "checkbox" when several rows can be selected at once. */
18 + readonly role?: "radio" | "checkbox";
19 + readonly isFirst?: boolean;
20 + readonly isLast?: boolean;
21 + readonly subtitle?: string;
22 + readonly title: string;
23 +}) {
24 + const role = props.role ?? "radio";
25 + const row =
26 + Platform.OS === "android" ? (
27 + <NavigationRow
28 + className="bg-grouped-card"
29 + title={props.title}
30 + subtitle={props.subtitle}
31 + leading={
32 + props.icon ? (
33 + <SymbolView name={props.icon} size={24} tintColorClassName="accent-icon-muted" />
34 + ) : (
35 + props.leading
36 + )
37 + }
38 + trailing={
39 + props.selected ? (
40 + <SymbolView name="checkmark" size={20} tintColorClassName="accent-focus" />
41 + ) : null
42 + }
43 + accessibilityRole={role}
44 + accessibilityState={{ checked: props.selected }}
45 + disabled={props.disabled}
46 + onPress={props.onPress}
47 + />
48 + ) : (
49 + <Pressable
50 + accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}
51 + accessibilityRole={role}
52 + accessibilityState={{ checked: props.selected }}
53 + className={cn(
54 + "min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3 active:bg-subtle",
55 + !props.isLast && "border-b border-border-subtle",
56 + )}
57 + disabled={props.disabled}
58 + onPress={props.onPress}
59 + style={{ opacity: props.disabled ? 0.45 : 1 }}
60 + >
61 + {props.icon ? (
62 + <SymbolView
63 + name={props.icon}
64 + size={17}
65 + tintColorClassName="accent-icon-muted"
66 + type="monochrome"
67 + />
68 + ) : (
69 + (props.leading ?? null)
70 + )}
71 + <View className="min-w-0 flex-1 gap-0.5">
72 + <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
73 + {props.title}
74 + </Text>
75 + {props.subtitle ? (
76 + <Text className="text-xs text-foreground-muted" numberOfLines={1}>
77 + {props.subtitle}
78 + </Text>
79 + ) : null}
80 + </View>
81 + {props.selected ? (
82 + <SymbolView
83 + name="checkmark"
84 + size={16}
85 + tintColorClassName="accent-icon"
86 + type="monochrome"
87 + weight="semibold"
88 + />
89 + ) : null}
90 + </Pressable>
91 + );
92 + if (!props.isFirst && !props.isLast) return row;
93 + return (
94 + <View
95 + className={cn(
96 + "overflow-hidden",
97 + props.isFirst && (Platform.OS === "android" ? "rounded-t-[28px]" : "rounded-t-2xl"),
98 + props.isLast && (Platform.OS === "android" ? "rounded-b-[28px]" : "rounded-b-2xl"),
99 + )}
100 + >
101 + {row}
102 + </View>
103 + );
104 +}
apps/mobile/src/features/pull-requests/PullRequestFilterSearchScreen.tsx new
+244
@@ -0,0 +1,244 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3 +import {
4 + EnvironmentId,
5 + ProjectId,
6 + type PullRequestFilterOptionKind,
7 + type PullRequestFilterOptionsInput,
8 +} from "@t3tools/contracts";
9 +import * as Option from "effect/Option";
10 +import { AsyncResult, Atom } from "effect/reactivity";
11 +import { useRef, useState } from "react";
12 +import { FlatList, Platform, View, type TextInputInstance } from "react-native";
13 +
14 +import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
15 +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
16 +import { EmptyState } from "../../components/ui/EmptyState";
17 +import { SearchField } from "../../components/ui/SearchField";
18 +import { SelectionRow } from "../../components/ui/SelectionRow";
19 +import { SheetHeader } from "../../components/ui/SheetHeader";
20 +import { Toolbar } from "../../components/ui/Toolbar";
21 +import { NativeStackScreenOptions } from "../../native/StackHeader";
22 +import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
23 +import { composerPullRequests } from "../../state/pull-requests";
24 +import { useDebouncedValue } from "../../state/queries";
25 +import {
26 + createNativeMailSearchToolbarItem,
27 + NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
28 +} from "../layout/native-mail-search-toolbar";
29 +import { pullRequestFilterChoices, pullRequestLabelColors } from "./pullRequestList";
30 +import { usePullRequestListControls } from "./usePullRequestListControls";
31 +
32 +export type PullRequestFilterSearchParams = {
33 + readonly kind: PullRequestFilterOptionKind;
34 + /** The list controls' own key: the environment the list is narrowed to, or every one. */
35 + readonly environmentId: string | null;
36 + /** The environments the list reads, which the host search covers as well. */
37 + readonly environmentIds: readonly string[];
38 + /** What the loaded rows already carry, offered before the host has answered. */
39 + readonly suggestions: readonly string[];
40 + /** Dot colors by lowercased label name, from the loaded rows. */
41 + readonly labelColors?: Readonly<Record<string, string>>;
42 +};
43 +
44 +const optionsFamily = Atom.family((key: string) => {
45 + const targets: readonly {
46 + readonly environmentId: EnvironmentId;
47 + readonly input: PullRequestFilterOptionsInput;
48 + }[] = JSON.parse(key);
49 + return Atom.make((get) => {
50 + const results = targets.map((target) => get(composerPullRequests.filterOptions(target)));
51 + return {
52 + values: results.flatMap((result) => Option.toArray(AsyncResult.value(result))),
53 + waiting: results.some((result) => result.waiting),
54 + failed: results.some(AsyncResult.isFailure),
55 + };
56 + });
57 +});
58 +
59 +export function PullRequestFilterSearchScreen({
60 + route,
61 +}: StaticScreenProps<PullRequestFilterSearchParams>) {
62 + const navigation = useNavigation();
63 + const { kind, environmentId, environmentIds, suggestions, labelColors } = route.params;
64 + const listControls = usePullRequestListControls();
65 + const controls = listControls.controlsFor(environmentId);
66 + const integratedSearch = useNativeMailSearchToolbar();
67 + const searchRef = useRef<TextInputInstance>(null);
68 + const [query, setQuery] = useState("");
69 + const typed = query.trim().slice(0, 100);
70 + const sent = useDebouncedValue(typed, 250);
71 + // Until the search catches up with the typing, the host's answers are for older text.
72 + const settled = sent === typed;
73 + const key = JSON.stringify(
74 + environmentIds.map((id) => ({
75 + environmentId: EnvironmentId.make(id),
76 + input: {
77 + kind,
78 + ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),
79 + ...(sent ? { query: sent } : {}),
80 + },
81 + })),
82 + );
83 + const hosted = useAtomValue(optionsFamily(key));
84 + const selectedLabels = controls.filters.labels?.flat() ?? [];
85 + const author = controls.filters.author;
86 + const selected = kind === "labels" ? selectedLabels : author ? [author] : [];
87 + const rows = pullRequestFilterChoices({
88 + selected,
89 + suggestions,
90 + hosted: (settled ? hosted.values : []).flatMap((options) =>
91 + kind === "labels"
92 + ? options.labels.map((label) => label.name)
93 + : options.authors.map((candidate) => candidate.login),
94 + ),
95 + query,
96 + });
97 + const colors = {
98 + ...pullRequestLabelColors(hosted.values.flatMap((options) => options.labels)),
99 + ...labelColors,
100 + };
101 + const isSelected = (value: string) =>
102 + selected.some((held) => held.toLowerCase() === value.toLowerCase());
103 + const choose = (value: string) => {
104 + if (kind === "authors") {
105 + listControls.setControls(environmentId, {
106 + ...controls,
107 + filters: { ...controls.filters, author: isSelected(value) ? undefined : value },
108 + });
109 + navigation.goBack();
110 + return;
111 + }
112 + const labels = isSelected(value)
113 + ? selectedLabels.filter((label) => label.toLowerCase() !== value.toLowerCase())
114 + : [...selectedLabels, value].slice(0, 10);
115 + listControls.setControls(environmentId, {
116 + ...controls,
117 + filters: {
118 + ...controls.filters,
119 + labels: labels.length ? labels.map((label) => [label]) : undefined,
120 + },
121 + });
122 + };
123 + const placeholder = kind === "labels" ? "Search labels" : "Search authors";
124 + const list = (
125 + <FlatList
126 + data={rows}
127 + keyExtractor={(value) => value.toLowerCase()}
128 + className="flex-1"
129 + contentInsetAdjustmentBehavior="automatic"
130 + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
131 + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
132 + keyboardShouldPersistTaps="handled"
133 + showsVerticalScrollIndicator={false}
134 + contentContainerStyle={{
135 + paddingHorizontal: 16,
136 + paddingTop: 16,
137 + paddingBottom: integratedSearch ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16 : 16,
138 + }}
139 + renderItem={({ item, index }) => (
140 + <SelectionRow
141 + title={item}
142 + role={kind === "labels" ? "checkbox" : "radio"}
143 + selected={isSelected(item)}
144 + isFirst={index === 0}
145 + isLast={index === rows.length - 1}
146 + leading={
147 + kind === "labels" ? (
148 + // Uncolored labels keep the dot's room so every name starts at the same edge.
149 + <View
150 + className="size-2.5 rounded-full"
151 + style={{ backgroundColor: colors[item.toLowerCase()] ?? "transparent" }}
152 + />
153 + ) : undefined
154 + }
155 + onPress={() => choose(item)}
156 + />
157 + )}
158 + ListEmptyComponent={
159 + hosted.waiting || !settled ? (
160 + <AppActivityIndicator className="my-8" />
161 + ) : (
162 + <EmptyState
163 + title={
164 + hosted.failed
165 + ? "Couldn't search the host"
166 + : kind === "labels"
167 + ? "No matching labels"
168 + : "No matching authors"
169 + }
170 + detail={
171 + hosted.failed
172 + ? "The host didn't answer. Try again in a moment."
173 + : kind === "labels"
174 + ? "Search the labels of the repositories this list covers."
175 + : "Search people by name or handle on the repositories' hosts."
176 + }
177 + variant="plain"
178 + />
179 + )
180 + }
181 + />
182 + );
183 + const title = kind === "labels" ? "Filter by label" : "Filter by author";
184 + if (Platform.OS === "android") {
185 + return (
186 + <View className="flex-1 bg-sheet" collapsable={false}>
187 + <AndroidScreenHeader title={title} hideBottomBorder onBack={() => navigation.goBack()} />
188 + <View className="bg-header px-4 pb-3 pt-1">
189 + <SearchField
190 + inputRef={searchRef}
191 + accessibilityLabel={placeholder}
192 + clearAccessibilityLabel={
193 + kind === "labels" ? "Clear label search" : "Clear author search"
194 + }
195 + onChangeText={setQuery}
196 + placeholder={placeholder}
197 + value={query}
198 + />
199 + </View>
200 + {list}
201 + </View>
202 + );
203 + }
204 + return (
205 + <View className="flex-1 bg-sheet">
206 + <SheetHeader
207 + title={title}
208 + onClose={() => navigation.goBack()}
209 + accessibilityLabel={kind === "labels" ? "Close label filter" : "Close author filter"}
210 + />
211 + <NativeStackScreenOptions
212 + options={{
213 + unstable_headerToolbarItems: integratedSearch
214 + ? () => [
215 + createNativeMailSearchToolbarItem({
216 + placeholder,
217 + onSearchTextChange: setQuery,
218 + showsSearchDismissButton: true,
219 + searchTextChangeId: "pr-filter-option-search",
220 + }),
221 + ]
222 + : undefined,
223 + headerSearchBarOptions: integratedSearch
224 + ? undefined
225 + : {
226 + placeholder,
227 + allowToolbarIntegration: true,
228 + autoCapitalize: "none",
229 + hideNavigationBar: false,
230 + obscureBackground: false,
231 + onChangeText: (event) => setQuery(event.nativeEvent.text),
232 + onCancelButtonPress: () => setQuery(""),
233 + },
234 + }}
235 + />
236 + {integratedSearch ? null : (
237 + <Toolbar placement="bottom">
238 + <Toolbar.SearchBarSlot />
239 + </Toolbar>
240 + )}
241 + {list}
242 + </View>
243 + );
244 +}
apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
+29 -14
@@ -73,7 +73,11 @@ export function PullRequestListFilters(props: {
73 readonly onChange: (value: PullRequestListControls) => void;
74 readonly authors: readonly string[];
75 readonly labels: readonly string[];
76 + /** Dot colors by lowercased label name, for the labels that have one. */
77 + readonly labelColors: Readonly<Record<string, string>>;
78 readonly projects: readonly { id: string; title: string; environmentId: string }[];
79 + /** Opens a picker that searches the host, for a label or author no loaded row carries. */
80 + readonly onSearch: (kind: "labels" | "authors") => void;
81 }) {
82 const { value } = props;
83 const projects = useProjectsInSidebarOrder(props.projects);
@@ -145,6 +149,9 @@ export function PullRequestListFilters(props: {
149 case "author":
150 props.onChange({ ...value, filters: { ...value.filters, author: next || undefined } });
151 break;
152 + case "search":
153 + if (next === "labels" || next === "authors") props.onSearch(next);
154 + break;
155 case "draft":
156 props.onChange({
157 ...value,
@@ -248,22 +255,30 @@ export function PullRequestListFilters(props: {
255 const stateActions = choices("state", STATES, value.state);
256 const involvementActions = choices("involvement", INVOLVEMENT, value.involvement);
257 const labelActions: MenuProps["actions"] = [
258 + { id: id("search", "labels"), title: "Search labels…", image: "magnifyingglass" },
259 { id: id("labels", ""), title: "All labels", state: selectedLabels.length ? "off" : "on" },
252 - ...labels.map((label) => ({
253 - id: id("label", label),
254 - title: label,
255 - state: selectedLabelSet.has(label) ? ("on" as const) : ("off" as const),
256 - })),
260 + ...labels.map((label) => {
261 + const color = props.labelColors[label.toLowerCase()];
262 + return {
263 + id: id("label", label),
264 + title: label,
265 + state: selectedLabelSet.has(label) ? ("on" as const) : ("off" as const),
266 + ...(color ? { image: "circle.fill", imageColor: color } : {}),
267 + };
268 + }),
269 + ];
270 + const authorActions: MenuProps["actions"] = [
271 + { id: id("search", "authors"), title: "Search authors…", image: "magnifyingglass" },
272 + ...choices(
273 + "author",
274 + Object.fromEntries([
275 + ["", "All authors"],
276 + ["me", "Me"],
277 + ...authors.map((login) => [login, login]),
278 + ]),
279 + author ?? "",
280 + ),
281 ];
258 - const authorActions = choices(
259 - "author",
260 - Object.fromEntries([
261 - ["", "All authors"],
262 - ["me", "Me"],
263 - ...authors.map((login) => [login, login]),
264 - ]),
265 - author ?? "",
266 - );
282 const customized = count > 0 || value.sort !== "updated" || props.environmentId !== null;
283 // The Android header's filter button opens every filter.
284 const headerMenu =
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+17
@@ -200,8 +200,14 @@ export function PullRequestsScreen(
200 ...facets.labels,
201 ]),
202 ].sort(),
203 + labelColors: {
204 + ...facets.labelColors,
205 + ...(previous.environmentId === environmentId ? previous.labelColors : {}),
206 + },
207 }));
208 }
209 + const labelColors =
210 + knownFacets.environmentId === environmentId ? knownFacets.labelColors : facets.labelColors;
211 const projects = allProjects.filter(
212 (project) =>
213 !project.isScratch && (environmentId === null || project.environmentId === environmentId),
@@ -318,7 +324,18 @@ export function PullRequestsScreen(
324 labels={
325 knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
326 }
327 + labelColors={labelColors}
328 projects={projects}
329 + onSearch={(kind) =>
330 + navigation.navigate("PullRequestFilterSearch", {
331 + kind,
332 + environmentId,
333 + environmentIds: targets.map((target) => String(target.environmentId)),
334 + suggestions:
335 + knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
336 + labelColors,
337 + })
338 + }
339 />
340 {result.data?.errors.length ? (
341 <PullRequestListErrors
apps/mobile/src/features/pull-requests/pullRequestList.test.ts
+41
@@ -13,6 +13,8 @@ import {
13 mergeEnvironmentPullRequestPages,
14 nextPullRequestListInput,
15 PR_LIST_PAGE_SIZE,
16 + pullRequestFilterChoices,
17 + pullRequestLabelColors,
18 pullRequestListHead,
19 pullRequestListInput,
20 scopedPullRequestListKey,
@@ -346,3 +348,42 @@ describe("withoutScratchProjectScope", () => {
348 expect(withoutScratchProjectScope(elsewhere, projects)).toBe(elsewhere);
349 });
350 });
351 +
352 +describe("pullRequestLabelColors", () => {
353 + it("keeps the first usable color each label name carries", () => {
354 + expect(
355 + pullRequestLabelColors([
356 + { name: "Bug", color: null },
357 + { name: "bug", color: "d73a4a" },
358 + { name: "BUG", color: "#000000" },
359 + { name: "docs", color: "not-a-color" },
360 + { name: "size:S", color: "#69C35F" },
361 + ]),
362 + ).toEqual({ bug: "#d73a4a", "size:s": "#69C35F" });
363 + });
364 +});
365 +
366 +describe("pullRequestFilterChoices", () => {
367 + it("keeps the picked value in view and adds host answers no loaded row carries, once", () => {
368 + expect(
369 + pullRequestFilterChoices({
370 + selected: ["size:XL"],
371 + suggestions: ["bug", "size:XL", "docs"],
372 + hosted: ["Bug", "backend"],
373 + query: "b",
374 + }),
375 + ).toEqual(["size:XL", "bug", "backend"]);
376 + });
377 +
378 + it("leaves room for the host's answers when loaded matches alone would fill the list", () => {
379 + const loaded = Array.from({ length: 120 }, (_, index) => `label-${index}`);
380 + const rows = pullRequestFilterChoices({
381 + selected: [],
382 + suggestions: loaded,
383 + hosted: ["label-from-host"],
384 + query: "label",
385 + });
386 + expect(rows).toHaveLength(100);
387 + expect(rows[50]).toBe("label-from-host");
388 + });
389 +});
apps/mobile/src/features/pull-requests/pullRequestList.ts
+45
@@ -184,6 +184,37 @@ export function appendPullRequestListPage(
184 };
185 }
186
187 +/**
188 + * A filter picker's rows: what is picked stays in view, then the loaded rows' values that match,
189 + * then the host's answers, each once. The host matched its own way (an author's display name, say),
190 + * so its answers are not narrowed again here.
191 + */
192 +const FILTER_CHOICE_LIMIT = 100;
193 +
194 +export function pullRequestFilterChoices(input: {
195 + readonly selected: readonly string[];
196 + readonly suggestions: readonly string[];
197 + readonly hosted: readonly string[];
198 + readonly query: string;
199 +}): readonly string[] {
200 + const needle = input.query.trim().toLowerCase();
201 + const seen = new Set<string>();
202 + const rows: string[] = [];
203 + const add = (value: string) => {
204 + const key = value.toLowerCase();
205 + if (seen.has(key)) return;
206 + seen.add(key);
207 + rows.push(value);
208 + };
209 + const loaded = input.suggestions.filter((value) => value.toLowerCase().includes(needle));
210 + for (const value of input.selected) add(value);
211 + // Loaded matches alone could fill the list, so the host's answers get room after the first half.
212 + for (const value of loaded.slice(0, FILTER_CHOICE_LIMIT / 2)) add(value);
213 + for (const value of input.hosted) add(value);
214 + for (const value of loaded.slice(FILTER_CHOICE_LIMIT / 2)) add(value);
215 + return rows.slice(0, FILTER_CHOICE_LIMIT);
216 +}
217 +
218 export function pullRequestListFacets(entries: readonly PullRequestListEntry[]) {
219 return {
220 authors: [
@@ -192,9 +223,23 @@ export function pullRequestListFacets(entries: readonly PullRequestListEntry[])
223 labels: [...new Set(entries.flatMap((entry) => entry.labels.map((label) => label.name)))].sort(
224 (a, b) => a.localeCompare(b),
225 ),
226 + labelColors: pullRequestLabelColors(entries.flatMap((entry) => entry.labels)),
227 };
228 }
229
230 +/** Each label's dot color by lowercased name; the first usable color a name carries wins. */
231 +export function pullRequestLabelColors(
232 + labels: readonly { readonly name: string; readonly color: string | null }[],
233 +): Readonly<Record<string, string>> {
234 + const colors: Record<string, string> = {};
235 + for (const label of labels) {
236 + const key = label.name.toLowerCase();
237 + const color = pullRequestLabelColor(label.color);
238 + if (color && !(key in colors)) colors[key] = color;
239 + }
240 + return colors;
241 +}
242 +
243 export function filterPullRequestList<
244 Entry extends PullRequestListEntry & { environmentId?: string },
245 >(
apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+6 -126
@@ -3,7 +3,7 @@ import { Button } from "../../components/ui/Button";
3 import { Toolbar } from "../../components/ui/Toolbar";
4 import * as Dialog from "../../components/ui/Dialog";
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 -import { NavigationRow } from "../../components/ui/NavigationRow";
6 +import { SelectionRow } from "../../components/ui/SelectionRow";
7 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8 import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
9 import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
@@ -136,90 +136,6 @@ function EnvironmentPickerRow(props: {
136 );
137 }
138
139 -function SelectionRow(props: {
140 - readonly icon?: "arrow.triangle.branch" | ReactNode;
141 - readonly onPress: () => void;
142 - readonly disabled?: boolean;
143 - readonly selected: boolean;
144 - readonly isLast?: boolean;
145 - readonly subtitle?: string;
146 - readonly title: string;
147 -}) {
148 - if (Platform.OS === "android") {
149 - return (
150 - <NavigationRow
151 - className="bg-grouped-card"
152 - title={props.title}
153 - subtitle={props.subtitle}
154 - leading={
155 - props.icon === "arrow.triangle.branch" ? (
156 - <SymbolView
157 - name="arrow.triangle.branch"
158 - size={24}
159 - tintColorClassName="accent-icon-muted"
160 - />
161 - ) : (
162 - props.icon
163 - )
164 - }
165 - trailing={
166 - props.selected ? (
167 - <SymbolView name="checkmark" size={20} tintColorClassName="accent-focus" />
168 - ) : null
169 - }
170 - accessibilityRole="radio"
171 - accessibilityState={{ checked: props.selected }}
172 - disabled={props.disabled}
173 - onPress={props.onPress}
174 - />
175 - );
176 - }
177 - return (
178 - <Pressable
179 - accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}
180 - accessibilityRole="radio"
181 - accessibilityState={{ checked: props.selected }}
182 - className={cn(
183 - "min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3 active:bg-subtle",
184 - !props.isLast && "border-b border-border-subtle",
185 - )}
186 - disabled={props.disabled}
187 - onPress={props.onPress}
188 - style={{ opacity: props.disabled ? 0.45 : 1 }}
189 - >
190 - {props.icon === "arrow.triangle.branch" ? (
191 - <SymbolView
192 - name="arrow.triangle.branch"
193 - size={17}
194 - tintColorClassName="accent-icon-muted"
195 - type="monochrome"
196 - />
197 - ) : (
198 - (props.icon ?? null)
199 - )}
200 - <View className="min-w-0 flex-1 gap-0.5">
201 - <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
202 - {props.title}
203 - </Text>
204 - {props.subtitle ? (
205 - <Text className="text-xs text-foreground-muted" numberOfLines={1}>
206 - {props.subtitle}
207 - </Text>
208 - ) : null}
209 - </View>
210 - {props.selected ? (
211 - <SymbolView
212 - name="checkmark"
213 - size={16}
214 - tintColorClassName="accent-icon"
215 - type="monochrome"
216 - weight="semibold"
217 - />
218 - ) : null}
219 - </Pressable>
220 - );
221 -}
222 -
139 function ToggleRow(props: {
140 readonly title: string;
141 readonly value: boolean;
@@ -245,43 +161,6 @@ function ToggleRow(props: {
161 );
162 }
163
248 -function BranchSelectionRow(props: {
249 - readonly badge: string | null;
250 - readonly branch: VcsRef;
251 - readonly disabled: boolean;
252 - readonly isFirst: boolean;
253 - readonly isLast: boolean;
254 - readonly onSelect: (branch: VcsRef) => void;
255 - readonly selected: boolean;
256 -}) {
257 - const onPress = () => props.onSelect(props.branch);
258 -
259 - return (
260 - <View
261 - className={cn(
262 - props.isFirst &&
263 - (Platform.OS === "android"
264 - ? "overflow-hidden rounded-t-[28px]"
265 - : "overflow-hidden rounded-t-2xl"),
266 - props.isLast &&
267 - (Platform.OS === "android"
268 - ? "overflow-hidden rounded-b-[28px]"
269 - : "overflow-hidden rounded-b-2xl"),
270 - )}
271 - >
272 - <SelectionRow
273 - icon="arrow.triangle.branch"
274 - disabled={props.disabled}
275 - isLast={props.isLast}
276 - onPress={onPress}
277 - selected={props.selected}
278 - subtitle={props.badge ? props.badge.toUpperCase() : undefined}
279 - title={props.branch.name}
280 - />
281 - </View>
282 - );
283 -}
284 -
164 function PickerSurface(props: { readonly children: ReactNode }) {
165 return (
166 <View
@@ -508,14 +387,15 @@ export function BranchPickerScreen(props: {
387 };
388
389 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
511 - <BranchSelectionRow
512 - badge={branchBadgeLabel({ branch: item, project: props.project })}
513 - branch={item}
390 + <SelectionRow
391 + icon="arrow.triangle.branch"
392 disabled={props.selectionDisabled ?? false}
393 isFirst={index === 0}
394 isLast={index === props.branches.length - 1}
517 - onSelect={props.onSelect}
395 + onPress={() => props.onSelect(item)}
396 selected={selectedBranchName === item.name}
397 + subtitle={branchBadgeLabel({ branch: item, project: props.project })?.toUpperCase()}
398 + title={item.name}
399 />
400 );
401
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -120,6 +120,7 @@ export const RPC_REQUIRED_SCOPES = {
120 [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
121 [WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
122 [WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
123 + [WS_METHODS.pullRequestsFilterOptions]: AuthOrchestrationReadScope,
124 [WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,
125 [WS_METHODS.pullRequestsRouting]: AuthOrchestrationReadScope,
126 [WS_METHODS.pullRequestsRoutingIdentity]: AuthOrchestrationReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -99,6 +99,7 @@ const RPC_AGGREGATES = {
99 [WS_METHODS.cloudInstallRelayClient]: "cloud",
100 [WS_METHODS.pullRequestsList]: "pull-requests",
101 [WS_METHODS.pullRequestsListStats]: "pull-requests",
102 + [WS_METHODS.pullRequestsFilterOptions]: "pull-requests",
103 [WS_METHODS.pullRequestsSummary]: "pull-requests",
104 [WS_METHODS.pullRequestsRouting]: "pull-requests",
105 [WS_METHODS.pullRequestsRoutingIdentity]: "pull-requests",
apps/server/src/pullRequest/PullRequestService.test.ts
+97
@@ -833,6 +833,103 @@ it.effect("keeps healthy repositories when one of them cannot be read", () =>
833 }),
834 );
835
836 +it.effect("offers each label once across repositories, despite one that cannot be read", () =>
837 + Effect.gen(function* () {
838 + const reads: Array<string> = [];
839 + const service = yield* makeService({
840 + projects: [
841 + project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
842 + project({
843 + id: "p5",
844 + title: "t3code worktree",
845 + workspaceRoot: "/e",
846 + repository: "pingdotgg/t3code",
847 + }),
848 + project({
849 + id: "p2",
850 + title: "uploadthing",
851 + workspaceRoot: "/b",
852 + repository: "pingdotgg/ut",
853 + }),
854 + project({ id: "p3", title: "broken", workspaceRoot: "/c", repository: "pingdotgg/broken" }),
855 + project({
856 + id: "p4",
857 + title: "elsewhere",
858 + workspaceRoot: "/d",
859 + repository: "group/app",
860 + provider: "gitlab",
861 + }),
862 + ],
863 + providers: [
864 + fakeProvider(SourceControlProviderKind.make("github"), {
865 + listRepositoryLabels: (input) => {
866 + reads.push(input.repository);
867 + return input.repository === "pingdotgg/broken"
868 + ? Effect.fail(requestFailed)
869 + : Effect.succeed({
870 + items:
871 + input.repository === "pingdotgg/t3code"
872 + ? [
873 + { name: "size:XL", color: "d93f0b" },
874 + { name: "bug", color: "d73a4a" },
875 + ]
876 + : [{ name: "Bug", color: "ee0701" }],
877 + truncated: false,
878 + });
879 + },
880 + }),
881 + // A host with no repository labels is left out rather than failing the answer.
882 + fakeProvider(SourceControlProviderKind.make("gitlab")),
883 + ],
884 + });
885 +
886 + const result = yield* service.filterOptions({ kind: "labels" });
887 +
888 + assert.deepStrictEqual(
889 + result.labels.map((label) => label.name),
890 + ["bug", "size:XL"],
891 + );
892 + assert.strictEqual(reads.filter((repository) => repository === "pingdotgg/t3code").length, 1);
893 + assert.strictEqual(result.truncated, false);
894 + }),
895 +);
896 +
897 +it.effect("puts the author a query names exactly ahead of those it only begins", () =>
898 + Effect.gen(function* () {
899 + const queries: Array<string | undefined> = [];
900 + const service = yield* makeService({
901 + projects: [
902 + project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
903 + ],
904 + providers: [
905 + fakeProvider(SourceControlProviderKind.make("github"), {
906 + searchRepositoryAuthors: (input) => {
907 + queries.push(input.query);
908 + return Effect.succeed({
909 + items: [
910 + { login: "theo-browne", name: null, avatarUrl: null },
911 + { login: "octocat", name: "Theo", avatarUrl: null },
912 + { login: "julius", name: "Julius", avatarUrl: null },
913 + { login: "t3dotgg", name: "theo", avatarUrl: null },
914 + ],
915 + truncated: true,
916 + });
917 + },
918 + }),
919 + ],
920 + });
921 +
922 + const result = yield* service.filterOptions({ kind: "authors", query: "theo" });
923 +
924 + assert.deepStrictEqual(queries, ["theo"]);
925 + assert.deepStrictEqual(
926 + result.authors.map((author) => author.login),
927 + ["octocat", "t3dotgg", "theo-browne"],
928 + );
929 + assert.strictEqual(result.truncated, true);
930 + }),
931 +);
932 +
933 it.effect("tries another workspace on the same host for the viewer", () =>
934 Effect.gen(function* () {
935 const service = yield* makeService({
apps/server/src/pullRequest/PullRequestService.ts
+121
@@ -51,6 +51,10 @@ import {
51 type PullRequestListProjectError,
52 type PullRequestListResult,
53 type PullRequestListStatsInput,
54 + type PullRequestFilterOptions,
55 + type PullRequestFilterOptionsInput,
56 + type PullRequestActor,
57 + type PullRequestLabel,
58 type PullRequestListStatsResult,
59 type PullRequestProviderSummary,
60 type PullRequestReactionInput,
@@ -88,6 +92,7 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPr
92 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
93 import {
94 type ProviderChangeRequest,
95 + type ProviderFilterOptionPage,
96 type ProviderListCursor,
97 type ProviderChangeRequestWatchFingerprint,
98 type PullRequestProviderApi,
@@ -175,6 +180,9 @@ export class PullRequestService extends Context.Service<
180 readonly listStats: (
181 input: PullRequestListStatsInput,
182 ) => Effect.Effect<PullRequestListStatsResult, PullRequestError>;
183 + readonly filterOptions: (
184 + input: PullRequestFilterOptionsInput,
185 + ) => Effect.Effect<PullRequestFilterOptions, PullRequestError>;
186 readonly routing: (
187 input: PullRequestRef,
188 ) => Effect.Effect<PullRequestRoutingResult, PullRequestError>;
@@ -574,6 +582,17 @@ function withRateLimitBackoff(
582 ? {}
583 : { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }),
584 ...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }),
585 + ...(api.listRepositoryLabels === undefined
586 + ? {}
587 + : { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }),
588 + ...(api.searchRepositoryAuthors === undefined
589 + ? {}
590 + : {
591 + searchRepositoryAuthors: interactive(
592 + "searchRepositoryAuthors",
593 + api.searchRepositoryAuthors,
594 + ),
595 + }),
596 replyToThread: interactive("replyToThread", api.replyToThread),
597 setReaction: interactive("setReaction", api.setReaction),
598 setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
@@ -583,6 +602,52 @@ function withRateLimitBackoff(
602 Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;
603 }
604
605 +const FILTER_OPTIONS_LIMIT = 100;
606 +
607 +/**
608 + * Exact matches first, then names that begin with the query, then the rest, so a short query
609 + * still puts the obvious answer at the top of a long list.
610 + */
611 +function rankFilterOptions<A>(
612 + pages: ReadonlyArray<ProviderFilterOptionPage<A>>,
613 + input: {
614 + readonly query: string | undefined;
615 + readonly keyOf: (item: A) => string;
616 + readonly textsOf: (item: A) => ReadonlyArray<string | null>;
617 + },
618 +): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {
619 + const query = input.query?.trim().toLowerCase() ?? "";
620 + const unique = new Map<string, A>();
621 + for (const page of pages) {
622 + for (const item of page.items) {
623 + const key = input.keyOf(item).toLowerCase();
624 + if (!unique.has(key)) unique.set(key, item);
625 + }
626 + }
627 + const rank = (item: A) => {
628 + const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : []));
629 + if (query.length === 0) return 0;
630 + if (texts.includes(query)) return 0;
631 + if (texts.some((text) => text.startsWith(query))) return 1;
632 + if (texts.some((text) => text.includes(query))) return 2;
633 + return null;
634 + };
635 + const ranked = [...unique.values()]
636 + .flatMap((item) => {
637 + const score = rank(item);
638 + return score === null ? [] : [{ item, score, key: input.keyOf(item) }];
639 + })
640 + .toSorted(
641 + (left, right) =>
642 + left.score - right.score ||
643 + left.key.localeCompare(right.key, undefined, { sensitivity: "base" }),
644 + );
645 + return {
646 + items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),
647 + truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated),
648 + };
649 +}
650 +
651 // Capture before the provider read so a slow response keeps its original freshness through caches.
652 const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {
653 const observedAt = yield* Clock.currentTimeMillis;
@@ -2326,6 +2391,61 @@ export const make = Effect.gen(function* () {
2391 }),
2392 );
2393
2394 + const filterOptions: PullRequestService["Service"]["filterOptions"] = Effect.fn(
2395 + "PullRequestService.filterOptions",
2396 + )(function* (input) {
2397 + const { supported } = yield* listWorkspaceProjects(input);
2398 + // Worktrees of one checkout are separate projects over the same repository.
2399 + const repositories = [
2400 + ...new Map(supported.map((project) => [project.cursorKey, project])).values(),
2401 + ];
2402 + const refOf = (project: SupportedProject) => ({
2403 + cwd: project.project.workspaceRoot,
2404 + repository: project.repository,
2405 + host: project.host,
2406 + query: input.query,
2407 + });
2408 + // One repository the host cannot read leaves the others' options standing, as a listing does.
2409 + const gather = <A>(
2410 + read: (
2411 + project: SupportedProject,
2412 + ) => Effect.Effect<ProviderFilterOptionPage<A>, PullRequestProviderError> | undefined,
2413 + ) =>
2414 + Effect.forEach(
2415 + repositories,
2416 + (project): Effect.Effect<ReadonlyArray<ProviderFilterOptionPage<A>>> => {
2417 + const page = read(project);
2418 + return page === undefined
2419 + ? Effect.succeed([])
2420 + : page.pipe(
2421 + Effect.map((answered) => [answered]),
2422 + Effect.orElseSucceed(() => []),
2423 + );
2424 + },
2425 + { concurrency: REPOSITORY_CONCURRENCY },
2426 + ).pipe(Effect.map((pages) => pages.flat()));
2427 + if (input.kind === "labels") {
2428 + const pages = yield* gather<PullRequestLabel>((project) =>
2429 + project.api.listRepositoryLabels?.(refOf(project)),
2430 + );
2431 + const { items, truncated } = rankFilterOptions(pages, {
2432 + query: input.query,
2433 + keyOf: (label) => label.name,
2434 + textsOf: (label) => [label.name],
2435 + });
2436 + return { labels: items, authors: [], truncated };
2437 + }
2438 + const pages = yield* gather<PullRequestActor>((project) =>
2439 + project.api.searchRepositoryAuthors?.(refOf(project)),
2440 + );
2441 + const { items, truncated } = rankFilterOptions(pages, {
2442 + query: input.query,
2443 + keyOf: (author) => author.login,
2444 + textsOf: (author) => [author.login, author.name],
2445 + });
2446 + return { labels: [], authors: items, truncated };
2447 + });
2448 +
2449 const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) =>
2450 requireProject(input).pipe(
2451 Effect.flatMap((project): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> => {
@@ -3432,6 +3552,7 @@ export const make = Effect.gen(function* () {
3552 routingIdentity,
3553 withRoutingCredential,
3554 list,
3555 + filterOptions,
3556 listStats: (input) =>
3557 Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe(
3558 Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })),
apps/server/src/ws.ts
+1
@@ -2509,6 +2509,7 @@ export const layerWsRpc = (
2509 ),
2510 [WS_METHODS.pullRequestsList]: (input) => pullRequests.list(input),
2511 [WS_METHODS.pullRequestsListStats]: (input) => pullRequests.listStats(input),
2512 + [WS_METHODS.pullRequestsFilterOptions]: (input) => pullRequests.filterOptions(input),
2513 [WS_METHODS.pullRequestsRoutingIdentity]: (input) => pullRequests.routingIdentity(input),
2514 [WS_METHODS.pullRequestsRouting]: (input) => pullRequests.routing(input),
2515 [WS_METHODS.pullRequestsSummary]: (input) =>
apps/web/src/components/pullRequest/PullRequestListFilters.tsx
+175 -85
@@ -2,6 +2,7 @@ import { Spinner } from "~/components/ui/spinner";
2 import type {
3 EnvironmentId,
4 ProjectId,
5 + PullRequestFilterOptionsInput,
6 PullRequestInvolvement,
7 PullRequestListFilters,
8 PullRequestListState,
@@ -23,6 +24,8 @@ import {
24 import { type ElementType, useState } from "react";
25
26 import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
27 +import { useDebouncedValue } from "~/state/queries";
28 +import { type EnvironmentQueryTarget, usePullRequestFilterOptions } from "~/state/pullRequests";
29 import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon";
30 import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
31 import { Button } from "../ui/button";
@@ -36,6 +39,7 @@ import {
39 MenuRadioGroup,
40 MenuRadioItem,
41 MenuRadioItemIndicator,
42 + MenuSearchInput,
43 MenuSeparator,
44 MenuSub,
45 MenuSubPopup,
@@ -44,6 +48,9 @@ import {
48 } from "../ui/menu";
49 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
50 import {
51 + pullRequestAuthorChoices,
52 + selectedPullRequestAuthor,
53 + pullRequestLabelChoices,
54 pullRequestLabelColor,
55 type PullRequestAuthorFacet,
56 type PullRequestLabelFacet,
@@ -232,30 +239,103 @@ function PullRequestFilterRadioSubmenu<Value extends string>({
239 );
240 }
241
235 -function PullRequestAuthorFilter({
242 +/** The listing's own scope, which the pickers search the host within. */
243 +export type PullRequestFilterOptionScope = EnvironmentQueryTarget<
244 + Omit<PullRequestFilterOptionsInput, "kind" | "query">
245 +>;
246 +
247 +const OPTION_SEARCH_DEBOUNCE_MS = 250;
248 +
249 +function useHostedFilterOptions(
250 + scope: ReadonlyArray<PullRequestFilterOptionScope>,
251 + kind: PullRequestFilterOptionsInput["kind"],
252 + query: string,
253 +) {
254 + const typed = query.trim().slice(0, 100);
255 + const sent = useDebouncedValue(typed, OPTION_SEARCH_DEBOUNCE_MS);
256 + const hosted = usePullRequestFilterOptions(
257 + scope.map(({ environmentId, input }) => ({
258 + environmentId,
259 + input: { ...input, kind, ...(sent ? { query: sent } : {}) },
260 + })),
261 + );
262 + // Until the search catches up with the typing, the host's answers are for older text.
263 + return sent === typed ? hosted : { labels: [], authors: [], error: null, isPending: true };
264 +}
265 +
266 +function PullRequestAuthorChoices({
267 value,
268 options,
269 + scope,
270 onChange,
271 }: {
272 value: string | undefined;
273 options: ReadonlyArray<PullRequestAuthorFacet>;
274 + scope: ReadonlyArray<PullRequestFilterOptionScope>;
275 onChange: (author: string | undefined) => void;
276 }) {
277 const [query, setQuery] = useState("");
245 - const needle = query.trim().toLowerCase();
278 + const hosted = useHostedFilterOptions(scope, "authors", query);
279 const login = value?.toLowerCase() ?? "";
247 - const selected = options.find((option) => option.actor.login.toLowerCase() === login);
280 + const selected = selectedPullRequestAuthor(options, hosted.authors, value);
281 const visible = [
282 ...(selected ? [selected] : []),
250 - ...options.filter(
251 - (option) =>
252 - option !== selected &&
253 - (needle.length === 0 ||
254 - option.actor.login.toLowerCase().includes(needle) ||
255 - option.actor.name?.toLowerCase().includes(needle)),
283 + ...pullRequestAuthorChoices(options, hosted.authors, query).filter(
284 + (option) => option.actor.login.toLowerCase() !== login,
285 ),
257 - ].slice(0, 10);
286 + ].slice(0, 30);
287 const select = (next: string) => next.toLowerCase() !== login && onChange(next || undefined);
288 + return (
289 + <>
290 + <MenuSearchInput
291 + autoFocus
292 + busy={hosted.isPending}
293 + value={query}
294 + onChange={(event) => setQuery(event.currentTarget.value)}
295 + placeholder="Search authors"
296 + aria-label="Search authors"
297 + />
298 + <MenuRadioGroup value={selected?.actor.login ?? value ?? ""} onValueChange={select}>
299 + <MenuRadioItem value="">
300 + <span className="flex min-w-0 items-center gap-2">
301 + <LayersIcon aria-hidden className="size-3.5" />
302 + Anyone
303 + </span>
304 + </MenuRadioItem>
305 + {visible.map((option) => (
306 + <MenuRadioItem key={option.actor.login.toLowerCase()} value={option.actor.login}>
307 + <span className="flex min-w-0 items-center gap-2">
308 + <PullRequestActorAvatar actor={option.actor} />
309 + <span className="min-w-0 flex-1 truncate">{option.actor.login}</span>
310 + {option.mergedCount > 0 ? (
311 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
312 + {option.mergedCount} merges loaded
313 + </span>
314 + ) : null}
315 + </span>
316 + </MenuRadioItem>
317 + ))}
318 + {visible.length === 0 && !hosted.isPending ? (
319 + <MenuItem disabled>
320 + {hosted.error === null ? "No authors found" : "Couldn't search authors on the host"}
321 + </MenuItem>
322 + ) : null}
323 + </MenuRadioGroup>
324 + </>
325 + );
326 +}
327 +
328 +function PullRequestAuthorFilter({
329 + value,
330 + options,
331 + scope,
332 + onChange,
333 +}: {
334 + value: string | undefined;
335 + options: ReadonlyArray<PullRequestAuthorFacet>;
336 + scope: ReadonlyArray<PullRequestFilterOptionScope>;
337 + onChange: (author: string | undefined) => void;
338 +}) {
339 return (
340 <MenuSub>
341 <MenuSubTrigger>
@@ -266,65 +346,99 @@ function PullRequestAuthorFilter({
346 </span>
347 </MenuSubTrigger>
348 <MenuSubPopup>
269 - <div className="p-1 pb-2">
270 - <InputGroup>
271 - <InputGroupAddon>
272 - <SearchIcon aria-hidden />
273 - </InputGroupAddon>
274 - <InputGroupInput
275 - autoFocus
276 - size="compact"
277 - value={query}
278 - onChange={(event) => setQuery(event.currentTarget.value)}
279 - onKeyDown={(event) => {
280 - if (event.key !== "ArrowDown" && event.key !== "Escape") event.stopPropagation();
281 - }}
282 - placeholder="Search authors"
283 - aria-label="Search authors"
284 - />
285 - </InputGroup>
286 - </div>
287 - <MenuRadioGroup value={selected?.actor.login ?? value ?? ""} onValueChange={select}>
288 - <MenuRadioItem value="">
289 - <span className="flex min-w-0 items-center gap-2">
290 - <LayersIcon aria-hidden className="size-3.5" />
291 - Anyone
292 - </span>
293 - </MenuRadioItem>
294 - {visible.map((option) => (
295 - <MenuRadioItem key={option.actor.login.toLowerCase()} value={option.actor.login}>
296 - <span className="flex min-w-0 items-center gap-2">
297 - <PullRequestActorAvatar actor={option.actor} />
298 - <span className="min-w-0 flex-1 truncate">{option.actor.login}</span>
299 - <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
300 - {option.mergedCount} merges loaded
301 - </span>
302 - </span>
303 - </MenuRadioItem>
304 - ))}
305 - {visible.length === 0 ? <MenuItem disabled>No authors found</MenuItem> : null}
306 - </MenuRadioGroup>
349 + <PullRequestAuthorChoices
350 + value={value}
351 + options={options}
352 + scope={scope}
353 + onChange={onChange}
354 + />
355 </MenuSubPopup>
356 </MenuSub>
357 );
358 }
359
312 -function PullRequestLabelFilter({
360 +function PullRequestLabelChoices({
361 value,
362 options,
363 + scope,
364 onChange,
365 }: {
366 value: ReadonlyArray<string>;
367 options: ReadonlyArray<PullRequestLabelFacet>;
368 + scope: ReadonlyArray<PullRequestFilterOptionScope>;
369 onChange: (labels: ReadonlyArray<string>) => void;
370 }) {
371 + const [query, setQuery] = useState("");
372 + const hosted = useHostedFilterOptions(scope, "labels", query);
373 const selected = new Set(value.map((name) => name.toLowerCase()));
374 + const choices = pullRequestLabelChoices(options, hosted.labels, query);
375 const visible = [
376 ...value
324 - .filter((name) => !options.some((option) => option.name.toLowerCase() === name.toLowerCase()))
377 + .filter((name) => !choices.some((option) => option.name.toLowerCase() === name.toLowerCase()))
378 .map((name) => ({ name, color: null, count: 0 })),
326 - ...options,
379 + ...choices,
380 ];
381 + return (
382 + <>
383 + <MenuSearchInput
384 + autoFocus
385 + busy={hosted.isPending}
386 + value={query}
387 + onChange={(event) => setQuery(event.currentTarget.value)}
388 + placeholder="Search labels"
389 + aria-label="Search labels"
390 + />
391 + {visible.length === 0 && !hosted.isPending ? (
392 + <MenuItem disabled>
393 + {hosted.error === null ? "No labels found" : "Couldn't search labels on the host"}
394 + </MenuItem>
395 + ) : null}
396 + {visible.map((option) => {
397 + const key = option.name.toLowerCase();
398 + const dot = pullRequestLabelColor(option.color);
399 + return (
400 + <MenuCheckboxItem
401 + key={key}
402 + checked={selected.has(key)}
403 + onCheckedChange={(next) =>
404 + onChange(
405 + next
406 + ? [...value, option.name]
407 + : value.filter((name) => name.toLowerCase() !== option.name.toLowerCase()),
408 + )
409 + }
410 + >
411 + <span className="flex min-w-0 items-center gap-2">
412 + <span
413 + aria-hidden
414 + className="size-2.5 shrink-0 rounded-full bg-muted-foreground"
415 + {...(dot ? { style: { backgroundColor: dot } } : {})}
416 + />
417 + <span className="min-w-0 flex-1 truncate">{option.name}</span>
418 + {option.count > 0 ? (
419 + <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
420 + {option.count}
421 + </span>
422 + ) : null}
423 + </span>
424 + </MenuCheckboxItem>
425 + );
426 + })}
427 + </>
428 + );
429 +}
430 +
431 +function PullRequestLabelFilter({
432 + value,
433 + options,
434 + scope,
435 + onChange,
436 +}: {
437 + value: ReadonlyArray<string>;
438 + options: ReadonlyArray<PullRequestLabelFacet>;
439 + scope: ReadonlyArray<PullRequestFilterOptionScope>;
440 + onChange: (labels: ReadonlyArray<string>) => void;
441 +}) {
442 return (
443 <MenuSub>
444 <MenuSubTrigger>
@@ -335,40 +449,12 @@ function PullRequestLabelFilter({
449 </span>
450 </MenuSubTrigger>
451 <MenuSubPopup>
338 - {visible.length === 0 ? (
339 - <MenuItem disabled>No labels in this view</MenuItem>
340 - ) : (
341 - visible.map((option) => {
342 - const key = option.name.toLowerCase();
343 - const checked = selected.has(key);
344 - const dot = pullRequestLabelColor(option.color);
345 - return (
346 - <MenuCheckboxItem
347 - key={key}
348 - checked={checked}
349 - onCheckedChange={(next) =>
350 - onChange(
351 - next
352 - ? [...value, option.name]
353 - : value.filter((name) => name.toLowerCase() !== option.name.toLowerCase()),
354 - )
355 - }
356 - >
357 - <span className="flex min-w-0 items-center gap-2">
358 - <span
359 - aria-hidden
360 - className="size-2.5 shrink-0 rounded-full bg-muted-foreground"
361 - {...(dot ? { style: { backgroundColor: dot } } : {})}
362 - />
363 - <span className="min-w-0 flex-1 truncate">{option.name}</span>
364 - <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
365 - {option.count}
366 - </span>
367 - </span>
368 - </MenuCheckboxItem>
369 - );
370 - })
371 - )}
452 + <PullRequestLabelChoices
453 + value={value}
454 + options={options}
455 + scope={scope}
456 + onChange={onChange}
457 + />
458 </MenuSubPopup>
459 </MenuSub>
460 );
@@ -386,6 +472,7 @@ export function PullRequestFiltersMenu({
472 onFilters,
473 authorOptions = [],
474 labelOptions = [],
475 + optionScope,
476 host,
477 hostOptions,
478 onHost,
@@ -409,6 +496,7 @@ export function PullRequestFiltersMenu({
496 onFilters: (filters: PullRequestListFilters) => void;
497 authorOptions?: ReadonlyArray<PullRequestAuthorFacet>;
498 labelOptions?: ReadonlyArray<PullRequestLabelFacet>;
499 + optionScope: ReadonlyArray<PullRequestFilterOptionScope>;
500 host: string | undefined;
501 hostOptions: ReadonlyArray<PullRequestFilterOption<string>>;
502 onHost: (host: string | undefined) => void;
@@ -494,11 +582,13 @@ export function PullRequestFiltersMenu({
582 <PullRequestAuthorFilter
583 value={filters.author}
584 options={authorOptions}
585 + scope={optionScope}
586 onChange={(author) => updateFilters({ author })}
587 />
588 <PullRequestLabelFilter
589 value={selectedLabels}
590 options={labelOptions}
591 + scope={optionScope}
592 onChange={(labels) =>
593 updateFilters({
594 labels: labels.length === 0 ? undefined : labels.slice(0, 10).map((label) => [label]),
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+9
@@ -348,6 +348,14 @@ export function PullRequestsPage() {
348 }));
349 })();
350 const facetQuery = usePullRequestList(facetTargets);
351 + const filterOptionScope = environmentQueries.map(({ environmentId, projectIds }) => ({
352 + environmentId,
353 + input: {
354 + ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
355 + ...(projectIds ? { projectIds } : {}),
356 + ...(search.host ? { host: search.host } : {}),
357 + },
358 + }));
359 const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
360 const partitionTargets = (() => {
361 // The main list goes first. Besides putting the visible rows on screen sooner, it proves
@@ -1258,6 +1266,7 @@ export function PullRequestsPage() {
1266 }}
1267 authorOptions={facets.authors}
1268 labelOptions={facets.labels}
1269 + optionScope={filterOptionScope}
1270 host={search.host}
1271 hostOptions={hostMenuOptions}
1272 onHost={(host) => updateListScope({ host })}
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+67
@@ -24,6 +24,9 @@ import {
24 partitionPullRequestsWithPriority,
25 readPullRequestListSnapshot,
26 writePullRequestListSnapshot,
27 + pullRequestAuthorChoices,
28 + selectedPullRequestAuthor,
29 + pullRequestLabelChoices,
30 rankPullRequestMatches,
31 rankPullRequestsBlockedOnAuthor,
32 rankPullRequestsByMergeReadiness,
@@ -815,3 +818,67 @@ describe("findProjectForRepository", () => {
818 ).toBeUndefined();
819 });
820 });
821 +
822 +describe("filter picker choices", () => {
823 + const actor = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null });
824 +
825 + it("offers authors the host found that no loaded row carries, after the loaded ones", () => {
826 + const loaded = [
827 + { actor: actor("julius", "Julius"), count: 4, mergedCount: 3 },
828 + { actor: actor("theo"), count: 1, mergedCount: 0 },
829 + ];
830 +
831 + const choices = pullRequestAuthorChoices(
832 + loaded,
833 + [actor("Julius"), actor("juliana", "Juliana")],
834 + "jul",
835 + );
836 +
837 + expect(choices.map((choice) => [choice.actor.login, choice.count])).toEqual([
838 + ["julius", 4],
839 + ["juliana", 0],
840 + ]);
841 + });
842 +
843 + it("keeps showing an author picked from the host's search once the search clears", () => {
844 + const loaded = [{ actor: actor("julius"), count: 4, mergedCount: 3 }];
845 + const hosted = [actor("Juliana", "Juliana")];
846 +
847 + expect(selectedPullRequestAuthor(loaded, hosted, "juliana")?.actor).toEqual(
848 + actor("Juliana", "Juliana"),
849 + );
850 + expect(selectedPullRequestAuthor(loaded, [], "juliana")?.actor.login).toBe("juliana");
851 + expect(selectedPullRequestAuthor(loaded, hosted, "JULIUS")?.count).toBe(4);
852 + expect(selectedPullRequestAuthor(loaded, hosted, undefined)).toBeUndefined();
853 + });
854 +
855 + it("puts the host's authors after the first loaded matches rather than after all of them", () => {
856 + const loaded = Array.from({ length: 40 }, (_, index) => ({
857 + actor: actor(`dev-${index}`),
858 + count: 1,
859 + mergedCount: 0,
860 + }));
861 +
862 + const choices = pullRequestAuthorChoices(loaded, [actor("dev-from-host")], "dev");
863 +
864 + expect(choices.slice(0, 30).map((choice) => choice.actor.login)).toContain("dev-from-host");
865 + });
866 +
867 + it("keeps a loaded label's count when only the host's search found it", () => {
868 + const loaded = [{ name: "size:XL", color: "d93f0b", count: 7 }];
869 +
870 + const choices = pullRequestLabelChoices(
871 + loaded,
872 + [
873 + { name: "size:XL", color: "d93f0b" },
874 + { name: "bug", color: null },
875 + ],
876 + "xl-ish",
877 + );
878 +
879 + expect(choices).toEqual([
880 + { name: "size:XL", color: "d93f0b", count: 7 },
881 + { name: "bug", color: null, count: 0 },
882 + ]);
883 + });
884 +});
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+78
@@ -129,6 +129,84 @@ export function collectPullRequestListFacets(
129 };
130 }
131
132 +/**
133 + * What a filter picker offers for `query`: the loaded rows that match keep their counts and lead,
134 + * then whatever the host found that no loaded row carries, so a name nobody has loaded yet is
135 + * still one search away.
136 + */
137 +/** How many loaded matches come before the host's answers. */
138 +const HOSTED_CHOICE_ROOM = 15;
139 +
140 +export function pullRequestAuthorChoices(
141 + facets: ReadonlyArray<PullRequestAuthorFacet>,
142 + hosted: ReadonlyArray<PullRequestActor>,
143 + query: string,
144 +): ReadonlyArray<PullRequestAuthorFacet> {
145 + const needle = normalize(query);
146 + const loaded = facets.filter(
147 + (facet) =>
148 + needle === null ||
149 + facet.actor.login.toLowerCase().includes(needle) ||
150 + facet.actor.name?.toLowerCase().includes(needle),
151 + );
152 + const known = new Map(facets.map((facet) => [normalize(facet.actor.login), facet]));
153 + const seen = new Set(loaded.map((facet) => normalize(facet.actor.login)));
154 + const added: PullRequestAuthorFacet[] = [];
155 + for (const actor of hosted) {
156 + const key = normalize(actor.login);
157 + if (seen.has(key)) continue;
158 + seen.add(key);
159 + added.push(known.get(key) ?? { actor, count: 0, mergedCount: 0 });
160 + }
161 + // The picker shows a short list, and loaded matches alone could fill it.
162 + return [...loaded.slice(0, HOSTED_CHOICE_ROOM), ...added, ...loaded.slice(HOSTED_CHOICE_ROOM)];
163 +}
164 +
165 +/**
166 + * The author a filter names, as a choice: an author picked from the host's answer is on no
167 + * loaded row, so it stays shown after the search that found it clears.
168 + */
169 +export function selectedPullRequestAuthor(
170 + facets: ReadonlyArray<PullRequestAuthorFacet>,
171 + hosted: ReadonlyArray<PullRequestActor>,
172 + value: string | undefined,
173 +): PullRequestAuthorFacet | undefined {
174 + if (value === undefined) return undefined;
175 + const key = normalize(value);
176 + return (
177 + facets.find((facet) => normalize(facet.actor.login) === key) ?? {
178 + actor: hosted.find((actor) => normalize(actor.login) === key) ?? {
179 + login: value,
180 + name: null,
181 + avatarUrl: null,
182 + },
183 + count: 0,
184 + mergedCount: 0,
185 + }
186 + );
187 +}
188 +
189 +export function pullRequestLabelChoices(
190 + facets: ReadonlyArray<PullRequestLabelFacet>,
191 + hosted: ReadonlyArray<PullRequestLabel>,
192 + query: string,
193 +): ReadonlyArray<PullRequestLabelFacet> {
194 + const needle = normalize(query);
195 + const loaded = facets.filter(
196 + (facet) => needle === null || facet.name.toLowerCase().includes(needle),
197 + );
198 + const known = new Map(facets.map((facet) => [normalize(facet.name), facet]));
199 + const seen = new Set(loaded.map((facet) => normalize(facet.name)));
200 + const added: PullRequestLabelFacet[] = [];
201 + for (const label of hosted) {
202 + const key = normalize(label.name);
203 + if (seen.has(key)) continue;
204 + seen.add(key);
205 + added.push(known.get(key) ?? { ...label, count: 0 });
206 + }
207 + return [...loaded, ...added];
208 +}
209 +
210 export function pullRequestEntryViewer(
211 entry: ScopedEntry,
212 viewers: PullRequestViewers,
apps/web/src/components/ui/menu.tsx
+42 -1
@@ -1,9 +1,11 @@
1 import { Menu as MenuPrimitive } from "@base-ui/react/menu";
2 -import { CheckIcon, ChevronRightIcon } from "lucide-react";
2 +import { CheckIcon, ChevronRightIcon, SearchIcon } from "lucide-react";
3 import type * as React from "react";
4
5 import { cn } from "~/lib/utils";
6 import { buttonVariants } from "./button";
7 +import { Input, type InputProps } from "./input";
8 +import { Spinner } from "./spinner";
9
10 const Menu = MenuPrimitive.Root;
11
@@ -67,6 +69,44 @@ function MenuPopup({
69 );
70 }
71
72 +/** A menu's filter field, drawn like `ComboboxSearchInput` so every searchable popup matches. */
73 +function MenuSearchInput({
74 + busy = false,
75 + onKeyDown,
76 + ...props
77 +}: Omit<InputProps, "className" | "size" | "unstyled" | "nativeInput"> & { busy?: boolean }) {
78 + return (
79 + <div className="min-w-0 shrink-0 px-2 pt-1.5 pb-1">
80 + <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
81 + {busy ? (
82 + <Spinner
83 + aria-hidden="true"
84 + size="md"
85 + tone="muted"
86 + className="pointer-events-none absolute top-1.5 left-0"
87 + />
88 + ) : (
89 + <SearchIcon
90 + aria-hidden="true"
91 + className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
92 + />
93 + )}
94 + <Input
95 + {...props}
96 + className="rounded-none bg-transparent text-sm [&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
97 + size="sm"
98 + unstyled
99 + onKeyDown={(event) => {
100 + // Menu typeahead would otherwise take the letters; arrows still reach the items.
101 + if (event.key !== "ArrowDown" && event.key !== "Escape") event.stopPropagation();
102 + onKeyDown?.(event);
103 + }}
104 + />
105 + </div>
106 + </div>
107 + );
108 +}
109 +
110 function MenuGroup(props: MenuPrimitive.Group.Props) {
111 return <MenuPrimitive.Group data-slot="menu-group" {...props} />;
112 }
@@ -327,6 +367,7 @@ export {
367 MenuTrigger as DropdownMenuTrigger,
368 MenuPopup,
369 MenuPopup as DropdownMenuContent,
370 + MenuSearchInput,
371 MenuGroup,
372 MenuGroup as DropdownMenuGroup,
373 MenuItem,
apps/web/src/state/pullRequests.ts
+18
@@ -9,6 +9,7 @@ import type {
9 EnvironmentId,
10 ProjectId,
11 PullRequestListInput,
12 + PullRequestFilterOptionsInput,
13 PullRequestListStatsInput,
14 PullRequestListEntry,
15 PullRequestRef,
@@ -308,6 +309,11 @@ const usePullRequestStatsQuery = createMergedEnvironmentQuery(
309 pullRequestEnvironment.listStats,
310 );
311
312 +const usePullRequestFilterOptionsQuery = createMergedEnvironmentQuery(
313 + "web-pull-requests:filter-options",
314 + pullRequestEnvironment.filterOptions,
315 +);
316 +
317 const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery(
318 "web-pull-requests:turn-refreshes",
319 ({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>
@@ -376,3 +382,15 @@ export function usePullRequestListStats(
382 );
383 return { stats, isPending: query.isPending, refresh: query.refresh };
384 }
385 +
386 +export function usePullRequestFilterOptions(
387 + targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestFilterOptionsInput>>,
388 +) {
389 + const query = usePullRequestFilterOptionsQuery(targets);
390 + return {
391 + labels: query.values.flatMap(([, options]) => options.labels),
392 + authors: query.values.flatMap(([, options]) => options.authors),
393 + error: query.error,
394 + isPending: query.isPending,
395 + };
396 +}
packages/client-runtime/src/state/pullRequests.ts
+5
@@ -322,6 +322,11 @@ export function createPullRequestEnvironmentAtoms<R, E>(
322 staleTimeMs: 60_000,
323 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
324 }),
325 + filterOptions: createEnvironmentRpcQueryAtomFamily(runtime, {
326 + label: "environment-data:pull-requests:filter-options",
327 + tag: WS_METHODS.pullRequestsFilterOptions,
328 + staleTimeMs: 5 * 60_000,
329 + }),
330 detail,
331 preview,
332 checks: normalizePullRequestQuery(
packages/contracts/src/pullRequest.ts
+20
@@ -525,6 +525,26 @@ export const PullRequestListStatsResult = Schema.Struct({
525 });
526 export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;
527
528 +export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors"]);
529 +export type PullRequestFilterOptionKind = typeof PullRequestFilterOptionKind.Type;
530 +
531 +/** Scoped like `PullRequestListInput`, so the options come from the repositories it lists. */
532 +export const PullRequestFilterOptionsInput = Schema.Struct({
533 + kind: PullRequestFilterOptionKind,
534 + projectId: Schema.optional(ProjectId),
535 + projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),
536 + host: Schema.optional(TrimmedNonEmptyString),
537 + query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),
538 +});
539 +export type PullRequestFilterOptionsInput = typeof PullRequestFilterOptionsInput.Type;
540 +
541 +export const PullRequestFilterOptions = Schema.Struct({
542 + labels: Schema.Array(PullRequestLabel),
543 + authors: Schema.Array(PullRequestActor),
544 + truncated: Schema.Boolean,
545 +});
546 +export type PullRequestFilterOptions = typeof PullRequestFilterOptions.Type;
547 +
548 /**
549 * A separate request rather than a flag on the reads, so an explicit "refresh" one person
550 * presses is the only thing that spends host requests — every ordinary read shares.
packages/contracts/src/rpc.ts
+10
@@ -180,6 +180,8 @@ import {
180 PullRequestListResult,
181 PullRequestListStatsInput,
182 PullRequestListStatsResult,
183 + PullRequestFilterOptions,
184 + PullRequestFilterOptionsInput,
185 PullRequestOperationError,
186 PullRequestReactionInput,
187 PullRequestRef,
@@ -526,6 +528,7 @@ export const WS_METHODS = {
528
529 pullRequestsList: "pullRequests.list",
530 pullRequestsListStats: "pullRequests.listStats",
531 + pullRequestsFilterOptions: "pullRequests.filterOptions",
532 pullRequestsSummary: "pullRequests.summary",
533 pullRequestsRouting: "pullRequests.routing",
534 pullRequestsRoutingIdentity: "pullRequests.routingIdentity",
@@ -963,6 +966,12 @@ const WsPullRequestsListStatsRpc = Rpc.make(WS_METHODS.pullRequestsListStats, {
966 error: PullRequestRpcError,
967 });
968
969 +const WsPullRequestsFilterOptionsRpc = Rpc.make(WS_METHODS.pullRequestsFilterOptions, {
970 + payload: PullRequestFilterOptionsInput,
971 + success: PullRequestFilterOptions,
972 + error: PullRequestRpcError,
973 +});
974 +
975 const WsPullRequestsRoutingRpc = Rpc.make(WS_METHODS.pullRequestsRouting, {
976 payload: PullRequestRef,
977 success: PullRequestRoutingResult,
@@ -1948,6 +1957,7 @@ export const WsRpcGroup = RpcGroup.make(
1957 WsCloudInstallRelayClientRpc,
1958 WsPullRequestsListRpc,
1959 WsPullRequestsListStatsRpc,
1960 + WsPullRequestsFilterOptionsRpc,
1961 WsPullRequestsSummaryRpc,
1962 WsPullRequestsRoutingRpc,
1963 WsPullRequestsRoutingIdentityRpc,
packages/source-control-core/src/server/PullRequestProvider.ts
+21
@@ -258,6 +258,11 @@ export interface ProviderFileRevisions {
258 readonly complete?: boolean;
259 }
260
261 +export interface ProviderFilterOptionPage<A> {
262 + readonly items: ReadonlyArray<A>;
263 + readonly truncated: boolean;
264 +}
265 +
266 export interface ProviderRepositoryRef {
267 readonly cwd: string;
268 readonly repository: string;
@@ -529,6 +534,22 @@ export interface PullRequestProviderApi {
534 input: ProviderRepositoryRef & { readonly number: number },
535 ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestProviderError>;
536
537 + /**
538 + * The labels a repository offers, for narrowing a listing by. `query` narrows by name as far as
539 + * the host can; the caller still matches the answer against it.
540 + */
541 + readonly listRepositoryLabels?: (
542 + input: ProviderRepositoryRef & { readonly query?: string | undefined },
543 + ) => Effect.Effect<ProviderFilterOptionPage<PullRequestLabel>, PullRequestProviderError>;
544 +
545 + /**
546 + * People who could have opened a change request in the repository, for narrowing a listing by
547 + * author. A host that can only search its whole user base answers from that.
548 + */
549 + readonly searchRepositoryAuthors?: (
550 + input: ProviderRepositoryRef & { readonly query?: string | undefined },
551 + ) => Effect.Effect<ProviderFilterOptionPage<PullRequestActor>, PullRequestProviderError>;
552 +
553 readonly setLabels?: (
554 input: ProviderRepositoryRef & {
555 readonly number: number;
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+57 -4
@@ -58,6 +58,11 @@ const CAPABILITIES: PullRequestCapabilities = {
58 reviewers: { request: true, listCandidates: true },
59 edit: { changeRequest: true, comment: true },
60 };
61 +const USER_SEARCH_LIMIT = 50;
62 +const ForgejoUserSearch = Schema.Struct({
63 + data: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
64 +});
65 +
66 const repoPath = (input: ProviderRepositoryRef) =>
67 `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
68 const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>
@@ -100,7 +105,8 @@ export const make = Effect.gen(function* () {
105 }),
106 ),
107 );
103 - const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(
108 + /** A response, and whether its `link` header points at a further page. */
109 + const readLinked = Effect.fn("ForgejoPullRequestProvider.readLinked")(function* <A>(
110 input: ForgejoCli.ForgejoApiInput,
111 schema: Schema.Codec<A, unknown, never, never>,
112 ) {
@@ -108,10 +114,15 @@ export const make = Effect.gen(function* () {
114 if (result.stdoutTruncated)
115 return yield* failure(input.path, "Forgejo response exceeded the output limit.");
116 const decoded = decodeJsonResult(schema)(result.stdout);
111 - return Result.isSuccess(decoded)
112 - ? decoded.success
113 - : yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
117 + if (Result.isFailure(decoded))
118 + return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);
119 + const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
120 + return { value: decoded.success, next: links !== undefined && /rel="?next"?/i.test(links) };
121 });
122 + const read = <A>(
123 + input: ForgejoCli.ForgejoApiInput,
124 + schema: Schema.Codec<A, unknown, never, never>,
125 + ) => readLinked(input, schema).pipe(Effect.map(({ value }) => value));
126 const readArray = <A>(
127 input: ForgejoCli.ForgejoApiInput,
128 schema: Schema.Codec<A, unknown, never, never>,
@@ -632,6 +643,48 @@ export const make = Effect.gen(function* () {
643 };
644 },
645 ),
646 + listRepositoryLabels: Effect.fn("ForgejoPullRequestProvider.listRepositoryLabels")(
647 + function* (input) {
648 + const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
649 + return {
650 + items: labels.items.map((label) => ({ name: label.name, color: label.color ?? null })),
651 + truncated: labels.truncated,
652 + };
653 + },
654 + ),
655 + searchRepositoryAuthors: Effect.fn("ForgejoPullRequestProvider.searchRepositoryAuthors")(
656 + function* (input) {
657 + const query = input.query?.trim() ?? "";
658 + const actors = (users: ReadonlyArray<typeof ForgejoUser.Type>) =>
659 + users.flatMap((user) => {
660 + const actor = forgejoActor(user);
661 + return actor ? [actor] : [];
662 + });
663 + // Before anything is typed the repository's own people stand in; a search reaches
664 + // contributors from forks, who are never assignable.
665 + if (query.length === 0) {
666 + const users = yield* page(
667 + { ...input, path: `${repoPath(input)}/assignees` },
668 + ForgejoUser,
669 + 100,
670 + );
671 + return { items: actors(users.items), truncated: users.truncated };
672 + }
673 + const found = yield* readLinked(
674 + {
675 + ...input,
676 + path: `users/search?${new URLSearchParams({ q: query, limit: String(USER_SEARCH_LIMIT) })}`,
677 + },
678 + ForgejoUserSearch,
679 + );
680 + const users = found.value.data ?? [];
681 + // A server may cap pages below the limit asked for; its `link` header still says more.
682 + return {
683 + items: actors(users),
684 + truncated: found.next || users.length >= USER_SEARCH_LIMIT,
685 + };
686 + },
687 + ),
688 setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {
689 const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
690 const selected = labels.items.filter((label) => input.labels.includes(label.name));
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
+34
@@ -554,6 +554,40 @@ it.effect("lists nothing for an author Forgejo has no account for", () =>
554 ),
555 );
556
557 +it.effect("says an author search was cut short by a server that pages below its limit", () =>
558 + Effect.gen(function* () {
559 + const provider = yield* ForgejoPullRequestProvider.make;
560 + const search = provider.searchRepositoryAuthors;
561 + if (search === undefined) return yield* Effect.die("author search missing");
562 + const found = yield* search({
563 + cwd: "/repo",
564 + repository: "maria/project",
565 + host: "forgejo.test",
566 + query: "dev",
567 + });
568 + assert.strictEqual(found.items.length, 30);
569 + assert.isTrue(found.truncated);
570 + }).pipe(
571 + Effect.provide(
572 + Layer.mock(ForgejoCli.ForgejoCli)({
573 + api: () =>
574 + encodeJsonEffect({
575 + ok: true,
576 + data: Array.from({ length: 30 }, (_, index) => ({ login: `dev-${index}` })),
577 + }).pipe(
578 + Effect.orDie,
579 + Effect.map((stdout) =>
580 + processOutput(stdout, {
581 + stderr:
582 + 'HTTP/1.1 200\nlink: <https://forgejo.test/api/v1/users/search?page=2>; rel="next"\n',
583 + }),
584 + ),
585 + ),
586 + }),
587 + ),
588 + ),
589 +);
590 +
591 it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
592 Effect.gen(function* () {
593 const provider = yield* ForgejoSourceControlProvider.make;
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+24
@@ -1073,6 +1073,30 @@ export const make = Effect.gen(function* () {
1073 };
1074 },
1075 ),
1076 + listRepositoryLabels: Effect.fn("GitCafePullRequestProvider.listRepositoryLabels")(
1077 + function* (input) {
1078 + const operation = "listRepositoryLabels";
1079 + const base = yield* repositoryPath(operation, input);
1080 + const labels = yield* readPages(operation, input, `${base}/labels`, Json.GitCafeLabels);
1081 + return {
1082 + items: labels.items.map((label) => ({ name: label.name, color: label.color })),
1083 + truncated: labels.next !== null,
1084 + };
1085 + },
1086 + ),
1087 + searchRepositoryAuthors: Effect.fn("GitCafePullRequestProvider.searchRepositoryAuthors")(
1088 + function* (input) {
1089 + const operation = "searchRepositoryAuthors";
1090 + const query = input.query?.trim() ?? "";
1091 + // User search needs two characters; before that the repository's own people stand in.
1092 + const path =
1093 + query.length < 2
1094 + ? `${yield* repositoryPath(operation, input)}/collaborators?${new URLSearchParams({ limit: "50" })}`
1095 + : `/users?${new URLSearchParams({ q: query, limit: "50" })}`;
1096 + const people = yield* read(operation, input, { path }, Json.GitCafePeople);
1097 + return { items: Json.toPeople(people, input.host), truncated: people.next !== null };
1098 + },
1099 + ),
1100 setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {
1101 const base = yield* repositoryPath("setLabels", input);
1102 const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);
packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts
+23
@@ -267,6 +267,29 @@ export const GitCafeChecks = Schema.Struct({
267 next: Schema.NullOr(Schema.String),
268 });
269
270 +/** A user search answer and a collaborator page carry the same fields a picker shows. */
271 +export const GitCafePeople = Schema.Struct({
272 + items: Schema.Array(
273 + Schema.Struct({
274 + handle: TrimmedNonEmptyString,
275 + displayName: Schema.optional(Schema.NullOr(Schema.String)),
276 + avatarUrl: Schema.optional(Schema.NullOr(Schema.String)),
277 + }),
278 + ),
279 + next: Schema.NullOr(Schema.String),
280 +});
281 +
282 +export function toPeople(
283 + people: typeof GitCafePeople.Type,
284 + host: string,
285 +): ReadonlyArray<PullRequestActor> {
286 + return people.items.map((person) => ({
287 + login: person.handle,
288 + name: person.displayName ?? null,
289 + avatarUrl: person.avatarUrl == null ? null : new URL(person.avatarUrl, `https://${host}`).href,
290 + }));
291 +}
292 +
293 interface RepositoryOnHost {
294 readonly repository: string;
295 readonly host: string;
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+47
@@ -37,6 +37,7 @@ import {
37 type PullRequestReviewVerdict,
38 type PullRequestReviewerCandidateList,
39 type PullRequestReviewerKind,
40 + type PullRequestLabel,
41 type PullRequestLabelCandidateList,
42 type PullRequestThreadCommentsResult,
43 type PullRequestUpdateMethod,
@@ -68,6 +69,8 @@ import {
69 pullRequestLookup,
70 toActorAvatars,
71 toLabelCandidates,
72 + toRepositoryAuthors,
73 + toRepositoryLabels,
74 toPullRequestActivityPage,
75 toPullRequestCheckContextsPage,
76 toPullRequestCore,
@@ -645,6 +648,26 @@ export class GitHubPullRequestApi extends Context.Service<
648 readonly number: number;
649 }) => Effect.Effect<PullRequestLabelCandidateList, GitHubPullRequestApiError>;
650
651 + readonly listRepositoryLabels: (input: {
652 + readonly cwd: string;
653 + readonly repository: string;
654 + readonly host: string;
655 + readonly query?: string | undefined;
656 + }) => Effect.Effect<
657 + { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },
658 + GitHubPullRequestApiError
659 + >;
660 +
661 + readonly searchRepositoryAuthors: (input: {
662 + readonly cwd: string;
663 + readonly repository: string;
664 + readonly host: string;
665 + readonly query?: string | undefined;
666 + }) => Effect.Effect<
667 + { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },
668 + GitHubPullRequestApiError
669 + >;
670 +
671 readonly setLabels: (input: {
672 readonly cwd: string;
673 readonly repository: string;
@@ -2334,6 +2357,30 @@ export const make = Effect.gen(function* () {
2357 );
2358 },
2359
2360 + listRepositoryLabels: (input) => {
2361 + const { owner, name } = parseRepositorySelector(input.repository);
2362 + const operation = "listRepositoryLabels";
2363 + return client
2364 + .RepositoryLabels({ owner, name, query: input.query ?? null })
2365 + .pipe(
2366 + graphql({ ...input, operation, allowReserve: true }),
2367 + Effect.map(toRepositoryLabels),
2368 + Effect.flatMap(found({ ...input, operation })),
2369 + );
2370 + },
2371 +
2372 + searchRepositoryAuthors: (input) => {
2373 + const { owner, name } = parseRepositorySelector(input.repository);
2374 + const operation = "searchRepositoryAuthors";
2375 + return client
2376 + .RepositoryAuthors({ owner, name, query: input.query ?? null })
2377 + .pipe(
2378 + graphql({ ...input, operation, allowReserve: true }),
2379 + Effect.map(toRepositoryAuthors),
2380 + Effect.flatMap(found({ ...input, operation })),
2381 + );
2382 + },
2383 +
2384 setLabels: (input) => {
2385 const { owner, name } = parseRepositorySelector(input.repository);
2386 const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+6
@@ -547,6 +547,12 @@ export const make = Effect.gen(function* () {
547 listLabelCandidates: (input) =>
548 cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
549
550 + listRepositoryLabels: (input) =>
551 + cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),
552 +
553 + searchRepositoryAuthors: (input) =>
554 + cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
555 +
556 setLabels: (input) =>
557 cli
558 .setLabels({
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+32
@@ -60,6 +60,8 @@ import type {
60 PullRequestHeads,
61 PullRequestPreview as PullRequestPreviewQuery,
62 PullRequestSubject,
63 + RepositoryAuthors,
64 + RepositoryLabels,
65 ReviewerCandidates,
66 ViewerPermissions,
67 } from "./pullRequestReads.graphql.ts";
@@ -1658,6 +1660,36 @@ export function toLabelCandidates(
1660 };
1661 }
1662
1663 +export function toRepositoryLabels(
1664 + result: RepositoryLabels.Result,
1665 +): { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean } | null {
1666 + const repository = result.repository;
1667 + if (repository == null) return null;
1668 + return {
1669 + items: nodesOf(repository.labels).flatMap((node) => {
1670 + const name = trimmed(node.name);
1671 + return name === null ? [] : [{ name, color: trimmed(node.color) }];
1672 + }),
1673 + truncated: repository.labels?.pageInfo.hasNextPage === true,
1674 + };
1675 +}
1676 +
1677 +export function toRepositoryAuthors(
1678 + result: RepositoryAuthors.Result,
1679 +): { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean } | null {
1680 + const repository = result.repository;
1681 + if (repository == null) return null;
1682 + return {
1683 + items: nodesOf(repository.mentionableUsers).flatMap((node) => {
1684 + const login = trimmed(node.login);
1685 + return login === null
1686 + ? []
1687 + : [{ login, name: trimmed(node.name), avatarUrl: trimmed(node.avatarUrl) }];
1688 + }),
1689 + truncated: repository.mentionableUsers.pageInfo.hasNextPage,
1690 + };
1691 +}
1692 +
1693 export function buildLabelRequest(labels: ReadonlyArray<string>): {
1694 readonly labels: ReadonlyArray<string>;
1695 } {
packages/source-control-github/src/server/pullRequestReads.graphql
+31
@@ -455,6 +455,37 @@ query LabelCandidates($owner: String!, $name: String!, $number: Int!) {
455 }
456 }
457
458 +query RepositoryLabels($owner: String!, $name: String!, $query: String) {
459 + repository(owner: $owner, name: $name) {
460 + labels(first: 100, query: $query, orderBy: { field: NAME, direction: ASC }) {
461 + pageInfo {
462 + hasNextPage
463 + }
464 + nodes {
465 + name
466 + color
467 + }
468 + }
469 + }
470 +}
471 +
472 +# Mentionable rather than assignable users: a pull request from a fork is opened by someone with
473 +# no access to the repository, and a listing is still narrowed by them.
474 +query RepositoryAuthors($owner: String!, $name: String!, $query: String) {
475 + repository(owner: $owner, name: $name) {
476 + mentionableUsers(first: 50, query: $query) {
477 + pageInfo {
478 + hasNextPage
479 + }
480 + nodes {
481 + login
482 + name
483 + avatarUrl
484 + }
485 + }
486 + }
487 +}
488 +
489 # Which files of a pull request the signed-in account has cleared. GraphQL only, since the REST
490 # files endpoint the patch is read from carries no viewed state, so this is a second read rather
491 # than a wider version of the first.
packages/source-control-github/src/server/pullRequestReads.graphql.ts
+83 -4
@@ -1170,13 +1170,13 @@ export const RepositoryLabelsNodesLabel = Schema.Struct({
1170 export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type<typeof RepositoryLabelsNodesLabel.fields> {}
1171
1172 /** The connection type for Label. */
1173 -export const RepositoryLabelsLabelConnection = Schema.Struct({
1173 +export const LabelCandidatesRepositoryLabelsLabelConnection = Schema.Struct({
1174 /** Information to aid in pagination. */
1175 pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1176 /** A list of nodes. */
1177 nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel)))
1178 })
1179 -export interface RepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof RepositoryLabelsLabelConnection.fields> {}
1179 +export interface LabelCandidatesRepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof LabelCandidatesRepositoryLabelsLabelConnection.fields> {}
1180
1181 /** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */
1182 export const LabelCandidatesRepositoryPullRequestLabelsNodesLabel = Schema.Struct({
@@ -1202,7 +1202,7 @@ export interface LabelCandidatesRepositoryPullRequestPullRequest extends Schema.
1202 /** A repository contains the content for a project. */
1203 export const LabelCandidatesRepositoryRepository = Schema.Struct({
1204 /** A list of labels associated with the repository. */
1205 - labels: Schema.NullOr(RepositoryLabelsLabelConnection),
1205 + labels: Schema.NullOr(LabelCandidatesRepositoryLabelsLabelConnection),
1206 /** Returns a single pull request from the current repository by number. */
1207 pullRequest: Schema.NullOr(LabelCandidatesRepositoryPullRequestPullRequest)
1208 })
@@ -1236,6 +1236,85 @@ export declare namespace LabelCandidates {
1236 export type Result = typeof LabelCandidates.result.Type
1237 }
1238
1239 +/** The connection type for Label. */
1240 +export const RepositoryLabelsRepositoryLabelsLabelConnection = Schema.Struct({
1241 + /** Information to aid in pagination. */
1242 + pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1243 + /** A list of nodes. */
1244 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel)))
1245 +})
1246 +export interface RepositoryLabelsRepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof RepositoryLabelsRepositoryLabelsLabelConnection.fields> {}
1247 +
1248 +/** A repository contains the content for a project. */
1249 +export const RepositoryLabelsRepositoryRepository = Schema.Struct({
1250 + /** A list of labels associated with the repository. */
1251 + labels: Schema.NullOr(RepositoryLabelsRepositoryLabelsLabelConnection)
1252 +})
1253 +export interface RepositoryLabelsRepositoryRepository extends Schema.Struct.Type<typeof RepositoryLabelsRepositoryRepository.fields> {}
1254 +
1255 +/** `query RepositoryLabels` */
1256 +export const RepositoryLabels = GraphQL.query("RepositoryLabels", {
1257 + document: {
1258 + variables: [
1259 + { name: "owner", body: "String!" },
1260 + { name: "name", body: "String!" },
1261 + { name: "query", body: "String" }
1262 + ],
1263 + selections: [
1264 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){labels(first:100 query:$", "query", " orderBy:{field:NAME direction:ASC}){pageInfo{hasNextPage}nodes{name color}}}"] }
1265 + ],
1266 + fragments: []
1267 + },
1268 + variables: {
1269 + owner: Schema.String,
1270 + name: Schema.String,
1271 + query: Schema.optional(Schema.NullOr(Schema.String))
1272 + },
1273 + result: Schema.Struct({
1274 + /** Lookup a given repository by the owner and repository name. */
1275 + repository: Schema.NullOr(RepositoryLabelsRepositoryRepository)
1276 + })
1277 +})
1278 +export declare namespace RepositoryLabels {
1279 + export type Variables = typeof RepositoryLabels.variables.Type
1280 + export type Result = typeof RepositoryLabels.result.Type
1281 +}
1282 +
1283 +/** A repository contains the content for a project. */
1284 +export const RepositoryAuthorsRepositoryRepository = Schema.Struct({
1285 + /** A list of Users that can be mentioned in the context of the repository. */
1286 + mentionableUsers: UserConnection
1287 +})
1288 +export interface RepositoryAuthorsRepositoryRepository extends Schema.Struct.Type<typeof RepositoryAuthorsRepositoryRepository.fields> {}
1289 +
1290 +/** `query RepositoryAuthors` */
1291 +export const RepositoryAuthors = GraphQL.query("RepositoryAuthors", {
1292 + document: {
1293 + variables: [
1294 + { name: "owner", body: "String!" },
1295 + { name: "name", body: "String!" },
1296 + { name: "query", body: "String" }
1297 + ],
1298 + selections: [
1299 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mentionableUsers(first:50 query:$", "query", "){pageInfo{hasNextPage}nodes{login name avatarUrl}}}"] }
1300 + ],
1301 + fragments: []
1302 + },
1303 + variables: {
1304 + owner: Schema.String,
1305 + name: Schema.String,
1306 + query: Schema.optional(Schema.NullOr(Schema.String))
1307 + },
1308 + result: Schema.Struct({
1309 + /** Lookup a given repository by the owner and repository name. */
1310 + repository: Schema.NullOr(RepositoryAuthorsRepositoryRepository)
1311 + })
1312 +})
1313 +export declare namespace RepositoryAuthors {
1314 + export type Variables = typeof RepositoryAuthors.variables.Type
1315 + export type Result = typeof RepositoryAuthors.result.Type
1316 +}
1317 +
1318 /** A file changed in a pull request. */
1319 export const PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({
1320 /** The path of the file. */
@@ -1587,4 +1666,4 @@ export declare namespace PullRequestSourceBranch {
1666 }
1667
1668 /** Every operation in pullRequestReads.graphql. */
1590 -export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
1669 +export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+57
@@ -6,9 +6,11 @@ import * as Schema from "effect/Schema";
6 import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
7 import type {
8 PullRequestAction,
9 + PullRequestActor,
10 PullRequestComment,
11 PullRequestCommit,
12 PullRequestInvolvement,
13 + PullRequestLabel,
14 PullRequestListFilters,
15 PullRequestListState,
16 PullRequestMergeCapabilities,
@@ -37,6 +39,7 @@ import {
39 decodeNotesJson,
40 decodeOwnAwardIdJson,
41 decodeProjectMergeCapabilitiesJson,
42 + decodeProjectLabelsJson,
43 decodeProjectUsersJson,
44 decodeRepositoryBlobsJson,
45 decodeViewerJson,
@@ -287,6 +290,24 @@ export class GitLabPullRequestCli extends Context.Service<
290 readonly number: number;
291 }) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;
292
293 + readonly listProjectLabels: (input: {
294 + readonly cwd: string;
295 + readonly repository: string;
296 + readonly search?: string | undefined;
297 + }) => Effect.Effect<
298 + { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },
299 + GitLabPullRequestCliError
300 + >;
301 +
302 + readonly listProjectUsers: (input: {
303 + readonly cwd: string;
304 + readonly repository: string;
305 + readonly search?: string | undefined;
306 + }) => Effect.Effect<
307 + { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },
308 + GitLabPullRequestCliError
309 + >;
310 +
311 readonly setReviewerRequest: (input: {
312 readonly cwd: string;
313 readonly repository: string;
@@ -919,11 +940,13 @@ export const make = Effect.gen(function* () {
940 const projectUsers = (input: {
941 readonly cwd: string;
942 readonly repository: string;
943 + readonly search?: string | undefined;
944 }): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>
945 api({
946 cwd: input.cwd,
947 path: `projects/${projectPath(input.repository)}/users?${query([
948 ["per_page", String(MAX_PAGE_SIZE)],
949 + ...searchParams(input.search),
950 ])}`,
951 }).pipe(
952 Effect.flatMap((result) => {
@@ -1277,6 +1300,40 @@ export const make = Effect.gen(function* () {
1300 }),
1301 ),
1302
1303 + listProjectLabels: (input) =>
1304 + api({
1305 + cwd: input.cwd,
1306 + path: `projects/${projectPath(input.repository)}/labels?${query([
1307 + ["per_page", String(MAX_PAGE_SIZE)],
1308 + ...searchParams(input.search),
1309 + ])}`,
1310 + }).pipe(
1311 + Effect.flatMap((result) => {
1312 + const decoded = decodeProjectLabelsJson(result.stdout.trim());
1313 + return Result.isSuccess(decoded)
1314 + ? Effect.succeed({
1315 + items: decoded.success.labels,
1316 + truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
1317 + })
1318 + : Effect.fail(
1319 + new GitLabMergeRequestReadError({
1320 + command: "glab",
1321 + cwd: input.cwd,
1322 + operation: "listProjectLabels",
1323 + cause: decoded.failure,
1324 + }),
1325 + );
1326 + }),
1327 + ),
1328 +
1329 + listProjectUsers: (input) =>
1330 + projectUsers(input).pipe(
1331 + Effect.map(({ candidates, rawCount }) => ({
1332 + items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
1333 + truncated: rawCount >= MAX_PAGE_SIZE,
1334 + })),
1335 + ),
1336 +
1337 listReviewerCandidates: (input) =>
1338 Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(
1339 Effect.map(([mergeRequest, users]) => {
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+10
@@ -232,6 +232,16 @@ export const make = Effect.gen(function* () {
232 })
233 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
234
235 + listRepositoryLabels: (input) =>
236 + cli
237 + .listProjectLabels({ cwd: input.cwd, repository: input.repository, search: input.query })
238 + .pipe(Effect.mapError(fail("listRepositoryLabels"))),
239 +
240 + searchRepositoryAuthors: (input) =>
241 + cli
242 + .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })
243 + .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
244 +
245 setReviewerRequest: (input) =>
246 cli
247 .setReviewerRequest({
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+28
@@ -441,6 +441,34 @@ export function decodeProjectUsersJson(
441 return Result.succeed({ candidates, rawCount: decoded.success.length });
442 }
443
444 +const RawLabelSchema = Schema.Struct({
445 + name: Schema.String,
446 + color: Schema.optional(Schema.NullOr(Schema.String)),
447 +});
448 +const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
449 +
450 +export interface GitLabProjectLabels {
451 + readonly labels: ReadonlyArray<PullRequestLabel>;
452 + readonly rawCount: number;
453 +}
454 +
455 +export function decodeProjectLabelsJson(
456 + raw: string,
457 +): Result.Result<GitLabProjectLabels, DecodeFailure> {
458 + const decoded = decodeUnknownList(raw);
459 + if (!Result.isSuccess(decoded)) {
460 + return Result.fail(decoded.failure);
461 + }
462 + const labels: PullRequestLabel[] = [];
463 + for (const entry of decoded.success) {
464 + const label = decodeLabelEntry(entry);
465 + if (Exit.isFailure(label)) continue;
466 + const name = trimmed(label.value.name);
467 + if (name !== null) labels.push({ name, color: trimmed(label.value.color) });
468 + }
469 + return Result.succeed({ labels, rawCount: decoded.success.length });
470 +}
471 +
472 export function decodeProjectMergeCapabilitiesJson(
473 raw: string,
474 ): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {