TypeScript
feat(pull-requests): PR composers complete #123 and GitLab !123 references (#30857)
Antonye4ff5da0d344
diff --git a/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx b/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsxnew file mode 100644index 00000000000..2d403d68727--- /dev/null+++ b/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx@@ -0,0 +1,105 @@+import { Pressable, ScrollView, StyleSheet, View } from "react-native";++import { AppText as Text } from "../../components/ui/AppText";+import { GlassSurface } from "../../components/ui/GlassSurface";+import { PullRequestAvatar } from "./PullRequestPresentation";+import type { PullRequestCompletion } from "@t3tools/shared/pullRequestComposerTrigger";+import type { usePullRequestCompletions } from "./usePullRequestCompletions";++const COPY = {+ mention: {+ label: "Mention a user",+ pending: "Searching users...",+ failed: "Couldn't search users on the host",+ none: "No matching users",+ },+ reference: {+ label: "Reference an issue or change request",+ pending: "Searching...",+ failed: "Couldn't search the host",+ none: "No matching issues or change requests",+ },+} as const;++const STATE_LABEL = { open: "Open", closed: "Closed", merged: "Merged" } as const;++function CompletionRow({ completion }: { readonly completion: PullRequestCompletion }) {+ if (completion.kind === "mention") {+ const { actor } = completion;+ return (+ <>+ <PullRequestAvatar actor={actor} size={20} />+ <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>+ {actor.login}+ </Text>+ {actor.name && actor.name !== actor.login ? (+ <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>+ {actor.name}+ </Text>+ ) : null}+ </>+ );+ }+ const { candidate } = completion;+ return (+ <>+ <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>+ {candidate.reference}+ </Text>+ <Text className="min-w-0 flex-1 text-sm text-foreground-muted" numberOfLines={1}>+ {candidate.title}+ </Text>+ <Text className="shrink-0 text-xs text-foreground-tertiary">+ {STATE_LABEL[candidate.state]}+ </Text>+ </>+ );+}++/** The `@`, `#` and `!` suggestions for a pull request text input, rendered just above it. */+export function PullRequestCompletionSuggestions({+ completions,+}: {+ readonly completions: ReturnType<typeof usePullRequestCompletions>;+}) {+ if (completions.kind === null) return null;+ const copy = COPY[completions.kind];+ return (+ <GlassSurface+ glassEffectStyle="clear"+ tintColorClassName="accent-glass-surface"+ style={{ borderRadius: 16, overflow: "hidden" }}+ >+ {completions.candidates.length > 0 ? (+ <ScrollView+ className="max-h-[180px]"+ keyboardShouldPersistTaps="always"+ showsVerticalScrollIndicator={false}+ accessibilityLabel={copy.label}+ >+ {completions.candidates.map((completion, index) => (+ <Pressable+ key={completion.token}+ accessibilityRole="button"+ accessibilityLabel={`Insert ${completion.token}`}+ onPress={() => completions.select(completion)}+ className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60"+ style={{+ borderBottomWidth:+ index === completions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth,+ }}+ >+ <CompletionRow completion={completion} />+ </Pressable>+ ))}+ </ScrollView>+ ) : (+ <View className="px-3.5 py-2.5">+ <Text className="text-xs text-foreground-tertiary">+ {copy[completions.isLoading ? "pending" : completions.failed ? "failed" : "none"]}+ </Text>+ </View>+ )}+ </GlassSurface>+ );+}diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsxindex e3ed028b592..9e4231ad65d 100644--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx@@ -26,8 +26,8 @@ import { PullRequestCommentFooter } from "./PullRequestReactions";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";import { usePullRequestPermissions } from "./usePullRequestPermissions";import { pullRequestReviewKey } from "./pullRequestReviewDrafts";-import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";-import { usePullRequestMentions } from "./usePullRequestMentions";+import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";+import { usePullRequestCompletions } from "./usePullRequestCompletions";export function PullRequestDiscussionScreen({route,@@ -57,12 +57,12 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discussconst loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false });const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId);const [body, setBody] = useState("");- const mentions = usePullRequestMentions({+ const completions = usePullRequestCompletions({environmentId: params.environmentId,projectId: params.projectId,value: body,onChangeValue: setBody,- enabled: detail.data?.capabilities.mentions === true,+ support: detail.data?.capabilities ?? null,});const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);const [cursor, setCursor] = useState<string | null | undefined>();@@ -235,7 +235,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discussclassName="absolute inset-x-4 bottom-0 gap-2"style={{ paddingBottom: bottomInset }}>- <PullRequestMentionSuggestions mentions={mentions} />+ <PullRequestCompletionSuggestions completions={completions} /><GlassSurfacechrome="none"onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}@@ -243,9 +243,9 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss><TextInputaccessibilityLabel="Discussion reply"- selection={mentions.selection}- onSelectionChange={mentions.onSelectionChange}- onBlur={mentions.onBlur}+ selection={completions.selection}+ onSelectionChange={completions.onSelectionChange}+ onBlur={completions.onBlur}multilinemaxLength={65536}placeholder="Reply…"diff --git a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsxindex 1d6eb374e54..b12853ad23f 100644--- a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx@@ -16,8 +16,8 @@ import { useAtomCommand } from "../../state/use-atom-command";import { PullRequestSheetContent } from "./PullRequestSheetContent";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";import { usePullRequestPermissions } from "./usePullRequestPermissions";-import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";-import { usePullRequestMentions } from "./usePullRequestMentions";+import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";+import { usePullRequestCompletions } from "./usePullRequestCompletions";export type PullRequestEditParams = PullRequestParams &(@@ -51,12 +51,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd: (pr?.body ?? null);const [draft, setDraft] = useState<string | null>(null);const value = draft ?? original ?? "";- const mentions = usePullRequestMentions({+ const completions = usePullRequestCompletions({environmentId: params.environmentId,projectId: params.projectId,value: value,onChangeValue: setDraft,- enabled: params.field !== "title" && pr?.capabilities.mentions === true,+ support: params.field === "title" ? null : (pr?.capabilities ?? null),});const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -140,12 +140,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd/>}>- <PullRequestMentionSuggestions mentions={mentions} />+ <PullRequestCompletionSuggestions completions={completions} /><TextInputmultiline={params.field !== "title"}- selection={mentions.selection}- onSelectionChange={mentions.onSelectionChange}- onBlur={mentions.onBlur}+ selection={completions.selection}+ onSelectionChange={completions.onSelectionChange}+ onBlur={completions.onBlur}editable={!busy && original !== null}autoFocusaccessibilityLabel={diff --git a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsxindex 68de1a2f2f3..d199fe3990c 100644--- a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx@@ -15,8 +15,8 @@ import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";import { reviewPositionLabel } from "./pullRequestDiffComments";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";import { usePullRequestPermissions } from "./usePullRequestPermissions";-import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";-import { usePullRequestMentions } from "./usePullRequestMentions";+import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";+import { usePullRequestCompletions } from "./usePullRequestCompletions";export type InlineCommentParams = PullRequestParams & {readonly draftId?: string;@@ -35,12 +35,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inliconst body = editedBody ?? saved?.body ?? "";const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params)));const { refresh: refreshDetail } = detail;- const mentions = usePullRequestMentions({+ const completions = usePullRequestCompletions({environmentId: params.environmentId,projectId: params.projectId,value: body,onChangeValue: setBody,- enabled: detail.data?.capabilities.mentions === true,+ support: detail.data?.capabilities ?? null,});useFocusEffect(refreshDetail);const permissions = usePullRequestPermissions(params, detail.data);@@ -110,12 +110,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli{params.code}</Text></View>- <PullRequestMentionSuggestions mentions={mentions} />+ <PullRequestCompletionSuggestions completions={completions} /><TextInputmultiline- selection={mentions.selection}- onSelectionChange={mentions.onSelectionChange}- onBlur={mentions.onBlur}+ selection={completions.selection}+ onSelectionChange={completions.onSelectionChange}+ onBlur={completions.onBlur}editable={store.ready && !busy}autoFocusaccessibilityLabel="Inline review comment"diff --git a/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx b/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsxdeleted file mode 100644index d91dcde9968..00000000000--- a/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { Pressable, ScrollView, StyleSheet, View } from "react-native";--import { AppText as Text } from "../../components/ui/AppText";-import { GlassSurface } from "../../components/ui/GlassSurface";-import { PullRequestAvatar } from "./PullRequestPresentation";-import type { usePullRequestMentions } from "./usePullRequestMentions";--/** The `@` suggestions for a pull request text input, rendered just above it. */-export function PullRequestMentionSuggestions({- mentions,-}: {- readonly mentions: ReturnType<typeof usePullRequestMentions>;-}) {- if (!mentions.open) return null;- return (- <GlassSurface- glassEffectStyle="clear"- tintColorClassName="accent-glass-surface"- style={{ borderRadius: 16, overflow: "hidden" }}- >- {mentions.candidates.length > 0 ? (- <ScrollView- className="max-h-[180px]"- keyboardShouldPersistTaps="always"- showsVerticalScrollIndicator={false}- accessibilityLabel="Mention a user"- >- {mentions.candidates.map((actor, index) => (- <Pressable- key={actor.login}- accessibilityRole="button"- accessibilityLabel={`Mention ${actor.login}`}- onPress={() => mentions.select(actor)}- className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60"- style={{- borderBottomWidth:- index === mentions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth,- }}- >- <PullRequestAvatar actor={actor} size={20} />- <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>- {actor.login}- </Text>- {actor.name && actor.name !== actor.login ? (- <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>- {actor.name}- </Text>- ) : null}- </Pressable>- ))}- </ScrollView>- ) : (- <View className="px-3.5 py-2.5">- <Text className="text-xs text-foreground-tertiary">- {mentions.isLoading- ? "Searching users..."- : mentions.failed- ? "Couldn't search users on the host"- : "No matching users"}- </Text>- </View>- )}- </GlassSurface>- );-}diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsxindex 3b5fa30d181..ab121d0c41e 100644--- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx@@ -19,8 +19,8 @@ import { useAtomCommand } from "../../state/use-atom-command";import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetContent";import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";import { usePullRequestPermissions } from "./usePullRequestPermissions";-import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";-import { usePullRequestMentions } from "./usePullRequestMentions";+import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";+import { usePullRequestCompletions } from "./usePullRequestCompletions";function useActionSubmission(params: PullRequestParams) {const navigation = useNavigation();@@ -83,12 +83,12 @@ export function PullRequestReviewSheet({...draft,...(params.mode === "review" ? { summary: body } : { comment: body }),}));- const mentions = usePullRequestMentions({+ const completions = usePullRequestCompletions({environmentId: params.environmentId,projectId: params.projectId,value: body,onChangeValue: setBody,- enabled: result.data?.capabilities.mentions === true,+ support: result.data?.capabilities ?? null,});const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha);const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");@@ -178,12 +178,12 @@ export function PullRequestReviewSheet({<Text className="px-4 text-xs text-foreground-muted">{reviewing ? "Summary" : "Comment"}</Text>- <PullRequestMentionSuggestions mentions={mentions} />+ <PullRequestCompletionSuggestions completions={completions} /><TextInputmultiline- selection={mentions.selection}- onSelectionChange={mentions.onSelectionChange}- onBlur={mentions.onBlur}+ selection={completions.selection}+ onSelectionChange={completions.onSelectionChange}+ onBlur={completions.onBlur}accessibilityLabel={reviewing ? "Review summary" : "Comment"}placeholder={reviewingdiff --git a/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts b/apps/mobile/src/features/pull-requests/usePullRequestCompletions.tsnew file mode 100644index 00000000000..8f03e5c948f--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts@@ -0,0 +1,82 @@+import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import {+ debouncedPullRequestCompletionSearch,+ detectPullRequestComposerTrigger,+ insertPullRequestCompletion,+ pullRequestCompletionKey,+ pullRequestCompletions,+ type PullRequestCompletion,+ type PullRequestCompletionSupport,+} from "@t3tools/shared/pullRequestComposerTrigger";+import { useState } from "react";+import type { TextInputSelectionChangeEvent } from "react-native";++import { composerPullRequests } from "../../state/pull-requests";+import { useEnvironmentQuery } from "../../state/query";+import { useDebouncedValue } from "../../state/queries";++const COMPLETION_SUGGESTION_LIMIT = 6;++/** Completes `@login`, `#123` and GitLab `!123` in a pull request text input. */+export function usePullRequestCompletions(input: {+ readonly environmentId: string;+ readonly projectId: string;+ readonly value: string;+ readonly onChangeValue: (value: string) => void;+ /** What the pull request's host completes (its `capabilities`); null where the field takes none. */+ readonly support: PullRequestCompletionSupport | null;+}) {+ const [selection, setSelection] = useState<{ start: number; end: number } | null>(null);+ // Set only right after an insertion, so the native input keeps its own caret otherwise.+ const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null);+ const trigger =+ input.support === null || selection === null || selection.start !== selection.end+ ? null+ : detectPullRequestComposerTrigger(input.value, selection.start, input.support);+ const key = pullRequestCompletionKey(trigger);+ const sentKey = useDebouncedValue(key, 250);+ const sent =+ trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey);+ const hosted = useEnvironmentQuery(+ trigger === null+ ? null+ : composerPullRequests.filterOptions({+ environmentId: EnvironmentId.make(input.environmentId),+ input:+ trigger.kind === "mention"+ ? {+ kind: "authors",+ projectId: ProjectId.make(input.projectId),+ ...(sent ? { query: sent } : {}),+ }+ : {+ kind: "references",+ projectId: ProjectId.make(input.projectId),+ sigil: trigger.sigil,+ ...(sent ? { query: sent } : {}),+ },+ }),+ );+ // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.+ const candidates = pullRequestCompletions(trigger, hosted.data, COMPLETION_SUGGESTION_LIMIT);++ return {+ kind: trigger?.kind ?? null,+ candidates,+ isLoading: hosted.isPending || sentKey !== key,+ failed: hosted.error !== null,+ selection: placed ?? undefined,+ onSelectionChange: (event: TextInputSelectionChangeEvent) => {+ setSelection(event.nativeEvent.selection);+ setPlaced(null);+ },+ onBlur: () => setSelection(null),+ select: (completion: PullRequestCompletion) => {+ if (trigger === null) return;+ const next = insertPullRequestCompletion(input.value, trigger, completion.token);+ input.onChangeValue(next.text);+ setSelection({ start: next.cursor, end: next.cursor });+ setPlaced({ start: next.cursor, end: next.cursor });+ },+ };+}diff --git a/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts b/apps/mobile/src/features/pull-requests/usePullRequestMentions.tsdeleted file mode 100644index 8c2a759bef8..00000000000--- a/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts+++ /dev/null@@ -1,73 +0,0 @@-import { EnvironmentId, ProjectId, type PullRequestActor } from "@t3tools/contracts";-import {- detectPullRequestMention,- insertPullRequestMention,- narrowPullRequestMentions,-} from "@t3tools/shared/pullRequestComposerTrigger";-import { useState } from "react";-import type { TextInputSelectionChangeEvent } from "react-native";--import { composerPullRequests } from "../../state/pull-requests";-import { useEnvironmentQuery } from "../../state/query";-import { useDebouncedValue } from "../../state/queries";--const MENTION_SUGGESTION_LIMIT = 6;--/** Completes `@login` in a pull request text input from the repository's users. */-export function usePullRequestMentions(input: {- readonly environmentId: string;- readonly projectId: string;- readonly value: string;- readonly onChangeValue: (value: string) => void;- /** The pull request's host completes mentions (`capabilities.mentions`), and the field takes them. */- readonly enabled: boolean;-}) {- const [selection, setSelection] = useState<{ start: number; end: number } | null>(null);- // Set only right after an insertion, so the native input keeps its own caret otherwise.- const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null);- const trigger =- !input.enabled || selection === null || selection.start !== selection.end- ? null- : detectPullRequestMention(input.value, selection.start);- const typed = trigger?.query ?? "";- const search = typed === "" ? undefined : typed.slice(0, 100);- const sent = useDebouncedValue(search, 250);- const hosted = useEnvironmentQuery(- trigger === null- ? null- : composerPullRequests.filterOptions({- environmentId: EnvironmentId.make(input.environmentId),- input: {- kind: "authors",- projectId: ProjectId.make(input.projectId),- ...(sent ? { query: sent } : {}),- },- }),- );- // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.- const candidates = narrowPullRequestMentions(- hosted.data?.authors ?? [],- typed,- MENTION_SUGGESTION_LIMIT,- );-- return {- open: trigger !== null,- candidates,- isLoading: hosted.isPending || sent !== search,- failed: hosted.error !== null,- selection: placed ?? undefined,- onSelectionChange: (event: TextInputSelectionChangeEvent) => {- setSelection(event.nativeEvent.selection);- setPlaced(null);- },- onBlur: () => setSelection(null),- select: (actor: PullRequestActor) => {- if (trigger === null) return;- const next = insertPullRequestMention(input.value, trigger, actor.login);- input.onChangeValue(next.text);- setSelection({ start: next.cursor, end: next.cursor });- setPlaced({ start: next.cursor, end: next.cursor });- },- };-}diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 7a43394c2a2..e559bc84dd9 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -1067,6 +1067,50 @@ it.effect("puts the author a query names exactly ahead of those it only begins",}),);+it.effect("ranks references by number, keeping the host's recent-first order", () =>+ Effect.gen(function* () {+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),+ project({ id: "p2", title: "tree", workspaceRoot: "/b", repository: "pingdotgg/t3code" }),+ ],+ providers: [+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {+ searchRepositoryReferences: () =>+ Effect.succeed({+ items: [+ { reference: "#129", kind: "issue", number: 129, title: "Newest", state: "open" },+ {+ reference: "#7",+ kind: "issue",+ number: 7,+ title: "Fix #12 again",+ state: "open",+ },+ {+ reference: "#12",+ kind: "change-request",+ number: 12,+ title: "Exact",+ state: "merged",+ },+ { reference: "#120", kind: "issue", number: 120, title: "Older", state: "closed" },+ ],+ truncated: false,+ }),+ }),+ ],+ });++ const result = yield* service.filterOptions({ kind: "references", query: "12" });++ assert.deepStrictEqual(+ result.references.map((candidate) => candidate.reference),+ ["#12", "#129", "#120", "#7"],+ );+ }),+);+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 6600f6810bc..80d6d101336 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -47,6 +47,7 @@ import {type PullRequestFilterOptions,type PullRequestFilterOptionsInput,type PullRequestActor,+ type PullRequestReferenceCandidate,type PullRequestLabel,type PullRequestListStatsResult,type PullRequestProviderSummary,@@ -622,6 +623,14 @@ function withRateLimitBackoff(api.searchRepositoryAuthors,),}),+ ...(api.searchRepositoryReferences === undefined+ ? {}+ : {+ searchRepositoryReferences: interactive(+ "searchRepositoryReferences",+ api.searchRepositoryReferences,+ ),+ }),replyToThread: interactive("replyToThread", api.replyToThread),setReaction: interactive("setReaction", api.setReaction),setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),@@ -643,6 +652,8 @@ function rankFilterOptions<A>(readonly query: string | undefined;readonly keyOf: (item: A) => string;readonly textsOf: (item: A) => ReadonlyArray<string | null>;+ /** Ties keep the hosts' order instead of sorting by key. */+ readonly hostOrder?: boolean;},): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {const query = input.query?.trim().toLowerCase() ?? "";@@ -669,7 +680,9 @@ function rankFilterOptions<A>(.toSorted((left, right) =>left.score - right.score ||- left.key.localeCompare(right.key, undefined, { sensitivity: "base" }),+ (input.hostOrder === true+ ? 0+ : left.key.localeCompare(right.key, undefined, { sensitivity: "base" })),);return {items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),@@ -2578,7 +2591,19 @@ export const make = Effect.gen(function* () {keyOf: (label) => label.name,textsOf: (label) => [label.name],});- return { labels: items, authors: [], truncated };+ return { labels: items, authors: [], references: [], truncated };+ }+ if (input.kind === "references") {+ const pages = yield* gather<PullRequestReferenceCandidate>((project) =>+ project.api.searchRepositoryReferences?.({ ...refOf(project), sigil: input.sigil }),+ );+ const { items, truncated } = rankFilterOptions(pages, {+ query: input.query,+ keyOf: (candidate) => candidate.reference,+ textsOf: (candidate) => [String(candidate.number), candidate.title],+ hostOrder: true,+ });+ return { labels: [], authors: [], references: items, truncated };}const pages = yield* gather<PullRequestActor>((project) =>project.api.searchRepositoryAuthors?.(refOf(project)),@@ -2588,7 +2613,7 @@ export const make = Effect.gen(function* () {keyOf: (author) => author.login,textsOf: (author) => [author.login, author.name],});- return { labels: [], authors: items, truncated };+ return { labels: [], authors: items, references: [], truncated };});const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) =>diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.tsxindex f012daf098d..1c7b6eb5273 100644--- a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx+++ b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx@@ -5,7 +5,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react";import { Button } from "~/components/ui/button";import {PullRequestMarkdownTextarea,- type PullRequestMentionScope,+ type PullRequestCompletionScope,} from "~/components/pullRequest/PullRequestMarkdownTextarea";import {SpeechTextField,@@ -41,7 +41,7 @@ interface DiffCommentAnnotationProps {secondaryAction?: DiffCommentSecondaryAction;focusOnMount?: boolean;/** Set only for pull request comments, where `@` completes the repository's users. */- mentionScope?: PullRequestMentionScope | null;+ completionScope?: PullRequestCompletionScope | null;}export function DiffCommentAnnotation({@@ -60,7 +60,7 @@ export function DiffCommentAnnotation({pending = false,secondaryAction,focusOnMount = true,- mentionScope = null,+ completionScope = null,}: DiffCommentAnnotationProps) {const [localDraftText, setLocalDraftText] = useState("");const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;@@ -129,7 +129,7 @@ export function DiffCommentAnnotation({><PullRequestMarkdownTextarearef={textareaRef}- mentionScope={mentionScope}+ completionScope={completionScope}readOnly={speech?.freezesEditor}autoFocus={focusOnMount}size="sm"diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 72482811543..a456c84bf53 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -113,7 +113,7 @@ import {ReviewThreadCard,toViewerSide,} from "./PullRequestReviewAnnotation";-import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";+import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";import {getFileViewedRange,isFileDiffCollapsed,@@ -558,7 +558,7 @@ function PullRequestCodeTab({commit,cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,});- const mentionScope = pullRequestMentionScope(detail, environmentId, reference);+ const completionScope = pullRequestCompletionScope(detail, environmentId, reference);const hostReview = detail.capabilities.review;const review = {inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,@@ -969,7 +969,7 @@ function PullRequestCodeTab({canReact={detail.capabilities.reactions === true}environmentId={environmentId}reference={reference}- mentionScope={mentionScope}+ completionScope={completionScope}pending={threadPending}fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}fixLabel={fixFindingLabel}@@ -1044,7 +1044,7 @@ function PullRequestCodeTab({kind="draft"rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}text=""- mentionScope={canCommentOnLines ? mentionScope : null}+ completionScope={canCommentOnLines ? completionScope : null}submitLabel={canCommentOnLines ? "Add to review" : "Add to agent"}{...(canCommentOnLines && onAddToAgentSelection? {diff --git a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsxindex f108ddd918f..f7aa2ece22a 100644--- a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx@@ -12,7 +12,7 @@ import { toastManager } from "../ui/toast";import { PullRequestGlyph } from "./pullRequestIcons";import {PullRequestMarkdownTextarea,- pullRequestMentionScope,+ pullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";import { pullRequestReviewKey } from "./pullRequestReviewStore";import { useInlineActionConfirm } from "./useInlineActionConfirm";@@ -113,7 +113,7 @@ export function PullRequestCommentForm({<div className="space-y-2"><PullRequestMarkdownTextarearef={textareaRef}- mentionScope={pullRequestMentionScope(detail, environmentId, reference)}+ completionScope={pullRequestCompletionScope(detail, environmentId, reference)}// Lock while posting because success clears the draft.disabled={locked}readOnly={speech.freezesEditor}diff --git a/apps/web/src/components/pullRequest/PullRequestComposer.tsx b/apps/web/src/components/pullRequest/PullRequestComposer.tsxindex 0c9f8f95e30..f954c2b262d 100644--- a/apps/web/src/components/pullRequest/PullRequestComposer.tsx+++ b/apps/web/src/components/pullRequest/PullRequestComposer.tsx@@ -16,7 +16,7 @@ import {usePendingReviewComments,usePullRequestReviewStore,} from "./pullRequestReviewStore";-import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";+import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";export function PullRequestComposer({environmentId,@@ -155,7 +155,7 @@ export function PullRequestComposer({active={open && mode === "review"}environmentId={environmentId}reference={reference}- mentionScope={pullRequestMentionScope(detail, environmentId, reference)}+ completionScope={pullRequestCompletionScope(detail, environmentId, reference)}term={term}verdicts={verdicts}requestChangesSummaryRequired={sourceControlClientsdiff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex a517cf1ce7c..9d0f6193f7e 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -66,7 +66,7 @@ import { useLiveRefresh } from "~/hooks/useLiveRefresh";import { pullRequestEnvironment, usePullRequestTurnRefresh } from "~/state/pullRequests";import { useAtomCommand } from "~/state/use-atom-command";import { PullRequestStackMenu } from "./PullRequestStackMenu";-import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";+import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";import {capitalizeTerm,@@ -1779,7 +1779,7 @@ export function PullRequestDetailPanel({detail.capabilities.review.inlineComment && detail.viewerPermissions.comment}rangeComments={detail.capabilities.review.rangeComment === true}- mentionScope={pullRequestMentionScope(detail, environmentId, reference)}+ completionScope={pullRequestCompletionScope(detail, environmentId, reference)}onAskAboutLines={(comment, request) =>addSelectionToAgent({ comment, request }, { keepGuide: true })}diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsxindex d1a1a249d78..127e4b4cc9c 100644--- a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx@@ -55,7 +55,7 @@ it("keeps Try again inside a short panel when a failed guide has long diagnosticactivecanComment={false}rangeComments={false}- mentionScope={null}+ completionScope={null}onAskAboutLines={null}onAskAboutStop={null}onFinishReview={null}diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsxindex 8952c785a96..fda10783728 100644--- a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx@@ -17,7 +17,7 @@ import {usePendingReviewComments,usePullRequestReviewStore,} from "./pullRequestReviewStore";-import type { PullRequestMentionScope } from "./PullRequestMarkdownTextarea";+import type { PullRequestCompletionScope } from "./PullRequestMarkdownTextarea";export function PullRequestGuideTab({environmentId,@@ -27,7 +27,7 @@ export function PullRequestGuideTab({active,canComment,rangeComments,- mentionScope,+ completionScope,onAskAboutLines,onAskAboutStop,onFinishReview,@@ -41,7 +41,7 @@ export function PullRequestGuideTab({active: boolean;canComment: boolean;rangeComments: boolean;- mentionScope: PullRequestMentionScope | null;+ completionScope: PullRequestCompletionScope | null;onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null;onAskAboutStop:| ((stop: PullRequestReviewGuideStop, index: number, question: string) => void)@@ -65,7 +65,7 @@ export function PullRequestGuideTab({: {canComment,rangeComments,- mentionScope,+ completionScope,pending,onComment: ({ path, oldPath, position, startPosition, body }) =>addComment(reviewKey, {diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsxindex 31dfb68338d..1f946c684f6 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx@@ -37,6 +37,13 @@ vi.mock(import("~/state/pullRequests"), async (original) => ({{ login: "julius", name: "Julius", avatarUrl: null },{ login: "theo", name: "Theo", avatarUrl: null },],+ references:+ targets.length === 0+ ? []+ : [+ { reference: "#12", kind: "issue", number: 12, title: "Crash", state: "open" },+ { reference: "!12", kind: "change-request", number: 12, title: "Fix", state: "open" },+ ],error: null,isPending: false,}),@@ -61,7 +68,11 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {value={options?.value ?? "Original description"}cwd="/repo"environmentId={secondary}- mentionScope={{ environmentId: secondary, projectId: ProjectId.make("project") }}+ completionScope={{+ environmentId: secondary,+ projectId: ProjectId.make("project"),+ support: { mentions: true, referenceSigils: ["#", "!"] },+ }}label="Pull request description"saving={false}allowEmpty={options?.allowEmpty ?? false}@@ -106,7 +117,7 @@ it("keeps an edited draft through revocation and saves it after access returns wexpect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");});-it("completes an @mention on Enter and closes the list on Escape until the next keystroke", async () => {+it("completes @mentions and !references on Enter, and Escape closes the list until the next keystroke", async () => {setup();permissions.allowed.add(secondary);await using screen = await openEditor({ value: "" });@@ -122,9 +133,13 @@ it("completes an @mention on Enter and closes the list on Escape until the nextawait expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();await userEvent.keyboard("{Escape}");await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();- expect(onCancel).not.toHaveBeenCalled();-await userEvent.type(textarea, "t");await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();++ await userEvent.type(textarea, " fixes !1");+ await expect.element(page.getByRole("option", { name: /Fix/ })).toBeVisible();+ await userEvent.keyboard("{Enter}");+ expect(textarea.value).toBe("Thanks @julius and @t fixes !12 ");+ expect(onCancel).not.toHaveBeenCalled();expect(onSave).not.toHaveBeenCalled();});diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsxindex aeb834ae312..2ff293f9571 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx@@ -13,14 +13,14 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";import { PullRequestMarkdown } from "./PullRequestMarkdown";import {PullRequestMarkdownTextarea,- type PullRequestMentionScope,+ type PullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";export function PullRequestMarkdownEditor({value,cwd,environmentId,- mentionScope,+ completionScope,threadRef = null,placeholder,label,@@ -33,7 +33,7 @@ export function PullRequestMarkdownEditor({readonly value: string;readonly cwd: string;readonly environmentId: EnvironmentId;- readonly mentionScope: PullRequestMentionScope | null;+ readonly completionScope: PullRequestCompletionScope | null;readonly threadRef?: ScopedThreadRef | null;readonly placeholder?: string | undefined;readonly label: string;@@ -110,7 +110,7 @@ export function PullRequestMarkdownEditor({<PullRequestMarkdownTextareaautoFocusdisabled={saving}- mentionScope={mentionScope}+ completionScope={completionScope}value={draft}rows={6}placeholder={placeholder}diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsxindex 3029059f229..7f48eeefad3 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx@@ -1,15 +1,21 @@import type {EnvironmentId,ProjectId,- PullRequestActor,PullRequestDetailView,PullRequestRef,+ PullRequestReferenceCandidate,} from "@t3tools/contracts";import {- detectPullRequestMention,- insertPullRequestMention,- narrowPullRequestMentions,+ debouncedPullRequestCompletionSearch,+ detectPullRequestComposerTrigger,+ insertPullRequestCompletion,+ pullRequestCompletionKey,+ pullRequestCompletions,+ type PullRequestCompletion,+ type PullRequestCompletionSupport,+ type PullRequestComposerTrigger,} from "@t3tools/shared/pullRequestComposerTrigger";+import { CircleCheckIcon, CircleDotIcon } from "lucide-react";import { useId, useState, type Ref } from "react";import { flushSync } from "react-dom";@@ -19,27 +25,27 @@ import { useDebouncedValue } from "~/state/queries";import { Popover, PopoverPopup } from "../ui/popover";import { Textarea, type TextareaProps } from "../ui/textarea";-import { PullRequestActorAvatar } from "./pullRequestPresentation";+import { PULL_REQUEST_STATE_PRESENTATION } from "./pullRequestIcons";+import { PullRequestActorAvatar, resolvePullRequestState } from "./pullRequestPresentation";-/** The repository whose users an `@` completes. */-export interface PullRequestMentionScope {+/** The repository whose users `@` completes and whose issues and change requests `#` does. */+export interface PullRequestCompletionScope {readonly environmentId: EnvironmentId;readonly projectId: ProjectId;+ readonly support: PullRequestCompletionSupport;}-/** Null on hosts that cannot search their users, so `@` never opens a list that cannot fill. */-export function pullRequestMentionScope(+/** Null on hosts that complete nothing, so no sigil opens a list that cannot fill. */+export function pullRequestCompletionScope(detail: Pick<PullRequestDetailView, "capabilities">,environmentId: EnvironmentId,reference: PullRequestRef,-): PullRequestMentionScope | null {- return detail.capabilities.mentions === true- ? { environmentId, projectId: reference.projectId }+): PullRequestCompletionScope | null {+ const { mentions, referenceSigils } = detail.capabilities;+ return mentions === true || (referenceSigils?.length ?? 0) > 0+ ? { environmentId, projectId: reference.projectId, support: { mentions, referenceSigils } }: null;}--const MENTION_SEARCH_DEBOUNCE_MS = 200;-const MENTION_SUGGESTION_LIMIT = 8;// About a full list of suggestions. The popup fits itself to the space it opens into, so it never// flips once results grow it; the side is picked up front from the room a full list needs.const SUGGESTION_LIST_HEIGHT = 320;@@ -50,43 +56,117 @@ function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" {return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom";}-function useMentionCandidates(scope: PullRequestMentionScope | null, query: string | null) {- const typed = query ?? "";- const search = typed === "" ? undefined : typed.slice(0, 100);- const sent = useDebouncedValue(search, MENTION_SEARCH_DEBOUNCE_MS);+const COMPLETION_SEARCH_DEBOUNCE_MS = 200;+const COMPLETION_SUGGESTION_LIMIT = 8;++function useCompletions(+ scope: PullRequestCompletionScope | null,+ trigger: PullRequestComposerTrigger | null,+) {+ const key = pullRequestCompletionKey(trigger);+ const sentKey = useDebouncedValue(key, COMPLETION_SEARCH_DEBOUNCE_MS);+ const sent =+ trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey);const hosted = usePullRequestFilterOptions(- scope === null || query === null+ scope === null || trigger === null? []: [{environmentId: scope.environmentId,- input: {- kind: "authors",- projectId: scope.projectId,- ...(sent ? { query: sent } : {}),- },+ input:+ trigger.kind === "mention"+ ? { kind: "authors", projectId: scope.projectId, ...(sent ? { query: sent } : {}) }+ : {+ kind: "references",+ projectId: scope.projectId,+ sigil: trigger.sigil,+ ...(sent ? { query: sent } : {}),+ },},],);// Older answers stay useful while the debounced search catches up, narrowed to what is typed now.+ const completions = pullRequestCompletions(trigger, hosted, COMPLETION_SUGGESTION_LIMIT);return {- candidates: narrowPullRequestMentions(hosted.authors, typed, MENTION_SUGGESTION_LIMIT),- isPending: hosted.isPending || sent !== search,+ completions,+ isPending: hosted.isPending || sentKey !== key,failed: hosted.error !== null,};}+function ReferenceStateIcon({ candidate }: { candidate: PullRequestReferenceCandidate }) {+ const presentation =+ candidate.kind === "change-request"+ ? resolvePullRequestState({ state: candidate.state, isDraft: false })+ : candidate.state === "open"+ ? {+ label: "Open issue",+ Icon: CircleDotIcon,+ toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName,+ }+ : {+ label: "Closed issue",+ Icon: CircleCheckIcon,+ toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName,+ };+ return (+ <presentation.Icon+ role="img"+ aria-label={presentation.label}+ className={cn("size-4 shrink-0", presentation.toneClassName)}+ />+ );+}++function CompletionRow({ completion }: { completion: PullRequestCompletion }) {+ if (completion.kind === "mention") {+ const { actor } = completion;+ return (+ <>+ <PullRequestActorAvatar actor={actor} className="size-5" />+ <span className="truncate font-medium">{actor.login}</span>+ {actor.name && actor.name !== actor.login ? (+ <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>+ ) : null}+ </>+ );+ }+ const { candidate } = completion;+ return (+ <>+ <ReferenceStateIcon candidate={candidate} />+ <span className="shrink-0 font-medium tabular-nums">{candidate.reference}</span>+ <span className="min-w-0 truncate text-muted-foreground">{candidate.title}</span>+ </>+ );+}++const EMPTY_STATE = {+ mention: {+ label: "Mention a user",+ pending: "Searching users...",+ failed: "Couldn't search users on the host",+ none: "No matching users",+ },+ reference: {+ label: "Reference an issue or change request",+ pending: "Searching...",+ failed: "Couldn't search the host",+ none: "No matching issues or change requests",+ },+} as const;+function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {if (typeof ref === "function") ref(value);else if (ref) ref.current = value;}-/** A markdown textarea for pull request text that completes `@login` from the repository's users. */+/** A markdown textarea for pull request text that completes `@login`, `#123` and GitLab `!123`. */export function PullRequestMarkdownTextarea({ref,value,onValueChange,- mentionScope,+ completionScope,onKeyDown,onSelect,onFocus,@@ -95,7 +175,7 @@ export function PullRequestMarkdownTextarea({}: Omit<TextareaProps, "value" | "onChange"> & {readonly value: string;readonly onValueChange: (value: string) => void;- readonly mentionScope: PullRequestMentionScope | null;+ readonly completionScope: PullRequestCompletionScope | null;}) {const listId = useId();const [element, setElement] = useState<HTMLTextAreaElement | null>(null);@@ -105,29 +185,30 @@ export function PullRequestMarkdownTextarea({const [highlight, setHighlight] = useState({ query: "", index: 0 });const trigger =- mentionScope === null || caret === null || props.readOnly+ completionScope === null || caret === null || props.readOnly? null- : detectPullRequestMention(value, caret);+ : detectPullRequestComposerTrigger(value, caret, completionScope.support);const open = trigger !== null && trigger.rangeStart !== dismissedAt;- const { candidates, isPending, failed } = useMentionCandidates(- mentionScope,- open ? trigger.query : null,- );+ const {+ completions: candidates,+ isPending,+ failed,+ } = useCompletions(completionScope, open ? trigger : null);const activeIndex =trigger !== null && highlight.query === trigger.query? Math.min(highlight.index, Math.max(0, candidates.length - 1)): 0;const active = open ? candidates[activeIndex] : undefined;- const optionId = (login: string) => `${listId}-${login}`;+ const optionId = (token: string) => `${listId}-${token}`;const syncCaret = (target: HTMLTextAreaElement) => {setSide(suggestionSide(target));setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null);};- const select = (actor: PullRequestActor) => {+ const select = (completion: PullRequestCompletion) => {if (trigger === null || element === null) return;- const next = insertPullRequestMention(value, trigger, actor.login);+ const next = insertPullRequestCompletion(value, trigger, completion.token);flushSync(() => onValueChange(next.text));element.setSelectionRange(next.cursor, next.cursor);setCaret(next.cursor);@@ -142,11 +223,11 @@ export function PullRequestMarkdownTextarea({assignRef(ref, node);}}value={value}- role={mentionScope === null ? undefined : "combobox"}- aria-autocomplete={mentionScope === null ? undefined : "list"}- aria-expanded={mentionScope === null ? undefined : open}+ role={completionScope === null ? undefined : "combobox"}+ aria-autocomplete={completionScope === null ? undefined : "list"}+ aria-expanded={completionScope === null ? undefined : open}aria-controls={open && candidates.length > 0 ? listId : undefined}- aria-activedescendant={active ? optionId(active.login) : undefined}+ aria-activedescendant={active ? optionId(active.token) : undefined}onChange={(event) => {onValueChange(event.target.value);syncCaret(event.target);@@ -210,16 +291,21 @@ export function PullRequestMarkdownTextarea({side={side}align="start"padding="compact"- width="sm"+ width={trigger?.kind === "reference" ? "md" : "sm"}initialFocus={false}finalFocus={false}>{candidates.length > 0 ? (- <div id={listId} role="listbox" aria-label="Mention a user" className="-mx-1.5">- {candidates.map((actor, index) => (+ <div+ id={listId}+ role="listbox"+ aria-label={EMPTY_STATE[trigger?.kind ?? "mention"].label}+ className="-mx-1.5"+ >+ {candidates.map((completion, index) => (<div- key={actor.login}- id={optionId(actor.login)}+ key={completion.token}+ id={optionId(completion.token)}role="option"aria-selected={index === activeIndex}className={cn(@@ -231,23 +317,19 @@ export function PullRequestMarkdownTextarea({}}// Keeps focus, and the caret, in the textarea.onMouseDown={(event) => event.preventDefault()}- onClick={() => select(actor)}+ onClick={() => select(completion)}>- <PullRequestActorAvatar actor={actor} className="size-5" />- <span className="truncate font-medium">{actor.login}</span>- {actor.name && actor.name !== actor.login ? (- <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>- ) : null}+ <CompletionRow completion={completion} /></div>))}</div>) : (<p className="px-1 text-xs text-muted-foreground">- {isPending- ? "Searching users..."- : failed- ? "Couldn't search users on the host"- : "No matching users"}+ {+ EMPTY_STATE[trigger?.kind ?? "mention"][+ isPending ? "pending" : failed ? "failed" : "none"+ ]+ }</p>)}</PopoverPopup>diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsxindex 2fe3f96431b..d2ae440fde9 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx@@ -32,7 +32,7 @@ import { PullRequestReactionBar } from "./PullRequestReactions";import type { PendingReviewComment } from "./pullRequestReviewStore";import {PullRequestMarkdownTextarea,- type PullRequestMentionScope,+ type PullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";const CARD_CLASS =@@ -117,7 +117,7 @@ export function ReviewThreadCard({canReact,environmentId,reference,- mentionScope,+ completionScope,pending,fixPending,fixLabel = "Fix in a thread",@@ -137,7 +137,7 @@ export function ReviewThreadCard({canReact: boolean;environmentId: EnvironmentId;reference: PullRequestRef;- mentionScope: PullRequestMentionScope | null;+ completionScope: PullRequestCompletionScope | null;pending: boolean;fixPending?: boolean;fixLabel?: string;@@ -310,7 +310,7 @@ export function ReviewThreadCard({value={comment.body}cwd={workspaceRoot}environmentId={environmentId}- mentionScope={mentionScope}+ completionScope={completionScope}label="Edit comment"saving={savingEdit}onSave={(body) => void saveEdit(comment.id, body)}@@ -366,7 +366,7 @@ export function ReviewThreadCard({readOnly={speech.freezesEditor}autoFocussize="sm"- mentionScope={mentionScope}+ completionScope={completionScope}value={reply}placeholder="Reply"aria-label="Reply to this conversation"diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsxindex 23c82d5c38d..eae69143d31 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx@@ -37,7 +37,7 @@ it("submits only the line comments still in the draft when dictation finishes",activeenvironmentId={EnvironmentId.make("test")}reference={reference}- mentionScope={null}+ completionScope={null}term="pull request"verdicts={["comment"]}requestChangesSummaryRequired={false}diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsxindex edf718d8489..5308c632089 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx@@ -20,7 +20,7 @@ import {} from "./pullRequestReviewStore";import {PullRequestMarkdownTextarea,- type PullRequestMentionScope,+ type PullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";const VERDICTS: ReadonlyArray<{@@ -53,7 +53,7 @@ export function PullRequestReviewForm({environmentId,active,reference,- mentionScope,+ completionScope,term,verdicts,requestChangesSummaryRequired,@@ -66,7 +66,7 @@ export function PullRequestReviewForm({/** False while the form stays mounted but hidden; dictation is cancelled then. */active: boolean;reference: PullRequestRef;- mentionScope: PullRequestMentionScope | null;+ completionScope: PullRequestCompletionScope | null;/** The host's word for a change request, as in "pull request". */term: string;verdicts: ReadonlyArray<PullRequestReviewVerdict>;@@ -157,7 +157,7 @@ export function PullRequestReviewForm({<><PullRequestMarkdownTextarearef={textareaRef}- mentionScope={mentionScope}+ completionScope={completionScope}rows={3}readOnly={speech.freezesEditor}value={body}diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsxindex 03e014a47a0..89434eca594 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx@@ -87,8 +87,8 @@ import { PullRequestCommentBody } from "./PullRequestCommentBody";import { PullRequestMoreReplies } from "./PullRequestMoreReplies";import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";import {- type PullRequestMentionScope,- pullRequestMentionScope,+ type PullRequestCompletionScope,+ pullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";import { PullRequestReactionBar } from "./PullRequestReactions";import { PullRequestConversationGhost } from "./PullRequestGhosts";@@ -169,7 +169,7 @@ function reviewStateLabel(state: string): string {interface CommentEditing {readonly cwd: string;readonly environmentId: EnvironmentId;- readonly mentionScope: PullRequestMentionScope | null;+ readonly completionScope: PullRequestCompletionScope | null;readonly threadRef: ScopedThreadRef | null;readonly canEdit: (comment: PullRequestComment) => boolean;readonly editingId: string | null;@@ -194,7 +194,7 @@ function CommentBody({value={comment.body}cwd={editing.cwd}environmentId={editing.environmentId}- mentionScope={editing.mentionScope}+ completionScope={editing.completionScope}threadRef={editing.threadRef}label="Edit comment"saving={editing.saving}@@ -584,11 +584,11 @@ export function PullRequestSummaryTab({if (body !== description) void saveDescription(body);};- const mentionScope = pullRequestMentionScope(detail, environmentId, reference);+ const completionScope = pullRequestCompletionScope(detail, environmentId, reference);const commentEditing: CommentEditing = {cwd: detail.workspaceRoot,environmentId,- mentionScope,+ completionScope,threadRef,canEdit: (comment) => canEditPullRequestComment(detail, comment),editingId: editingCommentId,@@ -845,7 +845,7 @@ export function PullRequestSummaryTab({value={bodyScope.body}cwd={detail.workspaceRoot}environmentId={environmentId}- mentionScope={mentionScope}+ completionScope={completionScope}threadRef={threadRef}label={`${capitalizeTerm(terminology.singular)} description`}placeholder={`Describe this ${terminology.singular}`}diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsxindex 60357c75712..36dca98e231 100644--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx@@ -60,8 +60,8 @@ import {} from "./pullRequestPresentation";import { PullRequestGlyph } from "./pullRequestIcons";import {- type PullRequestMentionScope,- pullRequestMentionScope,+ type PullRequestCompletionScope,+ pullRequestCompletionScope,} from "./PullRequestMarkdownTextarea";import { LegendList, type LegendListRef } from "@legendapp/list/react";@@ -72,7 +72,7 @@ interface ReactionSurface {readonly environmentId: EnvironmentId;readonly threadRef: ScopedThreadRef | null;readonly reference: PullRequestRef;- readonly mentionScope: PullRequestMentionScope | null;+ readonly completionScope: PullRequestCompletionScope | null;readonly onRefresh: () => void;}@@ -306,7 +306,7 @@ function ConversationCard({value={editable.body}cwd={cwd}environmentId={reactions.environmentId}- mentionScope={reactions.mentionScope}+ completionScope={reactions.completionScope}threadRef={reactions.threadRef}label="Edit comment"saving={saving}@@ -704,7 +704,7 @@ export function PullRequestTimelineTab({environmentId,threadRef,reference,- mentionScope: pullRequestMentionScope(detail, environmentId, reference),+ completionScope: pullRequestCompletionScope(detail, environmentId, reference),onRefresh,};const editable = new Map(diff --git a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsxindex e419a165002..cf1c248a3c5 100644--- a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx+++ b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx@@ -37,7 +37,7 @@ import {fileDiffRows,rowsToPatch,} from "@t3tools/client-runtime/review-guide-tour";-import type { PullRequestMentionScope } from "../PullRequestMarkdownTextarea";+import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea";import { GuideNoteMarker } from "./GuideNotes";import { GuideProse } from "./GuideProse";@@ -56,7 +56,7 @@ export interface ExcerptCommenting {readonly canComment: boolean;/** The host anchors a comment to a range of lines rather than to its last one. */readonly rangeComments: boolean;- readonly mentionScope: PullRequestMentionScope | null;+ readonly completionScope: PullRequestCompletionScope | null;readonly pending: ReadonlyArray<PendingReviewComment>;readonly onComment: (comment: {readonly path: string;@@ -325,7 +325,7 @@ function ExcerptDiff({kind="draft"rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}text=""- mentionScope={commenting.canComment ? commenting.mentionScope : null}+ completionScope={commenting.canComment ? commenting.completionScope : null}placeholder={commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"}diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.tsindex c8ac23ced05..914b6e6c720 100644--- a/apps/web/src/state/pullRequests.ts+++ b/apps/web/src/state/pullRequests.ts@@ -647,6 +647,7 @@ export function usePullRequestFilterOptions(return {labels: query.values.flatMap(([, options]) => options.labels),authors: query.values.flatMap(([, options]) => options.authors),+ references: query.values.flatMap(([, options]) => options.references),error: query.error,isPending: query.isPending,};diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex e96d1f3dfdb..5dbec3e2dd3 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -257,6 +257,10 @@ export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabiliexport const PullRequestViewedFilesStore = Schema.Literals(["host", "environment"]);export type PullRequestViewedFilesStore = typeof PullRequestViewedFilesStore.Type;+/** `#` references issues (and GitHub pull requests); `!` references GitLab merge requests. */+export const PullRequestReferenceSigil = Schema.Literals(["#", "!"]);+export type PullRequestReferenceSigil = typeof PullRequestReferenceSigil.Type;+export const PullRequestCapabilities = Schema.Struct({diff: Schema.Boolean,comment: Schema.Boolean,@@ -279,6 +283,8 @@ export const PullRequestCapabilities = Schema.Struct({labels: Schema.optional(Schema.Boolean),/** The host searches the repository's users, so composers can complete `@login`. */mentions: Schema.optional(Schema.Boolean),+ /** The sigils whose issue and change request references composers can complete. */+ referenceSigils: Schema.optional(ForwardCompatibleArray(PullRequestReferenceSigil)),/*** Every head gets at least one check, so a head that has gone a while without any means none* reported rather than that the repository runs none. Absent means an empty list says nothing.@@ -523,7 +529,7 @@ export const PullRequestListStatsResult = Schema.Struct({});export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;-export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors"]);+export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors", "references"]);export type PullRequestFilterOptionKind = typeof PullRequestFilterOptionKind.Type;/** Scoped like `PullRequestListInput`, so the options come from the repositories it lists. */@@ -533,12 +539,28 @@ export const PullRequestFilterOptionsInput = Schema.Struct({projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),host: Schema.optional(TrimmedNonEmptyString),query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),+ /** For `references`, the sigil typed, so a host can search only what it links. */+ sigil: Schema.optional(PullRequestReferenceSigil),});export type PullRequestFilterOptionsInput = typeof PullRequestFilterOptionsInput.Type;+/** An issue or change request a composer can reference, with the text the host links. */+export const PullRequestReferenceCandidate = Schema.Struct({+ reference: TrimmedNonEmptyString,+ kind: Schema.Literals(["issue", "change-request"]),+ number: PositiveInt,+ title: Schema.String,+ state: Schema.Literals(["open", "closed", "merged"]),+});+export type PullRequestReferenceCandidate = typeof PullRequestReferenceCandidate.Type;+export const PullRequestFilterOptions = Schema.Struct({labels: Schema.Array(PullRequestLabel),authors: Schema.Array(PullRequestActor),+ // Servers from before reference completion send no key.+ references: Schema.Array(PullRequestReferenceCandidate).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),truncated: Schema.Boolean,});export type PullRequestFilterOptions = typeof PullRequestFilterOptions.Type;diff --git a/packages/shared/src/pullRequestComposerTrigger.test.ts b/packages/shared/src/pullRequestComposerTrigger.test.tsindex 0aa786a581a..c17beab3a12 100644--- a/packages/shared/src/pullRequestComposerTrigger.test.ts+++ b/packages/shared/src/pullRequestComposerTrigger.test.ts@@ -1,20 +1,30 @@import { describe, expect, it } from "vite-plus/test";import {- detectPullRequestMention,- insertPullRequestMention,+ debouncedPullRequestCompletionSearch,+ detectPullRequestComposerTrigger,+ insertPullRequestCompletion,narrowPullRequestMentions,+ narrowPullRequestReferences,} from "./pullRequestComposerTrigger.ts";-describe("detectPullRequestMention", () => {+const GITLAB = { mentions: true, referenceSigils: ["#", "!"] } as const;++describe("detectPullRequestComposerTrigger", () => {it.each([- ["@", 0, ""],- ["cc @ju", 3, "ju"],- ["line one\[email protected]", 9, "first.last"],- ["@jane-doe more", 0, "jane-doe"],- ])("finds the mention in %j", (text, rangeStart, query) => {+ ["@", 0, "@", ""],+ ["cc @ju", 3, "@", "ju"],+ ["line one\[email protected]", 9, "@", "first.last"],+ ["@jane-doe more", 0, "@", "jane-doe"],+ ["fixes #", 6, "#", ""],+ ["see #12", 4, "#", "12"],+ ["after !5", 6, "!", "5"],+ ["#crash", 0, "#", "crash"],+ ])("finds the trigger in %j", (text, rangeStart, sigil, query) => {const cursor = rangeStart + 1 + query.length;- expect(detectPullRequestMention(text, cursor)).toEqual({+ expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toEqual({+ kind: sigil === "@" ? "mention" : "reference",+ sigil,query,rangeStart,rangeEnd: cursor,@@ -27,18 +37,30 @@ describe("detectPullRequestMention", () => {["@-jane", "@-jane".length],["`@decorator`", "`@decorator".length],["@jane", 3],+ ["C#", 2],+ ["![image", "![image".length],+ ["## Heading", 2],])("ignores %j", (text, cursor) => {- expect(detectPullRequestMention(text, cursor)).toBeNull();+ expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toBeNull();+ });++ it.each([+ ["@ju", {}],+ ["#12", { mentions: true }],+ ["!important", { mentions: true, referenceSigils: ["#"] }],+ ["#12", { mentions: true, referenceSigils: [] }],+ ] as const)("ignores %j on a host that cannot complete it", (text, support) => {+ expect(detectPullRequestComposerTrigger(text, text.length, support)).toBeNull();});});-describe("insertPullRequestMention", () => {+describe("insertPullRequestCompletion", () => {it.each(["", "\nnext line", "\r\nnext line"])(- "replaces the partial login and adds a space before %j",+ "replaces the partial token and adds a space before %j",(suffix) => {const text = `thanks @ju${suffix}`;- const trigger = detectPullRequestMention(text, "thanks @ju".length)!;- expect(insertPullRequestMention(text, trigger, "julius")).toEqual({+ const trigger = detectPullRequestComposerTrigger(text, "thanks @ju".length, GITLAB)!;+ expect(insertPullRequestCompletion(text, trigger, "@julius")).toEqual({text: `thanks @julius ${suffix}`,cursor: "thanks @julius ".length,});@@ -46,11 +68,23 @@ describe("insertPullRequestMention", () => {);it("reuses the space that already follows and moves past it", () => {- const text = "@ju please look";- const trigger = detectPullRequestMention(text, 3)!;- const inserted = insertPullRequestMention(text, trigger, "julius");- expect(inserted).toEqual({ text: "@julius please look", cursor: "@julius ".length });- expect(detectPullRequestMention(inserted.text, inserted.cursor)).toBeNull();+ const text = "#1 please look";+ const trigger = detectPullRequestComposerTrigger(text, 2, GITLAB)!;+ const inserted = insertPullRequestCompletion(text, trigger, "#123");+ expect(inserted).toEqual({ text: "#123 please look", cursor: "#123 ".length });+ expect(detectPullRequestComposerTrigger(inserted.text, inserted.cursor, GITLAB)).toBeNull();+ });+});++describe("debouncedPullRequestCompletionSearch", () => {+ it.each([+ ["a settled search", { sigil: "#" }, "#crash", "crash"],+ ["a settled bare sigil", { sigil: "@" }, "@", undefined],+ ["a lagging search", { sigil: "#" }, "#cra", "cra"],+ ["the other sigil's key", { sigil: "!" }, "#12", undefined],+ ["no key yet", { sigil: "#" }, null, undefined],+ ] as const)("sends %s as the host search", (_, trigger, key, sent) => {+ expect(debouncedPullRequestCompletionSearch(trigger, key)).toBe(sent);});});@@ -68,3 +102,19 @@ describe("narrowPullRequestMentions", () => {expect(narrowPullRequestMentions(users, "", 2)).toHaveLength(2);});});++describe("narrowPullRequestReferences", () => {+ it("keeps the sigil's kind and matches a number prefix or the title", () => {+ const candidates = [+ { reference: "#12", number: 12, title: "Crash on start" },+ { reference: "!12", number: 12, title: "Fix the crash" },+ { reference: "#3", number: 3, title: "Issue 12 follow-up" },+ { reference: "#120", number: 120, title: "Docs" },+ ];+ const narrowed = (sigil: "#" | "!", query: string) =>+ narrowPullRequestReferences(candidates, { sigil, query }, 5).map((c) => c.reference);+ expect(narrowed("#", "12")).toEqual(["#12", "#3", "#120"]);+ expect(narrowed("!", "CRASH")).toEqual(["!12"]);+ expect(narrowed("#", "")).toEqual(["#12", "#3", "#120"]);+ });+});diff --git a/packages/shared/src/pullRequestComposerTrigger.ts b/packages/shared/src/pullRequestComposerTrigger.tsindex a2e64f924c9..6a14f0fcc82 100644--- a/packages/shared/src/pullRequestComposerTrigger.ts+++ b/packages/shared/src/pullRequestComposerTrigger.ts@@ -1,42 +1,92 @@+import type {+ PullRequestActor,+ PullRequestCapabilities,+ PullRequestFilterOptions,+ PullRequestReferenceCandidate,+ PullRequestReferenceSigil,+} from "@t3tools/contracts";+import { replaceTextRange } from "./composerTrigger.ts";-export interface PullRequestMentionTrigger {+export type PullRequestComposerTrigger = {readonly query: string;readonly rangeStart: number;readonly rangeEnd: number;-}+} & (+ | { readonly kind: "mention"; readonly sigil: "@" }+ | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil }+);++// Mentions cover GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).+const TOKEN = /^(?:@([A-Za-z0-9_][A-Za-z0-9_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u;-// Covers GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).-const MENTION_TOKEN = /^@([A-Za-z0-9_][A-Za-z0-9_.-]*)?$/;+/** What a pull request's host can complete; absent fields complete nothing. */+export type PullRequestCompletionSupport = Pick<+ PullRequestCapabilities,+ "mentions" | "referenceSigils"+>;-/** The `@login` being typed at the caret, when the caret sits at its end. */-export function detectPullRequestMention(+/**+ * The `@login`, `#123` or `!123` being typed at the caret, when the caret sits at its end and the+ * host completes that sigil.+ */+export function detectPullRequestComposerTrigger(text: string,cursor: number,-): PullRequestMentionTrigger | null {+ support: PullRequestCompletionSupport,+): PullRequestComposerTrigger | null {const end = Math.max(0, Math.min(text.length, cursor));const next = text[end];if (next !== undefined && !/\s/.test(next)) return null;let start = end;while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;- const match = MENTION_TOKEN.exec(text.slice(start, end));+ const match = TOKEN.exec(text.slice(start, end));if (!match) return null;- return { query: match[1] ?? "", rangeStart: start, rangeEnd: end };+ const sigil = match[2];+ if (sigil === "#" || sigil === "!") {+ return support.referenceSigils?.includes(sigil)+ ? { kind: "reference", sigil, query: match[3] ?? "", rangeStart: start, rangeEnd: end }+ : null;+ }+ return support.mentions === true+ ? { kind: "mention", sigil: "@", query: match[1] ?? "", rangeStart: start, rangeEnd: end }+ : null;}-export function insertPullRequestMention(+/** Replaces the trigger with `token` and leaves the caret past the space after it. */+export function insertPullRequestCompletion(text: string,- trigger: PullRequestMentionTrigger,- login: string,+ trigger: PullRequestComposerTrigger,+ token: string,): { text: string; cursor: number } {const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? "");if (!followedBySpace) {- return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login} `);+ return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `${token} `);}- const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login}`);+ const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, token);return { ...inserted, cursor: inserted.cursor + 1 };}+/** The key a debounce delays: the trigger's sigil and its host search, or `null` with no trigger. */+export function pullRequestCompletionKey(+ trigger: Pick<PullRequestComposerTrigger, "sigil" | "query"> | null,+): string | null {+ return trigger === null ? null : `${trigger.sigil}${trigger.query.slice(0, 100)}`;+}++/**+ * The search to send for `trigger` given a debounced key. Until a key for this sigil settles, the+ * host is asked for its unsearched list, which narrows locally, so a burst of typing sends one query.+ */+export function debouncedPullRequestCompletionSearch(+ trigger: Pick<PullRequestComposerTrigger, "sigil">,+ debouncedKey: string | null,+): string | undefined {+ return debouncedKey?.startsWith(trigger.sigil)+ ? debouncedKey.slice(trigger.sigil.length) || undefined+ : undefined;+}+export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(users: ReadonlyArray<A>,typed: string,@@ -51,3 +101,50 @@ export function narrowPullRequestMentions<A extends { login: string; name: strin).slice(0, limit);}++/** Candidates the typed sigil links, by number prefix or title. */+export function narrowPullRequestReferences<+ A extends { reference: string; number: number; title: string },+>(+ candidates: ReadonlyArray<A>,+ trigger: Pick<PullRequestComposerTrigger, "sigil" | "query">,+ limit: number,+): A[] {+ const needle = trigger.query.toLowerCase();+ return candidates+ .filter(+ (candidate) =>+ candidate.reference.startsWith(trigger.sigil) &&+ (String(candidate.number).startsWith(needle) ||+ candidate.title.toLowerCase().includes(needle)),+ )+ .slice(0, limit);+}++export type PullRequestCompletion =+ | { readonly kind: "mention"; readonly token: string; readonly actor: PullRequestActor }+ | {+ readonly kind: "reference";+ readonly token: string;+ readonly candidate: PullRequestReferenceCandidate;+ };++/** The host's options for `trigger`, narrowed to what is typed now. */+export function pullRequestCompletions(+ trigger: PullRequestComposerTrigger | null,+ options: Pick<PullRequestFilterOptions, "authors" | "references"> | null,+ limit: number,+): ReadonlyArray<PullRequestCompletion> {+ if (trigger === null) return [];+ return trigger.kind === "mention"+ ? narrowPullRequestMentions(options?.authors ?? [], trigger.query, limit).map((actor) => ({+ kind: "mention",+ token: `@${actor.login}`,+ actor,+ }))+ : narrowPullRequestReferences(options?.references ?? [], trigger, limit).map((candidate) => ({+ kind: "reference",+ token: candidate.reference,+ candidate,+ }));+}diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.tsindex 7f3aa0561fc..061a5d0f931 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts@@ -53,6 +53,7 @@ const CAPABILITIES: PullRequestCapabilities = {search: false,reactions: false,mentions: false,+ referenceSigils: [],review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },// Reviewer candidates require separate identity/graph APIs and permissions.reviewers: { request: true, listCandidates: false },diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.tsindex 9123f34c7ef..1f7729ee2a5 100644--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts@@ -24,6 +24,7 @@ const CAPABILITIES: PullRequestCapabilities = {search: true,reactions: false,mentions: false,+ referenceSigils: [],review: {inlineComment: true,reply: true,diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex 9769bc66347..549210e3827 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -5,6 +5,8 @@ import type {PullRequestAction,PullRequestStackHead,PullRequestActor,+ PullRequestReferenceCandidate,+ PullRequestReferenceSigil,PullRequestBaseComparison,PullRequestCapabilities,PullRequestChecksState,@@ -555,6 +557,20 @@ export interface PullRequestProviderApi {input: ProviderRepositoryRef & { readonly query?: string | undefined },) => Effect.Effect<ProviderFilterOptionPage<PullRequestActor>, PullRequestProviderError>;+ /**+ * Issues and change requests a composer can reference, recently updated first. A numeric+ * `query` also finds that number exactly; other text matches titles as far as the host can.+ */+ readonly searchRepositoryReferences?: (+ input: ProviderRepositoryRef & {+ readonly query?: string | undefined;+ readonly sigil?: PullRequestReferenceSigil | undefined;+ },+ ) => Effect.Effect<+ ProviderFilterOptionPage<PullRequestReferenceCandidate>,+ 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 f41dbe0d0d8..cd2047664a3 100644--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts@@ -49,6 +49,7 @@ const CAPABILITIES: PullRequestCapabilities = {search: false,reactions: true,mentions: true,+ referenceSigils: [],labels: true,// Forgejo's public API has no thread replies/resolution or draft conversion endpoint.review: {diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex f465da71a41..565f0b76722 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -35,6 +35,7 @@ const CAPABILITIES: PullRequestCapabilities = {stackActions: true,reactions: true,mentions: true,+ referenceSigils: [],labels: true,// Line comments go through GitCafe's review drafts, which arrive with revision fencing.review: {diff --git a/packages/source-control-github/schema/github.graphql.ts b/packages/source-control-github/schema/github.graphql.tsindex 9ac930c9ffe..332060b960f 100644--- a/packages/source-control-github/schema/github.graphql.ts+++ b/packages/source-control-github/schema/github.graphql.ts@@ -86,6 +86,15 @@ export type DiffSide = typeof DiffSide.Typeexport const FileViewedState = Schema.Literals(["DISMISSED", "UNVIEWED", "VIEWED"])export type FileViewedState = typeof FileViewedState.Type+/**+ * The possible states of an issue.+ *+ * - `CLOSED`: An issue that has been closed+ * - `OPEN`: An issue that is still open+ */+export const IssueState = Schema.Literals(["CLOSED", "OPEN"])+export type IssueState = typeof IssueState.Type+/*** Detailed status information about a pull request merge.*@@ -291,6 +300,8 @@ export declare namespace Typename {export type Actor = "Bot" | "EnterpriseUserAccount" | "Mannequin" | "Organization" | "User"/** Every possible `__typename` of interface `GitObject`. */export type GitObject = "Blob" | "Commit" | "Tag" | "Tree"+ /** Every possible `__typename` of union `IssueOrPullRequest`. */+ export type IssueOrPullRequest = "Issue" | "PullRequest"/** Every possible `__typename` of interface `Node`. */export type Node =| "AddedToMergeQueueEvent" | "AddedToProjectEvent" | "AddedToProjectV2Event" | "AddedToStackEvent" | "App"diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.tsindex 4ba8dceeee5..14b50258d71 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts@@ -731,6 +731,43 @@ it.effect();layer("GitHubPullRequestApi.layer", (it) => {+ it.effect("keeps recent references when the typed number does not exist", () =>+ Effect.gen(function* () {+ const search = {+ pageInfo: { hasNextPage: false },+ nodes: [{ __typename: "Issue", number: 7, title: "Seven", issueState: "OPEN" }],+ };+ mockedExecute.mockImplementation((call) =>+ Effect.succeed(+ output(+ encodeJson(+ call.kind === "graphql" && call.variables?.["exact"] === true+ ? {+ data: { search, repository: { issueOrPullRequest: null } },+ errors: [+ {+ type: "NOT_FOUND",+ path: ["repository", "issueOrPullRequest"],+ message: "Could not resolve to an issue or pull request.",+ },+ ],+ }+ : { data: { search } },+ ),+ ),+ ),+ );+ const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;+ const result = yield* api.searchRepositoryReferences({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ query: "99",+ });+ expect(result.items.map((item) => item.reference)).toEqual(["#7"]);+ }),+ );+it.effect("turns maintainer edits off without rewriting the pull request's text", () =>Effect.gen(function* () {mockedExecute.mockImplementation((call) =>diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex cb3c3d994b4..372e0a83820 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -24,6 +24,7 @@ import {type PullRequestAction,type PullRequestStackHead,type PullRequestActor,+ type PullRequestReferenceCandidate,type PullRequestComment,type PullRequestCommit,type PullRequestFileViewed,@@ -74,6 +75,9 @@ import {pullRequestLookup,toLabelCandidates,toRepositoryAuthors,+ toRepositoryReferences,+ referenceSearchQuery,+ searchPhrase,toRepositoryLabels,toPullRequestActivityPage,toPullRequestActionSummary,@@ -642,6 +646,19 @@ export class GitHubPullRequestApi extends Context.Service<GitHubPullRequestApiError>;+ readonly searchRepositoryReferences: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly query?: string | undefined;+ }) => Effect.Effect<+ {+ readonly items: ReadonlyArray<PullRequestReferenceCandidate>;+ readonly truncated: boolean;+ },+ GitHubPullRequestApiError+ >;+readonly setLabels: (input: {readonly cwd: string;readonly repository: string;@@ -743,11 +760,6 @@ function diffCursorPage(cursor: string): number | null {return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;}-/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */-function searchPhrase(query: string): string {- return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;-}-const REVIEW_QUALIFIERS = {approved: "approved","changes-requested": "changes_requested",@@ -2373,6 +2385,32 @@ export const make = Effect.gen(function* () {},),+ searchRepositoryReferences: Effect.fn("GitHubPullRequestApi.searchRepositoryReferences")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const parsed = /^\d+$/.test(input.query ?? "") ? Number(input.query) : 0;+ // GraphQL validates `$number: Int!` even when `@include` skips the lookup.+ const exact = parsed > 0 && parsed <= 2_147_483_647;+ const search = (lookup: boolean) =>+ client.RepositoryReferences({+ owner,+ name,+ q: referenceSearchQuery(input.repository, input.query),+ number: lookup ? parsed : 0,+ exact: lookup,+ });+ return search(exact).pipe(+ // A missing number fails the whole query, which would discard the search results.+ Effect.catchIf(+ (error) => exact && isNotFoundOnly(error),+ () => search(false),+ ),+ graphql({ ...input, operation: "searchRepositoryReferences", allowReserve: true }),+ Effect.map(toRepositoryReferences),+ );+ },+ ),+setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (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 6e0f0af0cad..d281b90f30a 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -42,6 +42,7 @@ const CAPABILITIES: PullRequestCapabilities = {search: true,reactions: true,mentions: true,+ referenceSigils: ["#"],viewedFiles: "host",review: {inlineComment: true,@@ -657,6 +658,11 @@ export const make = Effect.gen(function* () {searchRepositoryAuthors: (input) =>cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),+ searchRepositoryReferences: (input) =>+ cli+ .searchRepositoryReferences(input)+ .pipe(Effect.mapError(fail("searchRepositoryReferences"))),+setLabels: (input) =>cli.setLabels({diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.tsindex 58b7969277c..f06c847471d 100644--- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts@@ -6,6 +6,8 @@ import {buildReviewSubmission,buildReviewerRequest,pullRequestLookup,+ referenceSearchQuery,+ toRepositoryReferences,toPullRequestWatchFingerprint,decodePullRequestFilesJson,decodePullRequestStacksJson,@@ -1629,6 +1631,40 @@ const decodeWatchedResult = Schema.decodeUnknownSync(PullRequestWatchFingerprintconst decodeWatched = (pullRequest: object) =>decodeWatchedResult({ repository: { pullRequest } }).repository!.pullRequest!;+describe("repository references", () => {+ it.each([+ [undefined, "repo:o/r sort:updated-desc"],+ ["12", "repo:o/r sort:updated-desc"],+ ['say "hi"', 'repo:o/r in:title "say \\"hi\\"" sort:updated-desc'],+ ])("searches %j as %j", (query, q) => {+ expect(referenceSearchQuery("o/r", query)).toBe(q);+ });++ it("puts the exact number first and maps issue and pull request states", () => {+ const result = toRepositoryReferences({+ search: {+ pageInfo: { hasNextPage: true },+ nodes: [+ { __typename: "PullRequest", number: 3, title: "Merged", pullRequestState: "MERGED" },+ { __typename: "Issue", number: 2, title: "Closed", issueState: "CLOSED" },+ null,+ ],+ },+ repository: {+ issueOrPullRequest: { __typename: "Issue", number: 1, title: "Exact", issueState: "OPEN" },+ },+ });+ expect(result).toEqual({+ items: [+ { reference: "#1", kind: "issue", number: 1, title: "Exact", state: "open" },+ { reference: "#3", kind: "change-request", number: 3, title: "Merged", state: "merged" },+ { reference: "#2", kind: "issue", number: 2, title: "Closed", state: "closed" },+ ],+ truncated: true,+ });+ });+});+describe("pull request lookups", () => {it("refuses what GitHub cannot name, so one bad row cannot fail a whole batch", () => {expect(pullRequestLookup({ repository: "acme/web", number: 7 })).toEqual({diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.tsindex 76c101766b3..5c6fce4a0f3 100644--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts@@ -7,6 +7,7 @@ import { GraphQL } from "effect/graphql";import type {PullRequestStackMembership,PullRequestActor,+ PullRequestReferenceCandidate,PullRequestPreview,PullRequestCheck,PullRequestCheckStatus,@@ -65,6 +66,8 @@ import type {PullRequestSubject,RepositoryAuthors,RepositoryLabels,+ RepositoryReferences,+ ReferenceCandidate,ReviewerCandidates,ViewerPermissions,} from "./pullRequestReads.graphql.ts";@@ -1576,6 +1579,64 @@ export function toRepositoryAuthors(};}+/** The `search` string for {@link toRepositoryReferences}; a numeric query searches recent items. */+export function referenceSearchQuery(repository: string, query: string | undefined): string {+ const text = query?.trim() ?? "";+ const titled = text.length === 0 || /^\d+$/.test(text) ? [] : [`in:title ${searchPhrase(text)}`];+ return [`repo:${repository}`, ...titled, "sort:updated-desc"].join(" ");+}++/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */+export function searchPhrase(query: string): string {+ return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;+}++type ReferenceNode =+ | ReferenceCandidate+ | NonNullable<NonNullable<RepositoryReferences.Result["search"]["nodes"]>[number]>;++function toReferenceCandidate(node: ReferenceNode): PullRequestReferenceCandidate | null {+ if (node.__typename === "Issue") {+ return {+ reference: `#${node.number}`,+ kind: "issue",+ number: node.number,+ title: node.title,+ state: node.issueState === "OPEN" ? "open" : "closed",+ };+ }+ if (node.__typename === "PullRequest") {+ return {+ reference: `#${node.number}`,+ kind: "change-request",+ number: node.number,+ title: node.title,+ state:+ node.pullRequestState === "OPEN"+ ? "open"+ : node.pullRequestState === "MERGED"+ ? "merged"+ : "closed",+ };+ }+ return null;+}++export function toRepositoryReferences(result: RepositoryReferences.Result): {+ readonly items: ReadonlyArray<PullRequestReferenceCandidate>;+ readonly truncated: boolean;+} {+ const exact = result.repository?.issueOrPullRequest;+ const nodes = [...(exact == null ? [] : [exact]), ...nodesOf(result.search)];+ return {+ items: nodes.flatMap((node) => {+ const candidate = toReferenceCandidate(node);+ return candidate === null ? [] : [candidate];+ }),+ truncated: result.search.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 f317ae0f5ea..61f77a289a7 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql+++ b/packages/source-control-github/src/server/pullRequestReads.graphql@@ -487,6 +487,43 @@ query RepositoryLabels($owner: String!, $name: String!, $query: String) {}}+fragment ReferenceCandidate on IssueOrPullRequest {+ __typename+ ... on Issue {+ number+ title+ issueState: state+ }+ ... on PullRequest {+ number+ title+ pullRequestState: state+ }+}++# `search` cannot match a number, so a numeric query also looks the number up directly.+query RepositoryReferences(+ $owner: String!+ $name: String!+ $q: String!+ $number: Int!+ $exact: Boolean!+) {+ search(query: $q, type: ISSUE, first: 20) {+ pageInfo {+ hasNextPage+ }+ nodes {+ ...ReferenceCandidate+ }+ }+ repository(owner: $owner, name: $name) @include(if: $exact) {+ issueOrPullRequest(number: $number) {+ ...ReferenceCandidate+ }+ }+}+# 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) {diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.tsindex ff19cfd0f6a..fca2349bcfc 100644--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts@@ -82,6 +82,48 @@ export const CheckContext = Schema.Union([])export type CheckContext = typeof CheckContext.Type+/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */+export const Issue = Schema.Struct({+ __typename: Schema.Literal("Issue"),+ /** Identifies the issue number. */+ number: Shared.Int,+ /** Identifies the issue title. */+ title: Schema.String,+ /** Identifies the state of the issue. */+ issueState: GraphQL.enumLiterals(Shared.IssueState.literals)+})+export interface Issue extends Schema.Struct.Type<typeof Issue.fields> {}++/** A repository pull request. */+export const ReferenceCandidatePullRequest = Schema.Struct({+ __typename: Schema.Literal("PullRequest"),+ /** Identifies the pull request number. */+ number: Shared.Int,+ /** Identifies the pull request title. */+ title: Schema.String,+ /** Identifies the state of the pull request. */+ pullRequestState: GraphQL.enumLiterals(Shared.PullRequestState.literals)+})+export interface ReferenceCandidatePullRequest extends Schema.Struct.Type<typeof ReferenceCandidatePullRequest.fields> {}++/** Used for return value of Repository.issueOrPullRequest. */+export const IssueOrPullRequestOther = Schema.Struct({+ __typename: GraphQL.otherTypename<Shared.Typename.IssueOrPullRequest>()(["Issue", "PullRequest"])+})+export interface IssueOrPullRequestOther extends Schema.Struct.Type<typeof IssueOrPullRequestOther.fields> {}++/**+ * `fragment ReferenceCandidate on IssueOrPullRequest`+ *+ * Used for return value of Repository.issueOrPullRequest.+ */+export const ReferenceCandidate = Schema.Union([+ Issue,+ ReferenceCandidatePullRequest,+ IssueOrPullRequestOther+])+export type ReferenceCandidate = typeof ReferenceCandidate.Type+/** A user is an individual's account on GitHub that owns repositories and can make new content. */export const ViewerUser = Schema.Struct({/** Identifies the primary key from the database. */@@ -1301,6 +1343,73 @@ export declare namespace RepositoryLabels {export type Result = typeof RepositoryLabels.result.Type}+/** The results of a search. */+export const SearchResultItemOther = Schema.Struct({+ __typename: GraphQL.otherTypename<Shared.Typename.SearchResultItem>()(["Issue", "PullRequest"])+})+export interface SearchResultItemOther extends Schema.Struct.Type<typeof SearchResultItemOther.fields> {}++/**+ * A list of results that matched against a search query. Regardless of the number+ * of matches, a maximum of 1,000 results will be available across all types,+ * potentially split across many pages.+ */+export const SearchResultItemConnection = Schema.Struct({+ /** Information to aid in pagination. */+ pageInfo: AssignableUsersPageInfoPageInfo,+ /** A list of nodes. */+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([+ Issue,+ ReferenceCandidatePullRequest,+ SearchResultItemOther+ ]))))+})+export interface SearchResultItemConnection extends Schema.Struct.Type<typeof SearchResultItemConnection.fields> {}++/** A repository contains the content for a project. */+export const RepositoryReferencesRepositoryRepository = Schema.Struct({+ /** Returns a single issue-like object from the current repository by number. */+ issueOrPullRequest: Schema.NullOr(ReferenceCandidate)+})+export interface RepositoryReferencesRepositoryRepository extends Schema.Struct.Type<typeof RepositoryReferencesRepositoryRepository.fields> {}++/** `query RepositoryReferences` */+export const RepositoryReferences = GraphQL.query("RepositoryReferences", {+ document: {+ variables: [+ { name: "owner", body: "String!" },+ { name: "name", body: "String!" },+ { name: "q", body: "String!" },+ { name: "number", body: "Int!" },+ { name: "exact", body: "Boolean!" }+ ],+ selections: [+ { name: "search", body: ["(query:$", "q", " type:ISSUE first:20){pageInfo{hasNextPage}nodes{__typename...ReferenceCandidate}}"] },+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", ")@include(if:$", "exact", "){issueOrPullRequest(number:$", "number", "){__typename...ReferenceCandidate}}"] }+ ],+ fragments: [+ { name: "ReferenceCandidate", body: ["on IssueOrPullRequest{__typename...on Issue{number title issueState:state}...on PullRequest{number title pullRequestState:state}}"] }+ ]+ },+ variables: {+ owner: Schema.String,+ name: Schema.String,+ q: Schema.String,+ number: Shared.Int,+ exact: Schema.Boolean+ },+ result: Schema.Struct({+ /** Perform a search across resources, returning a maximum of 1,000 results. */+ search: SearchResultItemConnection,+ /** Lookup a given repository by the owner and repository name. */+ repository: Schema.optionalKey(Schema.NullOr(RepositoryReferencesRepositoryRepository))+ })+})+export declare namespace RepositoryReferences {+ export type Variables = typeof RepositoryReferences.variables.Type+ export type Result = typeof RepositoryReferences.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. */@@ -1687,4 +1796,4 @@ export declare namespace PullRequestSourceBranch {}/** Every operation in pullRequestReads.graphql. */-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestCommitStats, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)+export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestCommitStats, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryReferences, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.tsindex 8e19295cdbd..1641ff79dc1 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts@@ -2211,6 +2211,27 @@ layer("GitLabPullRequestCli.layer", (it) => {expect(result).toMatchObject({ _tag: "Failure", failure: error });}),);++ it.effect("keeps merge request references when the issue search fails", () =>+ Effect.gen(function* () {+ mockedExecute.mockImplementation((input) =>+ JSON.stringify(input).includes("/issues?")+ ? Effect.fail(+ new GitLabCli.GitLabCliCommandError({+ operation: "execute",+ command: "glab",+ cwd: "/w",+ cause: null,+ }),+ )+ : Effect.succeed(output(JSON.stringify([{ iid: 5, title: "Ship it", state: "opened" }]))),+ );+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;+ const page = yield* cli.searchProjectReferences({ cwd: "/w", repository: "acme/web" });+ expect(page.items.map((item) => item.reference)).toEqual(["!5"]);+ }),+ );+describe("the head pipeline's stages", () => {const pipeline = {id: 9,@@ -2379,3 +2400,31 @@ layer("GitLabPullRequestCli.layer", (it) => {);});});++it("asks for a numeric reference's iid besides the recent issues and merge requests", () => {+ const recent = [+ ["order_by", "updated_at"],+ ["sort", "desc"],+ ];+ expect(GitLabPullRequestCli.referenceSearches("12")).toEqual([+ { kind: "issue", params: [["iids[]", "12"]] },+ { kind: "change-request", params: [["iids[]", "12"]] },+ { kind: "issue", params: recent },+ { kind: "change-request", params: recent },+ ]);+ expect(GitLabPullRequestCli.referenceSearches("crash")).toEqual([+ { kind: "issue", params: [...recent, ["search", "crash"], ["in", "title"]] },+ { kind: "change-request", params: [...recent, ["search", "crash"], ["in", "title"]] },+ ]);+ expect(GitLabPullRequestCli.referenceSearches("cr")).toEqual([+ { kind: "issue", params: recent },+ { kind: "change-request", params: recent },+ ]);+ expect(GitLabPullRequestCli.referenceSearches("12", "!")).toEqual([+ { kind: "change-request", params: [["iids[]", "12"]] },+ { kind: "change-request", params: recent },+ ]);+ expect(GitLabPullRequestCli.referenceSearches(undefined, "#")).toEqual([+ { kind: "issue", params: recent },+ ]);+});diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex 43f54b1651c..7eda058ceb4 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -11,6 +11,8 @@ import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/coimport type {PullRequestAction,PullRequestActor,+ PullRequestReferenceCandidate,+ PullRequestReferenceSigil,PullRequestCheck,PullRequestComment,PullRequestCommit,@@ -58,6 +60,7 @@ import {decodeProjectMergeCapabilitiesJson,decodeProjectLabelsJson,decodeProjectUsersJson,+ decodeReferenceCandidatesJson,decodeRepositoryBlobsJson,decodeListStatesJson,decodeSourceBranchJson,@@ -512,6 +515,20 @@ export class GitLabPullRequestCli extends Context.Service<GitLabPullRequestCliError>;+ readonly searchProjectReferences: (input: {+ readonly cwd: string;+ readonly host?: string | undefined;+ readonly repository: string;+ readonly search?: string | undefined;+ readonly sigil?: PullRequestReferenceSigil | undefined;+ }) => Effect.Effect<+ {+ readonly items: ReadonlyArray<PullRequestReferenceCandidate>;+ readonly truncated: boolean;+ },+ GitLabPullRequestCliError+ >;+readonly setReviewerRequest: (input: {readonly cwd: string;readonly host?: string | undefined;@@ -791,6 +808,58 @@ function searchParams(search: string | undefined): ReadonlyArray<readonly [strinreturn trimmed.length === 0 ? [] : [["search", trimmed]];}+// GitLab's user, issue and merge request searches answer nothing under three characters, so+// shorter text reads the unsearched page, which the server narrows.+function hostSearchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {+ return (search?.trim().length ?? 0) >= 3 ? searchParams(search) : [];+}++const REFERENCE_PAGE_SIZE = 20;++/**+ * Recently updated issues and merge requests, by title for text. Issue and MR search cannot match+ * a number, so a numeric query also asks for that iid of each.+ */+export function referenceSearches(+ search: string | undefined,+ sigil?: PullRequestReferenceSigil | undefined,+): ReadonlyArray<{+ readonly kind: PullRequestReferenceCandidate["kind"];+ readonly params: ReadonlyArray<readonly [string, string]>;+}> {+ const text = search?.trim() ?? "";+ const numeric = /^\d+$/.test(text);+ const recent: ReadonlyArray<readonly [string, string]> = [+ ["order_by", "updated_at"],+ ["sort", "desc"],+ ...(numeric || hostSearchParams(text).length === 0+ ? []+ : ([...hostSearchParams(text), ["in", "title"]] as const)),+ ];+ const kinds =+ sigil === "#"+ ? (["issue"] as const)+ : sigil === "!"+ ? (["change-request"] as const)+ : (["issue", "change-request"] as const);+ return [+ ...(numeric ? kinds.map((kind) => ({ kind, params: [["iids[]", text]] as const })) : []),+ ...kinds.map((kind) => ({ kind, params: recent })),+ ];+}++function mergeReferencePages(+ pages: ReadonlyArray<{+ readonly items: ReadonlyArray<PullRequestReferenceCandidate>;+ readonly rawCount: number;+ }>,+) {+ return {+ items: pages.flatMap((page) => page.items),+ truncated: pages.some((page) => page.rawCount >= REFERENCE_PAGE_SIZE),+ };+}+function query(params: ReadonlyArray<readonly [string, string]>): string {return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");}@@ -1317,9 +1386,7 @@ export const make = Effect.gen(function* () {host: input.host,path: `projects/${projectPath(input.repository)}/users?${query([["per_page", String(MAX_PAGE_SIZE)],- // GitLab answers nothing for a user search under three characters; callers narrow the- // unsearched page instead.- ...((input.search?.trim().length ?? 0) >= 3 ? searchParams(input.search) : []),+ ...hostSearchParams(input.search),])}`,}).pipe(Effect.flatMap((result) => {@@ -1337,6 +1404,35 @@ export const make = Effect.gen(function* () {}),);+ const projectReferences = (input: {+ readonly cwd: string;+ readonly host?: string | undefined;+ readonly repository: string;+ readonly kind: PullRequestReferenceCandidate["kind"];+ readonly params: ReadonlyArray<readonly [string, string]>;+ }) =>+ api({+ cwd: input.cwd,+ host: input.host,+ path: `projects/${projectPath(input.repository)}/${+ input.kind === "issue" ? "issues" : "merge_requests"+ }?${query([...input.params, ["per_page", String(REFERENCE_PAGE_SIZE)]])}`,+ }).pipe(+ Effect.flatMap((result) => {+ const decoded = decodeReferenceCandidatesJson(result.stdout.trim(), input.kind);+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "searchProjectReferences",+ cause: decoded.failure,+ }),+ );+ }),+ );+const awardSubjectPath = (input: {readonly repository: string;readonly number: number;@@ -2222,6 +2318,32 @@ export const make = Effect.gen(function* () {);}),+ searchProjectReferences: Effect.fn("GitLabPullRequestCli.searchProjectReferences")(+ function (input) {+ return Effect.forEach(+ referenceSearches(input.search, input.sigil),+ ({ kind, params }) =>+ projectReferences({ ...input, kind, params }).pipe(+ // A project with issues turned off answers 403 for issues; its merge requests still+ // complete. An unusable CLI or account still reaches the caller.+ Effect.catchIf(+ (cause) =>+ cause._tag !== "GitLabCliUnavailableError" &&+ cause._tag !== "GitLabCliAuthenticationError" &&+ cause._tag !== "GitLabCliRateLimitError",+ (cause) =>+ Effect.logWarning("GitLab reference search failed", {+ repository: input.repository,+ kind,+ reason: cause._tag,+ }).pipe(Effect.as({ items: [], rawCount: 0 })),+ ),+ ),+ { concurrency: "unbounded" },+ ).pipe(Effect.map(mergeReferencePages));+ },+ ),+listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")(function (input) {return Effect.all([mergeRequestDetail(input), projectUsers(input)], {diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.tsindex c7a38794ee6..4247008c273 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts@@ -33,6 +33,7 @@ const CAPABILITIES: PullRequestCapabilities = {search: true,reactions: true,mentions: true,+ referenceSigils: ["#", "!"],// GitLab's viewed marks live in browser-local storage.viewedFiles: "environment",review: {@@ -534,6 +535,17 @@ export const make = Effect.gen(function* () {}).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),+ searchRepositoryReferences: (input) =>+ cli+ .searchProjectReferences({+ cwd: input.cwd,+ host: input.host,+ repository: input.repository,+ search: input.query,+ sigil: input.sigil,+ })+ .pipe(Effect.mapError(fail("searchRepositoryReferences"))),+setReviewerRequest: writing((input) =>cli.setReviewerRequest({diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.tsindex f755f185adc..181b73a44b7 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts@@ -13,6 +13,7 @@ import {decodeMergeRequestListJson,decodeMergeRequestFileStatsJson,decodeMergeRequestStatsJson,+ decodeReferenceCandidatesJson,decodeNotesJson,decodeOwnAwardIdJson,decodeListStatesJson,@@ -1052,6 +1053,28 @@ describe("decodeListStatesJson", () => {});});+describe("decodeReferenceCandidatesJson", () => {+ it("prefixes merge requests with ! and skips malformed entries", () => {+ const raw = JSON.stringify([+ { iid: 5, title: "Ship it", state: "merged" },+ { iid: 6, title: "Draft", state: "opened" },+ { iid: 7, title: "Locked", state: "locked" },+ { title: "No iid", state: "opened" },+ ]);+ const decoded = decodeReferenceCandidatesJson(raw, "change-request");+ expect(Result.isSuccess(decoded) && decoded.success).toEqual({+ items: [+ { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" },+ { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" },+ { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" },+ ],+ rawCount: 4,+ });+ const issues = decodeReferenceCandidatesJson(raw, "issue");+ expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5");+ });+});+describe("decodeMergeRequestStatsJson", () => {it("keys the counts by merge request number", () => {const stats = expectSuccess(diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.tsindex 18366b53678..602d5971f09 100644--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts@@ -16,6 +16,7 @@ import type {PullRequestMergeMethod,PullRequestReaction,PullRequestReactionContent,+ PullRequestReferenceCandidate,PullRequestReviewDecision,PullRequestReviewThread,PullRequestReviewerCandidate,@@ -655,6 +656,40 @@ export function decodeProjectUsersJson(return Result.succeed({ candidates, rawCount: decoded.success.length });}+const RawReferenceSchema = Schema.Struct({+ iid: Schema.Number,+ title: Schema.String,+ state: Schema.String,+});+const decodeReferenceEntry = Schema.decodeUnknownExit(RawReferenceSchema);++/** A list of issues (`#`) or merge requests (`!`), as composers reference them. */+export function decodeReferenceCandidatesJson(+ raw: string,+ kind: PullRequestReferenceCandidate["kind"],+): Result.Result<+ { readonly items: ReadonlyArray<PullRequestReferenceCandidate>; readonly rawCount: number },+ DecodeFailure+> {+ const decoded = decodeUnknownList(raw);+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);+ const items: PullRequestReferenceCandidate[] = [];+ for (const entry of decoded.success) {+ const reference = decodeReferenceEntry(entry);+ if (Exit.isFailure(reference) || !Number.isInteger(reference.value.iid)) continue;+ if (reference.value.iid < 1) continue;+ const { iid, title, state } = reference.value;+ items.push({+ reference: `${kind === "issue" ? "#" : "!"}${iid}`,+ kind,+ number: iid,+ title,+ state: state === "merged" ? "merged" : state === "opened" ? "open" : "closed",+ });+ }+ return Result.succeed({ items, rawCount: decoded.success.length });+}+const RawLabelSchema = Schema.Struct({name: Schema.String,color: Schema.optional(Schema.NullOr(Schema.String)),