@devries-cameron20 / t3code Mirror · read-only / commits / e4ff5da0d3
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 03:15 UTC

feat(pull-requests): PR composers complete #123 and GitLab !123 references (#30857)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>

Antony committed Nov 6, 2026 at 02:41 UTC e4ff5da0d344909de1d80eff73803d9924cd7aaa
48 files changed +1308 -327
apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx new
+105
@@ -0,0 +1,105 @@
1 +import { Pressable, ScrollView, StyleSheet, View } from "react-native";
2 +
3 +import { AppText as Text } from "../../components/ui/AppText";
4 +import { GlassSurface } from "../../components/ui/GlassSurface";
5 +import { PullRequestAvatar } from "./PullRequestPresentation";
6 +import type { PullRequestCompletion } from "@t3tools/shared/pullRequestComposerTrigger";
7 +import type { usePullRequestCompletions } from "./usePullRequestCompletions";
8 +
9 +const COPY = {
10 + mention: {
11 + label: "Mention a user",
12 + pending: "Searching users...",
13 + failed: "Couldn't search users on the host",
14 + none: "No matching users",
15 + },
16 + reference: {
17 + label: "Reference an issue or change request",
18 + pending: "Searching...",
19 + failed: "Couldn't search the host",
20 + none: "No matching issues or change requests",
21 + },
22 +} as const;
23 +
24 +const STATE_LABEL = { open: "Open", closed: "Closed", merged: "Merged" } as const;
25 +
26 +function CompletionRow({ completion }: { readonly completion: PullRequestCompletion }) {
27 + if (completion.kind === "mention") {
28 + const { actor } = completion;
29 + return (
30 + <>
31 + <PullRequestAvatar actor={actor} size={20} />
32 + <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
33 + {actor.login}
34 + </Text>
35 + {actor.name && actor.name !== actor.login ? (
36 + <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
37 + {actor.name}
38 + </Text>
39 + ) : null}
40 + </>
41 + );
42 + }
43 + const { candidate } = completion;
44 + return (
45 + <>
46 + <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
47 + {candidate.reference}
48 + </Text>
49 + <Text className="min-w-0 flex-1 text-sm text-foreground-muted" numberOfLines={1}>
50 + {candidate.title}
51 + </Text>
52 + <Text className="shrink-0 text-xs text-foreground-tertiary">
53 + {STATE_LABEL[candidate.state]}
54 + </Text>
55 + </>
56 + );
57 +}
58 +
59 +/** The `@`, `#` and `!` suggestions for a pull request text input, rendered just above it. */
60 +export function PullRequestCompletionSuggestions({
61 + completions,
62 +}: {
63 + readonly completions: ReturnType<typeof usePullRequestCompletions>;
64 +}) {
65 + if (completions.kind === null) return null;
66 + const copy = COPY[completions.kind];
67 + return (
68 + <GlassSurface
69 + glassEffectStyle="clear"
70 + tintColorClassName="accent-glass-surface"
71 + style={{ borderRadius: 16, overflow: "hidden" }}
72 + >
73 + {completions.candidates.length > 0 ? (
74 + <ScrollView
75 + className="max-h-[180px]"
76 + keyboardShouldPersistTaps="always"
77 + showsVerticalScrollIndicator={false}
78 + accessibilityLabel={copy.label}
79 + >
80 + {completions.candidates.map((completion, index) => (
81 + <Pressable
82 + key={completion.token}
83 + accessibilityRole="button"
84 + accessibilityLabel={`Insert ${completion.token}`}
85 + onPress={() => completions.select(completion)}
86 + className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60"
87 + style={{
88 + borderBottomWidth:
89 + index === completions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth,
90 + }}
91 + >
92 + <CompletionRow completion={completion} />
93 + </Pressable>
94 + ))}
95 + </ScrollView>
96 + ) : (
97 + <View className="px-3.5 py-2.5">
98 + <Text className="text-xs text-foreground-tertiary">
99 + {copy[completions.isLoading ? "pending" : completions.failed ? "failed" : "none"]}
100 + </Text>
101 + </View>
102 + )}
103 + </GlassSurface>
104 + );
105 +}
apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+8 -8
@@ -26,8 +26,8 @@ import { PullRequestCommentFooter } from "./PullRequestReactions";
26 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
27 import { usePullRequestPermissions } from "./usePullRequestPermissions";
28 import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
29 -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
30 -import { usePullRequestMentions } from "./usePullRequestMentions";
29 +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
30 +import { usePullRequestCompletions } from "./usePullRequestCompletions";
31
32 export function PullRequestDiscussionScreen({
33 route,
@@ -57,12 +57,12 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
57 const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false });
58 const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId);
59 const [body, setBody] = useState("");
60 - const mentions = usePullRequestMentions({
60 + const completions = usePullRequestCompletions({
61 environmentId: params.environmentId,
62 projectId: params.projectId,
63 value: body,
64 onChangeValue: setBody,
65 - enabled: detail.data?.capabilities.mentions === true,
65 + support: detail.data?.capabilities ?? null,
66 });
67 const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);
68 const [cursor, setCursor] = useState<string | null | undefined>();
@@ -235,7 +235,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
235 className="absolute inset-x-4 bottom-0 gap-2"
236 style={{ paddingBottom: bottomInset }}
237 >
238 - <PullRequestMentionSuggestions mentions={mentions} />
238 + <PullRequestCompletionSuggestions completions={completions} />
239 <GlassSurface
240 chrome="none"
241 onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
@@ -243,9 +243,9 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
243 >
244 <TextInput
245 accessibilityLabel="Discussion reply"
246 - selection={mentions.selection}
247 - onSelectionChange={mentions.onSelectionChange}
248 - onBlur={mentions.onBlur}
246 + selection={completions.selection}
247 + onSelectionChange={completions.onSelectionChange}
248 + onBlur={completions.onBlur}
249 multiline
250 maxLength={65536}
251 placeholder="Reply…"
apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx
+8 -8
@@ -16,8 +16,8 @@ import { useAtomCommand } from "../../state/use-atom-command";
16 import { PullRequestSheetContent } from "./PullRequestSheetContent";
17 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
18 import { usePullRequestPermissions } from "./usePullRequestPermissions";
19 -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
20 -import { usePullRequestMentions } from "./usePullRequestMentions";
19 +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
20 +import { usePullRequestCompletions } from "./usePullRequestCompletions";
21
22 export type PullRequestEditParams = PullRequestParams &
23 (
@@ -51,12 +51,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd
51 : (pr?.body ?? null);
52 const [draft, setDraft] = useState<string | null>(null);
53 const value = draft ?? original ?? "";
54 - const mentions = usePullRequestMentions({
54 + const completions = usePullRequestCompletions({
55 environmentId: params.environmentId,
56 projectId: params.projectId,
57 value: value,
58 onChangeValue: setDraft,
59 - enabled: params.field !== "title" && pr?.capabilities.mentions === true,
59 + support: params.field === "title" ? null : (pr?.capabilities ?? null),
60 });
61 const [busy, setBusy] = useState(false);
62 const [error, setError] = useState<string | null>(null);
@@ -140,12 +140,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd
140 />
141 }
142 >
143 - <PullRequestMentionSuggestions mentions={mentions} />
143 + <PullRequestCompletionSuggestions completions={completions} />
144 <TextInput
145 multiline={params.field !== "title"}
146 - selection={mentions.selection}
147 - onSelectionChange={mentions.onSelectionChange}
148 - onBlur={mentions.onBlur}
146 + selection={completions.selection}
147 + onSelectionChange={completions.onSelectionChange}
148 + onBlur={completions.onBlur}
149 editable={!busy && original !== null}
150 autoFocus
151 accessibilityLabel={
apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
+8 -8
@@ -15,8 +15,8 @@ import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
15 import { reviewPositionLabel } from "./pullRequestDiffComments";
16 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
17 import { usePullRequestPermissions } from "./usePullRequestPermissions";
18 -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
19 -import { usePullRequestMentions } from "./usePullRequestMentions";
18 +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
19 +import { usePullRequestCompletions } from "./usePullRequestCompletions";
20
21 export type InlineCommentParams = PullRequestParams & {
22 readonly draftId?: string;
@@ -35,12 +35,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
35 const body = editedBody ?? saved?.body ?? "";
36 const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params)));
37 const { refresh: refreshDetail } = detail;
38 - const mentions = usePullRequestMentions({
38 + const completions = usePullRequestCompletions({
39 environmentId: params.environmentId,
40 projectId: params.projectId,
41 value: body,
42 onChangeValue: setBody,
43 - enabled: detail.data?.capabilities.mentions === true,
43 + support: detail.data?.capabilities ?? null,
44 });
45 useFocusEffect(refreshDetail);
46 const permissions = usePullRequestPermissions(params, detail.data);
@@ -110,12 +110,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
110 {params.code}
111 </Text>
112 </View>
113 - <PullRequestMentionSuggestions mentions={mentions} />
113 + <PullRequestCompletionSuggestions completions={completions} />
114 <TextInput
115 multiline
116 - selection={mentions.selection}
117 - onSelectionChange={mentions.onSelectionChange}
118 - onBlur={mentions.onBlur}
116 + selection={completions.selection}
117 + onSelectionChange={completions.onSelectionChange}
118 + onBlur={completions.onBlur}
119 editable={store.ready && !busy}
120 autoFocus
121 accessibilityLabel="Inline review comment"
apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx deleted
-65
@@ -1,65 +0,0 @@
1 -import { Pressable, ScrollView, StyleSheet, View } from "react-native";
2 -
3 -import { AppText as Text } from "../../components/ui/AppText";
4 -import { GlassSurface } from "../../components/ui/GlassSurface";
5 -import { PullRequestAvatar } from "./PullRequestPresentation";
6 -import type { usePullRequestMentions } from "./usePullRequestMentions";
7 -
8 -/** The `@` suggestions for a pull request text input, rendered just above it. */
9 -export function PullRequestMentionSuggestions({
10 - mentions,
11 -}: {
12 - readonly mentions: ReturnType<typeof usePullRequestMentions>;
13 -}) {
14 - if (!mentions.open) return null;
15 - return (
16 - <GlassSurface
17 - glassEffectStyle="clear"
18 - tintColorClassName="accent-glass-surface"
19 - style={{ borderRadius: 16, overflow: "hidden" }}
20 - >
21 - {mentions.candidates.length > 0 ? (
22 - <ScrollView
23 - className="max-h-[180px]"
24 - keyboardShouldPersistTaps="always"
25 - showsVerticalScrollIndicator={false}
26 - accessibilityLabel="Mention a user"
27 - >
28 - {mentions.candidates.map((actor, index) => (
29 - <Pressable
30 - key={actor.login}
31 - accessibilityRole="button"
32 - accessibilityLabel={`Mention ${actor.login}`}
33 - onPress={() => mentions.select(actor)}
34 - className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60"
35 - style={{
36 - borderBottomWidth:
37 - index === mentions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth,
38 - }}
39 - >
40 - <PullRequestAvatar actor={actor} size={20} />
41 - <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
42 - {actor.login}
43 - </Text>
44 - {actor.name && actor.name !== actor.login ? (
45 - <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
46 - {actor.name}
47 - </Text>
48 - ) : null}
49 - </Pressable>
50 - ))}
51 - </ScrollView>
52 - ) : (
53 - <View className="px-3.5 py-2.5">
54 - <Text className="text-xs text-foreground-tertiary">
55 - {mentions.isLoading
56 - ? "Searching users..."
57 - : mentions.failed
58 - ? "Couldn't search users on the host"
59 - : "No matching users"}
60 - </Text>
61 - </View>
62 - )}
63 - </GlassSurface>
64 - );
65 -}
apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
+8 -8
@@ -19,8 +19,8 @@ import { useAtomCommand } from "../../state/use-atom-command";
19 import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetContent";
20 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
21 import { usePullRequestPermissions } from "./usePullRequestPermissions";
22 -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
23 -import { usePullRequestMentions } from "./usePullRequestMentions";
22 +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions";
23 +import { usePullRequestCompletions } from "./usePullRequestCompletions";
24
25 function useActionSubmission(params: PullRequestParams) {
26 const navigation = useNavigation();
@@ -83,12 +83,12 @@ export function PullRequestReviewSheet({
83 ...draft,
84 ...(params.mode === "review" ? { summary: body } : { comment: body }),
85 }));
86 - const mentions = usePullRequestMentions({
86 + const completions = usePullRequestCompletions({
87 environmentId: params.environmentId,
88 projectId: params.projectId,
89 value: body,
90 onChangeValue: setBody,
91 - enabled: result.data?.capabilities.mentions === true,
91 + support: result.data?.capabilities ?? null,
92 });
93 const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha);
94 const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");
@@ -178,12 +178,12 @@ export function PullRequestReviewSheet({
178 <Text className="px-4 text-xs text-foreground-muted">
179 {reviewing ? "Summary" : "Comment"}
180 </Text>
181 - <PullRequestMentionSuggestions mentions={mentions} />
181 + <PullRequestCompletionSuggestions completions={completions} />
182 <TextInput
183 multiline
184 - selection={mentions.selection}
185 - onSelectionChange={mentions.onSelectionChange}
186 - onBlur={mentions.onBlur}
184 + selection={completions.selection}
185 + onSelectionChange={completions.onSelectionChange}
186 + onBlur={completions.onBlur}
187 accessibilityLabel={reviewing ? "Review summary" : "Comment"}
188 placeholder={
189 reviewing
apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts new
+82
@@ -0,0 +1,82 @@
1 +import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 +import {
3 + debouncedPullRequestCompletionSearch,
4 + detectPullRequestComposerTrigger,
5 + insertPullRequestCompletion,
6 + pullRequestCompletionKey,
7 + pullRequestCompletions,
8 + type PullRequestCompletion,
9 + type PullRequestCompletionSupport,
10 +} from "@t3tools/shared/pullRequestComposerTrigger";
11 +import { useState } from "react";
12 +import type { TextInputSelectionChangeEvent } from "react-native";
13 +
14 +import { composerPullRequests } from "../../state/pull-requests";
15 +import { useEnvironmentQuery } from "../../state/query";
16 +import { useDebouncedValue } from "../../state/queries";
17 +
18 +const COMPLETION_SUGGESTION_LIMIT = 6;
19 +
20 +/** Completes `@login`, `#123` and GitLab `!123` in a pull request text input. */
21 +export function usePullRequestCompletions(input: {
22 + readonly environmentId: string;
23 + readonly projectId: string;
24 + readonly value: string;
25 + readonly onChangeValue: (value: string) => void;
26 + /** What the pull request's host completes (its `capabilities`); null where the field takes none. */
27 + readonly support: PullRequestCompletionSupport | null;
28 +}) {
29 + const [selection, setSelection] = useState<{ start: number; end: number } | null>(null);
30 + // Set only right after an insertion, so the native input keeps its own caret otherwise.
31 + const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null);
32 + const trigger =
33 + input.support === null || selection === null || selection.start !== selection.end
34 + ? null
35 + : detectPullRequestComposerTrigger(input.value, selection.start, input.support);
36 + const key = pullRequestCompletionKey(trigger);
37 + const sentKey = useDebouncedValue(key, 250);
38 + const sent =
39 + trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey);
40 + const hosted = useEnvironmentQuery(
41 + trigger === null
42 + ? null
43 + : composerPullRequests.filterOptions({
44 + environmentId: EnvironmentId.make(input.environmentId),
45 + input:
46 + trigger.kind === "mention"
47 + ? {
48 + kind: "authors",
49 + projectId: ProjectId.make(input.projectId),
50 + ...(sent ? { query: sent } : {}),
51 + }
52 + : {
53 + kind: "references",
54 + projectId: ProjectId.make(input.projectId),
55 + sigil: trigger.sigil,
56 + ...(sent ? { query: sent } : {}),
57 + },
58 + }),
59 + );
60 + // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
61 + const candidates = pullRequestCompletions(trigger, hosted.data, COMPLETION_SUGGESTION_LIMIT);
62 +
63 + return {
64 + kind: trigger?.kind ?? null,
65 + candidates,
66 + isLoading: hosted.isPending || sentKey !== key,
67 + failed: hosted.error !== null,
68 + selection: placed ?? undefined,
69 + onSelectionChange: (event: TextInputSelectionChangeEvent) => {
70 + setSelection(event.nativeEvent.selection);
71 + setPlaced(null);
72 + },
73 + onBlur: () => setSelection(null),
74 + select: (completion: PullRequestCompletion) => {
75 + if (trigger === null) return;
76 + const next = insertPullRequestCompletion(input.value, trigger, completion.token);
77 + input.onChangeValue(next.text);
78 + setSelection({ start: next.cursor, end: next.cursor });
79 + setPlaced({ start: next.cursor, end: next.cursor });
80 + },
81 + };
82 +}
apps/mobile/src/features/pull-requests/usePullRequestMentions.ts deleted
-73
@@ -1,73 +0,0 @@
1 -import { EnvironmentId, ProjectId, type PullRequestActor } from "@t3tools/contracts";
2 -import {
3 - detectPullRequestMention,
4 - insertPullRequestMention,
5 - narrowPullRequestMentions,
6 -} from "@t3tools/shared/pullRequestComposerTrigger";
7 -import { useState } from "react";
8 -import type { TextInputSelectionChangeEvent } from "react-native";
9 -
10 -import { composerPullRequests } from "../../state/pull-requests";
11 -import { useEnvironmentQuery } from "../../state/query";
12 -import { useDebouncedValue } from "../../state/queries";
13 -
14 -const MENTION_SUGGESTION_LIMIT = 6;
15 -
16 -/** Completes `@login` in a pull request text input from the repository's users. */
17 -export function usePullRequestMentions(input: {
18 - readonly environmentId: string;
19 - readonly projectId: string;
20 - readonly value: string;
21 - readonly onChangeValue: (value: string) => void;
22 - /** The pull request's host completes mentions (`capabilities.mentions`), and the field takes them. */
23 - readonly enabled: boolean;
24 -}) {
25 - const [selection, setSelection] = useState<{ start: number; end: number } | null>(null);
26 - // Set only right after an insertion, so the native input keeps its own caret otherwise.
27 - const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null);
28 - const trigger =
29 - !input.enabled || selection === null || selection.start !== selection.end
30 - ? null
31 - : detectPullRequestMention(input.value, selection.start);
32 - const typed = trigger?.query ?? "";
33 - const search = typed === "" ? undefined : typed.slice(0, 100);
34 - const sent = useDebouncedValue(search, 250);
35 - const hosted = useEnvironmentQuery(
36 - trigger === null
37 - ? null
38 - : composerPullRequests.filterOptions({
39 - environmentId: EnvironmentId.make(input.environmentId),
40 - input: {
41 - kind: "authors",
42 - projectId: ProjectId.make(input.projectId),
43 - ...(sent ? { query: sent } : {}),
44 - },
45 - }),
46 - );
47 - // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
48 - const candidates = narrowPullRequestMentions(
49 - hosted.data?.authors ?? [],
50 - typed,
51 - MENTION_SUGGESTION_LIMIT,
52 - );
53 -
54 - return {
55 - open: trigger !== null,
56 - candidates,
57 - isLoading: hosted.isPending || sent !== search,
58 - failed: hosted.error !== null,
59 - selection: placed ?? undefined,
60 - onSelectionChange: (event: TextInputSelectionChangeEvent) => {
61 - setSelection(event.nativeEvent.selection);
62 - setPlaced(null);
63 - },
64 - onBlur: () => setSelection(null),
65 - select: (actor: PullRequestActor) => {
66 - if (trigger === null) return;
67 - const next = insertPullRequestMention(input.value, trigger, actor.login);
68 - input.onChangeValue(next.text);
69 - setSelection({ start: next.cursor, end: next.cursor });
70 - setPlaced({ start: next.cursor, end: next.cursor });
71 - },
72 - };
73 -}
apps/server/src/pullRequest/PullRequestService.test.ts
+44
@@ -1067,6 +1067,50 @@ it.effect("puts the author a query names exactly ahead of those it only begins",
1067 }),
1068 );
1069
1070 +it.effect("ranks references by number, keeping the host's recent-first order", () =>
1071 + Effect.gen(function* () {
1072 + const service = yield* makeService({
1073 + projects: [
1074 + project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
1075 + project({ id: "p2", title: "tree", workspaceRoot: "/b", repository: "pingdotgg/t3code" }),
1076 + ],
1077 + providers: [
1078 + fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1079 + searchRepositoryReferences: () =>
1080 + Effect.succeed({
1081 + items: [
1082 + { reference: "#129", kind: "issue", number: 129, title: "Newest", state: "open" },
1083 + {
1084 + reference: "#7",
1085 + kind: "issue",
1086 + number: 7,
1087 + title: "Fix #12 again",
1088 + state: "open",
1089 + },
1090 + {
1091 + reference: "#12",
1092 + kind: "change-request",
1093 + number: 12,
1094 + title: "Exact",
1095 + state: "merged",
1096 + },
1097 + { reference: "#120", kind: "issue", number: 120, title: "Older", state: "closed" },
1098 + ],
1099 + truncated: false,
1100 + }),
1101 + }),
1102 + ],
1103 + });
1104 +
1105 + const result = yield* service.filterOptions({ kind: "references", query: "12" });
1106 +
1107 + assert.deepStrictEqual(
1108 + result.references.map((candidate) => candidate.reference),
1109 + ["#12", "#129", "#120", "#7"],
1110 + );
1111 + }),
1112 +);
1113 +
1114 it.effect("tries another workspace on the same host for the viewer", () =>
1115 Effect.gen(function* () {
1116 const service = yield* makeService({
apps/server/src/pullRequest/PullRequestService.ts
+28 -3
@@ -47,6 +47,7 @@ import {
47 type PullRequestFilterOptions,
48 type PullRequestFilterOptionsInput,
49 type PullRequestActor,
50 + type PullRequestReferenceCandidate,
51 type PullRequestLabel,
52 type PullRequestListStatsResult,
53 type PullRequestProviderSummary,
@@ -622,6 +623,14 @@ function withRateLimitBackoff(
623 api.searchRepositoryAuthors,
624 ),
625 }),
626 + ...(api.searchRepositoryReferences === undefined
627 + ? {}
628 + : {
629 + searchRepositoryReferences: interactive(
630 + "searchRepositoryReferences",
631 + api.searchRepositoryReferences,
632 + ),
633 + }),
634 replyToThread: interactive("replyToThread", api.replyToThread),
635 setReaction: interactive("setReaction", api.setReaction),
636 setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
@@ -643,6 +652,8 @@ function rankFilterOptions<A>(
652 readonly query: string | undefined;
653 readonly keyOf: (item: A) => string;
654 readonly textsOf: (item: A) => ReadonlyArray<string | null>;
655 + /** Ties keep the hosts' order instead of sorting by key. */
656 + readonly hostOrder?: boolean;
657 },
658 ): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } {
659 const query = input.query?.trim().toLowerCase() ?? "";
@@ -669,7 +680,9 @@ function rankFilterOptions<A>(
680 .toSorted(
681 (left, right) =>
682 left.score - right.score ||
672 - left.key.localeCompare(right.key, undefined, { sensitivity: "base" }),
683 + (input.hostOrder === true
684 + ? 0
685 + : left.key.localeCompare(right.key, undefined, { sensitivity: "base" })),
686 );
687 return {
688 items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item),
@@ -2578,7 +2591,19 @@ export const make = Effect.gen(function* () {
2591 keyOf: (label) => label.name,
2592 textsOf: (label) => [label.name],
2593 });
2581 - return { labels: items, authors: [], truncated };
2594 + return { labels: items, authors: [], references: [], truncated };
2595 + }
2596 + if (input.kind === "references") {
2597 + const pages = yield* gather<PullRequestReferenceCandidate>((project) =>
2598 + project.api.searchRepositoryReferences?.({ ...refOf(project), sigil: input.sigil }),
2599 + );
2600 + const { items, truncated } = rankFilterOptions(pages, {
2601 + query: input.query,
2602 + keyOf: (candidate) => candidate.reference,
2603 + textsOf: (candidate) => [String(candidate.number), candidate.title],
2604 + hostOrder: true,
2605 + });
2606 + return { labels: [], authors: [], references: items, truncated };
2607 }
2608 const pages = yield* gather<PullRequestActor>((project) =>
2609 project.api.searchRepositoryAuthors?.(refOf(project)),
@@ -2588,7 +2613,7 @@ export const make = Effect.gen(function* () {
2613 keyOf: (author) => author.login,
2614 textsOf: (author) => [author.login, author.name],
2615 });
2591 - return { labels: [], authors: items, truncated };
2616 + return { labels: [], authors: items, references: [], truncated };
2617 });
2618
2619 const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) =>
apps/web/src/components/diffs/DiffCommentAnnotation.tsx
+4 -4
@@ -5,7 +5,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
5 import { Button } from "~/components/ui/button";
6 import {
7 PullRequestMarkdownTextarea,
8 - type PullRequestMentionScope,
8 + type PullRequestCompletionScope,
9 } from "~/components/pullRequest/PullRequestMarkdownTextarea";
10 import {
11 SpeechTextField,
@@ -41,7 +41,7 @@ interface DiffCommentAnnotationProps {
41 secondaryAction?: DiffCommentSecondaryAction;
42 focusOnMount?: boolean;
43 /** Set only for pull request comments, where `@` completes the repository's users. */
44 - mentionScope?: PullRequestMentionScope | null;
44 + completionScope?: PullRequestCompletionScope | null;
45 }
46
47 export function DiffCommentAnnotation({
@@ -60,7 +60,7 @@ export function DiffCommentAnnotation({
60 pending = false,
61 secondaryAction,
62 focusOnMount = true,
63 - mentionScope = null,
63 + completionScope = null,
64 }: DiffCommentAnnotationProps) {
65 const [localDraftText, setLocalDraftText] = useState("");
66 const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
@@ -129,7 +129,7 @@ export function DiffCommentAnnotation({
129 >
130 <PullRequestMarkdownTextarea
131 ref={textareaRef}
132 - mentionScope={mentionScope}
132 + completionScope={completionScope}
133 readOnly={speech?.freezesEditor}
134 autoFocus={focusOnMount}
135 size="sm"
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+4 -4
@@ -113,7 +113,7 @@ import {
113 ReviewThreadCard,
114 toViewerSide,
115 } from "./PullRequestReviewAnnotation";
116 -import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
116 +import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
117 import {
118 getFileViewedRange,
119 isFileDiffCollapsed,
@@ -558,7 +558,7 @@ function PullRequestCodeTab({
558 commit,
559 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
560 });
561 - const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
561 + const completionScope = pullRequestCompletionScope(detail, environmentId, reference);
562 const hostReview = detail.capabilities.review;
563 const review = {
564 inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -969,7 +969,7 @@ function PullRequestCodeTab({
969 canReact={detail.capabilities.reactions === true}
970 environmentId={environmentId}
971 reference={reference}
972 - mentionScope={mentionScope}
972 + completionScope={completionScope}
973 pending={threadPending}
974 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
975 fixLabel={fixFindingLabel}
@@ -1044,7 +1044,7 @@ function PullRequestCodeTab({
1044 kind="draft"
1045 rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
1046 text=""
1047 - mentionScope={canCommentOnLines ? mentionScope : null}
1047 + completionScope={canCommentOnLines ? completionScope : null}
1048 submitLabel={canCommentOnLines ? "Add to review" : "Add to agent"}
1049 {...(canCommentOnLines && onAddToAgentSelection
1050 ? {
apps/web/src/components/pullRequest/PullRequestCommentForm.tsx
+2 -2
@@ -12,7 +12,7 @@ import { toastManager } from "../ui/toast";
12 import { PullRequestGlyph } from "./pullRequestIcons";
13 import {
14 PullRequestMarkdownTextarea,
15 - pullRequestMentionScope,
15 + pullRequestCompletionScope,
16 } from "./PullRequestMarkdownTextarea";
17 import { pullRequestReviewKey } from "./pullRequestReviewStore";
18 import { useInlineActionConfirm } from "./useInlineActionConfirm";
@@ -113,7 +113,7 @@ export function PullRequestCommentForm({
113 <div className="space-y-2">
114 <PullRequestMarkdownTextarea
115 ref={textareaRef}
116 - mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
116 + completionScope={pullRequestCompletionScope(detail, environmentId, reference)}
117 // Lock while posting because success clears the draft.
118 disabled={locked}
119 readOnly={speech.freezesEditor}
apps/web/src/components/pullRequest/PullRequestComposer.tsx
+2 -2
@@ -16,7 +16,7 @@ import {
16 usePendingReviewComments,
17 usePullRequestReviewStore,
18 } from "./pullRequestReviewStore";
19 -import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
19 +import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
20
21 export function PullRequestComposer({
22 environmentId,
@@ -155,7 +155,7 @@ export function PullRequestComposer({
155 active={open && mode === "review"}
156 environmentId={environmentId}
157 reference={reference}
158 - mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
158 + completionScope={pullRequestCompletionScope(detail, environmentId, reference)}
159 term={term}
160 verdicts={verdicts}
161 requestChangesSummaryRequired={sourceControlClients
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+2 -2
@@ -66,7 +66,7 @@ import { useLiveRefresh } from "~/hooks/useLiveRefresh";
66 import { pullRequestEnvironment, usePullRequestTurnRefresh } from "~/state/pullRequests";
67 import { useAtomCommand } from "~/state/use-atom-command";
68 import { PullRequestStackMenu } from "./PullRequestStackMenu";
69 -import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
69 +import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
70 import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
71 import {
72 capitalizeTerm,
@@ -1779,7 +1779,7 @@ export function PullRequestDetailPanel({
1779 detail.capabilities.review.inlineComment && detail.viewerPermissions.comment
1780 }
1781 rangeComments={detail.capabilities.review.rangeComment === true}
1782 - mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
1782 + completionScope={pullRequestCompletionScope(detail, environmentId, reference)}
1783 onAskAboutLines={(comment, request) =>
1784 addSelectionToAgent({ comment, request }, { keepGuide: true })
1785 }
apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx
+1 -1
@@ -55,7 +55,7 @@ it("keeps Try again inside a short panel when a failed guide has long diagnostic
55 active
56 canComment={false}
57 rangeComments={false}
58 - mentionScope={null}
58 + completionScope={null}
59 onAskAboutLines={null}
60 onAskAboutStop={null}
61 onFinishReview={null}
apps/web/src/components/pullRequest/PullRequestGuideTab.tsx
+4 -4
@@ -17,7 +17,7 @@ import {
17 usePendingReviewComments,
18 usePullRequestReviewStore,
19 } from "./pullRequestReviewStore";
20 -import type { PullRequestMentionScope } from "./PullRequestMarkdownTextarea";
20 +import type { PullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
21
22 export function PullRequestGuideTab({
23 environmentId,
@@ -27,7 +27,7 @@ export function PullRequestGuideTab({
27 active,
28 canComment,
29 rangeComments,
30 - mentionScope,
30 + completionScope,
31 onAskAboutLines,
32 onAskAboutStop,
33 onFinishReview,
@@ -41,7 +41,7 @@ export function PullRequestGuideTab({
41 active: boolean;
42 canComment: boolean;
43 rangeComments: boolean;
44 - mentionScope: PullRequestMentionScope | null;
44 + completionScope: PullRequestCompletionScope | null;
45 onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null;
46 onAskAboutStop:
47 | ((stop: PullRequestReviewGuideStop, index: number, question: string) => void)
@@ -65,7 +65,7 @@ export function PullRequestGuideTab({
65 : {
66 canComment,
67 rangeComments,
68 - mentionScope,
68 + completionScope,
69 pending,
70 onComment: ({ path, oldPath, position, startPosition, body }) =>
71 addComment(reviewKey, {
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
+19 -4
@@ -37,6 +37,13 @@ vi.mock(import("~/state/pullRequests"), async (original) => ({
37 { login: "julius", name: "Julius", avatarUrl: null },
38 { login: "theo", name: "Theo", avatarUrl: null },
39 ],
40 + references:
41 + targets.length === 0
42 + ? []
43 + : [
44 + { reference: "#12", kind: "issue", number: 12, title: "Crash", state: "open" },
45 + { reference: "!12", kind: "change-request", number: 12, title: "Fix", state: "open" },
46 + ],
47 error: null,
48 isPending: false,
49 }),
@@ -61,7 +68,11 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
68 value={options?.value ?? "Original description"}
69 cwd="/repo"
70 environmentId={secondary}
64 - mentionScope={{ environmentId: secondary, projectId: ProjectId.make("project") }}
71 + completionScope={{
72 + environmentId: secondary,
73 + projectId: ProjectId.make("project"),
74 + support: { mentions: true, referenceSigils: ["#", "!"] },
75 + }}
76 label="Pull request description"
77 saving={false}
78 allowEmpty={options?.allowEmpty ?? false}
@@ -106,7 +117,7 @@ it("keeps an edited draft through revocation and saves it after access returns w
117 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
118 });
119
109 -it("completes an @mention on Enter and closes the list on Escape until the next keystroke", async () => {
120 +it("completes @mentions and !references on Enter, and Escape closes the list until the next keystroke", async () => {
121 setup();
122 permissions.allowed.add(secondary);
123 await using screen = await openEditor({ value: "" });
@@ -122,9 +133,13 @@ it("completes an @mention on Enter and closes the list on Escape until the next
133 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
134 await userEvent.keyboard("{Escape}");
135 await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
125 - expect(onCancel).not.toHaveBeenCalled();
126 -
136 await userEvent.type(textarea, "t");
137 await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
138 +
139 + await userEvent.type(textarea, " fixes !1");
140 + await expect.element(page.getByRole("option", { name: /Fix/ })).toBeVisible();
141 + await userEvent.keyboard("{Enter}");
142 + expect(textarea.value).toBe("Thanks @julius and @t fixes !12 ");
143 + expect(onCancel).not.toHaveBeenCalled();
144 expect(onSave).not.toHaveBeenCalled();
145 });
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
+4 -4
@@ -13,14 +13,14 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";
13 import { PullRequestMarkdown } from "./PullRequestMarkdown";
14 import {
15 PullRequestMarkdownTextarea,
16 - type PullRequestMentionScope,
16 + type PullRequestCompletionScope,
17 } from "./PullRequestMarkdownTextarea";
18
19 export function PullRequestMarkdownEditor({
20 value,
21 cwd,
22 environmentId,
23 - mentionScope,
23 + completionScope,
24 threadRef = null,
25 placeholder,
26 label,
@@ -33,7 +33,7 @@ export function PullRequestMarkdownEditor({
33 readonly value: string;
34 readonly cwd: string;
35 readonly environmentId: EnvironmentId;
36 - readonly mentionScope: PullRequestMentionScope | null;
36 + readonly completionScope: PullRequestCompletionScope | null;
37 readonly threadRef?: ScopedThreadRef | null;
38 readonly placeholder?: string | undefined;
39 readonly label: string;
@@ -110,7 +110,7 @@ export function PullRequestMarkdownEditor({
110 <PullRequestMarkdownTextarea
111 autoFocus
112 disabled={saving}
113 - mentionScope={mentionScope}
113 + completionScope={completionScope}
114 value={draft}
115 rows={6}
116 placeholder={placeholder}
apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx
+141 -59
@@ -1,15 +1,21 @@
1 import type {
2 EnvironmentId,
3 ProjectId,
4 - PullRequestActor,
4 PullRequestDetailView,
5 PullRequestRef,
6 + PullRequestReferenceCandidate,
7 } from "@t3tools/contracts";
8 import {
9 - detectPullRequestMention,
10 - insertPullRequestMention,
11 - narrowPullRequestMentions,
9 + debouncedPullRequestCompletionSearch,
10 + detectPullRequestComposerTrigger,
11 + insertPullRequestCompletion,
12 + pullRequestCompletionKey,
13 + pullRequestCompletions,
14 + type PullRequestCompletion,
15 + type PullRequestCompletionSupport,
16 + type PullRequestComposerTrigger,
17 } from "@t3tools/shared/pullRequestComposerTrigger";
18 +import { CircleCheckIcon, CircleDotIcon } from "lucide-react";
19 import { useId, useState, type Ref } from "react";
20 import { flushSync } from "react-dom";
21
@@ -19,27 +25,27 @@ import { useDebouncedValue } from "~/state/queries";
25
26 import { Popover, PopoverPopup } from "../ui/popover";
27 import { Textarea, type TextareaProps } from "../ui/textarea";
22 -import { PullRequestActorAvatar } from "./pullRequestPresentation";
28 +import { PULL_REQUEST_STATE_PRESENTATION } from "./pullRequestIcons";
29 +import { PullRequestActorAvatar, resolvePullRequestState } from "./pullRequestPresentation";
30
24 -/** The repository whose users an `@` completes. */
25 -export interface PullRequestMentionScope {
31 +/** The repository whose users `@` completes and whose issues and change requests `#` does. */
32 +export interface PullRequestCompletionScope {
33 readonly environmentId: EnvironmentId;
34 readonly projectId: ProjectId;
35 + readonly support: PullRequestCompletionSupport;
36 }
37
30 -/** Null on hosts that cannot search their users, so `@` never opens a list that cannot fill. */
31 -export function pullRequestMentionScope(
38 +/** Null on hosts that complete nothing, so no sigil opens a list that cannot fill. */
39 +export function pullRequestCompletionScope(
40 detail: Pick<PullRequestDetailView, "capabilities">,
41 environmentId: EnvironmentId,
42 reference: PullRequestRef,
35 -): PullRequestMentionScope | null {
36 - return detail.capabilities.mentions === true
37 - ? { environmentId, projectId: reference.projectId }
43 +): PullRequestCompletionScope | null {
44 + const { mentions, referenceSigils } = detail.capabilities;
45 + return mentions === true || (referenceSigils?.length ?? 0) > 0
46 + ? { environmentId, projectId: reference.projectId, support: { mentions, referenceSigils } }
47 : null;
48 }
40 -
41 -const MENTION_SEARCH_DEBOUNCE_MS = 200;
42 -const MENTION_SUGGESTION_LIMIT = 8;
49 // About a full list of suggestions. The popup fits itself to the space it opens into, so it never
50 // flips once results grow it; the side is picked up front from the room a full list needs.
51 const SUGGESTION_LIST_HEIGHT = 320;
@@ -50,43 +56,117 @@ function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" {
56 return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom";
57 }
58
53 -function useMentionCandidates(scope: PullRequestMentionScope | null, query: string | null) {
54 - const typed = query ?? "";
55 - const search = typed === "" ? undefined : typed.slice(0, 100);
56 - const sent = useDebouncedValue(search, MENTION_SEARCH_DEBOUNCE_MS);
59 +const COMPLETION_SEARCH_DEBOUNCE_MS = 200;
60 +const COMPLETION_SUGGESTION_LIMIT = 8;
61 +
62 +function useCompletions(
63 + scope: PullRequestCompletionScope | null,
64 + trigger: PullRequestComposerTrigger | null,
65 +) {
66 + const key = pullRequestCompletionKey(trigger);
67 + const sentKey = useDebouncedValue(key, COMPLETION_SEARCH_DEBOUNCE_MS);
68 + const sent =
69 + trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey);
70 const hosted = usePullRequestFilterOptions(
58 - scope === null || query === null
71 + scope === null || trigger === null
72 ? []
73 : [
74 {
75 environmentId: scope.environmentId,
63 - input: {
64 - kind: "authors",
65 - projectId: scope.projectId,
66 - ...(sent ? { query: sent } : {}),
67 - },
76 + input:
77 + trigger.kind === "mention"
78 + ? { kind: "authors", projectId: scope.projectId, ...(sent ? { query: sent } : {}) }
79 + : {
80 + kind: "references",
81 + projectId: scope.projectId,
82 + sigil: trigger.sigil,
83 + ...(sent ? { query: sent } : {}),
84 + },
85 },
86 ],
87 );
88 // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
89 + const completions = pullRequestCompletions(trigger, hosted, COMPLETION_SUGGESTION_LIMIT);
90 return {
73 - candidates: narrowPullRequestMentions(hosted.authors, typed, MENTION_SUGGESTION_LIMIT),
74 - isPending: hosted.isPending || sent !== search,
91 + completions,
92 + isPending: hosted.isPending || sentKey !== key,
93 failed: hosted.error !== null,
94 };
95 }
96
97 +function ReferenceStateIcon({ candidate }: { candidate: PullRequestReferenceCandidate }) {
98 + const presentation =
99 + candidate.kind === "change-request"
100 + ? resolvePullRequestState({ state: candidate.state, isDraft: false })
101 + : candidate.state === "open"
102 + ? {
103 + label: "Open issue",
104 + Icon: CircleDotIcon,
105 + toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName,
106 + }
107 + : {
108 + label: "Closed issue",
109 + Icon: CircleCheckIcon,
110 + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName,
111 + };
112 + return (
113 + <presentation.Icon
114 + role="img"
115 + aria-label={presentation.label}
116 + className={cn("size-4 shrink-0", presentation.toneClassName)}
117 + />
118 + );
119 +}
120 +
121 +function CompletionRow({ completion }: { completion: PullRequestCompletion }) {
122 + if (completion.kind === "mention") {
123 + const { actor } = completion;
124 + return (
125 + <>
126 + <PullRequestActorAvatar actor={actor} className="size-5" />
127 + <span className="truncate font-medium">{actor.login}</span>
128 + {actor.name && actor.name !== actor.login ? (
129 + <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>
130 + ) : null}
131 + </>
132 + );
133 + }
134 + const { candidate } = completion;
135 + return (
136 + <>
137 + <ReferenceStateIcon candidate={candidate} />
138 + <span className="shrink-0 font-medium tabular-nums">{candidate.reference}</span>
139 + <span className="min-w-0 truncate text-muted-foreground">{candidate.title}</span>
140 + </>
141 + );
142 +}
143 +
144 +const EMPTY_STATE = {
145 + mention: {
146 + label: "Mention a user",
147 + pending: "Searching users...",
148 + failed: "Couldn't search users on the host",
149 + none: "No matching users",
150 + },
151 + reference: {
152 + label: "Reference an issue or change request",
153 + pending: "Searching...",
154 + failed: "Couldn't search the host",
155 + none: "No matching issues or change requests",
156 + },
157 +} as const;
158 +
159 function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
160 if (typeof ref === "function") ref(value);
161 else if (ref) ref.current = value;
162 }
163
84 -/** A markdown textarea for pull request text that completes `@login` from the repository's users. */
164 +/** A markdown textarea for pull request text that completes `@login`, `#123` and GitLab `!123`. */
165 export function PullRequestMarkdownTextarea({
166 ref,
167 value,
168 onValueChange,
89 - mentionScope,
169 + completionScope,
170 onKeyDown,
171 onSelect,
172 onFocus,
@@ -95,7 +175,7 @@ export function PullRequestMarkdownTextarea({
175 }: Omit<TextareaProps, "value" | "onChange"> & {
176 readonly value: string;
177 readonly onValueChange: (value: string) => void;
98 - readonly mentionScope: PullRequestMentionScope | null;
178 + readonly completionScope: PullRequestCompletionScope | null;
179 }) {
180 const listId = useId();
181 const [element, setElement] = useState<HTMLTextAreaElement | null>(null);
@@ -105,29 +185,30 @@ export function PullRequestMarkdownTextarea({
185 const [highlight, setHighlight] = useState({ query: "", index: 0 });
186
187 const trigger =
108 - mentionScope === null || caret === null || props.readOnly
188 + completionScope === null || caret === null || props.readOnly
189 ? null
110 - : detectPullRequestMention(value, caret);
190 + : detectPullRequestComposerTrigger(value, caret, completionScope.support);
191 const open = trigger !== null && trigger.rangeStart !== dismissedAt;
112 - const { candidates, isPending, failed } = useMentionCandidates(
113 - mentionScope,
114 - open ? trigger.query : null,
115 - );
192 + const {
193 + completions: candidates,
194 + isPending,
195 + failed,
196 + } = useCompletions(completionScope, open ? trigger : null);
197 const activeIndex =
198 trigger !== null && highlight.query === trigger.query
199 ? Math.min(highlight.index, Math.max(0, candidates.length - 1))
200 : 0;
201 const active = open ? candidates[activeIndex] : undefined;
121 - const optionId = (login: string) => `${listId}-${login}`;
202 + const optionId = (token: string) => `${listId}-${token}`;
203
204 const syncCaret = (target: HTMLTextAreaElement) => {
205 setSide(suggestionSide(target));
206 setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null);
207 };
208
128 - const select = (actor: PullRequestActor) => {
209 + const select = (completion: PullRequestCompletion) => {
210 if (trigger === null || element === null) return;
130 - const next = insertPullRequestMention(value, trigger, actor.login);
211 + const next = insertPullRequestCompletion(value, trigger, completion.token);
212 flushSync(() => onValueChange(next.text));
213 element.setSelectionRange(next.cursor, next.cursor);
214 setCaret(next.cursor);
@@ -142,11 +223,11 @@ export function PullRequestMarkdownTextarea({
223 assignRef(ref, node);
224 }}
225 value={value}
145 - role={mentionScope === null ? undefined : "combobox"}
146 - aria-autocomplete={mentionScope === null ? undefined : "list"}
147 - aria-expanded={mentionScope === null ? undefined : open}
226 + role={completionScope === null ? undefined : "combobox"}
227 + aria-autocomplete={completionScope === null ? undefined : "list"}
228 + aria-expanded={completionScope === null ? undefined : open}
229 aria-controls={open && candidates.length > 0 ? listId : undefined}
149 - aria-activedescendant={active ? optionId(active.login) : undefined}
230 + aria-activedescendant={active ? optionId(active.token) : undefined}
231 onChange={(event) => {
232 onValueChange(event.target.value);
233 syncCaret(event.target);
@@ -210,16 +291,21 @@ export function PullRequestMarkdownTextarea({
291 side={side}
292 align="start"
293 padding="compact"
213 - width="sm"
294 + width={trigger?.kind === "reference" ? "md" : "sm"}
295 initialFocus={false}
296 finalFocus={false}
297 >
298 {candidates.length > 0 ? (
218 - <div id={listId} role="listbox" aria-label="Mention a user" className="-mx-1.5">
219 - {candidates.map((actor, index) => (
299 + <div
300 + id={listId}
301 + role="listbox"
302 + aria-label={EMPTY_STATE[trigger?.kind ?? "mention"].label}
303 + className="-mx-1.5"
304 + >
305 + {candidates.map((completion, index) => (
306 <div
221 - key={actor.login}
222 - id={optionId(actor.login)}
307 + key={completion.token}
308 + id={optionId(completion.token)}
309 role="option"
310 aria-selected={index === activeIndex}
311 className={cn(
@@ -231,23 +317,19 @@ export function PullRequestMarkdownTextarea({
317 }}
318 // Keeps focus, and the caret, in the textarea.
319 onMouseDown={(event) => event.preventDefault()}
234 - onClick={() => select(actor)}
320 + onClick={() => select(completion)}
321 >
236 - <PullRequestActorAvatar actor={actor} className="size-5" />
237 - <span className="truncate font-medium">{actor.login}</span>
238 - {actor.name && actor.name !== actor.login ? (
239 - <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>
240 - ) : null}
322 + <CompletionRow completion={completion} />
323 </div>
324 ))}
325 </div>
326 ) : (
327 <p className="px-1 text-xs text-muted-foreground">
246 - {isPending
247 - ? "Searching users..."
248 - : failed
249 - ? "Couldn't search users on the host"
250 - : "No matching users"}
328 + {
329 + EMPTY_STATE[trigger?.kind ?? "mention"][
330 + isPending ? "pending" : failed ? "failed" : "none"
331 + ]
332 + }
333 </p>
334 )}
335 </PopoverPopup>
apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+5 -5
@@ -32,7 +32,7 @@ import { PullRequestReactionBar } from "./PullRequestReactions";
32 import type { PendingReviewComment } from "./pullRequestReviewStore";
33 import {
34 PullRequestMarkdownTextarea,
35 - type PullRequestMentionScope,
35 + type PullRequestCompletionScope,
36 } from "./PullRequestMarkdownTextarea";
37
38 const CARD_CLASS =
@@ -117,7 +117,7 @@ export function ReviewThreadCard({
117 canReact,
118 environmentId,
119 reference,
120 - mentionScope,
120 + completionScope,
121 pending,
122 fixPending,
123 fixLabel = "Fix in a thread",
@@ -137,7 +137,7 @@ export function ReviewThreadCard({
137 canReact: boolean;
138 environmentId: EnvironmentId;
139 reference: PullRequestRef;
140 - mentionScope: PullRequestMentionScope | null;
140 + completionScope: PullRequestCompletionScope | null;
141 pending: boolean;
142 fixPending?: boolean;
143 fixLabel?: string;
@@ -310,7 +310,7 @@ export function ReviewThreadCard({
310 value={comment.body}
311 cwd={workspaceRoot}
312 environmentId={environmentId}
313 - mentionScope={mentionScope}
313 + completionScope={completionScope}
314 label="Edit comment"
315 saving={savingEdit}
316 onSave={(body) => void saveEdit(comment.id, body)}
@@ -366,7 +366,7 @@ export function ReviewThreadCard({
366 readOnly={speech.freezesEditor}
367 autoFocus
368 size="sm"
369 - mentionScope={mentionScope}
369 + completionScope={completionScope}
370 value={reply}
371 placeholder="Reply"
372 aria-label="Reply to this conversation"
apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx
+1 -1
@@ -37,7 +37,7 @@ it("submits only the line comments still in the draft when dictation finishes",
37 active
38 environmentId={EnvironmentId.make("test")}
39 reference={reference}
40 - mentionScope={null}
40 + completionScope={null}
41 term="pull request"
42 verdicts={["comment"]}
43 requestChangesSummaryRequired={false}
apps/web/src/components/pullRequest/PullRequestReviewForm.tsx
+4 -4
@@ -20,7 +20,7 @@ import {
20 } from "./pullRequestReviewStore";
21 import {
22 PullRequestMarkdownTextarea,
23 - type PullRequestMentionScope,
23 + type PullRequestCompletionScope,
24 } from "./PullRequestMarkdownTextarea";
25
26 const VERDICTS: ReadonlyArray<{
@@ -53,7 +53,7 @@ export function PullRequestReviewForm({
53 environmentId,
54 active,
55 reference,
56 - mentionScope,
56 + completionScope,
57 term,
58 verdicts,
59 requestChangesSummaryRequired,
@@ -66,7 +66,7 @@ export function PullRequestReviewForm({
66 /** False while the form stays mounted but hidden; dictation is cancelled then. */
67 active: boolean;
68 reference: PullRequestRef;
69 - mentionScope: PullRequestMentionScope | null;
69 + completionScope: PullRequestCompletionScope | null;
70 /** The host's word for a change request, as in "pull request". */
71 term: string;
72 verdicts: ReadonlyArray<PullRequestReviewVerdict>;
@@ -157,7 +157,7 @@ export function PullRequestReviewForm({
157 <>
158 <PullRequestMarkdownTextarea
159 ref={textareaRef}
160 - mentionScope={mentionScope}
160 + completionScope={completionScope}
161 rows={3}
162 readOnly={speech.freezesEditor}
163 value={body}
apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+7 -7
@@ -87,8 +87,8 @@ import { PullRequestCommentBody } from "./PullRequestCommentBody";
87 import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
88 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
89 import {
90 - type PullRequestMentionScope,
91 - pullRequestMentionScope,
90 + type PullRequestCompletionScope,
91 + pullRequestCompletionScope,
92 } from "./PullRequestMarkdownTextarea";
93 import { PullRequestReactionBar } from "./PullRequestReactions";
94 import { PullRequestConversationGhost } from "./PullRequestGhosts";
@@ -169,7 +169,7 @@ function reviewStateLabel(state: string): string {
169 interface CommentEditing {
170 readonly cwd: string;
171 readonly environmentId: EnvironmentId;
172 - readonly mentionScope: PullRequestMentionScope | null;
172 + readonly completionScope: PullRequestCompletionScope | null;
173 readonly threadRef: ScopedThreadRef | null;
174 readonly canEdit: (comment: PullRequestComment) => boolean;
175 readonly editingId: string | null;
@@ -194,7 +194,7 @@ function CommentBody({
194 value={comment.body}
195 cwd={editing.cwd}
196 environmentId={editing.environmentId}
197 - mentionScope={editing.mentionScope}
197 + completionScope={editing.completionScope}
198 threadRef={editing.threadRef}
199 label="Edit comment"
200 saving={editing.saving}
@@ -584,11 +584,11 @@ export function PullRequestSummaryTab({
584 if (body !== description) void saveDescription(body);
585 };
586
587 - const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
587 + const completionScope = pullRequestCompletionScope(detail, environmentId, reference);
588 const commentEditing: CommentEditing = {
589 cwd: detail.workspaceRoot,
590 environmentId,
591 - mentionScope,
591 + completionScope,
592 threadRef,
593 canEdit: (comment) => canEditPullRequestComment(detail, comment),
594 editingId: editingCommentId,
@@ -845,7 +845,7 @@ export function PullRequestSummaryTab({
845 value={bodyScope.body}
846 cwd={detail.workspaceRoot}
847 environmentId={environmentId}
848 - mentionScope={mentionScope}
848 + completionScope={completionScope}
849 threadRef={threadRef}
850 label={`${capitalizeTerm(terminology.singular)} description`}
851 placeholder={`Describe this ${terminology.singular}`}
apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+5 -5
@@ -60,8 +60,8 @@ import {
60 } from "./pullRequestPresentation";
61 import { PullRequestGlyph } from "./pullRequestIcons";
62 import {
63 - type PullRequestMentionScope,
64 - pullRequestMentionScope,
63 + type PullRequestCompletionScope,
64 + pullRequestCompletionScope,
65 } from "./PullRequestMarkdownTextarea";
66 import { LegendList, type LegendListRef } from "@legendapp/list/react";
67
@@ -72,7 +72,7 @@ interface ReactionSurface {
72 readonly environmentId: EnvironmentId;
73 readonly threadRef: ScopedThreadRef | null;
74 readonly reference: PullRequestRef;
75 - readonly mentionScope: PullRequestMentionScope | null;
75 + readonly completionScope: PullRequestCompletionScope | null;
76 readonly onRefresh: () => void;
77 }
78
@@ -306,7 +306,7 @@ function ConversationCard({
306 value={editable.body}
307 cwd={cwd}
308 environmentId={reactions.environmentId}
309 - mentionScope={reactions.mentionScope}
309 + completionScope={reactions.completionScope}
310 threadRef={reactions.threadRef}
311 label="Edit comment"
312 saving={saving}
@@ -704,7 +704,7 @@ export function PullRequestTimelineTab({
704 environmentId,
705 threadRef,
706 reference,
707 - mentionScope: pullRequestMentionScope(detail, environmentId, reference),
707 + completionScope: pullRequestCompletionScope(detail, environmentId, reference),
708 onRefresh,
709 };
710 const editable = new Map(
apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
+3 -3
@@ -37,7 +37,7 @@ import {
37 fileDiffRows,
38 rowsToPatch,
39 } from "@t3tools/client-runtime/review-guide-tour";
40 -import type { PullRequestMentionScope } from "../PullRequestMarkdownTextarea";
40 +import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea";
41 import { GuideNoteMarker } from "./GuideNotes";
42 import { GuideProse } from "./GuideProse";
43
@@ -56,7 +56,7 @@ export interface ExcerptCommenting {
56 readonly canComment: boolean;
57 /** The host anchors a comment to a range of lines rather than to its last one. */
58 readonly rangeComments: boolean;
59 - readonly mentionScope: PullRequestMentionScope | null;
59 + readonly completionScope: PullRequestCompletionScope | null;
60 readonly pending: ReadonlyArray<PendingReviewComment>;
61 readonly onComment: (comment: {
62 readonly path: string;
@@ -325,7 +325,7 @@ function ExcerptDiff({
325 kind="draft"
326 rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
327 text=""
328 - mentionScope={commenting.canComment ? commenting.mentionScope : null}
328 + completionScope={commenting.canComment ? commenting.completionScope : null}
329 placeholder={
330 commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"
331 }
apps/web/src/state/pullRequests.ts
+1
@@ -647,6 +647,7 @@ export function usePullRequestFilterOptions(
647 return {
648 labels: query.values.flatMap(([, options]) => options.labels),
649 authors: query.values.flatMap(([, options]) => options.authors),
650 + references: query.values.flatMap(([, options]) => options.references),
651 error: query.error,
652 isPending: query.isPending,
653 };
packages/contracts/src/pullRequest.ts
+23 -1
@@ -257,6 +257,10 @@ export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabili
257 export const PullRequestViewedFilesStore = Schema.Literals(["host", "environment"]);
258 export type PullRequestViewedFilesStore = typeof PullRequestViewedFilesStore.Type;
259
260 +/** `#` references issues (and GitHub pull requests); `!` references GitLab merge requests. */
261 +export const PullRequestReferenceSigil = Schema.Literals(["#", "!"]);
262 +export type PullRequestReferenceSigil = typeof PullRequestReferenceSigil.Type;
263 +
264 export const PullRequestCapabilities = Schema.Struct({
265 diff: Schema.Boolean,
266 comment: Schema.Boolean,
@@ -279,6 +283,8 @@ export const PullRequestCapabilities = Schema.Struct({
283 labels: Schema.optional(Schema.Boolean),
284 /** The host searches the repository's users, so composers can complete `@login`. */
285 mentions: Schema.optional(Schema.Boolean),
286 + /** The sigils whose issue and change request references composers can complete. */
287 + referenceSigils: Schema.optional(ForwardCompatibleArray(PullRequestReferenceSigil)),
288 /**
289 * Every head gets at least one check, so a head that has gone a while without any means none
290 * reported rather than that the repository runs none. Absent means an empty list says nothing.
@@ -523,7 +529,7 @@ export const PullRequestListStatsResult = Schema.Struct({
529 });
530 export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;
531
526 -export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors"]);
532 +export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors", "references"]);
533 export type PullRequestFilterOptionKind = typeof PullRequestFilterOptionKind.Type;
534
535 /** Scoped like `PullRequestListInput`, so the options come from the repositories it lists. */
@@ -533,12 +539,28 @@ export const PullRequestFilterOptionsInput = Schema.Struct({
539 projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),
540 host: Schema.optional(TrimmedNonEmptyString),
541 query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),
542 + /** For `references`, the sigil typed, so a host can search only what it links. */
543 + sigil: Schema.optional(PullRequestReferenceSigil),
544 });
545 export type PullRequestFilterOptionsInput = typeof PullRequestFilterOptionsInput.Type;
546
547 +/** An issue or change request a composer can reference, with the text the host links. */
548 +export const PullRequestReferenceCandidate = Schema.Struct({
549 + reference: TrimmedNonEmptyString,
550 + kind: Schema.Literals(["issue", "change-request"]),
551 + number: PositiveInt,
552 + title: Schema.String,
553 + state: Schema.Literals(["open", "closed", "merged"]),
554 +});
555 +export type PullRequestReferenceCandidate = typeof PullRequestReferenceCandidate.Type;
556 +
557 export const PullRequestFilterOptions = Schema.Struct({
558 labels: Schema.Array(PullRequestLabel),
559 authors: Schema.Array(PullRequestActor),
560 + // Servers from before reference completion send no key.
561 + references: Schema.Array(PullRequestReferenceCandidate).pipe(
562 + Schema.withDecodingDefault(Effect.succeed([])),
563 + ),
564 truncated: Schema.Boolean,
565 });
566 export type PullRequestFilterOptions = typeof PullRequestFilterOptions.Type;
packages/shared/src/pullRequestComposerTrigger.test.ts
+69 -19
@@ -1,20 +1,30 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 - detectPullRequestMention,
5 - insertPullRequestMention,
4 + debouncedPullRequestCompletionSearch,
5 + detectPullRequestComposerTrigger,
6 + insertPullRequestCompletion,
7 narrowPullRequestMentions,
8 + narrowPullRequestReferences,
9 } from "./pullRequestComposerTrigger.ts";
10
9 -describe("detectPullRequestMention", () => {
11 +const GITLAB = { mentions: true, referenceSigils: ["#", "!"] } as const;
12 +
13 +describe("detectPullRequestComposerTrigger", () => {
14 it.each([
11 - ["@", 0, ""],
12 - ["cc @ju", 3, "ju"],
13 - ["line one\n@first.last", 9, "first.last"],
14 - ["@jane-doe more", 0, "jane-doe"],
15 - ])("finds the mention in %j", (text, rangeStart, query) => {
15 + ["@", 0, "@", ""],
16 + ["cc @ju", 3, "@", "ju"],
17 + ["line one\n@first.last", 9, "@", "first.last"],
18 + ["@jane-doe more", 0, "@", "jane-doe"],
19 + ["fixes #", 6, "#", ""],
20 + ["see #12", 4, "#", "12"],
21 + ["after !5", 6, "!", "5"],
22 + ["#crash", 0, "#", "crash"],
23 + ])("finds the trigger in %j", (text, rangeStart, sigil, query) => {
24 const cursor = rangeStart + 1 + query.length;
17 - expect(detectPullRequestMention(text, cursor)).toEqual({
25 + expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toEqual({
26 + kind: sigil === "@" ? "mention" : "reference",
27 + sigil,
28 query,
29 rangeStart,
30 rangeEnd: cursor,
@@ -27,18 +37,30 @@ describe("detectPullRequestMention", () => {
37 ["@-jane", "@-jane".length],
38 ["`@decorator`", "`@decorator".length],
39 ["@jane", 3],
40 + ["C#", 2],
41 + ["![image", "![image".length],
42 + ["## Heading", 2],
43 ])("ignores %j", (text, cursor) => {
31 - expect(detectPullRequestMention(text, cursor)).toBeNull();
44 + expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toBeNull();
45 + });
46 +
47 + it.each([
48 + ["@ju", {}],
49 + ["#12", { mentions: true }],
50 + ["!important", { mentions: true, referenceSigils: ["#"] }],
51 + ["#12", { mentions: true, referenceSigils: [] }],
52 + ] as const)("ignores %j on a host that cannot complete it", (text, support) => {
53 + expect(detectPullRequestComposerTrigger(text, text.length, support)).toBeNull();
54 });
55 });
56
35 -describe("insertPullRequestMention", () => {
57 +describe("insertPullRequestCompletion", () => {
58 it.each(["", "\nnext line", "\r\nnext line"])(
37 - "replaces the partial login and adds a space before %j",
59 + "replaces the partial token and adds a space before %j",
60 (suffix) => {
61 const text = `thanks @ju${suffix}`;
40 - const trigger = detectPullRequestMention(text, "thanks @ju".length)!;
41 - expect(insertPullRequestMention(text, trigger, "julius")).toEqual({
62 + const trigger = detectPullRequestComposerTrigger(text, "thanks @ju".length, GITLAB)!;
63 + expect(insertPullRequestCompletion(text, trigger, "@julius")).toEqual({
64 text: `thanks @julius ${suffix}`,
65 cursor: "thanks @julius ".length,
66 });
@@ -46,11 +68,23 @@ describe("insertPullRequestMention", () => {
68 );
69
70 it("reuses the space that already follows and moves past it", () => {
49 - const text = "@ju please look";
50 - const trigger = detectPullRequestMention(text, 3)!;
51 - const inserted = insertPullRequestMention(text, trigger, "julius");
52 - expect(inserted).toEqual({ text: "@julius please look", cursor: "@julius ".length });
53 - expect(detectPullRequestMention(inserted.text, inserted.cursor)).toBeNull();
71 + const text = "#1 please look";
72 + const trigger = detectPullRequestComposerTrigger(text, 2, GITLAB)!;
73 + const inserted = insertPullRequestCompletion(text, trigger, "#123");
74 + expect(inserted).toEqual({ text: "#123 please look", cursor: "#123 ".length });
75 + expect(detectPullRequestComposerTrigger(inserted.text, inserted.cursor, GITLAB)).toBeNull();
76 + });
77 +});
78 +
79 +describe("debouncedPullRequestCompletionSearch", () => {
80 + it.each([
81 + ["a settled search", { sigil: "#" }, "#crash", "crash"],
82 + ["a settled bare sigil", { sigil: "@" }, "@", undefined],
83 + ["a lagging search", { sigil: "#" }, "#cra", "cra"],
84 + ["the other sigil's key", { sigil: "!" }, "#12", undefined],
85 + ["no key yet", { sigil: "#" }, null, undefined],
86 + ] as const)("sends %s as the host search", (_, trigger, key, sent) => {
87 + expect(debouncedPullRequestCompletionSearch(trigger, key)).toBe(sent);
88 });
89 });
90
@@ -68,3 +102,19 @@ describe("narrowPullRequestMentions", () => {
102 expect(narrowPullRequestMentions(users, "", 2)).toHaveLength(2);
103 });
104 });
105 +
106 +describe("narrowPullRequestReferences", () => {
107 + it("keeps the sigil's kind and matches a number prefix or the title", () => {
108 + const candidates = [
109 + { reference: "#12", number: 12, title: "Crash on start" },
110 + { reference: "!12", number: 12, title: "Fix the crash" },
111 + { reference: "#3", number: 3, title: "Issue 12 follow-up" },
112 + { reference: "#120", number: 120, title: "Docs" },
113 + ];
114 + const narrowed = (sigil: "#" | "!", query: string) =>
115 + narrowPullRequestReferences(candidates, { sigil, query }, 5).map((c) => c.reference);
116 + expect(narrowed("#", "12")).toEqual(["#12", "#3", "#120"]);
117 + expect(narrowed("!", "CRASH")).toEqual(["!12"]);
118 + expect(narrowed("#", "")).toEqual(["#12", "#3", "#120"]);
119 + });
120 +});
packages/shared/src/pullRequestComposerTrigger.ts
+111 -14
@@ -1,42 +1,92 @@
1 +import type {
2 + PullRequestActor,
3 + PullRequestCapabilities,
4 + PullRequestFilterOptions,
5 + PullRequestReferenceCandidate,
6 + PullRequestReferenceSigil,
7 +} from "@t3tools/contracts";
8 +
9 import { replaceTextRange } from "./composerTrigger.ts";
10
3 -export interface PullRequestMentionTrigger {
11 +export type PullRequestComposerTrigger = {
12 readonly query: string;
13 readonly rangeStart: number;
14 readonly rangeEnd: number;
7 -}
15 +} & (
16 + | { readonly kind: "mention"; readonly sigil: "@" }
17 + | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil }
18 +);
19 +
20 +// Mentions cover GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).
21 +const TOKEN = /^(?:@([A-Za-z0-9_][A-Za-z0-9_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u;
22
9 -// Covers GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).
10 -const MENTION_TOKEN = /^@([A-Za-z0-9_][A-Za-z0-9_.-]*)?$/;
23 +/** What a pull request's host can complete; absent fields complete nothing. */
24 +export type PullRequestCompletionSupport = Pick<
25 + PullRequestCapabilities,
26 + "mentions" | "referenceSigils"
27 +>;
28
12 -/** The `@login` being typed at the caret, when the caret sits at its end. */
13 -export function detectPullRequestMention(
29 +/**
30 + * The `@login`, `#123` or `!123` being typed at the caret, when the caret sits at its end and the
31 + * host completes that sigil.
32 + */
33 +export function detectPullRequestComposerTrigger(
34 text: string,
35 cursor: number,
16 -): PullRequestMentionTrigger | null {
36 + support: PullRequestCompletionSupport,
37 +): PullRequestComposerTrigger | null {
38 const end = Math.max(0, Math.min(text.length, cursor));
39 const next = text[end];
40 if (next !== undefined && !/\s/.test(next)) return null;
41 let start = end;
42 while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;
22 - const match = MENTION_TOKEN.exec(text.slice(start, end));
43 + const match = TOKEN.exec(text.slice(start, end));
44 if (!match) return null;
24 - return { query: match[1] ?? "", rangeStart: start, rangeEnd: end };
45 + const sigil = match[2];
46 + if (sigil === "#" || sigil === "!") {
47 + return support.referenceSigils?.includes(sigil)
48 + ? { kind: "reference", sigil, query: match[3] ?? "", rangeStart: start, rangeEnd: end }
49 + : null;
50 + }
51 + return support.mentions === true
52 + ? { kind: "mention", sigil: "@", query: match[1] ?? "", rangeStart: start, rangeEnd: end }
53 + : null;
54 }
55
27 -export function insertPullRequestMention(
56 +/** Replaces the trigger with `token` and leaves the caret past the space after it. */
57 +export function insertPullRequestCompletion(
58 text: string,
29 - trigger: PullRequestMentionTrigger,
30 - login: string,
59 + trigger: PullRequestComposerTrigger,
60 + token: string,
61 ): { text: string; cursor: number } {
62 const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? "");
63 if (!followedBySpace) {
34 - return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login} `);
64 + return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `${token} `);
65 }
36 - const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login}`);
66 + const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, token);
67 return { ...inserted, cursor: inserted.cursor + 1 };
68 }
69
70 +/** The key a debounce delays: the trigger's sigil and its host search, or `null` with no trigger. */
71 +export function pullRequestCompletionKey(
72 + trigger: Pick<PullRequestComposerTrigger, "sigil" | "query"> | null,
73 +): string | null {
74 + return trigger === null ? null : `${trigger.sigil}${trigger.query.slice(0, 100)}`;
75 +}
76 +
77 +/**
78 + * The search to send for `trigger` given a debounced key. Until a key for this sigil settles, the
79 + * host is asked for its unsearched list, which narrows locally, so a burst of typing sends one query.
80 + */
81 +export function debouncedPullRequestCompletionSearch(
82 + trigger: Pick<PullRequestComposerTrigger, "sigil">,
83 + debouncedKey: string | null,
84 +): string | undefined {
85 + return debouncedKey?.startsWith(trigger.sigil)
86 + ? debouncedKey.slice(trigger.sigil.length) || undefined
87 + : undefined;
88 +}
89 +
90 export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(
91 users: ReadonlyArray<A>,
92 typed: string,
@@ -51,3 +101,50 @@ export function narrowPullRequestMentions<A extends { login: string; name: strin
101 )
102 .slice(0, limit);
103 }
104 +
105 +/** Candidates the typed sigil links, by number prefix or title. */
106 +export function narrowPullRequestReferences<
107 + A extends { reference: string; number: number; title: string },
108 +>(
109 + candidates: ReadonlyArray<A>,
110 + trigger: Pick<PullRequestComposerTrigger, "sigil" | "query">,
111 + limit: number,
112 +): A[] {
113 + const needle = trigger.query.toLowerCase();
114 + return candidates
115 + .filter(
116 + (candidate) =>
117 + candidate.reference.startsWith(trigger.sigil) &&
118 + (String(candidate.number).startsWith(needle) ||
119 + candidate.title.toLowerCase().includes(needle)),
120 + )
121 + .slice(0, limit);
122 +}
123 +
124 +export type PullRequestCompletion =
125 + | { readonly kind: "mention"; readonly token: string; readonly actor: PullRequestActor }
126 + | {
127 + readonly kind: "reference";
128 + readonly token: string;
129 + readonly candidate: PullRequestReferenceCandidate;
130 + };
131 +
132 +/** The host's options for `trigger`, narrowed to what is typed now. */
133 +export function pullRequestCompletions(
134 + trigger: PullRequestComposerTrigger | null,
135 + options: Pick<PullRequestFilterOptions, "authors" | "references"> | null,
136 + limit: number,
137 +): ReadonlyArray<PullRequestCompletion> {
138 + if (trigger === null) return [];
139 + return trigger.kind === "mention"
140 + ? narrowPullRequestMentions(options?.authors ?? [], trigger.query, limit).map((actor) => ({
141 + kind: "mention",
142 + token: `@${actor.login}`,
143 + actor,
144 + }))
145 + : narrowPullRequestReferences(options?.references ?? [], trigger, limit).map((candidate) => ({
146 + kind: "reference",
147 + token: candidate.reference,
148 + candidate,
149 + }));
150 +}
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+1
@@ -53,6 +53,7 @@ const CAPABILITIES: PullRequestCapabilities = {
53 search: false,
54 reactions: false,
55 mentions: false,
56 + referenceSigils: [],
57 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
58 // Reviewer candidates require separate identity/graph APIs and permissions.
59 reviewers: { request: true, listCandidates: false },
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+1
@@ -24,6 +24,7 @@ const CAPABILITIES: PullRequestCapabilities = {
24 search: true,
25 reactions: false,
26 mentions: false,
27 + referenceSigils: [],
28 review: {
29 inlineComment: true,
30 reply: true,
packages/source-control-core/src/server/PullRequestProvider.ts
+16
@@ -5,6 +5,8 @@ import type {
5 PullRequestAction,
6 PullRequestStackHead,
7 PullRequestActor,
8 + PullRequestReferenceCandidate,
9 + PullRequestReferenceSigil,
10 PullRequestBaseComparison,
11 PullRequestCapabilities,
12 PullRequestChecksState,
@@ -555,6 +557,20 @@ export interface PullRequestProviderApi {
557 input: ProviderRepositoryRef & { readonly query?: string | undefined },
558 ) => Effect.Effect<ProviderFilterOptionPage<PullRequestActor>, PullRequestProviderError>;
559
560 + /**
561 + * Issues and change requests a composer can reference, recently updated first. A numeric
562 + * `query` also finds that number exactly; other text matches titles as far as the host can.
563 + */
564 + readonly searchRepositoryReferences?: (
565 + input: ProviderRepositoryRef & {
566 + readonly query?: string | undefined;
567 + readonly sigil?: PullRequestReferenceSigil | undefined;
568 + },
569 + ) => Effect.Effect<
570 + ProviderFilterOptionPage<PullRequestReferenceCandidate>,
571 + PullRequestProviderError
572 + >;
573 +
574 readonly setLabels?: (
575 input: ProviderRepositoryRef & {
576 readonly number: number;
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+1
@@ -49,6 +49,7 @@ const CAPABILITIES: PullRequestCapabilities = {
49 search: false,
50 reactions: true,
51 mentions: true,
52 + referenceSigils: [],
53 labels: true,
54 // Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
55 review: {
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+1
@@ -35,6 +35,7 @@ const CAPABILITIES: PullRequestCapabilities = {
35 stackActions: true,
36 reactions: true,
37 mentions: true,
38 + referenceSigils: [],
39 labels: true,
40 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
41 review: {
packages/source-control-github/schema/github.graphql.ts
+11
@@ -86,6 +86,15 @@ export type DiffSide = typeof DiffSide.Type
86 export const FileViewedState = Schema.Literals(["DISMISSED", "UNVIEWED", "VIEWED"])
87 export type FileViewedState = typeof FileViewedState.Type
88
89 +/**
90 + * The possible states of an issue.
91 + *
92 + * - `CLOSED`: An issue that has been closed
93 + * - `OPEN`: An issue that is still open
94 + */
95 +export const IssueState = Schema.Literals(["CLOSED", "OPEN"])
96 +export type IssueState = typeof IssueState.Type
97 +
98 /**
99 * Detailed status information about a pull request merge.
100 *
@@ -291,6 +300,8 @@ export declare namespace Typename {
300 export type Actor = "Bot" | "EnterpriseUserAccount" | "Mannequin" | "Organization" | "User"
301 /** Every possible `__typename` of interface `GitObject`. */
302 export type GitObject = "Blob" | "Commit" | "Tag" | "Tree"
303 + /** Every possible `__typename` of union `IssueOrPullRequest`. */
304 + export type IssueOrPullRequest = "Issue" | "PullRequest"
305 /** Every possible `__typename` of interface `Node`. */
306 export type Node =
307 | "AddedToMergeQueueEvent" | "AddedToProjectEvent" | "AddedToProjectV2Event" | "AddedToStackEvent" | "App"
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+37
@@ -731,6 +731,43 @@ it.effect(
731 );
732
733 layer("GitHubPullRequestApi.layer", (it) => {
734 + it.effect("keeps recent references when the typed number does not exist", () =>
735 + Effect.gen(function* () {
736 + const search = {
737 + pageInfo: { hasNextPage: false },
738 + nodes: [{ __typename: "Issue", number: 7, title: "Seven", issueState: "OPEN" }],
739 + };
740 + mockedExecute.mockImplementation((call) =>
741 + Effect.succeed(
742 + output(
743 + encodeJson(
744 + call.kind === "graphql" && call.variables?.["exact"] === true
745 + ? {
746 + data: { search, repository: { issueOrPullRequest: null } },
747 + errors: [
748 + {
749 + type: "NOT_FOUND",
750 + path: ["repository", "issueOrPullRequest"],
751 + message: "Could not resolve to an issue or pull request.",
752 + },
753 + ],
754 + }
755 + : { data: { search } },
756 + ),
757 + ),
758 + ),
759 + );
760 + const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
761 + const result = yield* api.searchRepositoryReferences({
762 + cwd: "/w",
763 + repository: "acme/web",
764 + host: "github.com",
765 + query: "99",
766 + });
767 + expect(result.items.map((item) => item.reference)).toEqual(["#7"]);
768 + }),
769 + );
770 +
771 it.effect("turns maintainer edits off without rewriting the pull request's text", () =>
772 Effect.gen(function* () {
773 mockedExecute.mockImplementation((call) =>
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+43 -5
@@ -24,6 +24,7 @@ import {
24 type PullRequestAction,
25 type PullRequestStackHead,
26 type PullRequestActor,
27 + type PullRequestReferenceCandidate,
28 type PullRequestComment,
29 type PullRequestCommit,
30 type PullRequestFileViewed,
@@ -74,6 +75,9 @@ import {
75 pullRequestLookup,
76 toLabelCandidates,
77 toRepositoryAuthors,
78 + toRepositoryReferences,
79 + referenceSearchQuery,
80 + searchPhrase,
81 toRepositoryLabels,
82 toPullRequestActivityPage,
83 toPullRequestActionSummary,
@@ -642,6 +646,19 @@ export class GitHubPullRequestApi extends Context.Service<
646 GitHubPullRequestApiError
647 >;
648
649 + readonly searchRepositoryReferences: (input: {
650 + readonly cwd: string;
651 + readonly repository: string;
652 + readonly host: string;
653 + readonly query?: string | undefined;
654 + }) => Effect.Effect<
655 + {
656 + readonly items: ReadonlyArray<PullRequestReferenceCandidate>;
657 + readonly truncated: boolean;
658 + },
659 + GitHubPullRequestApiError
660 + >;
661 +
662 readonly setLabels: (input: {
663 readonly cwd: string;
664 readonly repository: string;
@@ -743,11 +760,6 @@ function diffCursorPage(cursor: string): number | null {
760 return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
761 }
762
746 -/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */
747 -function searchPhrase(query: string): string {
748 - return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
749 -}
750 -
763 const REVIEW_QUALIFIERS = {
764 approved: "approved",
765 "changes-requested": "changes_requested",
@@ -2373,6 +2385,32 @@ export const make = Effect.gen(function* () {
2385 },
2386 ),
2387
2388 + searchRepositoryReferences: Effect.fn("GitHubPullRequestApi.searchRepositoryReferences")(
2389 + function (input) {
2390 + const { owner, name } = parseRepositorySelector(input.repository);
2391 + const parsed = /^\d+$/.test(input.query ?? "") ? Number(input.query) : 0;
2392 + // GraphQL validates `$number: Int!` even when `@include` skips the lookup.
2393 + const exact = parsed > 0 && parsed <= 2_147_483_647;
2394 + const search = (lookup: boolean) =>
2395 + client.RepositoryReferences({
2396 + owner,
2397 + name,
2398 + q: referenceSearchQuery(input.repository, input.query),
2399 + number: lookup ? parsed : 0,
2400 + exact: lookup,
2401 + });
2402 + return search(exact).pipe(
2403 + // A missing number fails the whole query, which would discard the search results.
2404 + Effect.catchIf(
2405 + (error) => exact && isNotFoundOnly(error),
2406 + () => search(false),
2407 + ),
2408 + graphql({ ...input, operation: "searchRepositoryReferences", allowReserve: true }),
2409 + Effect.map(toRepositoryReferences),
2410 + );
2411 + },
2412 + ),
2413 +
2414 setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (input) {
2415 const { owner, name } = parseRepositorySelector(input.repository);
2416 const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+6
@@ -42,6 +42,7 @@ const CAPABILITIES: PullRequestCapabilities = {
42 search: true,
43 reactions: true,
44 mentions: true,
45 + referenceSigils: ["#"],
46 viewedFiles: "host",
47 review: {
48 inlineComment: true,
@@ -657,6 +658,11 @@ export const make = Effect.gen(function* () {
658 searchRepositoryAuthors: (input) =>
659 cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
660
661 + searchRepositoryReferences: (input) =>
662 + cli
663 + .searchRepositoryReferences(input)
664 + .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
665 +
666 setLabels: (input) =>
667 cli
668 .setLabels({
packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
+36
@@ -6,6 +6,8 @@ import {
6 buildReviewSubmission,
7 buildReviewerRequest,
8 pullRequestLookup,
9 + referenceSearchQuery,
10 + toRepositoryReferences,
11 toPullRequestWatchFingerprint,
12 decodePullRequestFilesJson,
13 decodePullRequestStacksJson,
@@ -1629,6 +1631,40 @@ const decodeWatchedResult = Schema.decodeUnknownSync(PullRequestWatchFingerprint
1631 const decodeWatched = (pullRequest: object) =>
1632 decodeWatchedResult({ repository: { pullRequest } }).repository!.pullRequest!;
1633
1634 +describe("repository references", () => {
1635 + it.each([
1636 + [undefined, "repo:o/r sort:updated-desc"],
1637 + ["12", "repo:o/r sort:updated-desc"],
1638 + ['say "hi"', 'repo:o/r in:title "say \\"hi\\"" sort:updated-desc'],
1639 + ])("searches %j as %j", (query, q) => {
1640 + expect(referenceSearchQuery("o/r", query)).toBe(q);
1641 + });
1642 +
1643 + it("puts the exact number first and maps issue and pull request states", () => {
1644 + const result = toRepositoryReferences({
1645 + search: {
1646 + pageInfo: { hasNextPage: true },
1647 + nodes: [
1648 + { __typename: "PullRequest", number: 3, title: "Merged", pullRequestState: "MERGED" },
1649 + { __typename: "Issue", number: 2, title: "Closed", issueState: "CLOSED" },
1650 + null,
1651 + ],
1652 + },
1653 + repository: {
1654 + issueOrPullRequest: { __typename: "Issue", number: 1, title: "Exact", issueState: "OPEN" },
1655 + },
1656 + });
1657 + expect(result).toEqual({
1658 + items: [
1659 + { reference: "#1", kind: "issue", number: 1, title: "Exact", state: "open" },
1660 + { reference: "#3", kind: "change-request", number: 3, title: "Merged", state: "merged" },
1661 + { reference: "#2", kind: "issue", number: 2, title: "Closed", state: "closed" },
1662 + ],
1663 + truncated: true,
1664 + });
1665 + });
1666 +});
1667 +
1668 describe("pull request lookups", () => {
1669 it("refuses what GitHub cannot name, so one bad row cannot fail a whole batch", () => {
1670 expect(pullRequestLookup({ repository: "acme/web", number: 7 })).toEqual({
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+61
@@ -7,6 +7,7 @@ import { GraphQL } from "effect/graphql";
7 import type {
8 PullRequestStackMembership,
9 PullRequestActor,
10 + PullRequestReferenceCandidate,
11 PullRequestPreview,
12 PullRequestCheck,
13 PullRequestCheckStatus,
@@ -65,6 +66,8 @@ import type {
66 PullRequestSubject,
67 RepositoryAuthors,
68 RepositoryLabels,
69 + RepositoryReferences,
70 + ReferenceCandidate,
71 ReviewerCandidates,
72 ViewerPermissions,
73 } from "./pullRequestReads.graphql.ts";
@@ -1576,6 +1579,64 @@ export function toRepositoryAuthors(
1579 };
1580 }
1581
1582 +/** The `search` string for {@link toRepositoryReferences}; a numeric query searches recent items. */
1583 +export function referenceSearchQuery(repository: string, query: string | undefined): string {
1584 + const text = query?.trim() ?? "";
1585 + const titled = text.length === 0 || /^\d+$/.test(text) ? [] : [`in:title ${searchPhrase(text)}`];
1586 + return [`repo:${repository}`, ...titled, "sort:updated-desc"].join(" ");
1587 +}
1588 +
1589 +/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */
1590 +export function searchPhrase(query: string): string {
1591 + return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
1592 +}
1593 +
1594 +type ReferenceNode =
1595 + | ReferenceCandidate
1596 + | NonNullable<NonNullable<RepositoryReferences.Result["search"]["nodes"]>[number]>;
1597 +
1598 +function toReferenceCandidate(node: ReferenceNode): PullRequestReferenceCandidate | null {
1599 + if (node.__typename === "Issue") {
1600 + return {
1601 + reference: `#${node.number}`,
1602 + kind: "issue",
1603 + number: node.number,
1604 + title: node.title,
1605 + state: node.issueState === "OPEN" ? "open" : "closed",
1606 + };
1607 + }
1608 + if (node.__typename === "PullRequest") {
1609 + return {
1610 + reference: `#${node.number}`,
1611 + kind: "change-request",
1612 + number: node.number,
1613 + title: node.title,
1614 + state:
1615 + node.pullRequestState === "OPEN"
1616 + ? "open"
1617 + : node.pullRequestState === "MERGED"
1618 + ? "merged"
1619 + : "closed",
1620 + };
1621 + }
1622 + return null;
1623 +}
1624 +
1625 +export function toRepositoryReferences(result: RepositoryReferences.Result): {
1626 + readonly items: ReadonlyArray<PullRequestReferenceCandidate>;
1627 + readonly truncated: boolean;
1628 +} {
1629 + const exact = result.repository?.issueOrPullRequest;
1630 + const nodes = [...(exact == null ? [] : [exact]), ...nodesOf(result.search)];
1631 + return {
1632 + items: nodes.flatMap((node) => {
1633 + const candidate = toReferenceCandidate(node);
1634 + return candidate === null ? [] : [candidate];
1635 + }),
1636 + truncated: result.search.pageInfo.hasNextPage,
1637 + };
1638 +}
1639 +
1640 export function buildLabelRequest(labels: ReadonlyArray<string>): {
1641 readonly labels: ReadonlyArray<string>;
1642 } {
packages/source-control-github/src/server/pullRequestReads.graphql
+37
@@ -487,6 +487,43 @@ query RepositoryLabels($owner: String!, $name: String!, $query: String) {
487 }
488 }
489
490 +fragment ReferenceCandidate on IssueOrPullRequest {
491 + __typename
492 + ... on Issue {
493 + number
494 + title
495 + issueState: state
496 + }
497 + ... on PullRequest {
498 + number
499 + title
500 + pullRequestState: state
501 + }
502 +}
503 +
504 +# `search` cannot match a number, so a numeric query also looks the number up directly.
505 +query RepositoryReferences(
506 + $owner: String!
507 + $name: String!
508 + $q: String!
509 + $number: Int!
510 + $exact: Boolean!
511 +) {
512 + search(query: $q, type: ISSUE, first: 20) {
513 + pageInfo {
514 + hasNextPage
515 + }
516 + nodes {
517 + ...ReferenceCandidate
518 + }
519 + }
520 + repository(owner: $owner, name: $name) @include(if: $exact) {
521 + issueOrPullRequest(number: $number) {
522 + ...ReferenceCandidate
523 + }
524 + }
525 +}
526 +
527 # Mentionable rather than assignable users: a pull request from a fork is opened by someone with
528 # no access to the repository, and a listing is still narrowed by them.
529 query RepositoryAuthors($owner: String!, $name: String!, $query: String) {
packages/source-control-github/src/server/pullRequestReads.graphql.ts
+110 -1
@@ -82,6 +82,48 @@ export const CheckContext = Schema.Union([
82 ])
83 export type CheckContext = typeof CheckContext.Type
84
85 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
86 +export const Issue = Schema.Struct({
87 + __typename: Schema.Literal("Issue"),
88 + /** Identifies the issue number. */
89 + number: Shared.Int,
90 + /** Identifies the issue title. */
91 + title: Schema.String,
92 + /** Identifies the state of the issue. */
93 + issueState: GraphQL.enumLiterals(Shared.IssueState.literals)
94 +})
95 +export interface Issue extends Schema.Struct.Type<typeof Issue.fields> {}
96 +
97 +/** A repository pull request. */
98 +export const ReferenceCandidatePullRequest = Schema.Struct({
99 + __typename: Schema.Literal("PullRequest"),
100 + /** Identifies the pull request number. */
101 + number: Shared.Int,
102 + /** Identifies the pull request title. */
103 + title: Schema.String,
104 + /** Identifies the state of the pull request. */
105 + pullRequestState: GraphQL.enumLiterals(Shared.PullRequestState.literals)
106 +})
107 +export interface ReferenceCandidatePullRequest extends Schema.Struct.Type<typeof ReferenceCandidatePullRequest.fields> {}
108 +
109 +/** Used for return value of Repository.issueOrPullRequest. */
110 +export const IssueOrPullRequestOther = Schema.Struct({
111 + __typename: GraphQL.otherTypename<Shared.Typename.IssueOrPullRequest>()(["Issue", "PullRequest"])
112 +})
113 +export interface IssueOrPullRequestOther extends Schema.Struct.Type<typeof IssueOrPullRequestOther.fields> {}
114 +
115 +/**
116 + * `fragment ReferenceCandidate on IssueOrPullRequest`
117 + *
118 + * Used for return value of Repository.issueOrPullRequest.
119 + */
120 +export const ReferenceCandidate = Schema.Union([
121 + Issue,
122 + ReferenceCandidatePullRequest,
123 + IssueOrPullRequestOther
124 +])
125 +export type ReferenceCandidate = typeof ReferenceCandidate.Type
126 +
127 /** A user is an individual's account on GitHub that owns repositories and can make new content. */
128 export const ViewerUser = Schema.Struct({
129 /** Identifies the primary key from the database. */
@@ -1301,6 +1343,73 @@ export declare namespace RepositoryLabels {
1343 export type Result = typeof RepositoryLabels.result.Type
1344 }
1345
1346 +/** The results of a search. */
1347 +export const SearchResultItemOther = Schema.Struct({
1348 + __typename: GraphQL.otherTypename<Shared.Typename.SearchResultItem>()(["Issue", "PullRequest"])
1349 +})
1350 +export interface SearchResultItemOther extends Schema.Struct.Type<typeof SearchResultItemOther.fields> {}
1351 +
1352 +/**
1353 + * A list of results that matched against a search query. Regardless of the number
1354 + * of matches, a maximum of 1,000 results will be available across all types,
1355 + * potentially split across many pages.
1356 + */
1357 +export const SearchResultItemConnection = Schema.Struct({
1358 + /** Information to aid in pagination. */
1359 + pageInfo: AssignableUsersPageInfoPageInfo,
1360 + /** A list of nodes. */
1361 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([
1362 + Issue,
1363 + ReferenceCandidatePullRequest,
1364 + SearchResultItemOther
1365 + ]))))
1366 +})
1367 +export interface SearchResultItemConnection extends Schema.Struct.Type<typeof SearchResultItemConnection.fields> {}
1368 +
1369 +/** A repository contains the content for a project. */
1370 +export const RepositoryReferencesRepositoryRepository = Schema.Struct({
1371 + /** Returns a single issue-like object from the current repository by number. */
1372 + issueOrPullRequest: Schema.NullOr(ReferenceCandidate)
1373 +})
1374 +export interface RepositoryReferencesRepositoryRepository extends Schema.Struct.Type<typeof RepositoryReferencesRepositoryRepository.fields> {}
1375 +
1376 +/** `query RepositoryReferences` */
1377 +export const RepositoryReferences = GraphQL.query("RepositoryReferences", {
1378 + document: {
1379 + variables: [
1380 + { name: "owner", body: "String!" },
1381 + { name: "name", body: "String!" },
1382 + { name: "q", body: "String!" },
1383 + { name: "number", body: "Int!" },
1384 + { name: "exact", body: "Boolean!" }
1385 + ],
1386 + selections: [
1387 + { name: "search", body: ["(query:$", "q", " type:ISSUE first:20){pageInfo{hasNextPage}nodes{__typename...ReferenceCandidate}}"] },
1388 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", ")@include(if:$", "exact", "){issueOrPullRequest(number:$", "number", "){__typename...ReferenceCandidate}}"] }
1389 + ],
1390 + fragments: [
1391 + { name: "ReferenceCandidate", body: ["on IssueOrPullRequest{__typename...on Issue{number title issueState:state}...on PullRequest{number title pullRequestState:state}}"] }
1392 + ]
1393 + },
1394 + variables: {
1395 + owner: Schema.String,
1396 + name: Schema.String,
1397 + q: Schema.String,
1398 + number: Shared.Int,
1399 + exact: Schema.Boolean
1400 + },
1401 + result: Schema.Struct({
1402 + /** Perform a search across resources, returning a maximum of 1,000 results. */
1403 + search: SearchResultItemConnection,
1404 + /** Lookup a given repository by the owner and repository name. */
1405 + repository: Schema.optionalKey(Schema.NullOr(RepositoryReferencesRepositoryRepository))
1406 + })
1407 +})
1408 +export declare namespace RepositoryReferences {
1409 + export type Variables = typeof RepositoryReferences.variables.Type
1410 + export type Result = typeof RepositoryReferences.result.Type
1411 +}
1412 +
1413 /** A repository contains the content for a project. */
1414 export const RepositoryAuthorsRepositoryRepository = Schema.Struct({
1415 /** A list of Users that can be mentioned in the context of the repository. */
@@ -1687,4 +1796,4 @@ export declare namespace PullRequestSourceBranch {
1796 }
1797
1798 /** Every operation in pullRequestReads.graphql. */
1690 -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)
1799 +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)
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+49
@@ -2211,6 +2211,27 @@ layer("GitLabPullRequestCli.layer", (it) => {
2211 expect(result).toMatchObject({ _tag: "Failure", failure: error });
2212 }),
2213 );
2214 +
2215 + it.effect("keeps merge request references when the issue search fails", () =>
2216 + Effect.gen(function* () {
2217 + mockedExecute.mockImplementation((input) =>
2218 + JSON.stringify(input).includes("/issues?")
2219 + ? Effect.fail(
2220 + new GitLabCli.GitLabCliCommandError({
2221 + operation: "execute",
2222 + command: "glab",
2223 + cwd: "/w",
2224 + cause: null,
2225 + }),
2226 + )
2227 + : Effect.succeed(output(JSON.stringify([{ iid: 5, title: "Ship it", state: "opened" }]))),
2228 + );
2229 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
2230 + const page = yield* cli.searchProjectReferences({ cwd: "/w", repository: "acme/web" });
2231 + expect(page.items.map((item) => item.reference)).toEqual(["!5"]);
2232 + }),
2233 + );
2234 +
2235 describe("the head pipeline's stages", () => {
2236 const pipeline = {
2237 id: 9,
@@ -2379,3 +2400,31 @@ layer("GitLabPullRequestCli.layer", (it) => {
2400 );
2401 });
2402 });
2403 +
2404 +it("asks for a numeric reference's iid besides the recent issues and merge requests", () => {
2405 + const recent = [
2406 + ["order_by", "updated_at"],
2407 + ["sort", "desc"],
2408 + ];
2409 + expect(GitLabPullRequestCli.referenceSearches("12")).toEqual([
2410 + { kind: "issue", params: [["iids[]", "12"]] },
2411 + { kind: "change-request", params: [["iids[]", "12"]] },
2412 + { kind: "issue", params: recent },
2413 + { kind: "change-request", params: recent },
2414 + ]);
2415 + expect(GitLabPullRequestCli.referenceSearches("crash")).toEqual([
2416 + { kind: "issue", params: [...recent, ["search", "crash"], ["in", "title"]] },
2417 + { kind: "change-request", params: [...recent, ["search", "crash"], ["in", "title"]] },
2418 + ]);
2419 + expect(GitLabPullRequestCli.referenceSearches("cr")).toEqual([
2420 + { kind: "issue", params: recent },
2421 + { kind: "change-request", params: recent },
2422 + ]);
2423 + expect(GitLabPullRequestCli.referenceSearches("12", "!")).toEqual([
2424 + { kind: "change-request", params: [["iids[]", "12"]] },
2425 + { kind: "change-request", params: recent },
2426 + ]);
2427 + expect(GitLabPullRequestCli.referenceSearches(undefined, "#")).toEqual([
2428 + { kind: "issue", params: recent },
2429 + ]);
2430 +});
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+125 -3
@@ -11,6 +11,8 @@ import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/co
11 import type {
12 PullRequestAction,
13 PullRequestActor,
14 + PullRequestReferenceCandidate,
15 + PullRequestReferenceSigil,
16 PullRequestCheck,
17 PullRequestComment,
18 PullRequestCommit,
@@ -58,6 +60,7 @@ import {
60 decodeProjectMergeCapabilitiesJson,
61 decodeProjectLabelsJson,
62 decodeProjectUsersJson,
63 + decodeReferenceCandidatesJson,
64 decodeRepositoryBlobsJson,
65 decodeListStatesJson,
66 decodeSourceBranchJson,
@@ -512,6 +515,20 @@ export class GitLabPullRequestCli extends Context.Service<
515 GitLabPullRequestCliError
516 >;
517
518 + readonly searchProjectReferences: (input: {
519 + readonly cwd: string;
520 + readonly host?: string | undefined;
521 + readonly repository: string;
522 + readonly search?: string | undefined;
523 + readonly sigil?: PullRequestReferenceSigil | undefined;
524 + }) => Effect.Effect<
525 + {
526 + readonly items: ReadonlyArray<PullRequestReferenceCandidate>;
527 + readonly truncated: boolean;
528 + },
529 + GitLabPullRequestCliError
530 + >;
531 +
532 readonly setReviewerRequest: (input: {
533 readonly cwd: string;
534 readonly host?: string | undefined;
@@ -791,6 +808,58 @@ function searchParams(search: string | undefined): ReadonlyArray<readonly [strin
808 return trimmed.length === 0 ? [] : [["search", trimmed]];
809 }
810
811 +// GitLab's user, issue and merge request searches answer nothing under three characters, so
812 +// shorter text reads the unsearched page, which the server narrows.
813 +function hostSearchParams(search: string | undefined): ReadonlyArray<readonly [string, string]> {
814 + return (search?.trim().length ?? 0) >= 3 ? searchParams(search) : [];
815 +}
816 +
817 +const REFERENCE_PAGE_SIZE = 20;
818 +
819 +/**
820 + * Recently updated issues and merge requests, by title for text. Issue and MR search cannot match
821 + * a number, so a numeric query also asks for that iid of each.
822 + */
823 +export function referenceSearches(
824 + search: string | undefined,
825 + sigil?: PullRequestReferenceSigil | undefined,
826 +): ReadonlyArray<{
827 + readonly kind: PullRequestReferenceCandidate["kind"];
828 + readonly params: ReadonlyArray<readonly [string, string]>;
829 +}> {
830 + const text = search?.trim() ?? "";
831 + const numeric = /^\d+$/.test(text);
832 + const recent: ReadonlyArray<readonly [string, string]> = [
833 + ["order_by", "updated_at"],
834 + ["sort", "desc"],
835 + ...(numeric || hostSearchParams(text).length === 0
836 + ? []
837 + : ([...hostSearchParams(text), ["in", "title"]] as const)),
838 + ];
839 + const kinds =
840 + sigil === "#"
841 + ? (["issue"] as const)
842 + : sigil === "!"
843 + ? (["change-request"] as const)
844 + : (["issue", "change-request"] as const);
845 + return [
846 + ...(numeric ? kinds.map((kind) => ({ kind, params: [["iids[]", text]] as const })) : []),
847 + ...kinds.map((kind) => ({ kind, params: recent })),
848 + ];
849 +}
850 +
851 +function mergeReferencePages(
852 + pages: ReadonlyArray<{
853 + readonly items: ReadonlyArray<PullRequestReferenceCandidate>;
854 + readonly rawCount: number;
855 + }>,
856 +) {
857 + return {
858 + items: pages.flatMap((page) => page.items),
859 + truncated: pages.some((page) => page.rawCount >= REFERENCE_PAGE_SIZE),
860 + };
861 +}
862 +
863 function query(params: ReadonlyArray<readonly [string, string]>): string {
864 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
865 }
@@ -1317,9 +1386,7 @@ export const make = Effect.gen(function* () {
1386 host: input.host,
1387 path: `projects/${projectPath(input.repository)}/users?${query([
1388 ["per_page", String(MAX_PAGE_SIZE)],
1320 - // GitLab answers nothing for a user search under three characters; callers narrow the
1321 - // unsearched page instead.
1322 - ...((input.search?.trim().length ?? 0) >= 3 ? searchParams(input.search) : []),
1389 + ...hostSearchParams(input.search),
1390 ])}`,
1391 }).pipe(
1392 Effect.flatMap((result) => {
@@ -1337,6 +1404,35 @@ export const make = Effect.gen(function* () {
1404 }),
1405 );
1406
1407 + const projectReferences = (input: {
1408 + readonly cwd: string;
1409 + readonly host?: string | undefined;
1410 + readonly repository: string;
1411 + readonly kind: PullRequestReferenceCandidate["kind"];
1412 + readonly params: ReadonlyArray<readonly [string, string]>;
1413 + }) =>
1414 + api({
1415 + cwd: input.cwd,
1416 + host: input.host,
1417 + path: `projects/${projectPath(input.repository)}/${
1418 + input.kind === "issue" ? "issues" : "merge_requests"
1419 + }?${query([...input.params, ["per_page", String(REFERENCE_PAGE_SIZE)]])}`,
1420 + }).pipe(
1421 + Effect.flatMap((result) => {
1422 + const decoded = decodeReferenceCandidatesJson(result.stdout.trim(), input.kind);
1423 + return Result.isSuccess(decoded)
1424 + ? Effect.succeed(decoded.success)
1425 + : Effect.fail(
1426 + new GitLabMergeRequestReadError({
1427 + command: "glab",
1428 + cwd: input.cwd,
1429 + operation: "searchProjectReferences",
1430 + cause: decoded.failure,
1431 + }),
1432 + );
1433 + }),
1434 + );
1435 +
1436 const awardSubjectPath = (input: {
1437 readonly repository: string;
1438 readonly number: number;
@@ -2222,6 +2318,32 @@ export const make = Effect.gen(function* () {
2318 );
2319 }),
2320
2321 + searchProjectReferences: Effect.fn("GitLabPullRequestCli.searchProjectReferences")(
2322 + function (input) {
2323 + return Effect.forEach(
2324 + referenceSearches(input.search, input.sigil),
2325 + ({ kind, params }) =>
2326 + projectReferences({ ...input, kind, params }).pipe(
2327 + // A project with issues turned off answers 403 for issues; its merge requests still
2328 + // complete. An unusable CLI or account still reaches the caller.
2329 + Effect.catchIf(
2330 + (cause) =>
2331 + cause._tag !== "GitLabCliUnavailableError" &&
2332 + cause._tag !== "GitLabCliAuthenticationError" &&
2333 + cause._tag !== "GitLabCliRateLimitError",
2334 + (cause) =>
2335 + Effect.logWarning("GitLab reference search failed", {
2336 + repository: input.repository,
2337 + kind,
2338 + reason: cause._tag,
2339 + }).pipe(Effect.as({ items: [], rawCount: 0 })),
2340 + ),
2341 + ),
2342 + { concurrency: "unbounded" },
2343 + ).pipe(Effect.map(mergeReferencePages));
2344 + },
2345 + ),
2346 +
2347 listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")(
2348 function (input) {
2349 return Effect.all([mergeRequestDetail(input), projectUsers(input)], {
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+12
@@ -33,6 +33,7 @@ const CAPABILITIES: PullRequestCapabilities = {
33 search: true,
34 reactions: true,
35 mentions: true,
36 + referenceSigils: ["#", "!"],
37 // GitLab's viewed marks live in browser-local storage.
38 viewedFiles: "environment",
39 review: {
@@ -534,6 +535,17 @@ export const make = Effect.gen(function* () {
535 })
536 .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
537
538 + searchRepositoryReferences: (input) =>
539 + cli
540 + .searchProjectReferences({
541 + cwd: input.cwd,
542 + host: input.host,
543 + repository: input.repository,
544 + search: input.query,
545 + sigil: input.sigil,
546 + })
547 + .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
548 +
549 setReviewerRequest: writing((input) =>
550 cli
551 .setReviewerRequest({
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
+23
@@ -13,6 +13,7 @@ import {
13 decodeMergeRequestListJson,
14 decodeMergeRequestFileStatsJson,
15 decodeMergeRequestStatsJson,
16 + decodeReferenceCandidatesJson,
17 decodeNotesJson,
18 decodeOwnAwardIdJson,
19 decodeListStatesJson,
@@ -1052,6 +1053,28 @@ describe("decodeListStatesJson", () => {
1053 });
1054 });
1055
1056 +describe("decodeReferenceCandidatesJson", () => {
1057 + it("prefixes merge requests with ! and skips malformed entries", () => {
1058 + const raw = JSON.stringify([
1059 + { iid: 5, title: "Ship it", state: "merged" },
1060 + { iid: 6, title: "Draft", state: "opened" },
1061 + { iid: 7, title: "Locked", state: "locked" },
1062 + { title: "No iid", state: "opened" },
1063 + ]);
1064 + const decoded = decodeReferenceCandidatesJson(raw, "change-request");
1065 + expect(Result.isSuccess(decoded) && decoded.success).toEqual({
1066 + items: [
1067 + { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" },
1068 + { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" },
1069 + { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" },
1070 + ],
1071 + rawCount: 4,
1072 + });
1073 + const issues = decodeReferenceCandidatesJson(raw, "issue");
1074 + expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5");
1075 + });
1076 +});
1077 +
1078 describe("decodeMergeRequestStatsJson", () => {
1079 it("keys the counts by merge request number", () => {
1080 const stats = expectSuccess(
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+35
@@ -16,6 +16,7 @@ import type {
16 PullRequestMergeMethod,
17 PullRequestReaction,
18 PullRequestReactionContent,
19 + PullRequestReferenceCandidate,
20 PullRequestReviewDecision,
21 PullRequestReviewThread,
22 PullRequestReviewerCandidate,
@@ -655,6 +656,40 @@ export function decodeProjectUsersJson(
656 return Result.succeed({ candidates, rawCount: decoded.success.length });
657 }
658
659 +const RawReferenceSchema = Schema.Struct({
660 + iid: Schema.Number,
661 + title: Schema.String,
662 + state: Schema.String,
663 +});
664 +const decodeReferenceEntry = Schema.decodeUnknownExit(RawReferenceSchema);
665 +
666 +/** A list of issues (`#`) or merge requests (`!`), as composers reference them. */
667 +export function decodeReferenceCandidatesJson(
668 + raw: string,
669 + kind: PullRequestReferenceCandidate["kind"],
670 +): Result.Result<
671 + { readonly items: ReadonlyArray<PullRequestReferenceCandidate>; readonly rawCount: number },
672 + DecodeFailure
673 +> {
674 + const decoded = decodeUnknownList(raw);
675 + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
676 + const items: PullRequestReferenceCandidate[] = [];
677 + for (const entry of decoded.success) {
678 + const reference = decodeReferenceEntry(entry);
679 + if (Exit.isFailure(reference) || !Number.isInteger(reference.value.iid)) continue;
680 + if (reference.value.iid < 1) continue;
681 + const { iid, title, state } = reference.value;
682 + items.push({
683 + reference: `${kind === "issue" ? "#" : "!"}${iid}`,
684 + kind,
685 + number: iid,
686 + title,
687 + state: state === "merged" ? "merged" : state === "opened" ? "open" : "closed",
688 + });
689 + }
690 + return Result.succeed({ items, rawCount: decoded.success.length });
691 +}
692 +
693 const RawLabelSchema = Schema.Struct({
694 name: Schema.String,
695 color: Schema.optional(Schema.NullOr(Schema.String)),