TypeScript
feat(pull-requests): label and author filters search the host (#23924)
Julius Marminge22dc1dabc6d3
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 4a99aca12cf..8c7e4709d71 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -34,6 +34,7 @@ import {import { PullRequestFilesSheet } from "./features/pull-requests/PullRequestFiles";import { PullRequestReviewSheet } from "./features/pull-requests/PullRequestReviewSheet";import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequestReviewersScreen";+import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen";import {RenderErrorBoundary,RenderFailureView,@@ -689,6 +690,21 @@ const RootStackConfig = createWorkspaceStackNavigator({headerBackVisible: false,},}),+ PullRequestFilterSearch: createNativeStackScreen({+ screen: PullRequestFilterSearchScreen,+ // Android pushes it like the branch picker; a formSheet there leaves the list's header+ // peeking above it once the keyboard opens.+ options:+ Platform.OS === "android"+ ? { presentation: "card", headerShown: false }+ : {+ ...DETAIL_HEADER_OPTIONS,+ ...HORIZONTAL_FORM_SHEET_OPTIONS,+ sheetAllowedDetents: formSheetDetents(0.75),+ sheetGrabberVisible: true,+ headerBackVisible: false,+ },+ }),PullRequestDiscussion: createNativeStackScreen({screen: PullRequestDiscussionScreen,options: DETAIL_HEADER_OPTIONS,diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsxindex 16a0f55d0a7..e2685dd5db2 100644--- a/apps/mobile/src/components/ui/AppSymbol.tsx+++ b/apps/mobile/src/components/ui/AppSymbol.tsx@@ -39,6 +39,7 @@ import IconChevronLeft from "@tabler/icons-react-native/IconChevronLeft";import IconChevronRight from "@tabler/icons-react-native/IconChevronRight";import IconChevronUp from "@tabler/icons-react-native/IconChevronUp";import IconCircle from "@tabler/icons-react-native/IconCircle";+import IconCircleFilled from "@tabler/icons-react-native/IconCircleFilled";import IconCircleCheck from "@tabler/icons-react-native/IconCircleCheck";import IconCircleDashed from "@tabler/icons-react-native/IconCircleDashed";import IconCircleDot from "@tabler/icons-react-native/IconCircleDot";@@ -176,6 +177,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {"checkmark.circle": IconCircleCheck,"checkmark.circle.fill": IconCircleCheck,circle: IconCircle,+ "circle.fill": IconCircleFilled,"circle.dashed": IconCircleDashed,"circle.inset.filled": IconCircleDot,"circle.dashed.inset.filled": IconCircleDot,diff --git a/apps/mobile/src/components/ui/MenuPopup.android.tsx b/apps/mobile/src/components/ui/MenuPopup.android.tsxindex 66a398bc21a..d761f3fd520 100644--- a/apps/mobile/src/components/ui/MenuPopup.android.tsx+++ b/apps/mobile/src/components/ui/MenuPopup.android.tsx@@ -8,6 +8,7 @@ import {Text,} from "@expo/ui/jetpack-compose";import { defaultMinSize, padding, size, width } from "@expo/ui/jetpack-compose/modifiers";+import type { MenuAction } from "@react-native-menu/menu";import { Pressable } from "react-native";import { resolveScaledTextRole } from "../../lib/appearancePreferences";@@ -21,6 +22,7 @@ import { isAppSymbolName, SymbolView, type AppSymbolName } from "./AppSymbol";// row's action itself; the row stays the accessible element.function MenuIcon(props: {readonly name: AppSymbolName;+ readonly color?: MenuAction["imageColor"];readonly onPress: () => void;readonly destructive?: boolean;readonly disabled?: boolean;@@ -40,13 +42,15 @@ function MenuIcon(props: {name={props.name}size={iconSize}type="monochrome"- tintColorClassName={- props.disabled- ? "accent-icon-subtle"- : props.destructive- ? "accent-danger-foreground"- : "accent-foreground"- }+ {...(typeof props.color === "string" && !props.disabled+ ? { tintColor: props.color }+ : {+ tintColorClassName: props.disabled+ ? "accent-icon-subtle"+ : props.destructive+ ? "accent-danger-foreground"+ : "accent-foreground",+ })}/></Pressable></RNHostView>@@ -96,6 +100,7 @@ export function MenuPopup(props: MenuPopupProps) {<DropdownMenuItem.LeadingIcon><MenuIconname={action.image}+ color={action.imageColor}onPress={() => props.onPress(action)}destructive={action.attributes?.destructive}disabled={action.attributes?.disabled}diff --git a/apps/mobile/src/components/ui/SelectionRow.tsx b/apps/mobile/src/components/ui/SelectionRow.tsxnew file mode 100644index 00000000000..db47aaeca11--- /dev/null+++ b/apps/mobile/src/components/ui/SelectionRow.tsx@@ -0,0 +1,104 @@+import type { ReactNode } from "react";+import { Platform, Pressable, View } from "react-native";++import { cn } from "../../lib/cn";+import { SymbolView, type AppSymbolName } from "./AppSymbol";+import { AppText as Text } from "./AppText";+import { NavigationRow } from "./NavigationRow";++/** A picker row in a grouped list; the first and last rows round the group's corners. */+export function SelectionRow(props: {+ readonly icon?: AppSymbolName;+ /** Drawn where the icon goes, for marks a symbol can't express (a label's color dot). */+ readonly leading?: ReactNode;+ readonly onPress: () => void;+ readonly disabled?: boolean;+ readonly selected: boolean;+ /** "checkbox" when several rows can be selected at once. */+ readonly role?: "radio" | "checkbox";+ readonly isFirst?: boolean;+ readonly isLast?: boolean;+ readonly subtitle?: string;+ readonly title: string;+}) {+ const role = props.role ?? "radio";+ const row =+ Platform.OS === "android" ? (+ <NavigationRow+ className="bg-grouped-card"+ title={props.title}+ subtitle={props.subtitle}+ leading={+ props.icon ? (+ <SymbolView name={props.icon} size={24} tintColorClassName="accent-icon-muted" />+ ) : (+ props.leading+ )+ }+ trailing={+ props.selected ? (+ <SymbolView name="checkmark" size={20} tintColorClassName="accent-focus" />+ ) : null+ }+ accessibilityRole={role}+ accessibilityState={{ checked: props.selected }}+ disabled={props.disabled}+ onPress={props.onPress}+ />+ ) : (+ <Pressable+ accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}+ accessibilityRole={role}+ accessibilityState={{ checked: props.selected }}+ className={cn(+ "min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3 active:bg-subtle",+ !props.isLast && "border-b border-border-subtle",+ )}+ disabled={props.disabled}+ onPress={props.onPress}+ style={{ opacity: props.disabled ? 0.45 : 1 }}+ >+ {props.icon ? (+ <SymbolView+ name={props.icon}+ size={17}+ tintColorClassName="accent-icon-muted"+ type="monochrome"+ />+ ) : (+ (props.leading ?? null)+ )}+ <View className="min-w-0 flex-1 gap-0.5">+ <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>+ {props.title}+ </Text>+ {props.subtitle ? (+ <Text className="text-xs text-foreground-muted" numberOfLines={1}>+ {props.subtitle}+ </Text>+ ) : null}+ </View>+ {props.selected ? (+ <SymbolView+ name="checkmark"+ size={16}+ tintColorClassName="accent-icon"+ type="monochrome"+ weight="semibold"+ />+ ) : null}+ </Pressable>+ );+ if (!props.isFirst && !props.isLast) return row;+ return (+ <View+ className={cn(+ "overflow-hidden",+ props.isFirst && (Platform.OS === "android" ? "rounded-t-[28px]" : "rounded-t-2xl"),+ props.isLast && (Platform.OS === "android" ? "rounded-b-[28px]" : "rounded-b-2xl"),+ )}+ >+ {row}+ </View>+ );+}diff --git a/apps/mobile/src/features/pull-requests/PullRequestFilterSearchScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestFilterSearchScreen.tsxnew file mode 100644index 00000000000..09bd4e2628b--- /dev/null+++ b/apps/mobile/src/features/pull-requests/PullRequestFilterSearchScreen.tsx@@ -0,0 +1,244 @@+import { useAtomValue } from "@effect/atom-react";+import { useNavigation, type StaticScreenProps } from "@react-navigation/native";+import {+ EnvironmentId,+ ProjectId,+ type PullRequestFilterOptionKind,+ type PullRequestFilterOptionsInput,+} from "@t3tools/contracts";+import * as Option from "effect/Option";+import { AsyncResult, Atom } from "effect/reactivity";+import { useRef, useState } from "react";+import { FlatList, Platform, View, type TextInputInstance } from "react-native";++import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";+import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";+import { EmptyState } from "../../components/ui/EmptyState";+import { SearchField } from "../../components/ui/SearchField";+import { SelectionRow } from "../../components/ui/SelectionRow";+import { SheetHeader } from "../../components/ui/SheetHeader";+import { Toolbar } from "../../components/ui/Toolbar";+import { NativeStackScreenOptions } from "../../native/StackHeader";+import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";+import { composerPullRequests } from "../../state/pull-requests";+import { useDebouncedValue } from "../../state/queries";+import {+ createNativeMailSearchToolbarItem,+ NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,+} from "../layout/native-mail-search-toolbar";+import { pullRequestFilterChoices, pullRequestLabelColors } from "./pullRequestList";+import { usePullRequestListControls } from "./usePullRequestListControls";++export type PullRequestFilterSearchParams = {+ readonly kind: PullRequestFilterOptionKind;+ /** The list controls' own key: the environment the list is narrowed to, or every one. */+ readonly environmentId: string | null;+ /** The environments the list reads, which the host search covers as well. */+ readonly environmentIds: readonly string[];+ /** What the loaded rows already carry, offered before the host has answered. */+ readonly suggestions: readonly string[];+ /** Dot colors by lowercased label name, from the loaded rows. */+ readonly labelColors?: Readonly<Record<string, string>>;+};++const optionsFamily = Atom.family((key: string) => {+ const targets: readonly {+ readonly environmentId: EnvironmentId;+ readonly input: PullRequestFilterOptionsInput;+ }[] = JSON.parse(key);+ return Atom.make((get) => {+ const results = targets.map((target) => get(composerPullRequests.filterOptions(target)));+ return {+ values: results.flatMap((result) => Option.toArray(AsyncResult.value(result))),+ waiting: results.some((result) => result.waiting),+ failed: results.some(AsyncResult.isFailure),+ };+ });+});++export function PullRequestFilterSearchScreen({+ route,+}: StaticScreenProps<PullRequestFilterSearchParams>) {+ const navigation = useNavigation();+ const { kind, environmentId, environmentIds, suggestions, labelColors } = route.params;+ const listControls = usePullRequestListControls();+ const controls = listControls.controlsFor(environmentId);+ const integratedSearch = useNativeMailSearchToolbar();+ const searchRef = useRef<TextInputInstance>(null);+ const [query, setQuery] = useState("");+ const typed = query.trim().slice(0, 100);+ const sent = useDebouncedValue(typed, 250);+ // Until the search catches up with the typing, the host's answers are for older text.+ const settled = sent === typed;+ const key = JSON.stringify(+ environmentIds.map((id) => ({+ environmentId: EnvironmentId.make(id),+ input: {+ kind,+ ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),+ ...(sent ? { query: sent } : {}),+ },+ })),+ );+ const hosted = useAtomValue(optionsFamily(key));+ const selectedLabels = controls.filters.labels?.flat() ?? [];+ const author = controls.filters.author;+ const selected = kind === "labels" ? selectedLabels : author ? [author] : [];+ const rows = pullRequestFilterChoices({+ selected,+ suggestions,+ hosted: (settled ? hosted.values : []).flatMap((options) =>+ kind === "labels"+ ? options.labels.map((label) => label.name)+ : options.authors.map((candidate) => candidate.login),+ ),+ query,+ });+ const colors = {+ ...pullRequestLabelColors(hosted.values.flatMap((options) => options.labels)),+ ...labelColors,+ };+ const isSelected = (value: string) =>+ selected.some((held) => held.toLowerCase() === value.toLowerCase());+ const choose = (value: string) => {+ if (kind === "authors") {+ listControls.setControls(environmentId, {+ ...controls,+ filters: { ...controls.filters, author: isSelected(value) ? undefined : value },+ });+ navigation.goBack();+ return;+ }+ const labels = isSelected(value)+ ? selectedLabels.filter((label) => label.toLowerCase() !== value.toLowerCase())+ : [...selectedLabels, value].slice(0, 10);+ listControls.setControls(environmentId, {+ ...controls,+ filters: {+ ...controls.filters,+ labels: labels.length ? labels.map((label) => [label]) : undefined,+ },+ });+ };+ const placeholder = kind === "labels" ? "Search labels" : "Search authors";+ const list = (+ <FlatList+ data={rows}+ keyExtractor={(value) => value.toLowerCase()}+ className="flex-1"+ contentInsetAdjustmentBehavior="automatic"+ automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}+ keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}+ keyboardShouldPersistTaps="handled"+ showsVerticalScrollIndicator={false}+ contentContainerStyle={{+ paddingHorizontal: 16,+ paddingTop: 16,+ paddingBottom: integratedSearch ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16 : 16,+ }}+ renderItem={({ item, index }) => (+ <SelectionRow+ title={item}+ role={kind === "labels" ? "checkbox" : "radio"}+ selected={isSelected(item)}+ isFirst={index === 0}+ isLast={index === rows.length - 1}+ leading={+ kind === "labels" ? (+ // Uncolored labels keep the dot's room so every name starts at the same edge.+ <View+ className="size-2.5 rounded-full"+ style={{ backgroundColor: colors[item.toLowerCase()] ?? "transparent" }}+ />+ ) : undefined+ }+ onPress={() => choose(item)}+ />+ )}+ ListEmptyComponent={+ hosted.waiting || !settled ? (+ <AppActivityIndicator className="my-8" />+ ) : (+ <EmptyState+ title={+ hosted.failed+ ? "Couldn't search the host"+ : kind === "labels"+ ? "No matching labels"+ : "No matching authors"+ }+ detail={+ hosted.failed+ ? "The host didn't answer. Try again in a moment."+ : kind === "labels"+ ? "Search the labels of the repositories this list covers."+ : "Search people by name or handle on the repositories' hosts."+ }+ variant="plain"+ />+ )+ }+ />+ );+ const title = kind === "labels" ? "Filter by label" : "Filter by author";+ if (Platform.OS === "android") {+ return (+ <View className="flex-1 bg-sheet" collapsable={false}>+ <AndroidScreenHeader title={title} hideBottomBorder onBack={() => navigation.goBack()} />+ <View className="bg-header px-4 pb-3 pt-1">+ <SearchField+ inputRef={searchRef}+ accessibilityLabel={placeholder}+ clearAccessibilityLabel={+ kind === "labels" ? "Clear label search" : "Clear author search"+ }+ onChangeText={setQuery}+ placeholder={placeholder}+ value={query}+ />+ </View>+ {list}+ </View>+ );+ }+ return (+ <View className="flex-1 bg-sheet">+ <SheetHeader+ title={title}+ onClose={() => navigation.goBack()}+ accessibilityLabel={kind === "labels" ? "Close label filter" : "Close author filter"}+ />+ <NativeStackScreenOptions+ options={{+ unstable_headerToolbarItems: integratedSearch+ ? () => [+ createNativeMailSearchToolbarItem({+ placeholder,+ onSearchTextChange: setQuery,+ showsSearchDismissButton: true,+ searchTextChangeId: "pr-filter-option-search",+ }),+ ]+ : undefined,+ headerSearchBarOptions: integratedSearch+ ? undefined+ : {+ placeholder,+ allowToolbarIntegration: true,+ autoCapitalize: "none",+ hideNavigationBar: false,+ obscureBackground: false,+ onChangeText: (event) => setQuery(event.nativeEvent.text),+ onCancelButtonPress: () => setQuery(""),+ },+ }}+ />+ {integratedSearch ? null : (+ <Toolbar placement="bottom">+ <Toolbar.SearchBarSlot />+ </Toolbar>+ )}+ {list}+ </View>+ );+}diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsxindex 2a9e71bc2f2..518d509332c 100644--- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx@@ -73,7 +73,11 @@ export function PullRequestListFilters(props: {readonly onChange: (value: PullRequestListControls) => void;readonly authors: readonly string[];readonly labels: readonly string[];+ /** Dot colors by lowercased label name, for the labels that have one. */+ readonly labelColors: Readonly<Record<string, string>>;readonly projects: readonly { id: string; title: string; environmentId: string }[];+ /** Opens a picker that searches the host, for a label or author no loaded row carries. */+ readonly onSearch: (kind: "labels" | "authors") => void;}) {const { value } = props;const projects = useProjectsInSidebarOrder(props.projects);@@ -145,6 +149,9 @@ export function PullRequestListFilters(props: {case "author":props.onChange({ ...value, filters: { ...value.filters, author: next || undefined } });break;+ case "search":+ if (next === "labels" || next === "authors") props.onSearch(next);+ break;case "draft":props.onChange({...value,@@ -248,22 +255,30 @@ export function PullRequestListFilters(props: {const stateActions = choices("state", STATES, value.state);const involvementActions = choices("involvement", INVOLVEMENT, value.involvement);const labelActions: MenuProps["actions"] = [+ { id: id("search", "labels"), title: "Search labels…", image: "magnifyingglass" },{ id: id("labels", ""), title: "All labels", state: selectedLabels.length ? "off" : "on" },- ...labels.map((label) => ({- id: id("label", label),- title: label,- state: selectedLabelSet.has(label) ? ("on" as const) : ("off" as const),- })),+ ...labels.map((label) => {+ const color = props.labelColors[label.toLowerCase()];+ return {+ id: id("label", label),+ title: label,+ state: selectedLabelSet.has(label) ? ("on" as const) : ("off" as const),+ ...(color ? { image: "circle.fill", imageColor: color } : {}),+ };+ }),+ ];+ const authorActions: MenuProps["actions"] = [+ { id: id("search", "authors"), title: "Search authors…", image: "magnifyingglass" },+ ...choices(+ "author",+ Object.fromEntries([+ ["", "All authors"],+ ["me", "Me"],+ ...authors.map((login) => [login, login]),+ ]),+ author ?? "",+ ),];- const authorActions = choices(- "author",- Object.fromEntries([- ["", "All authors"],- ["me", "Me"],- ...authors.map((login) => [login, login]),- ]),- author ?? "",- );const customized = count > 0 || value.sort !== "updated" || props.environmentId !== null;// The Android header's filter button opens every filter.const headerMenu =diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsxindex 0eb0e545b2b..cc096c05f10 100644--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx@@ -200,8 +200,14 @@ export function PullRequestsScreen(...facets.labels,]),].sort(),+ labelColors: {+ ...facets.labelColors,+ ...(previous.environmentId === environmentId ? previous.labelColors : {}),+ },}));}+ const labelColors =+ knownFacets.environmentId === environmentId ? knownFacets.labelColors : facets.labelColors;const projects = allProjects.filter((project) =>!project.isScratch && (environmentId === null || project.environmentId === environmentId),@@ -318,7 +324,18 @@ export function PullRequestsScreen(labels={knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels}+ labelColors={labelColors}projects={projects}+ onSearch={(kind) =>+ navigation.navigate("PullRequestFilterSearch", {+ kind,+ environmentId,+ environmentIds: targets.map((target) => String(target.environmentId)),+ suggestions:+ knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],+ labelColors,+ })+ }/>{result.data?.errors.length ? (<PullRequestListErrorsdiff --git a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts b/apps/mobile/src/features/pull-requests/pullRequestList.test.tsindex 06733a9cf36..59a0f723f77 100644--- a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestList.test.ts@@ -13,6 +13,8 @@ import {mergeEnvironmentPullRequestPages,nextPullRequestListInput,PR_LIST_PAGE_SIZE,+ pullRequestFilterChoices,+ pullRequestLabelColors,pullRequestListHead,pullRequestListInput,scopedPullRequestListKey,@@ -346,3 +348,42 @@ describe("withoutScratchProjectScope", () => {expect(withoutScratchProjectScope(elsewhere, projects)).toBe(elsewhere);});});++describe("pullRequestLabelColors", () => {+ it("keeps the first usable color each label name carries", () => {+ expect(+ pullRequestLabelColors([+ { name: "Bug", color: null },+ { name: "bug", color: "d73a4a" },+ { name: "BUG", color: "#000000" },+ { name: "docs", color: "not-a-color" },+ { name: "size:S", color: "#69C35F" },+ ]),+ ).toEqual({ bug: "#d73a4a", "size:s": "#69C35F" });+ });+});++describe("pullRequestFilterChoices", () => {+ it("keeps the picked value in view and adds host answers no loaded row carries, once", () => {+ expect(+ pullRequestFilterChoices({+ selected: ["size:XL"],+ suggestions: ["bug", "size:XL", "docs"],+ hosted: ["Bug", "backend"],+ query: "b",+ }),+ ).toEqual(["size:XL", "bug", "backend"]);+ });++ it("leaves room for the host's answers when loaded matches alone would fill the list", () => {+ const loaded = Array.from({ length: 120 }, (_, index) => `label-${index}`);+ const rows = pullRequestFilterChoices({+ selected: [],+ suggestions: loaded,+ hosted: ["label-from-host"],+ query: "label",+ });+ expect(rows).toHaveLength(100);+ expect(rows[50]).toBe("label-from-host");+ });+});diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.tsindex 976d62e1068..8040c12d6d8 100644--- a/apps/mobile/src/features/pull-requests/pullRequestList.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts@@ -184,6 +184,37 @@ export function appendPullRequestListPage(};}+/**+ * A filter picker's rows: what is picked stays in view, then the loaded rows' values that match,+ * then the host's answers, each once. The host matched its own way (an author's display name, say),+ * so its answers are not narrowed again here.+ */+const FILTER_CHOICE_LIMIT = 100;++export function pullRequestFilterChoices(input: {+ readonly selected: readonly string[];+ readonly suggestions: readonly string[];+ readonly hosted: readonly string[];+ readonly query: string;+}): readonly string[] {+ const needle = input.query.trim().toLowerCase();+ const seen = new Set<string>();+ const rows: string[] = [];+ const add = (value: string) => {+ const key = value.toLowerCase();+ if (seen.has(key)) return;+ seen.add(key);+ rows.push(value);+ };+ const loaded = input.suggestions.filter((value) => value.toLowerCase().includes(needle));+ for (const value of input.selected) add(value);+ // Loaded matches alone could fill the list, so the host's answers get room after the first half.+ for (const value of loaded.slice(0, FILTER_CHOICE_LIMIT / 2)) add(value);+ for (const value of input.hosted) add(value);+ for (const value of loaded.slice(FILTER_CHOICE_LIMIT / 2)) add(value);+ return rows.slice(0, FILTER_CHOICE_LIMIT);+}+export function pullRequestListFacets(entries: readonly PullRequestListEntry[]) {return {authors: [@@ -192,9 +223,23 @@ export function pullRequestListFacets(entries: readonly PullRequestListEntry[])labels: [...new Set(entries.flatMap((entry) => entry.labels.map((label) => label.name)))].sort((a, b) => a.localeCompare(b),),+ labelColors: pullRequestLabelColors(entries.flatMap((entry) => entry.labels)),};}+/** Each label's dot color by lowercased name; the first usable color a name carries wins. */+export function pullRequestLabelColors(+ labels: readonly { readonly name: string; readonly color: string | null }[],+): Readonly<Record<string, string>> {+ const colors: Record<string, string> = {};+ for (const label of labels) {+ const key = label.name.toLowerCase();+ const color = pullRequestLabelColor(label.color);+ if (color && !(key in colors)) colors[key] = color;+ }+ return colors;+}+export function filterPullRequestList<Entry extends PullRequestListEntry & { environmentId?: string },>(diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsxindex af4e46ef135..4aa9bd7a7af 100644--- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx@@ -3,7 +3,7 @@ import { Button } from "../../components/ui/Button";import { Toolbar } from "../../components/ui/Toolbar";import * as Dialog from "../../components/ui/Dialog";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";-import { NavigationRow } from "../../components/ui/NavigationRow";+import { SelectionRow } from "../../components/ui/SelectionRow";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";import type { VcsRef } from "@t3tools/client-runtime/state/vcs";@@ -136,90 +136,6 @@ function EnvironmentPickerRow(props: {);}-function SelectionRow(props: {- readonly icon?: "arrow.triangle.branch" | ReactNode;- readonly onPress: () => void;- readonly disabled?: boolean;- readonly selected: boolean;- readonly isLast?: boolean;- readonly subtitle?: string;- readonly title: string;-}) {- if (Platform.OS === "android") {- return (- <NavigationRow- className="bg-grouped-card"- title={props.title}- subtitle={props.subtitle}- leading={- props.icon === "arrow.triangle.branch" ? (- <SymbolView- name="arrow.triangle.branch"- size={24}- tintColorClassName="accent-icon-muted"- />- ) : (- props.icon- )- }- trailing={- props.selected ? (- <SymbolView name="checkmark" size={20} tintColorClassName="accent-focus" />- ) : null- }- accessibilityRole="radio"- accessibilityState={{ checked: props.selected }}- disabled={props.disabled}- onPress={props.onPress}- />- );- }- return (- <Pressable- accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}- accessibilityRole="radio"- accessibilityState={{ checked: props.selected }}- className={cn(- "min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3 active:bg-subtle",- !props.isLast && "border-b border-border-subtle",- )}- disabled={props.disabled}- onPress={props.onPress}- style={{ opacity: props.disabled ? 0.45 : 1 }}- >- {props.icon === "arrow.triangle.branch" ? (- <SymbolView- name="arrow.triangle.branch"- size={17}- tintColorClassName="accent-icon-muted"- type="monochrome"- />- ) : (- (props.icon ?? null)- )}- <View className="min-w-0 flex-1 gap-0.5">- <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>- {props.title}- </Text>- {props.subtitle ? (- <Text className="text-xs text-foreground-muted" numberOfLines={1}>- {props.subtitle}- </Text>- ) : null}- </View>- {props.selected ? (- <SymbolView- name="checkmark"- size={16}- tintColorClassName="accent-icon"- type="monochrome"- weight="semibold"- />- ) : null}- </Pressable>- );-}-function ToggleRow(props: {readonly title: string;readonly value: boolean;@@ -245,43 +161,6 @@ function ToggleRow(props: {);}-function BranchSelectionRow(props: {- readonly badge: string | null;- readonly branch: VcsRef;- readonly disabled: boolean;- readonly isFirst: boolean;- readonly isLast: boolean;- readonly onSelect: (branch: VcsRef) => void;- readonly selected: boolean;-}) {- const onPress = () => props.onSelect(props.branch);-- return (- <View- className={cn(- props.isFirst &&- (Platform.OS === "android"- ? "overflow-hidden rounded-t-[28px]"- : "overflow-hidden rounded-t-2xl"),- props.isLast &&- (Platform.OS === "android"- ? "overflow-hidden rounded-b-[28px]"- : "overflow-hidden rounded-b-2xl"),- )}- >- <SelectionRow- icon="arrow.triangle.branch"- disabled={props.disabled}- isLast={props.isLast}- onPress={onPress}- selected={props.selected}- subtitle={props.badge ? props.badge.toUpperCase() : undefined}- title={props.branch.name}- />- </View>- );-}-function PickerSurface(props: { readonly children: ReactNode }) {return (<View@@ -508,14 +387,15 @@ export function BranchPickerScreen(props: {};const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (- <BranchSelectionRow- badge={branchBadgeLabel({ branch: item, project: props.project })}- branch={item}+ <SelectionRow+ icon="arrow.triangle.branch"disabled={props.selectionDisabled ?? false}isFirst={index === 0}isLast={index === props.branches.length - 1}- onSelect={props.onSelect}+ onPress={() => props.onSelect(item)}selected={selectedBranchName === item.name}+ subtitle={branchBadgeLabel({ branch: item, project: props.project })?.toUpperCase()}+ title={item.name}/>);diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 18919cea55e..3f007b19059 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -120,6 +120,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,[WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,+ [WS_METHODS.pullRequestsFilterOptions]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsRouting]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsRoutingIdentity]: AuthOrchestrationReadScope,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 3f3942e75d0..0c018691e10 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -99,6 +99,7 @@ const RPC_AGGREGATES = {[WS_METHODS.cloudInstallRelayClient]: "cloud",[WS_METHODS.pullRequestsList]: "pull-requests",[WS_METHODS.pullRequestsListStats]: "pull-requests",+ [WS_METHODS.pullRequestsFilterOptions]: "pull-requests",[WS_METHODS.pullRequestsSummary]: "pull-requests",[WS_METHODS.pullRequestsRouting]: "pull-requests",[WS_METHODS.pullRequestsRoutingIdentity]: "pull-requests",diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 95571b4e5e9..1d2b879e11a 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -833,6 +833,103 @@ it.effect("keeps healthy repositories when one of them cannot be read", () =>}),);+it.effect("offers each label once across repositories, despite one that cannot be read", () =>+ Effect.gen(function* () {+ const reads: Array<string> = [];+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),+ project({+ id: "p5",+ title: "t3code worktree",+ workspaceRoot: "/e",+ repository: "pingdotgg/t3code",+ }),+ project({+ id: "p2",+ title: "uploadthing",+ workspaceRoot: "/b",+ repository: "pingdotgg/ut",+ }),+ project({ id: "p3", title: "broken", workspaceRoot: "/c", repository: "pingdotgg/broken" }),+ project({+ id: "p4",+ title: "elsewhere",+ workspaceRoot: "/d",+ repository: "group/app",+ provider: "gitlab",+ }),+ ],+ providers: [+ fakeProvider(SourceControlProviderKind.make("github"), {+ listRepositoryLabels: (input) => {+ reads.push(input.repository);+ return input.repository === "pingdotgg/broken"+ ? Effect.fail(requestFailed)+ : Effect.succeed({+ items:+ input.repository === "pingdotgg/t3code"+ ? [+ { name: "size:XL", color: "d93f0b" },+ { name: "bug", color: "d73a4a" },+ ]+ : [{ name: "Bug", color: "ee0701" }],+ truncated: false,+ });+ },+ }),+ // A host with no repository labels is left out rather than failing the answer.+ fakeProvider(SourceControlProviderKind.make("gitlab")),+ ],+ });++ const result = yield* service.filterOptions({ kind: "labels" });++ assert.deepStrictEqual(+ result.labels.map((label) => label.name),+ ["bug", "size:XL"],+ );+ assert.strictEqual(reads.filter((repository) => repository === "pingdotgg/t3code").length, 1);+ assert.strictEqual(result.truncated, false);+ }),+);++it.effect("puts the author a query names exactly ahead of those it only begins", () =>+ Effect.gen(function* () {+ const queries: Array<string | undefined> = [];+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),+ ],+ providers: [+ fakeProvider(SourceControlProviderKind.make("github"), {+ searchRepositoryAuthors: (input) => {+ queries.push(input.query);+ return Effect.succeed({+ items: [+ { login: "theo-browne", name: null, avatarUrl: null },+ { login: "octocat", name: "Theo", avatarUrl: null },+ { login: "julius", name: "Julius", avatarUrl: null },+ { login: "t3dotgg", name: "theo", avatarUrl: null },+ ],+ truncated: true,+ });+ },+ }),+ ],+ });++ const result = yield* service.filterOptions({ kind: "authors", query: "theo" });++ assert.deepStrictEqual(queries, ["theo"]);+ assert.deepStrictEqual(+ result.authors.map((author) => author.login),+ ["octocat", "t3dotgg", "theo-browne"],+ );+ assert.strictEqual(result.truncated, true);+ }),+);+it.effect("tries another workspace on the same host for the viewer", () =>Effect.gen(function* () {const service = yield* makeService({diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 8fad44c2905..c57375c3dd3 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -51,6 +51,10 @@ import {type PullRequestListProjectError,type PullRequestListResult,type PullRequestListStatsInput,+ type PullRequestFilterOptions,+ type PullRequestFilterOptionsInput,+ type PullRequestActor,+ type PullRequestLabel,type PullRequestListStatsResult,type PullRequestProviderSummary,type PullRequestReactionInput,@@ -88,6 +92,7 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPrimport * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";import {type ProviderChangeRequest,+ type ProviderFilterOptionPage,type ProviderListCursor,type ProviderChangeRequestWatchFingerprint,type PullRequestProviderApi,@@ -175,6 +180,9 @@ export class PullRequestService extends Context.Service<readonly listStats: (input: PullRequestListStatsInput,) => Effect.Effect<PullRequestListStatsResult, PullRequestError>;+ readonly filterOptions: (+ input: PullRequestFilterOptionsInput,+ ) => Effect.Effect<PullRequestFilterOptions, PullRequestError>;readonly routing: (input: PullRequestRef,) => Effect.Effect<PullRequestRoutingResult, PullRequestError>;@@ -574,6 +582,17 @@ function withRateLimitBackoff(? {}: { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }),...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }),+ ...(api.listRepositoryLabels === undefined+ ? {}+ : { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }),+ ...(api.searchRepositoryAuthors === undefined+ ? {}+ : {+ searchRepositoryAuthors: interactive(+ "searchRepositoryAuthors",+ api.searchRepositoryAuthors,+ ),+ }),replyToThread: interactive("replyToThread", api.replyToThread),setReaction: interactive("setReaction", api.setReaction),setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),@@ -583,6 +602,52 @@ function withRateLimitBackoff(Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;}+const FILTER_OPTIONS_LIMIT = 100;++/**+ * Exact matches first, then names that begin with the query, then the rest, so a short query+ * still puts the obvious answer at the top of a long list.+ */+function rankFilterOptions<A>(+ pages: ReadonlyArray<ProviderFilterOptionPage<A>>,+ input: {+ readonly query: string | undefined;+ readonly keyOf: (item: A) => string;+ readonly textsOf: (item: A) => ReadonlyArray<string | null>;+ },+): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {+ const query = input.query?.trim().toLowerCase() ?? "";+ const unique = new Map<string, A>();+ for (const page of pages) {+ for (const item of page.items) {+ const key = input.keyOf(item).toLowerCase();+ if (!unique.has(key)) unique.set(key, item);+ }+ }+ const rank = (item: A) => {+ const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : []));+ if (query.length === 0) return 0;+ if (texts.includes(query)) return 0;+ if (texts.some((text) => text.startsWith(query))) return 1;+ if (texts.some((text) => text.includes(query))) return 2;+ return null;+ };+ const ranked = [...unique.values()]+ .flatMap((item) => {+ const score = rank(item);+ return score === null ? [] : [{ item, score, key: input.keyOf(item) }];+ })+ .toSorted(+ (left, right) =>+ left.score - right.score ||+ left.key.localeCompare(right.key, undefined, { sensitivity: "base" }),+ );+ return {+ items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),+ truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated),+ };+}+// Capture before the provider read so a slow response keeps its original freshness through caches.const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {const observedAt = yield* Clock.currentTimeMillis;@@ -2326,6 +2391,61 @@ export const make = Effect.gen(function* () {}),);+ const filterOptions: PullRequestService["Service"]["filterOptions"] = Effect.fn(+ "PullRequestService.filterOptions",+ )(function* (input) {+ const { supported } = yield* listWorkspaceProjects(input);+ // Worktrees of one checkout are separate projects over the same repository.+ const repositories = [+ ...new Map(supported.map((project) => [project.cursorKey, project])).values(),+ ];+ const refOf = (project: SupportedProject) => ({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ query: input.query,+ });+ // One repository the host cannot read leaves the others' options standing, as a listing does.+ const gather = <A>(+ read: (+ project: SupportedProject,+ ) => Effect.Effect<ProviderFilterOptionPage<A>, PullRequestProviderError> | undefined,+ ) =>+ Effect.forEach(+ repositories,+ (project): Effect.Effect<ReadonlyArray<ProviderFilterOptionPage<A>>> => {+ const page = read(project);+ return page === undefined+ ? Effect.succeed([])+ : page.pipe(+ Effect.map((answered) => [answered]),+ Effect.orElseSucceed(() => []),+ );+ },+ { concurrency: REPOSITORY_CONCURRENCY },+ ).pipe(Effect.map((pages) => pages.flat()));+ if (input.kind === "labels") {+ const pages = yield* gather<PullRequestLabel>((project) =>+ project.api.listRepositoryLabels?.(refOf(project)),+ );+ const { items, truncated } = rankFilterOptions(pages, {+ query: input.query,+ keyOf: (label) => label.name,+ textsOf: (label) => [label.name],+ });+ return { labels: items, authors: [], truncated };+ }+ const pages = yield* gather<PullRequestActor>((project) =>+ project.api.searchRepositoryAuthors?.(refOf(project)),+ );+ const { items, truncated } = rankFilterOptions(pages, {+ query: input.query,+ keyOf: (author) => author.login,+ textsOf: (author) => [author.login, author.name],+ });+ return { labels: [], authors: items, truncated };+ });+const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) =>requireProject(input).pipe(Effect.flatMap((project): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> => {@@ -3432,6 +3552,7 @@ export const make = Effect.gen(function* () {routingIdentity,withRoutingCredential,list,+ filterOptions,listStats: (input) =>Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe(Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 7656ddca925..9a72a501f43 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -2509,6 +2509,7 @@ export const layerWsRpc = (),[WS_METHODS.pullRequestsList]: (input) => pullRequests.list(input),[WS_METHODS.pullRequestsListStats]: (input) => pullRequests.listStats(input),+ [WS_METHODS.pullRequestsFilterOptions]: (input) => pullRequests.filterOptions(input),[WS_METHODS.pullRequestsRoutingIdentity]: (input) => pullRequests.routingIdentity(input),[WS_METHODS.pullRequestsRouting]: (input) => pullRequests.routing(input),[WS_METHODS.pullRequestsSummary]: (input) =>diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsxindex 4038d60da4d..09a56e57358 100644--- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx+++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx@@ -2,6 +2,7 @@ import { Spinner } from "~/components/ui/spinner";import type {EnvironmentId,ProjectId,+ PullRequestFilterOptionsInput,PullRequestInvolvement,PullRequestListFilters,PullRequestListState,@@ -23,6 +24,8 @@ import {import { type ElementType, useState } from "react";import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";+import { useDebouncedValue } from "~/state/queries";+import { type EnvironmentQueryTarget, usePullRequestFilterOptions } from "~/state/pullRequests";import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon";import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";import { Button } from "../ui/button";@@ -36,6 +39,7 @@ import {MenuRadioGroup,MenuRadioItem,MenuRadioItemIndicator,+ MenuSearchInput,MenuSeparator,MenuSub,MenuSubPopup,@@ -44,6 +48,9 @@ import {} from "../ui/menu";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import {+ pullRequestAuthorChoices,+ selectedPullRequestAuthor,+ pullRequestLabelChoices,pullRequestLabelColor,type PullRequestAuthorFacet,type PullRequestLabelFacet,@@ -232,30 +239,103 @@ function PullRequestFilterRadioSubmenu<Value extends string>({);}-function PullRequestAuthorFilter({+/** The listing's own scope, which the pickers search the host within. */+export type PullRequestFilterOptionScope = EnvironmentQueryTarget<+ Omit<PullRequestFilterOptionsInput, "kind" | "query">+>;++const OPTION_SEARCH_DEBOUNCE_MS = 250;++function useHostedFilterOptions(+ scope: ReadonlyArray<PullRequestFilterOptionScope>,+ kind: PullRequestFilterOptionsInput["kind"],+ query: string,+) {+ const typed = query.trim().slice(0, 100);+ const sent = useDebouncedValue(typed, OPTION_SEARCH_DEBOUNCE_MS);+ const hosted = usePullRequestFilterOptions(+ scope.map(({ environmentId, input }) => ({+ environmentId,+ input: { ...input, kind, ...(sent ? { query: sent } : {}) },+ })),+ );+ // Until the search catches up with the typing, the host's answers are for older text.+ return sent === typed ? hosted : { labels: [], authors: [], error: null, isPending: true };+}++function PullRequestAuthorChoices({value,options,+ scope,onChange,}: {value: string | undefined;options: ReadonlyArray<PullRequestAuthorFacet>;+ scope: ReadonlyArray<PullRequestFilterOptionScope>;onChange: (author: string | undefined) => void;}) {const [query, setQuery] = useState("");- const needle = query.trim().toLowerCase();+ const hosted = useHostedFilterOptions(scope, "authors", query);const login = value?.toLowerCase() ?? "";- const selected = options.find((option) => option.actor.login.toLowerCase() === login);+ const selected = selectedPullRequestAuthor(options, hosted.authors, value);const visible = [...(selected ? [selected] : []),- ...options.filter(- (option) =>- option !== selected &&- (needle.length === 0 ||- option.actor.login.toLowerCase().includes(needle) ||- option.actor.name?.toLowerCase().includes(needle)),+ ...pullRequestAuthorChoices(options, hosted.authors, query).filter(+ (option) => option.actor.login.toLowerCase() !== login,),- ].slice(0, 10);+ ].slice(0, 30);const select = (next: string) => next.toLowerCase() !== login && onChange(next || undefined);+ return (+ <>+ <MenuSearchInput+ autoFocus+ busy={hosted.isPending}+ value={query}+ onChange={(event) => setQuery(event.currentTarget.value)}+ placeholder="Search authors"+ aria-label="Search authors"+ />+ <MenuRadioGroup value={selected?.actor.login ?? value ?? ""} onValueChange={select}>+ <MenuRadioItem value="">+ <span className="flex min-w-0 items-center gap-2">+ <LayersIcon aria-hidden className="size-3.5" />+ Anyone+ </span>+ </MenuRadioItem>+ {visible.map((option) => (+ <MenuRadioItem key={option.actor.login.toLowerCase()} value={option.actor.login}>+ <span className="flex min-w-0 items-center gap-2">+ <PullRequestActorAvatar actor={option.actor} />+ <span className="min-w-0 flex-1 truncate">{option.actor.login}</span>+ {option.mergedCount > 0 ? (+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {option.mergedCount} merges loaded+ </span>+ ) : null}+ </span>+ </MenuRadioItem>+ ))}+ {visible.length === 0 && !hosted.isPending ? (+ <MenuItem disabled>+ {hosted.error === null ? "No authors found" : "Couldn't search authors on the host"}+ </MenuItem>+ ) : null}+ </MenuRadioGroup>+ </>+ );+}++function PullRequestAuthorFilter({+ value,+ options,+ scope,+ onChange,+}: {+ value: string | undefined;+ options: ReadonlyArray<PullRequestAuthorFacet>;+ scope: ReadonlyArray<PullRequestFilterOptionScope>;+ onChange: (author: string | undefined) => void;+}) {return (<MenuSub><MenuSubTrigger>@@ -266,65 +346,99 @@ function PullRequestAuthorFilter({</span></MenuSubTrigger><MenuSubPopup>- <div className="p-1 pb-2">- <InputGroup>- <InputGroupAddon>- <SearchIcon aria-hidden />- </InputGroupAddon>- <InputGroupInput- autoFocus- size="compact"- value={query}- onChange={(event) => setQuery(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key !== "ArrowDown" && event.key !== "Escape") event.stopPropagation();- }}- placeholder="Search authors"- aria-label="Search authors"- />- </InputGroup>- </div>- <MenuRadioGroup value={selected?.actor.login ?? value ?? ""} onValueChange={select}>- <MenuRadioItem value="">- <span className="flex min-w-0 items-center gap-2">- <LayersIcon aria-hidden className="size-3.5" />- Anyone- </span>- </MenuRadioItem>- {visible.map((option) => (- <MenuRadioItem key={option.actor.login.toLowerCase()} value={option.actor.login}>- <span className="flex min-w-0 items-center gap-2">- <PullRequestActorAvatar actor={option.actor} />- <span className="min-w-0 flex-1 truncate">{option.actor.login}</span>- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">- {option.mergedCount} merges loaded- </span>- </span>- </MenuRadioItem>- ))}- {visible.length === 0 ? <MenuItem disabled>No authors found</MenuItem> : null}- </MenuRadioGroup>+ <PullRequestAuthorChoices+ value={value}+ options={options}+ scope={scope}+ onChange={onChange}+ /></MenuSubPopup></MenuSub>);}-function PullRequestLabelFilter({+function PullRequestLabelChoices({value,options,+ scope,onChange,}: {value: ReadonlyArray<string>;options: ReadonlyArray<PullRequestLabelFacet>;+ scope: ReadonlyArray<PullRequestFilterOptionScope>;onChange: (labels: ReadonlyArray<string>) => void;}) {+ const [query, setQuery] = useState("");+ const hosted = useHostedFilterOptions(scope, "labels", query);const selected = new Set(value.map((name) => name.toLowerCase()));+ const choices = pullRequestLabelChoices(options, hosted.labels, query);const visible = [...value- .filter((name) => !options.some((option) => option.name.toLowerCase() === name.toLowerCase()))+ .filter((name) => !choices.some((option) => option.name.toLowerCase() === name.toLowerCase())).map((name) => ({ name, color: null, count: 0 })),- ...options,+ ...choices,];+ return (+ <>+ <MenuSearchInput+ autoFocus+ busy={hosted.isPending}+ value={query}+ onChange={(event) => setQuery(event.currentTarget.value)}+ placeholder="Search labels"+ aria-label="Search labels"+ />+ {visible.length === 0 && !hosted.isPending ? (+ <MenuItem disabled>+ {hosted.error === null ? "No labels found" : "Couldn't search labels on the host"}+ </MenuItem>+ ) : null}+ {visible.map((option) => {+ const key = option.name.toLowerCase();+ const dot = pullRequestLabelColor(option.color);+ return (+ <MenuCheckboxItem+ key={key}+ checked={selected.has(key)}+ onCheckedChange={(next) =>+ onChange(+ next+ ? [...value, option.name]+ : value.filter((name) => name.toLowerCase() !== option.name.toLowerCase()),+ )+ }+ >+ <span className="flex min-w-0 items-center gap-2">+ <span+ aria-hidden+ className="size-2.5 shrink-0 rounded-full bg-muted-foreground"+ {...(dot ? { style: { backgroundColor: dot } } : {})}+ />+ <span className="min-w-0 flex-1 truncate">{option.name}</span>+ {option.count > 0 ? (+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {option.count}+ </span>+ ) : null}+ </span>+ </MenuCheckboxItem>+ );+ })}+ </>+ );+}++function PullRequestLabelFilter({+ value,+ options,+ scope,+ onChange,+}: {+ value: ReadonlyArray<string>;+ options: ReadonlyArray<PullRequestLabelFacet>;+ scope: ReadonlyArray<PullRequestFilterOptionScope>;+ onChange: (labels: ReadonlyArray<string>) => void;+}) {return (<MenuSub><MenuSubTrigger>@@ -335,40 +449,12 @@ function PullRequestLabelFilter({</span></MenuSubTrigger><MenuSubPopup>- {visible.length === 0 ? (- <MenuItem disabled>No labels in this view</MenuItem>- ) : (- visible.map((option) => {- const key = option.name.toLowerCase();- const checked = selected.has(key);- const dot = pullRequestLabelColor(option.color);- return (- <MenuCheckboxItem- key={key}- checked={checked}- onCheckedChange={(next) =>- onChange(- next- ? [...value, option.name]- : value.filter((name) => name.toLowerCase() !== option.name.toLowerCase()),- )- }- >- <span className="flex min-w-0 items-center gap-2">- <span- aria-hidden- className="size-2.5 shrink-0 rounded-full bg-muted-foreground"- {...(dot ? { style: { backgroundColor: dot } } : {})}- />- <span className="min-w-0 flex-1 truncate">{option.name}</span>- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">- {option.count}- </span>- </span>- </MenuCheckboxItem>- );- })- )}+ <PullRequestLabelChoices+ value={value}+ options={options}+ scope={scope}+ onChange={onChange}+ /></MenuSubPopup></MenuSub>);@@ -386,6 +472,7 @@ export function PullRequestFiltersMenu({onFilters,authorOptions = [],labelOptions = [],+ optionScope,host,hostOptions,onHost,@@ -409,6 +496,7 @@ export function PullRequestFiltersMenu({onFilters: (filters: PullRequestListFilters) => void;authorOptions?: ReadonlyArray<PullRequestAuthorFacet>;labelOptions?: ReadonlyArray<PullRequestLabelFacet>;+ optionScope: ReadonlyArray<PullRequestFilterOptionScope>;host: string | undefined;hostOptions: ReadonlyArray<PullRequestFilterOption<string>>;onHost: (host: string | undefined) => void;@@ -494,11 +582,13 @@ export function PullRequestFiltersMenu({<PullRequestAuthorFiltervalue={filters.author}options={authorOptions}+ scope={optionScope}onChange={(author) => updateFilters({ author })}/><PullRequestLabelFiltervalue={selectedLabels}options={labelOptions}+ scope={optionScope}onChange={(labels) =>updateFilters({labels: labels.length === 0 ? undefined : labels.slice(0, 10).map((label) => [label]),diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsxindex 4c72a9cd6eb..17a438bd07f 100644--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx@@ -348,6 +348,14 @@ export function PullRequestsPage() {}));})();const facetQuery = usePullRequestList(facetTargets);+ const filterOptionScope = environmentQueries.map(({ environmentId, projectIds }) => ({+ environmentId,+ input: {+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),+ ...(projectIds ? { projectIds } : {}),+ ...(search.host ? { host: search.host } : {}),+ },+ }));const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;const partitionTargets = (() => {// The main list goes first. Besides putting the visible rows on screen sooner, it proves@@ -1258,6 +1266,7 @@ export function PullRequestsPage() {}}authorOptions={facets.authors}labelOptions={facets.labels}+ optionScope={filterOptionScope}host={search.host}hostOptions={hostMenuOptions}onHost={(host) => updateListScope({ host })}diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.tsindex 7bbc0c3ab0a..44cf97bda85 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts@@ -24,6 +24,9 @@ import {partitionPullRequestsWithPriority,readPullRequestListSnapshot,writePullRequestListSnapshot,+ pullRequestAuthorChoices,+ selectedPullRequestAuthor,+ pullRequestLabelChoices,rankPullRequestMatches,rankPullRequestsBlockedOnAuthor,rankPullRequestsByMergeReadiness,@@ -815,3 +818,67 @@ describe("findProjectForRepository", () => {).toBeUndefined();});});++describe("filter picker choices", () => {+ const actor = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null });++ it("offers authors the host found that no loaded row carries, after the loaded ones", () => {+ const loaded = [+ { actor: actor("julius", "Julius"), count: 4, mergedCount: 3 },+ { actor: actor("theo"), count: 1, mergedCount: 0 },+ ];++ const choices = pullRequestAuthorChoices(+ loaded,+ [actor("Julius"), actor("juliana", "Juliana")],+ "jul",+ );++ expect(choices.map((choice) => [choice.actor.login, choice.count])).toEqual([+ ["julius", 4],+ ["juliana", 0],+ ]);+ });++ it("keeps showing an author picked from the host's search once the search clears", () => {+ const loaded = [{ actor: actor("julius"), count: 4, mergedCount: 3 }];+ const hosted = [actor("Juliana", "Juliana")];++ expect(selectedPullRequestAuthor(loaded, hosted, "juliana")?.actor).toEqual(+ actor("Juliana", "Juliana"),+ );+ expect(selectedPullRequestAuthor(loaded, [], "juliana")?.actor.login).toBe("juliana");+ expect(selectedPullRequestAuthor(loaded, hosted, "JULIUS")?.count).toBe(4);+ expect(selectedPullRequestAuthor(loaded, hosted, undefined)).toBeUndefined();+ });++ it("puts the host's authors after the first loaded matches rather than after all of them", () => {+ const loaded = Array.from({ length: 40 }, (_, index) => ({+ actor: actor(`dev-${index}`),+ count: 1,+ mergedCount: 0,+ }));++ const choices = pullRequestAuthorChoices(loaded, [actor("dev-from-host")], "dev");++ expect(choices.slice(0, 30).map((choice) => choice.actor.login)).toContain("dev-from-host");+ });++ it("keeps a loaded label's count when only the host's search found it", () => {+ const loaded = [{ name: "size:XL", color: "d93f0b", count: 7 }];++ const choices = pullRequestLabelChoices(+ loaded,+ [+ { name: "size:XL", color: "d93f0b" },+ { name: "bug", color: null },+ ],+ "xl-ish",+ );++ expect(choices).toEqual([+ { name: "size:XL", color: "d93f0b", count: 7 },+ { name: "bug", color: null, count: 0 },+ ]);+ });+});diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.tsindex 3d996b2e82b..fbd70381f87 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts@@ -129,6 +129,84 @@ export function collectPullRequestListFacets(};}+/**+ * What a filter picker offers for `query`: the loaded rows that match keep their counts and lead,+ * then whatever the host found that no loaded row carries, so a name nobody has loaded yet is+ * still one search away.+ */+/** How many loaded matches come before the host's answers. */+const HOSTED_CHOICE_ROOM = 15;++export function pullRequestAuthorChoices(+ facets: ReadonlyArray<PullRequestAuthorFacet>,+ hosted: ReadonlyArray<PullRequestActor>,+ query: string,+): ReadonlyArray<PullRequestAuthorFacet> {+ const needle = normalize(query);+ const loaded = facets.filter(+ (facet) =>+ needle === null ||+ facet.actor.login.toLowerCase().includes(needle) ||+ facet.actor.name?.toLowerCase().includes(needle),+ );+ const known = new Map(facets.map((facet) => [normalize(facet.actor.login), facet]));+ const seen = new Set(loaded.map((facet) => normalize(facet.actor.login)));+ const added: PullRequestAuthorFacet[] = [];+ for (const actor of hosted) {+ const key = normalize(actor.login);+ if (seen.has(key)) continue;+ seen.add(key);+ added.push(known.get(key) ?? { actor, count: 0, mergedCount: 0 });+ }+ // The picker shows a short list, and loaded matches alone could fill it.+ return [...loaded.slice(0, HOSTED_CHOICE_ROOM), ...added, ...loaded.slice(HOSTED_CHOICE_ROOM)];+}++/**+ * The author a filter names, as a choice: an author picked from the host's answer is on no+ * loaded row, so it stays shown after the search that found it clears.+ */+export function selectedPullRequestAuthor(+ facets: ReadonlyArray<PullRequestAuthorFacet>,+ hosted: ReadonlyArray<PullRequestActor>,+ value: string | undefined,+): PullRequestAuthorFacet | undefined {+ if (value === undefined) return undefined;+ const key = normalize(value);+ return (+ facets.find((facet) => normalize(facet.actor.login) === key) ?? {+ actor: hosted.find((actor) => normalize(actor.login) === key) ?? {+ login: value,+ name: null,+ avatarUrl: null,+ },+ count: 0,+ mergedCount: 0,+ }+ );+}++export function pullRequestLabelChoices(+ facets: ReadonlyArray<PullRequestLabelFacet>,+ hosted: ReadonlyArray<PullRequestLabel>,+ query: string,+): ReadonlyArray<PullRequestLabelFacet> {+ const needle = normalize(query);+ const loaded = facets.filter(+ (facet) => needle === null || facet.name.toLowerCase().includes(needle),+ );+ const known = new Map(facets.map((facet) => [normalize(facet.name), facet]));+ const seen = new Set(loaded.map((facet) => normalize(facet.name)));+ const added: PullRequestLabelFacet[] = [];+ for (const label of hosted) {+ const key = normalize(label.name);+ if (seen.has(key)) continue;+ seen.add(key);+ added.push(known.get(key) ?? { ...label, count: 0 });+ }+ return [...loaded, ...added];+}+export function pullRequestEntryViewer(entry: ScopedEntry,viewers: PullRequestViewers,diff --git a/apps/web/src/components/ui/menu.tsx b/apps/web/src/components/ui/menu.tsxindex 7880c17a32b..52c5eecc404 100644--- a/apps/web/src/components/ui/menu.tsx+++ b/apps/web/src/components/ui/menu.tsx@@ -1,9 +1,11 @@import { Menu as MenuPrimitive } from "@base-ui/react/menu";-import { CheckIcon, ChevronRightIcon } from "lucide-react";+import { CheckIcon, ChevronRightIcon, SearchIcon } from "lucide-react";import type * as React from "react";import { cn } from "~/lib/utils";import { buttonVariants } from "./button";+import { Input, type InputProps } from "./input";+import { Spinner } from "./spinner";const Menu = MenuPrimitive.Root;@@ -67,6 +69,44 @@ function MenuPopup({);}+/** A menu's filter field, drawn like `ComboboxSearchInput` so every searchable popup matches. */+function MenuSearchInput({+ busy = false,+ onKeyDown,+ ...props+}: Omit<InputProps, "className" | "size" | "unstyled" | "nativeInput"> & { busy?: boolean }) {+ return (+ <div className="min-w-0 shrink-0 px-2 pt-1.5 pb-1">+ <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">+ {busy ? (+ <Spinner+ aria-hidden="true"+ size="md"+ tone="muted"+ className="pointer-events-none absolute top-1.5 left-0"+ />+ ) : (+ <SearchIcon+ aria-hidden="true"+ className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"+ />+ )}+ <Input+ {...props}+ className="rounded-none bg-transparent text-sm [&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"+ size="sm"+ unstyled+ onKeyDown={(event) => {+ // Menu typeahead would otherwise take the letters; arrows still reach the items.+ if (event.key !== "ArrowDown" && event.key !== "Escape") event.stopPropagation();+ onKeyDown?.(event);+ }}+ />+ </div>+ </div>+ );+}+function MenuGroup(props: MenuPrimitive.Group.Props) {return <MenuPrimitive.Group data-slot="menu-group" {...props} />;}@@ -327,6 +367,7 @@ export {MenuTrigger as DropdownMenuTrigger,MenuPopup,MenuPopup as DropdownMenuContent,+ MenuSearchInput,MenuGroup,MenuGroup as DropdownMenuGroup,MenuItem,diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.tsindex 64d761f4d53..8757c4b6caf 100644--- a/apps/web/src/state/pullRequests.ts+++ b/apps/web/src/state/pullRequests.ts@@ -9,6 +9,7 @@ import type {EnvironmentId,ProjectId,PullRequestListInput,+ PullRequestFilterOptionsInput,PullRequestListStatsInput,PullRequestListEntry,PullRequestRef,@@ -308,6 +309,11 @@ const usePullRequestStatsQuery = createMergedEnvironmentQuery(pullRequestEnvironment.listStats,);+const usePullRequestFilterOptionsQuery = createMergedEnvironmentQuery(+ "web-pull-requests:filter-options",+ pullRequestEnvironment.filterOptions,+);+const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery("web-pull-requests:turn-refreshes",({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>@@ -376,3 +382,15 @@ export function usePullRequestListStats();return { stats, isPending: query.isPending, refresh: query.refresh };}++export function usePullRequestFilterOptions(+ targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestFilterOptionsInput>>,+) {+ const query = usePullRequestFilterOptionsQuery(targets);+ return {+ labels: query.values.flatMap(([, options]) => options.labels),+ authors: query.values.flatMap(([, options]) => options.authors),+ error: query.error,+ isPending: query.isPending,+ };+}diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex fa5385c09fa..4ebde3f59fb 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -322,6 +322,11 @@ export function createPullRequestEnvironmentAtoms<R, E>(staleTimeMs: 60_000,refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),}),+ filterOptions: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:pull-requests:filter-options",+ tag: WS_METHODS.pullRequestsFilterOptions,+ staleTimeMs: 5 * 60_000,+ }),detail,preview,checks: normalizePullRequestQuery(diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 5f9bc23048d..bf8f124c360 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -525,6 +525,26 @@ export const PullRequestListStatsResult = Schema.Struct({});export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;+export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors"]);+export type PullRequestFilterOptionKind = typeof PullRequestFilterOptionKind.Type;++/** Scoped like `PullRequestListInput`, so the options come from the repositories it lists. */+export const PullRequestFilterOptionsInput = Schema.Struct({+ kind: PullRequestFilterOptionKind,+ projectId: Schema.optional(ProjectId),+ projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),+ host: Schema.optional(TrimmedNonEmptyString),+ query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),+});+export type PullRequestFilterOptionsInput = typeof PullRequestFilterOptionsInput.Type;++export const PullRequestFilterOptions = Schema.Struct({+ labels: Schema.Array(PullRequestLabel),+ authors: Schema.Array(PullRequestActor),+ truncated: Schema.Boolean,+});+export type PullRequestFilterOptions = typeof PullRequestFilterOptions.Type;+/*** A separate request rather than a flag on the reads, so an explicit "refresh" one person* presses is the only thing that spends host requests — every ordinary read shares.diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex d7a11234c44..9723ea5a872 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -180,6 +180,8 @@ import {PullRequestListResult,PullRequestListStatsInput,PullRequestListStatsResult,+ PullRequestFilterOptions,+ PullRequestFilterOptionsInput,PullRequestOperationError,PullRequestReactionInput,PullRequestRef,@@ -526,6 +528,7 @@ export const WS_METHODS = {pullRequestsList: "pullRequests.list",pullRequestsListStats: "pullRequests.listStats",+ pullRequestsFilterOptions: "pullRequests.filterOptions",pullRequestsSummary: "pullRequests.summary",pullRequestsRouting: "pullRequests.routing",pullRequestsRoutingIdentity: "pullRequests.routingIdentity",@@ -963,6 +966,12 @@ const WsPullRequestsListStatsRpc = Rpc.make(WS_METHODS.pullRequestsListStats, {error: PullRequestRpcError,});+const WsPullRequestsFilterOptionsRpc = Rpc.make(WS_METHODS.pullRequestsFilterOptions, {+ payload: PullRequestFilterOptionsInput,+ success: PullRequestFilterOptions,+ error: PullRequestRpcError,+});+const WsPullRequestsRoutingRpc = Rpc.make(WS_METHODS.pullRequestsRouting, {payload: PullRequestRef,success: PullRequestRoutingResult,@@ -1948,6 +1957,7 @@ export const WsRpcGroup = RpcGroup.make(WsCloudInstallRelayClientRpc,WsPullRequestsListRpc,WsPullRequestsListStatsRpc,+ WsPullRequestsFilterOptionsRpc,WsPullRequestsSummaryRpc,WsPullRequestsRoutingRpc,WsPullRequestsRoutingIdentityRpc,diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex 882bef676a8..32a06d2b314 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -258,6 +258,11 @@ export interface ProviderFileRevisions {readonly complete?: boolean;}+export interface ProviderFilterOptionPage<A> {+ readonly items: ReadonlyArray<A>;+ readonly truncated: boolean;+}+export interface ProviderRepositoryRef {readonly cwd: string;readonly repository: string;@@ -529,6 +534,22 @@ export interface PullRequestProviderApi {input: ProviderRepositoryRef & { readonly number: number },) => Effect.Effect<PullRequestLabelCandidateList, PullRequestProviderError>;+ /**+ * The labels a repository offers, for narrowing a listing by. `query` narrows by name as far as+ * the host can; the caller still matches the answer against it.+ */+ readonly listRepositoryLabels?: (+ input: ProviderRepositoryRef & { readonly query?: string | undefined },+ ) => Effect.Effect<ProviderFilterOptionPage<PullRequestLabel>, PullRequestProviderError>;++ /**+ * People who could have opened a change request in the repository, for narrowing a listing by+ * author. A host that can only search its whole user base answers from that.+ */+ readonly searchRepositoryAuthors?: (+ input: ProviderRepositoryRef & { readonly query?: string | undefined },+ ) => Effect.Effect<ProviderFilterOptionPage<PullRequestActor>, PullRequestProviderError>;+readonly setLabels?: (input: ProviderRepositoryRef & {readonly number: number;diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.tsindex cbcc294ede8..b7616c276c3 100644--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts@@ -58,6 +58,11 @@ const CAPABILITIES: PullRequestCapabilities = {reviewers: { request: true, listCandidates: true },edit: { changeRequest: true, comment: true },};+const USER_SEARCH_LIMIT = 50;+const ForgejoUserSearch = Schema.Struct({+ data: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),+});+const repoPath = (input: ProviderRepositoryRef) =>`repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>@@ -100,7 +105,8 @@ export const make = Effect.gen(function* () {}),),);- const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(+ /** A response, and whether its `link` header points at a further page. */+ const readLinked = Effect.fn("ForgejoPullRequestProvider.readLinked")(function* <A>(input: ForgejoCli.ForgejoApiInput,schema: Schema.Codec<A, unknown, never, never>,) {@@ -108,10 +114,15 @@ export const make = Effect.gen(function* () {if (result.stdoutTruncated)return yield* failure(input.path, "Forgejo response exceeded the output limit.");const decoded = decodeJsonResult(schema)(result.stdout);- return Result.isSuccess(decoded)- ? decoded.success- : yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);+ if (Result.isFailure(decoded))+ return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);+ const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];+ return { value: decoded.success, next: links !== undefined && /rel="?next"?/i.test(links) };});+ const read = <A>(+ input: ForgejoCli.ForgejoApiInput,+ schema: Schema.Codec<A, unknown, never, never>,+ ) => readLinked(input, schema).pipe(Effect.map(({ value }) => value));const readArray = <A>(input: ForgejoCli.ForgejoApiInput,schema: Schema.Codec<A, unknown, never, never>,@@ -632,6 +643,48 @@ export const make = Effect.gen(function* () {};},),+ listRepositoryLabels: Effect.fn("ForgejoPullRequestProvider.listRepositoryLabels")(+ function* (input) {+ const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);+ return {+ items: labels.items.map((label) => ({ name: label.name, color: label.color ?? null })),+ truncated: labels.truncated,+ };+ },+ ),+ searchRepositoryAuthors: Effect.fn("ForgejoPullRequestProvider.searchRepositoryAuthors")(+ function* (input) {+ const query = input.query?.trim() ?? "";+ const actors = (users: ReadonlyArray<typeof ForgejoUser.Type>) =>+ users.flatMap((user) => {+ const actor = forgejoActor(user);+ return actor ? [actor] : [];+ });+ // Before anything is typed the repository's own people stand in; a search reaches+ // contributors from forks, who are never assignable.+ if (query.length === 0) {+ const users = yield* page(+ { ...input, path: `${repoPath(input)}/assignees` },+ ForgejoUser,+ 100,+ );+ return { items: actors(users.items), truncated: users.truncated };+ }+ const found = yield* readLinked(+ {+ ...input,+ path: `users/search?${new URLSearchParams({ q: query, limit: String(USER_SEARCH_LIMIT) })}`,+ },+ ForgejoUserSearch,+ );+ const users = found.value.data ?? [];+ // A server may cap pages below the limit asked for; its `link` header still says more.+ return {+ items: actors(users),+ truncated: found.next || users.length >= USER_SEARCH_LIMIT,+ };+ },+ ),setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);const selected = labels.items.filter((label) => input.labels.includes(label.name));diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.tsindex d6ec0221648..c3e8146f5f0 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts@@ -554,6 +554,40 @@ it.effect("lists nothing for an author Forgejo has no account for", () =>),);+it.effect("says an author search was cut short by a server that pages below its limit", () =>+ Effect.gen(function* () {+ const provider = yield* ForgejoPullRequestProvider.make;+ const search = provider.searchRepositoryAuthors;+ if (search === undefined) return yield* Effect.die("author search missing");+ const found = yield* search({+ cwd: "/repo",+ repository: "maria/project",+ host: "forgejo.test",+ query: "dev",+ });+ assert.strictEqual(found.items.length, 30);+ assert.isTrue(found.truncated);+ }).pipe(+ Effect.provide(+ Layer.mock(ForgejoCli.ForgejoCli)({+ api: () =>+ encodeJsonEffect({+ ok: true,+ data: Array.from({ length: 30 }, (_, index) => ({ login: `dev-${index}` })),+ }).pipe(+ Effect.orDie,+ Effect.map((stdout) =>+ processOutput(stdout, {+ stderr:+ 'HTTP/1.1 200\nlink: <https://forgejo.test/api/v1/users/search?page=2>; rel="next"\n',+ }),+ ),+ ),+ }),+ ),+ ),+);+it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>Effect.gen(function* () {const provider = yield* ForgejoSourceControlProvider.make;diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex 23c488e03b4..88cd6294b17 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -1073,6 +1073,30 @@ export const make = Effect.gen(function* () {};},),+ listRepositoryLabels: Effect.fn("GitCafePullRequestProvider.listRepositoryLabels")(+ function* (input) {+ const operation = "listRepositoryLabels";+ const base = yield* repositoryPath(operation, input);+ const labels = yield* readPages(operation, input, `${base}/labels`, Json.GitCafeLabels);+ return {+ items: labels.items.map((label) => ({ name: label.name, color: label.color })),+ truncated: labels.next !== null,+ };+ },+ ),+ searchRepositoryAuthors: Effect.fn("GitCafePullRequestProvider.searchRepositoryAuthors")(+ function* (input) {+ const operation = "searchRepositoryAuthors";+ const query = input.query?.trim() ?? "";+ // User search needs two characters; before that the repository's own people stand in.+ const path =+ query.length < 2+ ? `${yield* repositoryPath(operation, input)}/collaborators?${new URLSearchParams({ limit: "50" })}`+ : `/users?${new URLSearchParams({ q: query, limit: "50" })}`;+ const people = yield* read(operation, input, { path }, Json.GitCafePeople);+ return { items: Json.toPeople(people, input.host), truncated: people.next !== null };+ },+ ),setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {const base = yield* repositoryPath("setLabels", input);const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);diff --git a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.tsindex 8c3b0ac56e2..f6c700dba19 100644--- a/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts+++ b/packages/source-control-gitcafe/src/server/gitCafePullRequestJson.ts@@ -267,6 +267,29 @@ export const GitCafeChecks = Schema.Struct({next: Schema.NullOr(Schema.String),});+/** A user search answer and a collaborator page carry the same fields a picker shows. */+export const GitCafePeople = Schema.Struct({+ items: Schema.Array(+ Schema.Struct({+ handle: TrimmedNonEmptyString,+ displayName: Schema.optional(Schema.NullOr(Schema.String)),+ avatarUrl: Schema.optional(Schema.NullOr(Schema.String)),+ }),+ ),+ next: Schema.NullOr(Schema.String),+});++export function toPeople(+ people: typeof GitCafePeople.Type,+ host: string,+): ReadonlyArray<PullRequestActor> {+ return people.items.map((person) => ({+ login: person.handle,+ name: person.displayName ?? null,+ avatarUrl: person.avatarUrl == null ? null : new URL(person.avatarUrl, `https://${host}`).href,+ }));+}+interface RepositoryOnHost {readonly repository: string;readonly host: string;diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex c25699714d1..741f238f4b4 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -37,6 +37,7 @@ import {type PullRequestReviewVerdict,type PullRequestReviewerCandidateList,type PullRequestReviewerKind,+ type PullRequestLabel,type PullRequestLabelCandidateList,type PullRequestThreadCommentsResult,type PullRequestUpdateMethod,@@ -68,6 +69,8 @@ import {pullRequestLookup,toActorAvatars,toLabelCandidates,+ toRepositoryAuthors,+ toRepositoryLabels,toPullRequestActivityPage,toPullRequestCheckContextsPage,toPullRequestCore,@@ -645,6 +648,26 @@ export class GitHubPullRequestApi extends Context.Service<readonly number: number;}) => Effect.Effect<PullRequestLabelCandidateList, GitHubPullRequestApiError>;+ readonly listRepositoryLabels: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly query?: string | undefined;+ }) => Effect.Effect<+ { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },+ GitHubPullRequestApiError+ >;++ readonly searchRepositoryAuthors: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly query?: string | undefined;+ }) => Effect.Effect<+ { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },+ GitHubPullRequestApiError+ >;+readonly setLabels: (input: {readonly cwd: string;readonly repository: string;@@ -2334,6 +2357,30 @@ export const make = Effect.gen(function* () {);},+ listRepositoryLabels: (input) => {+ const { owner, name } = parseRepositorySelector(input.repository);+ const operation = "listRepositoryLabels";+ return client+ .RepositoryLabels({ owner, name, query: input.query ?? null })+ .pipe(+ graphql({ ...input, operation, allowReserve: true }),+ Effect.map(toRepositoryLabels),+ Effect.flatMap(found({ ...input, operation })),+ );+ },++ searchRepositoryAuthors: (input) => {+ const { owner, name } = parseRepositorySelector(input.repository);+ const operation = "searchRepositoryAuthors";+ return client+ .RepositoryAuthors({ owner, name, query: input.query ?? null })+ .pipe(+ graphql({ ...input, operation, allowReserve: true }),+ Effect.map(toRepositoryAuthors),+ Effect.flatMap(found({ ...input, operation })),+ );+ },+setLabels: (input) => {const { owner, name } = parseRepositorySelector(input.repository);const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex dd710dffcfd..ab770dac4e0 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -547,6 +547,12 @@ export const make = Effect.gen(function* () {listLabelCandidates: (input) =>cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),+ listRepositoryLabels: (input) =>+ cli.listRepositoryLabels(input).pipe(Effect.mapError(fail("listRepositoryLabels"))),++ searchRepositoryAuthors: (input) =>+ cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),+setLabels: (input) =>cli.setLabels({diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.tsindex 318ba41468c..6d9abb6d604 100644--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts@@ -60,6 +60,8 @@ import type {PullRequestHeads,PullRequestPreview as PullRequestPreviewQuery,PullRequestSubject,+ RepositoryAuthors,+ RepositoryLabels,ReviewerCandidates,ViewerPermissions,} from "./pullRequestReads.graphql.ts";@@ -1658,6 +1660,36 @@ export function toLabelCandidates(};}+export function toRepositoryLabels(+ result: RepositoryLabels.Result,+): { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean } | null {+ const repository = result.repository;+ if (repository == null) return null;+ return {+ items: nodesOf(repository.labels).flatMap((node) => {+ const name = trimmed(node.name);+ return name === null ? [] : [{ name, color: trimmed(node.color) }];+ }),+ truncated: repository.labels?.pageInfo.hasNextPage === true,+ };+}++export function toRepositoryAuthors(+ result: RepositoryAuthors.Result,+): { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean } | null {+ const repository = result.repository;+ if (repository == null) return null;+ return {+ items: nodesOf(repository.mentionableUsers).flatMap((node) => {+ const login = trimmed(node.login);+ return login === null+ ? []+ : [{ login, name: trimmed(node.name), avatarUrl: trimmed(node.avatarUrl) }];+ }),+ truncated: repository.mentionableUsers.pageInfo.hasNextPage,+ };+}+export function buildLabelRequest(labels: ReadonlyArray<string>): {readonly labels: ReadonlyArray<string>;} {diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphqlindex 7281af8c898..ba103d44ad8 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql+++ b/packages/source-control-github/src/server/pullRequestReads.graphql@@ -455,6 +455,37 @@ query LabelCandidates($owner: String!, $name: String!, $number: Int!) {}}+query RepositoryLabels($owner: String!, $name: String!, $query: String) {+ repository(owner: $owner, name: $name) {+ labels(first: 100, query: $query, orderBy: { field: NAME, direction: ASC }) {+ pageInfo {+ hasNextPage+ }+ nodes {+ name+ color+ }+ }+ }+}++# Mentionable rather than assignable users: a pull request from a fork is opened by someone with+# no access to the repository, and a listing is still narrowed by them.+query RepositoryAuthors($owner: String!, $name: String!, $query: String) {+ repository(owner: $owner, name: $name) {+ mentionableUsers(first: 50, query: $query) {+ pageInfo {+ hasNextPage+ }+ nodes {+ login+ name+ avatarUrl+ }+ }+ }+}+# Which files of a pull request the signed-in account has cleared. GraphQL only, since the REST# files endpoint the patch is read from carries no viewed state, so this is a second read rather# than a wider version of the first.diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.tsindex fd0fef547ea..b6a2524468d 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts@@ -1170,13 +1170,13 @@ export const RepositoryLabelsNodesLabel = Schema.Struct({export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type<typeof RepositoryLabelsNodesLabel.fields> {}/** The connection type for Label. */-export const RepositoryLabelsLabelConnection = Schema.Struct({+export const LabelCandidatesRepositoryLabelsLabelConnection = Schema.Struct({/** Information to aid in pagination. */pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,/** A list of nodes. */nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel)))})-export interface RepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof RepositoryLabelsLabelConnection.fields> {}+export interface LabelCandidatesRepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof LabelCandidatesRepositoryLabelsLabelConnection.fields> {}/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */export const LabelCandidatesRepositoryPullRequestLabelsNodesLabel = Schema.Struct({@@ -1202,7 +1202,7 @@ export interface LabelCandidatesRepositoryPullRequestPullRequest extends Schema./** A repository contains the content for a project. */export const LabelCandidatesRepositoryRepository = Schema.Struct({/** A list of labels associated with the repository. */- labels: Schema.NullOr(RepositoryLabelsLabelConnection),+ labels: Schema.NullOr(LabelCandidatesRepositoryLabelsLabelConnection),/** Returns a single pull request from the current repository by number. */pullRequest: Schema.NullOr(LabelCandidatesRepositoryPullRequestPullRequest)})@@ -1236,6 +1236,85 @@ export declare namespace LabelCandidates {export type Result = typeof LabelCandidates.result.Type}+/** The connection type for Label. */+export const RepositoryLabelsRepositoryLabelsLabelConnection = Schema.Struct({+ /** Information to aid in pagination. */+ pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,+ /** A list of nodes. */+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel)))+})+export interface RepositoryLabelsRepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof RepositoryLabelsRepositoryLabelsLabelConnection.fields> {}++/** A repository contains the content for a project. */+export const RepositoryLabelsRepositoryRepository = Schema.Struct({+ /** A list of labels associated with the repository. */+ labels: Schema.NullOr(RepositoryLabelsRepositoryLabelsLabelConnection)+})+export interface RepositoryLabelsRepositoryRepository extends Schema.Struct.Type<typeof RepositoryLabelsRepositoryRepository.fields> {}++/** `query RepositoryLabels` */+export const RepositoryLabels = GraphQL.query("RepositoryLabels", {+ document: {+ variables: [+ { name: "owner", body: "String!" },+ { name: "name", body: "String!" },+ { name: "query", body: "String" }+ ],+ selections: [+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){labels(first:100 query:$", "query", " orderBy:{field:NAME direction:ASC}){pageInfo{hasNextPage}nodes{name color}}}"] }+ ],+ fragments: []+ },+ variables: {+ owner: Schema.String,+ name: Schema.String,+ query: Schema.optional(Schema.NullOr(Schema.String))+ },+ result: Schema.Struct({+ /** Lookup a given repository by the owner and repository name. */+ repository: Schema.NullOr(RepositoryLabelsRepositoryRepository)+ })+})+export declare namespace RepositoryLabels {+ export type Variables = typeof RepositoryLabels.variables.Type+ export type Result = typeof RepositoryLabels.result.Type+}++/** A repository contains the content for a project. */+export const RepositoryAuthorsRepositoryRepository = Schema.Struct({+ /** A list of Users that can be mentioned in the context of the repository. */+ mentionableUsers: UserConnection+})+export interface RepositoryAuthorsRepositoryRepository extends Schema.Struct.Type<typeof RepositoryAuthorsRepositoryRepository.fields> {}++/** `query RepositoryAuthors` */+export const RepositoryAuthors = GraphQL.query("RepositoryAuthors", {+ document: {+ variables: [+ { name: "owner", body: "String!" },+ { name: "name", body: "String!" },+ { name: "query", body: "String" }+ ],+ selections: [+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mentionableUsers(first:50 query:$", "query", "){pageInfo{hasNextPage}nodes{login name avatarUrl}}}"] }+ ],+ fragments: []+ },+ variables: {+ owner: Schema.String,+ name: Schema.String,+ query: Schema.optional(Schema.NullOr(Schema.String))+ },+ result: Schema.Struct({+ /** Lookup a given repository by the owner and repository name. */+ repository: Schema.NullOr(RepositoryAuthorsRepositoryRepository)+ })+})+export declare namespace RepositoryAuthors {+ export type Variables = typeof RepositoryAuthors.variables.Type+ export type Result = typeof RepositoryAuthors.result.Type+}+/** A file changed in a pull request. */export const PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile = Schema.Struct({/** The path of the file. */@@ -1587,4 +1666,4 @@ export declare namespace PullRequestSourceBranch {}/** Every operation in pullRequestReads.graphql. */-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)+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)diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex e4a7937de5a..04fe88d03be 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -6,9 +6,11 @@ import * as Schema from "effect/Schema";import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";import type {PullRequestAction,+ PullRequestActor,PullRequestComment,PullRequestCommit,PullRequestInvolvement,+ PullRequestLabel,PullRequestListFilters,PullRequestListState,PullRequestMergeCapabilities,@@ -37,6 +39,7 @@ import {decodeNotesJson,decodeOwnAwardIdJson,decodeProjectMergeCapabilitiesJson,+ decodeProjectLabelsJson,decodeProjectUsersJson,decodeRepositoryBlobsJson,decodeViewerJson,@@ -287,6 +290,24 @@ export class GitLabPullRequestCli extends Context.Service<readonly number: number;}) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;+ readonly listProjectLabels: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly search?: string | undefined;+ }) => Effect.Effect<+ { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean },+ GitLabPullRequestCliError+ >;++ readonly listProjectUsers: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly search?: string | undefined;+ }) => Effect.Effect<+ { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean },+ GitLabPullRequestCliError+ >;+readonly setReviewerRequest: (input: {readonly cwd: string;readonly repository: string;@@ -919,11 +940,13 @@ export const make = Effect.gen(function* () {const projectUsers = (input: {readonly cwd: string;readonly repository: string;+ readonly search?: string | undefined;}): Effect.Effect<GitLabProjectUsers, GitLabPullRequestCliError> =>api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/users?${query([["per_page", String(MAX_PAGE_SIZE)],+ ...searchParams(input.search),])}`,}).pipe(Effect.flatMap((result) => {@@ -1277,6 +1300,40 @@ export const make = Effect.gen(function* () {}),),+ listProjectLabels: (input) =>+ api({+ cwd: input.cwd,+ path: `projects/${projectPath(input.repository)}/labels?${query([+ ["per_page", String(MAX_PAGE_SIZE)],+ ...searchParams(input.search),+ ])}`,+ }).pipe(+ Effect.flatMap((result) => {+ const decoded = decodeProjectLabelsJson(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed({+ items: decoded.success.labels,+ truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,+ })+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "listProjectLabels",+ cause: decoded.failure,+ }),+ );+ }),+ ),++ listProjectUsers: (input) =>+ projectUsers(input).pipe(+ Effect.map(({ candidates, rawCount }) => ({+ items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),+ truncated: rawCount >= MAX_PAGE_SIZE,+ })),+ ),+listReviewerCandidates: (input) =>Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(Effect.map(([mergeRequest, users]) => {diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex 295960aa407..297343fb9be 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -232,6 +232,16 @@ export const make = Effect.gen(function* () {}).pipe(Effect.mapError(fail("listReviewerCandidates"))),+ listRepositoryLabels: (input) =>+ cli+ .listProjectLabels({ cwd: input.cwd, repository: input.repository, search: input.query })+ .pipe(Effect.mapError(fail("listRepositoryLabels"))),++ searchRepositoryAuthors: (input) =>+ cli+ .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })+ .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),+setReviewerRequest: (input) =>cli.setReviewerRequest({diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex 249283b61f1..4edfbbdab18 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -441,6 +441,34 @@ export function decodeProjectUsersJson(return Result.succeed({ candidates, rawCount: decoded.success.length });}+const RawLabelSchema = Schema.Struct({+ name: Schema.String,+ color: Schema.optional(Schema.NullOr(Schema.String)),+});+const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);++export interface GitLabProjectLabels {+ readonly labels: ReadonlyArray<PullRequestLabel>;+ readonly rawCount: number;+}++export function decodeProjectLabelsJson(+ raw: string,+): Result.Result<GitLabProjectLabels, DecodeFailure> {+ const decoded = decodeUnknownList(raw);+ if (!Result.isSuccess(decoded)) {+ return Result.fail(decoded.failure);+ }+ const labels: PullRequestLabel[] = [];+ for (const entry of decoded.success) {+ const label = decodeLabelEntry(entry);+ if (Exit.isFailure(label)) continue;+ const name = trimmed(label.value.name);+ if (name !== null) labels.push({ name, color: trimmed(label.value.color) });+ }+ return Result.succeed({ labels, rawCount: decoded.success.length });+}+export function decodeProjectMergeCapabilitiesJson(raw: string,): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {