TypeScript
fix(prs): reviewer menu searches past the first page and keeps GitLab's requested reviewers (#22489)
Antonyc52df24d285a
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsxindex dad9ba1c1aa..e4a698dee5e 100644--- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx@@ -6,6 +6,11 @@ import { useAtomValue } from "@effect/atom-react";import { useNavigation, type StaticScreenProps } from "@react-navigation/native";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import {+ hostReviewerQuery,+ reviewerCandidateView,+ type ReviewerTruncation,+} from "@t3tools/client-runtime/pull-request-reviewers";import type { PullRequestReviewerCandidate } from "@t3tools/contracts";import { useRef, useState } from "react";import { FlatList, Pressable, ScrollView, View } from "react-native";@@ -17,10 +22,21 @@ import { Button } from "../../components/ui/Button";import { SymbolView } from "../../components/ui/AppSymbol";import { composerPullRequests } from "../../state/pull-requests";import { useEnvironmentQuery } from "../../state/query";+import { useDebouncedValue } from "../../state/queries";import { useAtomCommand } from "../../state/use-atom-command";import { PullRequestAvatar } from "./PullRequestPresentation";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";+const TRUNCATED_LABELS: Record<ReviewerTruncation, (error: string | null) => string> = {+ unsearchable: () =>+ "The provider has more reviewers than it returned. Find additional reviewers on the provider.",+ searchable: () => "The provider has more reviewers than are listed here. Search to find them.",+ "search-failed": (error) =>+ `Only listed reviewers are matched: the provider search failed. ${error ?? ""}`,+ "search-truncated": () =>+ "More reviewers match than the provider returned. Keep typing to narrow it down.",+};+export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequestParams>) {const navigation = useNavigation();const contentTopInset = useContentTopInset();@@ -51,16 +67,30 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequconst [pending, setPending] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const inFlight = useRef(false);- const candidates = (() => {- const needle = query.trim().toLowerCase();- return [...(result.data?.candidates ?? [])]- .filter((candidate) =>- `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle),- )- .sort(- (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),- );- })();+ const debouncedQuery = useDebouncedValue(query.trim(), 250);+ const searchInput = {+ loaded: result.data,+ searchable: pr?.capabilities.reviewers.searchCandidates === true,+ query,+ debouncedQuery,+ };+ const hostQuery = hostReviewerQuery(searchInput);+ const searchResult = useEnvironmentQuery(+ hostQuery !== null+ ? composerPullRequests.reviewerSearch({+ ...target,+ input: { ...target.input, query: hostQuery },+ })+ : null,+ );+ const view = reviewerCandidateView({+ ...searchInput,+ search: searchResult,+ });+ const candidates = [...view.candidates].sort(+ (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),+ );+ const queryError = result.error ?? view.searchError;// A new search shows its best matches from the top.const search = (next: string) => {setQuery(next);@@ -93,6 +123,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ);return;}+ if (hostQuery !== null) searchResult.refresh();if (!pr?.capabilities.reviewers.listCandidates) {search("");detail.refresh();@@ -181,30 +212,34 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ);}}ListEmptyComponent={- result.isPending && !result.data ? (+ (result.isPending && !result.data) || view.searchPending ? (<AppActivityIndicator className="my-8" />) : (<View className="px-4 py-6"><EmptyStatetitle={- result.error+ queryError? "Couldn't load reviewers": query.trim()? "No matching reviewers": "No reviewers available"}- detail={result.error ?? "Search people and teams with access to this repository."}+ detail={queryError ?? "Search people and teams with access to this repository."}variant="plain"/>- {result.error ? <Button label="Retry" onPress={result.refresh} /> : null}+ {queryError ? (+ <Button+ label="Retry"+ onPress={result.error ? result.refresh : searchResult.refresh}+ />+ ) : null}</View>)}ListFooterComponent={- result.data?.truncated ? (+ view.truncation ? (<Text className="px-4 py-4 text-xs text-foreground-muted">- The provider has more reviewers than it returned. Find additional reviewers on the- provider.+ {TRUNCATED_LABELS[view.truncation](view.searchError)}</Text>) : undefined}diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 80d6d101336..0140a3aa96e 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -58,6 +58,7 @@ import {type PullRequestRoutingIdentityResult,type PullRequestReviewVerdict,type PullRequestReviewerCandidateList,+ type PullRequestReviewerCandidatesInput,type PullRequestReviewerRequestInput,type PullRequestLabelCandidateList,type PullRequestLabelChangeInput,@@ -274,7 +275,7 @@ export class PullRequestService extends Context.Service<input: PullRequestReactionInput,) => Effect.Effect<void, PullRequestError>;readonly reviewerCandidates: (- input: PullRequestRef,+ input: PullRequestReviewerCandidatesInput,) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;readonly requestReviewers: (input: PullRequestReviewerRequestInput,@@ -2499,6 +2500,7 @@ export const make = Effect.gen(function* () {repository: project.repository,host: project.host,number: input.number,+ query: input.query,}).pipe(Effect.mapError(toPullRequestError("reviewerCandidates"))): Effect.fail(diff --git a/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx b/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsxindex b03f4f56758..729bd089be9 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx@@ -4,11 +4,17 @@ import type {PullRequestRef,PullRequestReviewerCandidate,} from "@t3tools/contracts";+import {+ hostReviewerQuery,+ reviewerCandidateView,+ type ReviewerTruncation,+} from "@t3tools/client-runtime/pull-request-reviewers";import { CheckIcon, UserPlusIcon } from "lucide-react";import { useState } from "react";import { pullRequestEnvironment } from "~/state/pullRequests";import { useEnvironmentQuery } from "~/state/query";+import { useDebouncedValue } from "~/state/queries";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { toastManager } from "../ui/toast";@@ -16,23 +22,27 @@ import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";import { PullRequestActorLabel } from "./pullRequestPresentation";import { readableFailure } from "./pullRequestDetail.logic";-function matches(candidate: PullRequestReviewerCandidate, query: string): boolean {- if (query.length === 0) return true;- const needle = query.toLowerCase();- return (- candidate.login.toLowerCase().includes(needle) ||- (candidate.name ?? "").toLowerCase().includes(needle)- );-}+const TRUNCATED_LABELS: Record<ReviewerTruncation, (error: string | null) => string> = {+ unsearchable: () =>+ "This repository has more people with access than are listed here. Ask for the rest on the host.",+ searchable: () =>+ "This repository has more people with access than are listed here. Search to find them.",+ "search-failed": (error) =>+ `Only the people already listed are matched: the host search failed. ${error ?? ""}`,+ "search-truncated": () =>+ "More people match than the host returned. Keep typing to narrow it down.",+};export function PullRequestReviewerPicker({environmentId,reference,allowed,+ searchable,}: {environmentId: EnvironmentId;reference: PullRequestRef;allowed: boolean;+ searchable: boolean;}) {const [open, setOpen] = useState(false);const [query, setQuery] = useState("");@@ -41,13 +51,26 @@ export function PullRequestReviewerPicker({const candidatesQuery = useEnvironmentQuery(open ? pullRequestEnvironment.reviewerCandidates({ environmentId, input: reference }) : null,);+ // Past the first page the host is asked, since what was loaded cannot answer for the rest.+ const debouncedQuery = useDebouncedValue(query.trim(), 250);+ const searchInput = { loaded: candidatesQuery.data, searchable, query, debouncedQuery };+ const hostQuery = hostReviewerQuery(searchInput);+ const searchResult = useEnvironmentQuery(+ open && hostQuery !== null+ ? pullRequestEnvironment.reviewerSearch({+ environmentId,+ input: { ...reference, query: hostQuery },+ })+ : null,+ );const requestReviewers = useAtomCommand(pullRequestEnvironment.requestReviewers, {reportFailure: false,});- const candidates = (candidatesQuery.data?.candidates ?? []).filter((entry) =>- matches(entry, query),- );+ const { candidates, searchPending, searchError, truncation } = reviewerCandidateView({+ ...searchInput,+ search: searchResult,+ });const toggle = async (candidate: PullRequestReviewerCandidate) => {if (pending !== null) return;@@ -74,6 +97,9 @@ export function PullRequestReviewerPicker({});return;}+ // The command reads the loaded list again only for somebody it lacked, and a search result+ // is keyed by what was typed, so the one on screen is read here or it keeps the old request.+ if (hostQuery !== null) searchResult.refresh();toastManager.add({type: "success",title: candidate.isRequested@@ -93,14 +119,20 @@ export function PullRequestReviewerPicker({query={query}onQueryChange={setQuery}searchLabel="Search people with access"- isPending={candidatesQuery.isPending && candidatesQuery.data === null}- error={candidatesQuery.data === null ? candidatesQuery.error : null}+ isPending={(candidatesQuery.isPending && candidatesQuery.data === null) || searchPending}+ error={+ candidatesQuery.data === null+ ? candidatesQuery.error+ : candidates.length === 0+ ? searchError+ : null+ }candidates={candidates}emptyLabel="Nobody else has access to this repository."noMatchLabel="Nobody with access matches that."errorLabel="The people with access could not be read."- truncated={candidatesQuery.data?.truncated === true}- truncatedLabel="This repository has more people with access than are listed here. Ask for the rest on the host."+ truncated={truncation !== null}+ truncatedLabel={truncation === null ? "" : TRUNCATED_LABELS[truncation](searchError)}candidateKey={(candidate) => `${candidate.kind}:${candidate.id}`}disabled={pending !== null}onSelect={(candidate) => void toggle(candidate)}diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsxindex 89434eca594..b98a48a817b 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx@@ -802,6 +802,7 @@ export function PullRequestSummaryTab({{detail.capabilities.reviewers.request &&detail.capabilities.reviewers.listCandidates ? (<PullRequestReviewerPicker+ searchable={detail.capabilities.reviewers.searchCandidates === true}environmentId={environmentId}reference={reference}allowed={detail.viewerPermissions.requestReviewers}diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 2161dc69c86..f52115577f1 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -527,6 +527,10 @@"types": "./src/modelTraits.ts","default": "./src/modelTraits.ts"},+ "./pull-request-reviewers": {+ "types": "./src/pullRequestReviewers.ts",+ "default": "./src/pullRequestReviewers.ts"+ },"./provider-clients": {"types": "./src/providerClients.ts","default": "./src/providerClients.ts"diff --git a/packages/client-runtime/src/pullRequestReviewers.test.ts b/packages/client-runtime/src/pullRequestReviewers.test.tsnew file mode 100644index 00000000000..fef411ee51c--- /dev/null+++ b/packages/client-runtime/src/pullRequestReviewers.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from "@effect/vitest";++import {+ hostReviewerQuery,+ mergeReviewerCandidates,+ reviewerCandidateView,+} from "./pullRequestReviewers.ts";++const reviewer = (+ login: string,+ { isRequested = false, name = null, kind = "user" } = {} as {+ isRequested?: boolean;+ name?: string | null;+ kind?: "user" | "team";+ },+) => ({ login, name, avatarUrl: null, id: login, kind, isRequested });++describe("mergeReviewerCandidates", () => {+ it("narrows the loaded candidates by login or name", () => {+ const loaded = [+ reviewer("ada"),+ reviewer("grace", { name: "Grace Hopper" }),+ reviewer("linus"),+ ];+ expect(mergeReviewerCandidates(loaded, [], "HOP").map((entry) => entry.login)).toEqual([+ "grace",+ ]);+ });++ it("adds candidates only the host's search found, after the loaded ones", () => {+ const loaded = [reviewer("ada"), reviewer("adam")];+ const searched = [reviewer("adam"), reviewer("adalbert")];+ expect(mergeReviewerCandidates(loaded, searched, "ada").map((entry) => entry.login)).toEqual([+ "ada",+ "adam",+ "adalbert",+ ]);+ });++ it("keeps the loaded entry for somebody both lists name, since a request updates that one", () => {+ const loaded = [reviewer("ada", { isRequested: true })];+ expect(mergeReviewerCandidates(loaded, [reviewer("ada")], "ada")).toEqual(loaded);+ });++ it("keeps a host match on a field absent from the loaded row", () => {+ const loaded = [reviewer("ada", { isRequested: true })];+ expect(mergeReviewerCandidates(loaded, [reviewer("ada")], "[email protected]")).toEqual(loaded);+ });++ it("tells a team from a person sharing its id", () => {+ const loaded = [reviewer("core", { kind: "team", isRequested: true })];+ expect(+ mergeReviewerCandidates(loaded, [reviewer("core")], "core").map((entry) => entry.kind),+ ).toEqual(["team", "user"]);+ });+});++describe("reviewerCandidateView", () => {+ const firstPage = { candidates: [reviewer("ada"), reviewer("grace")], truncated: true };+ const idle = { data: null, isPending: false, error: null };++ it.each([+ {+ name: "a host without search, as from an older server, narrows the loaded page itself",+ searchable: false,+ query: "zed",+ debouncedQuery: "zed",+ search: idle,+ expected: { hostQuery: null, logins: [], searchPending: false, truncation: "unsearchable" },+ },+ {+ name: "a searchable host is asked once the debounce catches up",+ searchable: true,+ query: "zed",+ debouncedQuery: "zed",+ search: {+ data: { candidates: [reviewer("zed")], truncated: false },+ isPending: false,+ error: null,+ },+ expected: { hostQuery: "zed", logins: ["zed"], searchPending: false, truncation: null },+ },+ {+ name: "results for text the debounce has not reached are neither shown nor a no-match",+ searchable: true,+ query: "zed",+ debouncedQuery: "ze",+ search: {+ data: { candidates: [reviewer("zelda")], truncated: false },+ isPending: false,+ error: null,+ },+ expected: { hostQuery: "ze", logins: [], searchPending: true, truncation: null },+ },+ {+ name: "a failed search falls back to the loaded page and says so",+ searchable: true,+ query: "gr",+ debouncedQuery: "gr",+ search: { data: null, isPending: false, error: "rate limited" },+ expected: {+ hostQuery: "gr",+ logins: ["grace"],+ searchPending: false,+ truncation: "search-failed",+ },+ },+ {+ name: "an empty query lists the loaded page and offers search",+ searchable: true,+ query: "",+ debouncedQuery: "",+ search: idle,+ expected: {+ hostQuery: null,+ logins: ["ada", "grace"],+ searchPending: false,+ truncation: "searchable",+ },+ },+ ])("$name", ({ searchable, query, debouncedQuery, search, expected }) => {+ const input = { loaded: firstPage, searchable, query, debouncedQuery };+ const view = reviewerCandidateView({ ...input, search });+ expect({+ hostQuery: hostReviewerQuery(input),+ logins: view.candidates.map((entry) => entry.login),+ searchPending: view.searchPending,+ truncation: view.truncation,+ }).toEqual(expected);+ });+});diff --git a/packages/client-runtime/src/pullRequestReviewers.ts b/packages/client-runtime/src/pullRequestReviewers.tsnew file mode 100644index 00000000000..be0cfb9966a--- /dev/null+++ b/packages/client-runtime/src/pullRequestReviewers.ts@@ -0,0 +1,101 @@+import type {+ PullRequestReviewerCandidate,+ PullRequestReviewerCandidateList,+} from "@t3tools/contracts";++// Loaded rows retain the request state updated by mutations.+export function mergeReviewerCandidates(+ loaded: ReadonlyArray<PullRequestReviewerCandidate>,+ searched: ReadonlyArray<PullRequestReviewerCandidate>,+ query: string,+): ReadonlyArray<PullRequestReviewerCandidate> {+ const needle = query.trim().toLowerCase();+ const key = (candidate: PullRequestReviewerCandidate) => `${candidate.kind}:${candidate.id}`;+ const known = new Set(loaded.map(key));+ const hostMatches = new Set(searched.map(key));+ return [+ ...loaded.filter(+ (candidate) =>+ hostMatches.has(key(candidate)) ||+ needle.length === 0 ||+ candidate.login.toLowerCase().includes(needle) ||+ (candidate.name ?? "").toLowerCase().includes(needle),+ ),+ // The host matched these on its own terms, an email for one, so they are not narrowed again.+ ...searched.filter((candidate) => !known.has(key(candidate))),+ ];+}++export interface ReviewerSearchInput {+ readonly loaded: PullRequestReviewerCandidateList | null;+ /** The host declared `reviewers.searchCandidates`. */+ readonly searchable: boolean;+ readonly query: string;+ readonly debouncedQuery: string;+}++/** What to ask the host for, or null when the loaded page already answers the query. */+export function hostReviewerQuery(input: ReviewerSearchInput): string | null {+ const debounced = input.debouncedQuery.trim();+ return input.searchable && input.loaded?.truncated === true && debounced.length > 0+ ? debounced+ : null;+}++/**+ * Why the list may be missing people: `unsearchable` hosts cannot be asked, `searchable` ones+ * can once something is typed, and a search that ran either `failed` or was `truncated` itself.+ */+export type ReviewerTruncation =+ | "unsearchable"+ | "searchable"+ | "search-failed"+ | "search-truncated";++export function reviewerCandidateView(+ input: ReviewerSearchInput & {+ readonly search: {+ readonly data: PullRequestReviewerCandidateList | null;+ readonly isPending: boolean;+ readonly error: string | null;+ };+ },+): {+ readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;+ /** Nothing matches yet and the host has not answered, which is not "nobody matches". */+ readonly searchPending: boolean;+ readonly searchError: string | null;+ readonly truncation: ReviewerTruncation | null;+} {+ const query = input.query.trim();+ const hostQuery = hostReviewerQuery(input);+ // Only once the debounce has caught up, or rows matching the previous text would linger.+ const searched = hostQuery !== null && hostQuery === query;+ const candidates = mergeReviewerCandidates(+ input.loaded?.candidates ?? [],+ searched ? (input.search.data?.candidates ?? []) : [],+ query,+ );+ const searching = input.searchable && input.loaded?.truncated === true && query.length > 0;+ const searchError = searched ? input.search.error : null;+ const truncation: ReviewerTruncation | null =+ input.loaded?.truncated !== true+ ? null+ : !input.searchable+ ? "unsearchable"+ : query.length === 0+ ? "searchable"+ : !searched+ ? null+ : searchError !== null+ ? "search-failed"+ : input.search.data?.truncated === true+ ? "search-truncated"+ : null;+ return {+ candidates,+ searchPending: candidates.length === 0 && searching && (!searched || input.search.isPending),+ searchError,+ truncation,+ };+}diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 0669421585e..e0ded133128 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -611,6 +611,13 @@ export function createPullRequestEnvironmentAtoms<R, E>(staleTimeMs: 60_000,}),);+ // Asked only when the menu's first page is not everybody, so a query cannot be answered from it.+ const reviewerSearch = createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:pull-requests:reviewer-search",+ tag: WS_METHODS.pullRequestsReviewerCandidates,+ execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),+ staleTimeMs: 60_000,+ });const loadDiff = Effect.fn("PullRequests.loadDiff")(function* (input: PullRequestDiffInput) {const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;@@ -914,6 +921,8 @@ export function createPullRequestEnvironmentAtoms<R, E>(concurrency: serialPerEnvironment,}),reviewerCandidates,+ /** The host's search for reviewers past the first page, keyed by what was typed. */+ reviewerSearch,requestReviewers: createEnvironmentRpcCommand(runtime, {label: "environment-data:pull-requests:request-reviewers",tag: WS_METHODS.pullRequestsRequestReviewers,@@ -932,12 +941,19 @@ export function createPullRequestEnvironmentAtoms<R, E>(),) ?? [];const missingIdentities = selected.length < reviewers.length;- updateCached(registry, candidatesAtom, (value) => ({- ...value,- candidates: value.candidates.map((candidate) =>- selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,- ),- }));+ // Somebody found only by the host's search is not in the loaded list yet; the host+ // puts requested reviewers first, so reading it again brings them in.+ updateCached(+ registry,+ candidatesAtom,+ (value) => ({+ ...value,+ candidates: value.candidates.map((candidate) =>+ selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,+ ),+ }),+ missingIdentities,+ );const selectedLogins = new Set(selected.map((candidate) => candidate.login.toLowerCase()),);diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 5dbec3e2dd3..2988870be35 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -251,6 +251,11 @@ export type PullRequestEditCapabilities = typeof PullRequestEditCapabilities.Typexport const PullRequestReviewerCapabilities = Schema.Struct({request: Schema.Boolean,listCandidates: Schema.Boolean,+ /**+ * Reviewer candidates take a `query` the host matches past the first page. Absent, as from a+ * server that predates it, means the client narrows the loaded page itself.+ */+ searchCandidates: Schema.optional(Schema.Boolean),});export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabilities.Type;@@ -411,6 +416,13 @@ export const PullRequestRef = Schema.Struct({});export type PullRequestRef = typeof PullRequestRef.Type;+/** `query` asks the host for matches past the first page of candidates. */+export const PullRequestReviewerCandidatesInput = Schema.Struct({+ ...PullRequestRef.fields,+ query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),+});+export type PullRequestReviewerCandidatesInput = typeof PullRequestReviewerCandidatesInput.Type;+export const PullRequestRoutingIdentityInput = Schema.Struct({host: TrimmedNonEmptyString,});diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 3106462d357..6465558d5fe 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -201,6 +201,7 @@ import {PullRequestLinkedThreadsResult,PullRequestSummary,PullRequestReviewerCandidateList,+ PullRequestReviewerCandidatesInput,PullRequestReviewerRequestInput,PullRequestLabelCandidateList,PullRequestLabelChangeInput,@@ -1187,7 +1188,7 @@ const WsPullRequestsSubscribeRefreshesRpc = Rpc.make(WS_METHODS.pullRequestsSubs// Fetch reviewer candidates only when the menu opens to avoid unused host requests.const WsPullRequestsReviewerCandidatesRpc = Rpc.make(WS_METHODS.pullRequestsReviewerCandidates, {- payload: PullRequestRef,+ payload: PullRequestReviewerCandidatesInput,success: PullRequestReviewerCandidateList,error: PullRequestRpcError,});diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.tsindex 061a5d0f931..dbd9ae94875 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts@@ -56,7 +56,7 @@ const CAPABILITIES: PullRequestCapabilities = {referenceSigils: [],review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },// Reviewer candidates require separate identity/graph APIs and permissions.- reviewers: { request: true, listCandidates: false },+ reviewers: { request: true, listCandidates: false, searchCandidates: false },edit: { changeRequest: true, comment: false },// Azure's viewed marks use an undocumented endpoint and are invalidated by each push.viewedFiles: "environment",diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.tsindex 1f7729ee2a5..9d5015ca680 100644--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts@@ -31,7 +31,7 @@ const CAPABILITIES: PullRequestCapabilities = {resolve: true,verdicts: ["comment", "approve", "request-changes"],},- reviewers: { request: true, listCandidates: true },+ reviewers: { request: true, listCandidates: true, searchCandidates: false },edit: { changeRequest: true, comment: true },// Bitbucket PR properties are shared, not per-reader viewed marks.viewedFiles: "environment",diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex 549210e3827..0c58f64c47a 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -523,7 +523,11 @@ export interface PullRequestProviderApi {/** Exclude the author using host-specific account identities. */readonly listReviewerCandidates: (- input: ProviderRepositoryRef & { readonly number: number },+ input: ProviderRepositoryRef & {+ readonly number: number;+ /** Asks the host to search past its first page of candidates. */+ readonly query?: string | undefined;+ },) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestProviderError>;readonly setReviewerRequest: (diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.tsindex cd2047664a3..d3b7cd6d4ba 100644--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts@@ -58,7 +58,7 @@ const CAPABILITIES: PullRequestCapabilities = {resolve: false,verdicts: ["comment", "approve", "request-changes"],},- reviewers: { request: true, listCandidates: true },+ reviewers: { request: true, listCandidates: true, searchCandidates: false },edit: { changeRequest: true, comment: true },};const USER_SEARCH_LIMIT = 50;diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex 565f0b76722..314fc309027 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -44,7 +44,7 @@ const CAPABILITIES: PullRequestCapabilities = {resolve: true,verdicts: ["approve", "request-changes", "comment"],},- reviewers: { request: true, listCandidates: true },+ reviewers: { request: true, listCandidates: true, searchCandidates: false },edit: { changeRequest: true, comment: true },};diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.tsindex 14b50258d71..705a25b13e8 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts@@ -4001,6 +4001,54 @@ layer("GitHubPullRequestApi.layer", (it) => {}),);+ it.effect("asks GitHub to search everyone assignable when the reviewer menu has a query", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValue(+ Effect.succeed(+ output(+ encodeJson({+ data: {+ repository: {+ assignableUsers: {+ pageInfo: { hasNextPage: false },+ nodes: [{ login: "octocat", name: null, avatarUrl: "https://avatars/octocat" }],+ },+ pullRequest: {+ author: { __typename: "User", login: "bilal" },+ reviewRequests: {+ nodes: ["octocat", "unrelated"].map((login) => ({+ requestedReviewer: {+ __typename: "User",+ login,+ name: null,+ avatarUrl: "https://avatars/user",+ },+ })),+ },+ },+ },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;++ const list = yield* cli.listReviewerCandidates({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ query: "octo",+ });++ expect(varsAt(0)).toMatchObject({ owner: "acme", name: "web", number: 7, query: "octo" });+ expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([+ ["octocat", true],+ ]);+ }),+ );+it.effect("takes labels off one at a time, naming each in the path encoded", () =>Effect.gen(function* () {mockedExecute.mockReturnValue(Effect.succeed(output("[]")));diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex 372e0a83820..c4fbbfcd9f6 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -605,6 +605,7 @@ export class GitHubPullRequestApi extends Context.Service<readonly repository: string;readonly host: string;readonly number: number;+ readonly query?: string | undefined;}) => Effect.Effect<PullRequestReviewerCandidateList, GitHubPullRequestApiError>;readonly setReviewerRequest: (input: {@@ -2325,10 +2326,10 @@ export const make = Effect.gen(function* () {const { owner, name } = parseRepositorySelector(input.repository);const operation = "listReviewerCandidates";return client- .ReviewerCandidates({ owner, name, number: input.number })+ .ReviewerCandidates({ owner, name, number: input.number, query: input.query ?? null }).pipe(graphql({ ...input, operation, allowReserve: true }),- Effect.map(toReviewerCandidates),+ Effect.map((result) => toReviewerCandidates(result, input.query)),Effect.flatMap(found({ ...input, operation })),);},diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex d281b90f30a..4309880d74d 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -51,7 +51,7 @@ const CAPABILITIES: PullRequestCapabilities = {resolve: true,verdicts: ["comment", "approve", "request-changes"],},- reviewers: { request: true, listCandidates: true },+ reviewers: { request: true, listCandidates: true, searchCandidates: true },edit: { changeRequest: true, comment: true, maintainerEdits: true },stacks: true,stackActions: true,diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.tsindex 5c6fce4a0f3..98a95a363e3 100644--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts@@ -1462,6 +1462,7 @@ export interface GitHubBaseComparison {/** assignableUsers avoids push/read:org requirements. Keep requested outsiders/apps removable. */export function toReviewerCandidates(result: ReviewerCandidates.Result,+ query?: string,): PullRequestReviewerCandidateList | null {const repository = result.repository;if (repository == null) return null;@@ -1485,8 +1486,10 @@ export function toReviewerCandidates(isRequested: true,});}+ const hostMatches = new Set<string>();for (const node of nodesOf(repository.assignableUsers)) {const login = trimmed(node.login);+ if (login !== null) hostMatches.add(login);if (login === null || login === author || candidates.has(`user ${login}`)) continue;candidates.set(`user ${login}`, {id: login,@@ -1498,7 +1501,9 @@ export function toReviewerCandidates(});}return {- candidates: [...candidates.values()],+ candidates: [...candidates.values()].filter(+ (candidate) => !query?.trim() || (candidate.kind === "user" && hostMatches.has(candidate.id)),+ ),truncated: repository.assignableUsers.pageInfo.hasNextPage,};}diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphqlindex 61f77a289a7..eb728b1ee06 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql+++ b/packages/source-control-github/src/server/pullRequestReads.graphql@@ -409,9 +409,9 @@ query ViewerPermissions($owner: String!, $name: String!, $number: Int!) {# taken back. The teams a repository could newly be sent to live on the owning organization and# need `read:org`, which a repository-scoped token need not carry, and a query GitHub refuses# fails whole, taking the people down with the teams.-query ReviewerCandidates($owner: String!, $name: String!, $number: Int!) {+query ReviewerCandidates($owner: String!, $name: String!, $number: Int!, $query: String) {repository(owner: $owner, name: $name) {- assignableUsers(first: 100) {+ assignableUsers(first: 100, query: $query) {pageInfo {hasNextPage}diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.tsindex fca2349bcfc..90ee834c318 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts@@ -1199,17 +1199,19 @@ export const ReviewerCandidates = GraphQL.query("ReviewerCandidates", {variables: [{ name: "owner", body: "String!" },{ name: "name", body: "String!" },- { name: "number", body: "Int!" }+ { name: "number", body: "Int!" },+ { name: "query", body: "String" }],selections: [- { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){assignableUsers(first:100){pageInfo{hasNextPage}nodes{login name avatarUrl}}pullRequest(number:$", "number", "){author{__typename login}reviewRequests(first:100){nodes{requestedReviewer{__typename...on User{login name avatarUrl}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}...on Bot{login avatarUrl}}}}}}"] }+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){assignableUsers(first:100 query:$", "query", "){pageInfo{hasNextPage}nodes{login name avatarUrl}}pullRequest(number:$", "number", "){author{__typename login}reviewRequests(first:100){nodes{requestedReviewer{__typename...on User{login name avatarUrl}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}...on Bot{login avatarUrl}}}}}}"] }],fragments: []},variables: {owner: Schema.String,name: Schema.String,- number: Shared.Int+ number: Shared.Int,+ query: Schema.optional(Schema.NullOr(Schema.String))},result: Schema.Struct({/** Lookup a given repository by the owner and repository name. */diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.tsindex e70941f1568..f7e2422a6bc 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts@@ -2069,6 +2069,82 @@ layer("GitLabPullRequestCli.layer", (it) => {}),);+ it.effect(+ "lists the requested reviewers first, even when the users page does not reach them",+ () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(output(mergeRequestJson({ reviewers: [{ id: 42, username: "late" }] }))),+ )+ .mockReturnValueOnce(Effect.succeed(output(JSON.stringify([author, reviewer]))));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const list = yield* cli.listReviewerCandidates({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ });++ expect(+ list.candidates.map((candidate) => [+ candidate.login,+ candidate.id,+ candidate.isRequested,+ ]),+ ).toEqual([+ ["late", "42", true],+ [reviewer.username, "5", false],+ ]);+ }),+ );++ it.effect("marks a reviewer GitLab sent without a username as requested on the users page", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(output(mergeRequestJson({ reviewers: [{ id: 5, username: "" }] }))),+ )+ .mockReturnValueOnce(Effect.succeed(output(JSON.stringify([author, reviewer]))));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const list = yield* cli.listReviewerCandidates({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ });++ expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([+ ["5", true],+ ]);+ }),+ );++ it.effect("asks GitLab to search the project's users when the menu has a query", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(mergeRequestJson({ reviewers: [reviewer, { id: 42, username: "unrelated" }] })),+ ),+ )+ .mockReturnValueOnce(Effect.succeed(output(JSON.stringify([reviewer]))));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ const list = yield* cli.listReviewerCandidates({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ query: "octo cat",+ });++ expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([+ [reviewer.username, true],+ ]);+ expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/users?per_page=100&search=octo%20cat");+ }),+ );+it.effect("writes the reviewer set back with the one being asked added to it", () =>Effect.gen(function* () {mockedExecute@@ -2089,6 +2165,27 @@ layer("GitLabPullRequestCli.layer", (it) => {}),);+ it.effect("keeps a reviewer it cannot show when writing the set back", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(output(mergeRequestJson({ reviewers: [{ id: 3, username: "" }] }))),+ )+ .mockReturnValueOnce(Effect.succeed(output("{}")));+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;++ yield* cli.setReviewerRequest({+ cwd: "/w",+ repository: "acme/web",+ number: 7,+ reviewers: [{ id: "9" }],+ requested: true,+ });++ expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [3, 9] });+ }),+ );+it.effect("takes a reviewer out of the set rather than clearing it", () =>Effect.gen(function* () {mockedExecutediff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex f8a52e9f33f..b178218cf16 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -481,6 +481,7 @@ export class GitLabPullRequestCli extends Context.Service<readonly host?: string | undefined;readonly repository: string;readonly number: number;+ readonly query?: string | undefined;}) => Effect.Effect<PullRequestReviewerCandidateList, GitLabPullRequestCliError>;readonly listProjectLabels: (input: {@@ -2358,19 +2359,42 @@ export const make = Effect.gen(function* () {listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")(function (input) {- return Effect.all([mergeRequestDetail(input), projectUsers(input)], {- concurrency: 2,- }).pipe(+ return Effect.all(+ [mergeRequestDetail(input), projectUsers({ ...input, search: input.query })],+ {+ concurrency: 2,+ },+ ).pipe(Effect.map(([mergeRequest, users]) => {const author = mergeRequest.author?.login;- const requested = new Set(mergeRequest.reviewRequestLogins);+ const requested = (input.query?.trim() ? [] : mergeRequest.reviewerUsers).map(+ ({ id, ...actor }) => ({+ ...actor,+ id: String(id),+ kind: "user" as const,+ isRequested: true,+ }),+ );+ const listed = new Set(requested.map((reviewer) => reviewer.id));+ // Every reviewer id, not just the ones shown above: a reviewer GitLab sent without a+ // username can still turn up on the users page, and must read as requested there or+ // choosing them would ask again instead of taking the request back.+ const requestedIds = new Set(mergeRequest.reviewerIds.map(String));return {- // GitLab forbids requesting a review from the MR author.- candidates: users.candidates.flatMap((candidate) =>- candidate.login === author- ? []- : [{ ...candidate, isRequested: requested.has(candidate.login) }],- ),+ // The reviewers lead, and come from the merge request rather than the users page:+ // that page stops at a hundred, and somebody missing from it could not be taken off.+ // The author is dropped rather than shown unusable: GitLab refuses to make the person+ // who opened a merge request its reviewer.+ candidates: [+ ...requested,+ ...users.candidates+ .filter((candidate) => candidate.login !== author && !listed.has(candidate.id))+ .map((candidate) =>+ requestedIds.has(candidate.id)+ ? { ...candidate, isRequested: true }+ : candidate,+ ),+ ],truncated: users.rawCount >= MAX_PAGE_SIZE,};}),diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.tsindex 926e793297a..080d128ca6c 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts@@ -189,6 +189,7 @@ describe("getChangeRequest base freshness", () => {checks: [],viewerCanMerge: true,reviewerIds: [],+ reviewerUsers: [],};it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)(@@ -344,6 +345,7 @@ describe("merge request reads", () => {checks: [],viewerCanMerge: true,reviewerIds: [],+ reviewerUsers: [],};const countingProvider = Effect.gen(function* () {@@ -537,6 +539,7 @@ describe("optional activity reads", () => {checks: [],viewerCanMerge: true,reviewerIds: [],+ reviewerUsers: [],diffRefs: currentRefs,}),listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),@@ -869,6 +872,7 @@ describe("review decisions", () => {checks: [],viewerCanMerge: true,reviewerIds: [],+ reviewerUsers: [],};const providerWith = (getListStates: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getListStates"],diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex ca0e9ffde5a..7a79f437ad6 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -42,7 +42,7 @@ const CAPABILITIES: PullRequestCapabilities = {resolve: true,verdicts: ["comment", "approve", "request-changes"],},- reviewers: { request: true, listCandidates: true },+ reviewers: { request: true, listCandidates: true, searchCandidates: true },labels: true,edit: { changeRequest: true, comment: true, maintainerEdits: true },};@@ -496,6 +496,7 @@ export const make = Effect.gen(function* () {host: input.host,repository: input.repository,number: input.number,+ query: input.query,}).pipe(Effect.mapError(fail("listReviewerCandidates"))),diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex e1115cd6603..6af07442403 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -219,7 +219,10 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {readonly viewerCanDeleteBranch?: boolean;/** Set by the detail read, which asks GraphQL; REST carries no label permission. */readonly viewerCanEditLabels?: boolean;+ /** Every reviewer id, even one without a username to show, since writes replace the set. */readonly reviewerIds: ReadonlyArray<number>;+ /** The candidate list leads with these, since one page of project users need not reach them. */+ readonly reviewerUsers: ReadonlyArray<PullRequestActor & { readonly id: number }>;readonly autoMergeEnabled?: boolean;readonly autoMergeMethod?: PullRequestMergeMethod;/** Absent means not counted, not up to date. */@@ -521,6 +524,10 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabreviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>reviewer.id === undefined ? [] : [reviewer.id],),+ reviewerUsers: (raw.reviewers ?? []).flatMap((reviewer) => {+ const actor = toActor(reviewer);+ return actor === null || reviewer.id === undefined ? [] : [{ ...actor, id: reviewer.id }];+ }),...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),...(autoMerge === true && raw.squash_on_merge === true? { autoMergeMethod: "squash" as const }