@devries-cameron20 / t3code-1 / commits / 7bc2a40ced
Fork 0

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

feat(pull-requests): PR composers complete @user mentions (#30747)

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:23 UTC 7bc2a40ced9094e2b5fd2f076e1bfeab734f8aed
35 files changed +728 -20
apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+17 -1
@@ -26,6 +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";
31
32 export function PullRequestDiscussionScreen({
33 route,
@@ -55,6 +57,13 @@ 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({
61 + environmentId: params.environmentId,
62 + projectId: params.projectId,
63 + value: body,
64 + onChangeValue: setBody,
65 + enabled: detail.data?.capabilities.mentions === true,
66 + });
67 const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);
68 const [cursor, setCursor] = useState<string | null | undefined>();
69 const [busy, setBusy] = useState(false);
@@ -222,7 +231,11 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
231 </ScrollView>
232 </ScrollViewMarker>
233 {canReply ? (
225 - <View className="absolute inset-x-4 bottom-0" style={{ paddingBottom: bottomInset }}>
234 + <View
235 + className="absolute inset-x-4 bottom-0 gap-2"
236 + style={{ paddingBottom: bottomInset }}
237 + >
238 + <PullRequestMentionSuggestions mentions={mentions} />
239 <GlassSurface
240 chrome="none"
241 onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
@@ -230,6 +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}
249 multiline
250 maxLength={65536}
251 placeholder="Reply…"
apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx
+13
@@ -16,6 +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";
21
22 export type PullRequestEditParams = PullRequestParams &
23 (
@@ -49,6 +51,13 @@ 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({
55 + environmentId: params.environmentId,
56 + projectId: params.projectId,
57 + value: value,
58 + onChangeValue: setDraft,
59 + enabled: params.field !== "title" && pr?.capabilities.mentions === true,
60 + });
61 const [busy, setBusy] = useState(false);
62 const [error, setError] = useState<string | null>(null);
63 const inFlight = useRef(false);
@@ -131,8 +140,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd
140 />
141 }
142 >
143 + <PullRequestMentionSuggestions mentions={mentions} />
144 <TextInput
145 multiline={params.field !== "title"}
146 + selection={mentions.selection}
147 + onSelectionChange={mentions.onSelectionChange}
148 + onBlur={mentions.onBlur}
149 editable={!busy && original !== null}
150 autoFocus
151 accessibilityLabel={
apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
+13
@@ -15,6 +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";
20
21 export type InlineCommentParams = PullRequestParams & {
22 readonly draftId?: string;
@@ -33,6 +35,13 @@ 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({
39 + environmentId: params.environmentId,
40 + projectId: params.projectId,
41 + value: body,
42 + onChangeValue: setBody,
43 + enabled: detail.data?.capabilities.mentions === true,
44 + });
45 useFocusEffect(refreshDetail);
46 const permissions = usePullRequestPermissions(params, detail.data);
47 const stale = detail.data && detail.data.headSha !== params.headSha;
@@ -101,8 +110,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
110 {params.code}
111 </Text>
112 </View>
113 + <PullRequestMentionSuggestions mentions={mentions} />
114 <TextInput
115 multiline
116 + selection={mentions.selection}
117 + onSelectionChange={mentions.onSelectionChange}
118 + onBlur={mentions.onBlur}
119 editable={store.ready && !busy}
120 autoFocus
121 accessibilityLabel="Inline review comment"
apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx new
+65
@@ -0,0 +1,65 @@
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
+13
@@ -19,6 +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";
24
25 function useActionSubmission(params: PullRequestParams) {
26 const navigation = useNavigation();
@@ -81,6 +83,13 @@ export function PullRequestReviewSheet({
83 ...draft,
84 ...(params.mode === "review" ? { summary: body } : { comment: body }),
85 }));
86 + const mentions = usePullRequestMentions({
87 + environmentId: params.environmentId,
88 + projectId: params.projectId,
89 + value: body,
90 + onChangeValue: setBody,
91 + enabled: result.data?.capabilities.mentions === true,
92 + });
93 const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha);
94 const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");
95 const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value));
@@ -169,8 +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} />
182 <TextInput
183 multiline
184 + selection={mentions.selection}
185 + onSelectionChange={mentions.onSelectionChange}
186 + onBlur={mentions.onBlur}
187 accessibilityLabel={reviewing ? "Review summary" : "Comment"}
188 placeholder={
189 reviewing
apps/mobile/src/features/pull-requests/usePullRequestMentions.ts new
+73
@@ -0,0 +1,73 @@
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/web/src/components/DiffPanel.browser.test.tsx
+1
@@ -79,6 +79,7 @@ vi.mock("~/hooks/useTheme", () => ({
79 vi.mock("~/state/queries", () => ({
80 useCheckpointDiff: () => ({ data: null, error: null, isPending: false }),
81 useTurnItemDetail: () => ({ data: null, error: null, isPending: false }),
82 + useDebouncedValue: <A,>(value: A) => value,
83 }));
84 vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
85 vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
apps/web/src/components/diffs/DiffCommentAnnotation.tsx
+10 -3
@@ -3,7 +3,10 @@ import { MessageCircle, Trash2 } from "lucide-react";
3 import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
4
5 import { Button } from "~/components/ui/button";
6 -import { Textarea } from "~/components/ui/textarea";
6 +import {
7 + PullRequestMarkdownTextarea,
8 + type PullRequestMentionScope,
9 +} from "~/components/pullRequest/PullRequestMarkdownTextarea";
10 import {
11 SpeechTextField,
12 TextFieldSpeechControls,
@@ -37,6 +40,8 @@ interface DiffCommentAnnotationProps {
40 pending?: boolean;
41 secondaryAction?: DiffCommentSecondaryAction;
42 focusOnMount?: boolean;
43 + /** Set only for pull request comments, where `@` completes the repository's users. */
44 + mentionScope?: PullRequestMentionScope | null;
45 }
46
47 export function DiffCommentAnnotation({
@@ -55,6 +60,7 @@ export function DiffCommentAnnotation({
60 pending = false,
61 secondaryAction,
62 focusOnMount = true,
63 + mentionScope = null,
64 }: DiffCommentAnnotationProps) {
65 const [localDraftText, setLocalDraftText] = useState("");
66 const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
@@ -121,8 +127,9 @@ export function DiffCommentAnnotation({
127 contentEditable={false}
128 onPointerDown={(event) => event.stopPropagation()}
129 >
124 - <Textarea
130 + <PullRequestMarkdownTextarea
131 ref={textareaRef}
132 + mentionScope={mentionScope}
133 readOnly={speech?.freezesEditor}
134 autoFocus={focusOnMount}
135 size="sm"
@@ -130,7 +137,7 @@ export function DiffCommentAnnotation({
137 dir={textDirection(displayedText)}
138 placeholder={placeholder}
139 aria-label={`Comment on lines ${rangeLabel}`}
133 - onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}
140 + onValueChange={onTextChange ?? setLocalDraftText}
141 onFocus={(event) => {
142 const end = event.currentTarget.value.length;
143 event.currentTarget.setSelectionRange(end, end);
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+4
@@ -109,6 +109,7 @@ import {
109 ReviewThreadCard,
110 toViewerSide,
111 } from "./PullRequestReviewAnnotation";
112 +import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
113 import {
114 getFileViewedRange,
115 isFileDiffCollapsed,
@@ -550,6 +551,7 @@ function PullRequestCodeTab({
551 commit,
552 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
553 });
554 + const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
555 const hostReview = detail.capabilities.review;
556 const review = {
557 inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -960,6 +962,7 @@ function PullRequestCodeTab({
962 canReact={detail.capabilities.reactions === true}
963 environmentId={environmentId}
964 reference={reference}
965 + mentionScope={mentionScope}
966 pending={threadPending}
967 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
968 fixLabel={fixFindingLabel}
@@ -1031,6 +1034,7 @@ function PullRequestCodeTab({
1034 kind="draft"
1035 rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
1036 text=""
1037 + mentionScope={canCommentOnLines ? mentionScope : null}
1038 submitLabel={canCommentOnLines ? "Add to review" : "Add to agent"}
1039 {...(canCommentOnLines && onAddToAgentSelection
1040 ? {
apps/web/src/components/pullRequest/PullRequestCommentForm.tsx
+7 -3
@@ -8,9 +8,12 @@ import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFie
8 import { pullRequestEnvironment } from "~/state/pullRequests";
9
10 import { Button } from "../ui/button";
11 -import { Textarea } from "../ui/textarea";
11 import { toastManager } from "../ui/toast";
12 import { PullRequestGlyph } from "./pullRequestIcons";
13 +import {
14 + PullRequestMarkdownTextarea,
15 + pullRequestMentionScope,
16 +} from "./PullRequestMarkdownTextarea";
17 import { pullRequestReviewKey } from "./pullRequestReviewStore";
18 import { useInlineActionConfirm } from "./useInlineActionConfirm";
19
@@ -108,8 +111,9 @@ export function PullRequestCommentForm({
111
112 return (
113 <div className="space-y-2">
111 - <Textarea
114 + <PullRequestMarkdownTextarea
115 ref={textareaRef}
116 + mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
117 // Lock while posting because success clears the draft.
118 disabled={locked}
119 readOnly={speech.freezesEditor}
@@ -117,7 +121,7 @@ export function PullRequestCommentForm({
121 rows={3}
122 placeholder="Leave a comment"
123 aria-label={`Comment on this ${sourceControlClients.get(detail.provider).changeRequest.singular}`}
120 - onChange={(event) => setBody(event.target.value)}
124 + onValueChange={setBody}
125 onKeyDown={(event) => {
126 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
127 if (
apps/web/src/components/pullRequest/PullRequestComposer.tsx
+2
@@ -16,6 +16,7 @@ import {
16 usePendingReviewComments,
17 usePullRequestReviewStore,
18 } from "./pullRequestReviewStore";
19 +import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
20
21 export function PullRequestComposer({
22 environmentId,
@@ -154,6 +155,7 @@ export function PullRequestComposer({
155 active={open && mode === "review"}
156 environmentId={environmentId}
157 reference={reference}
158 + mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
159 term={term}
160 verdicts={verdicts}
161 requestChangesSummaryRequired={sourceControlClients
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+2
@@ -66,6 +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";
70 import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
71 import {
72 capitalizeTerm,
@@ -1737,6 +1738,7 @@ export function PullRequestDetailPanel({
1738 detail.capabilities.review.inlineComment && detail.viewerPermissions.comment
1739 }
1740 rangeComments={detail.capabilities.review.rangeComment === true}
1741 + mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
1742 onAskAboutLines={(comment, request) =>
1743 addSelectionToAgent({ comment, request }, { keepGuide: true })
1744 }
apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx
+1
@@ -55,6 +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}
59 onAskAboutLines={null}
60 onAskAboutStop={null}
61 onFinishReview={null}
apps/web/src/components/pullRequest/PullRequestGuideTab.tsx
+4
@@ -17,6 +17,7 @@ import {
17 usePendingReviewComments,
18 usePullRequestReviewStore,
19 } from "./pullRequestReviewStore";
20 +import type { PullRequestMentionScope } from "./PullRequestMarkdownTextarea";
21
22 export function PullRequestGuideTab({
23 environmentId,
@@ -26,6 +27,7 @@ export function PullRequestGuideTab({
27 active,
28 canComment,
29 rangeComments,
30 + mentionScope,
31 onAskAboutLines,
32 onAskAboutStop,
33 onFinishReview,
@@ -39,6 +41,7 @@ export function PullRequestGuideTab({
41 active: boolean;
42 canComment: boolean;
43 rangeComments: boolean;
44 + mentionScope: PullRequestMentionScope | null;
45 onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null;
46 onAskAboutStop:
47 | ((stop: PullRequestReviewGuideStop, index: number, question: string) => void)
@@ -62,6 +65,7 @@ export function PullRequestGuideTab({
65 : {
66 canComment,
67 rangeComments,
68 + mentionScope,
69 pending,
70 onComment: ({ path, oldPath, position, startPosition, body }) =>
71 addComment(reviewKey, {
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
+42 -2
@@ -1,7 +1,7 @@
1 import { act, render, type Screen } from "../../../test/render";
2 -import { AuthSourceControlWriteScope, EnvironmentId } from "@t3tools/contracts";
2 +import { AuthSourceControlWriteScope, EnvironmentId, ProjectId } from "@t3tools/contracts";
3 import { expect, it, vi } from "vite-plus/test";
4 -import { userEvent } from "vite-plus/test/browser";
4 +import { page, userEvent } from "vite-plus/test/browser";
5
6 const permissions = vi.hoisted(() => ({
7 allowed: new Set<string>(),
@@ -26,6 +26,22 @@ vi.mock(import("~/state/session"), async (original) => {
26 };
27 });
28
29 +vi.mock(import("~/state/pullRequests"), async (original) => ({
30 + ...(await original()),
31 + usePullRequestFilterOptions: (targets: ReadonlyArray<unknown>) => ({
32 + labels: [],
33 + authors:
34 + targets.length === 0
35 + ? []
36 + : [
37 + { login: "julius", name: "Julius", avatarUrl: null },
38 + { login: "theo", name: "Theo", avatarUrl: null },
39 + ],
40 + error: null,
41 + isPending: false,
42 + }),
43 +}));
44 +
45 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
46
47 const secondary = EnvironmentId.make("secondary");
@@ -45,6 +61,7 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
61 value={options?.value ?? "Original description"}
62 cwd="/repo"
63 environmentId={secondary}
64 + mentionScope={{ environmentId: secondary, projectId: ProjectId.make("project") }}
65 label="Pull request description"
66 saving={false}
67 allowEmpty={options?.allowEmpty ?? false}
@@ -88,3 +105,26 @@ it("keeps an edited draft through revocation and saves it after access returns w
105 await clickSave(screen);
106 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
107 });
108 +
109 +it("completes an @mention on Enter and closes the list on Escape until the next keystroke", async () => {
110 + setup();
111 + permissions.allowed.add(secondary);
112 + await using screen = await openEditor({ value: "" });
113 + const textarea = screen.container.querySelector("textarea")!;
114 + await userEvent.type(textarea, "Thanks @ju");
115 + await expect.element(page.getByRole("option", { name: /julius/ })).toBeVisible();
116 +
117 + await userEvent.keyboard("{Enter}");
118 + expect(textarea.value).toBe("Thanks @julius ");
119 + await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
120 +
121 + await userEvent.type(textarea, "and @");
122 + await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
123 + await userEvent.keyboard("{Escape}");
124 + await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
125 + expect(onCancel).not.toHaveBeenCalled();
126 +
127 + await userEvent.type(textarea, "t");
128 + await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
129 + expect(onSave).not.toHaveBeenCalled();
130 +});
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
+9 -3
@@ -9,14 +9,18 @@ import { cn } from "~/lib/utils";
9 import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
10
11 import { Button } from "../ui/button";
12 -import { Textarea } from "../ui/textarea";
12 import { Toggle, ToggleGroup } from "../ui/toggle-group";
13 import { PullRequestMarkdown } from "./PullRequestMarkdown";
14 +import {
15 + PullRequestMarkdownTextarea,
16 + type PullRequestMentionScope,
17 +} from "./PullRequestMarkdownTextarea";
18
19 export function PullRequestMarkdownEditor({
20 value,
21 cwd,
22 environmentId,
23 + mentionScope,
24 threadRef = null,
25 placeholder,
26 label,
@@ -29,6 +33,7 @@ export function PullRequestMarkdownEditor({
33 readonly value: string;
34 readonly cwd: string;
35 readonly environmentId: EnvironmentId;
36 + readonly mentionScope: PullRequestMentionScope | null;
37 readonly threadRef?: ScopedThreadRef | null;
38 readonly placeholder?: string | undefined;
39 readonly label: string;
@@ -102,14 +107,15 @@ export function PullRequestMarkdownEditor({
107 )}
108 </div>
109 ) : (
105 - <Textarea
110 + <PullRequestMarkdownTextarea
111 autoFocus
112 disabled={saving}
113 + mentionScope={mentionScope}
114 value={draft}
115 rows={6}
116 placeholder={placeholder}
117 aria-label={label}
112 - onChange={(event) => setDraft(event.target.value)}
118 + onValueChange={setDraft}
119 />
120 )}
121 <div className="flex justify-end gap-2">
apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx new
+257
@@ -0,0 +1,257 @@
1 +import type {
2 + EnvironmentId,
3 + ProjectId,
4 + PullRequestActor,
5 + PullRequestDetailView,
6 + PullRequestRef,
7 +} from "@t3tools/contracts";
8 +import {
9 + detectPullRequestMention,
10 + insertPullRequestMention,
11 + narrowPullRequestMentions,
12 +} from "@t3tools/shared/pullRequestComposerTrigger";
13 +import { useId, useState, type Ref } from "react";
14 +import { flushSync } from "react-dom";
15 +
16 +import { cn } from "~/lib/utils";
17 +import { usePullRequestFilterOptions } from "~/state/pullRequests";
18 +import { useDebouncedValue } from "~/state/queries";
19 +
20 +import { Popover, PopoverPopup } from "../ui/popover";
21 +import { Textarea, type TextareaProps } from "../ui/textarea";
22 +import { PullRequestActorAvatar } from "./pullRequestPresentation";
23 +
24 +/** The repository whose users an `@` completes. */
25 +export interface PullRequestMentionScope {
26 + readonly environmentId: EnvironmentId;
27 + readonly projectId: ProjectId;
28 +}
29 +
30 +/** Null on hosts that cannot search their users, so `@` never opens a list that cannot fill. */
31 +export function pullRequestMentionScope(
32 + detail: Pick<PullRequestDetailView, "capabilities">,
33 + environmentId: EnvironmentId,
34 + reference: PullRequestRef,
35 +): PullRequestMentionScope | null {
36 + return detail.capabilities.mentions === true
37 + ? { environmentId, projectId: reference.projectId }
38 + : null;
39 +}
40 +
41 +const MENTION_SEARCH_DEBOUNCE_MS = 200;
42 +const MENTION_SUGGESTION_LIMIT = 8;
43 +// About a full list of suggestions. The popup fits itself to the space it opens into, so it never
44 +// flips once results grow it; the side is picked up front from the room a full list needs.
45 +const SUGGESTION_LIST_HEIGHT = 320;
46 +
47 +function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" {
48 + const rect = target.getBoundingClientRect();
49 + const below = window.innerHeight - rect.bottom;
50 + return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom";
51 +}
52 +
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);
57 + const hosted = usePullRequestFilterOptions(
58 + scope === null || query === null
59 + ? []
60 + : [
61 + {
62 + environmentId: scope.environmentId,
63 + input: {
64 + kind: "authors",
65 + projectId: scope.projectId,
66 + ...(sent ? { query: sent } : {}),
67 + },
68 + },
69 + ],
70 + );
71 + // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
72 + return {
73 + candidates: narrowPullRequestMentions(hosted.authors, typed, MENTION_SUGGESTION_LIMIT),
74 + isPending: hosted.isPending || sent !== search,
75 + failed: hosted.error !== null,
76 + };
77 +}
78 +
79 +function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
80 + if (typeof ref === "function") ref(value);
81 + else if (ref) ref.current = value;
82 +}
83 +
84 +/** A markdown textarea for pull request text that completes `@login` from the repository's users. */
85 +export function PullRequestMarkdownTextarea({
86 + ref,
87 + value,
88 + onValueChange,
89 + mentionScope,
90 + onKeyDown,
91 + onSelect,
92 + onFocus,
93 + onBlur,
94 + ...props
95 +}: Omit<TextareaProps, "value" | "onChange"> & {
96 + readonly value: string;
97 + readonly onValueChange: (value: string) => void;
98 + readonly mentionScope: PullRequestMentionScope | null;
99 +}) {
100 + const listId = useId();
101 + const [element, setElement] = useState<HTMLTextAreaElement | null>(null);
102 + const [caret, setCaret] = useState<number | null>(null);
103 + const [side, setSide] = useState<"top" | "bottom">("bottom");
104 + const [dismissedAt, setDismissedAt] = useState<number | null>(null);
105 + const [highlight, setHighlight] = useState({ query: "", index: 0 });
106 +
107 + const trigger =
108 + mentionScope === null || caret === null || props.readOnly
109 + ? null
110 + : detectPullRequestMention(value, caret);
111 + const open = trigger !== null && trigger.rangeStart !== dismissedAt;
112 + const { candidates, isPending, failed } = useMentionCandidates(
113 + mentionScope,
114 + open ? trigger.query : null,
115 + );
116 + const activeIndex =
117 + trigger !== null && highlight.query === trigger.query
118 + ? Math.min(highlight.index, Math.max(0, candidates.length - 1))
119 + : 0;
120 + const active = open ? candidates[activeIndex] : undefined;
121 + const optionId = (login: string) => `${listId}-${login}`;
122 +
123 + const syncCaret = (target: HTMLTextAreaElement) => {
124 + setSide(suggestionSide(target));
125 + setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null);
126 + };
127 +
128 + const select = (actor: PullRequestActor) => {
129 + if (trigger === null || element === null) return;
130 + const next = insertPullRequestMention(value, trigger, actor.login);
131 + flushSync(() => onValueChange(next.text));
132 + element.setSelectionRange(next.cursor, next.cursor);
133 + setCaret(next.cursor);
134 + };
135 +
136 + return (
137 + <>
138 + <Textarea
139 + {...props}
140 + ref={(node) => {
141 + setElement(node);
142 + assignRef(ref, node);
143 + }}
144 + value={value}
145 + role={mentionScope === null ? undefined : "combobox"}
146 + aria-autocomplete={mentionScope === null ? undefined : "list"}
147 + aria-expanded={mentionScope === null ? undefined : open}
148 + aria-controls={open && candidates.length > 0 ? listId : undefined}
149 + aria-activedescendant={active ? optionId(active.login) : undefined}
150 + onChange={(event) => {
151 + onValueChange(event.target.value);
152 + syncCaret(event.target);
153 + setDismissedAt(null);
154 + }}
155 + onSelect={(event) => {
156 + syncCaret(event.currentTarget);
157 + onSelect?.(event);
158 + }}
159 + onFocus={(event) => {
160 + syncCaret(event.currentTarget);
161 + onFocus?.(event);
162 + }}
163 + onBlur={(event) => {
164 + setCaret(null);
165 + onBlur?.(event);
166 + }}
167 + onKeyDown={(event) => {
168 + // Some IMEs confirm a composition with an Enter that reports keyCode 229 but not isComposing.
169 + if (open && !event.nativeEvent.isComposing && event.nativeEvent.keyCode !== 229) {
170 + const handled = (() => {
171 + if (event.key === "Escape") {
172 + setDismissedAt(trigger.rangeStart);
173 + return true;
174 + }
175 + if (candidates.length === 0) return false;
176 + if (event.key === "ArrowDown" || event.key === "ArrowUp") {
177 + const step = event.key === "ArrowDown" ? 1 : -1;
178 + setHighlight({
179 + query: trigger.query,
180 + index: (activeIndex + step + candidates.length) % candidates.length,
181 + });
182 + return true;
183 + }
184 + const plain = !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey;
185 + if ((event.key === "Enter" || event.key === "Tab") && plain && active) {
186 + select(active);
187 + return true;
188 + }
189 + return false;
190 + })();
191 + if (handled) {
192 + event.preventDefault();
193 + event.stopPropagation();
194 + return;
195 + }
196 + }
197 + onKeyDown?.(event);
198 + }}
199 + />
200 + <Popover
201 + open={open}
202 + modal={false}
203 + onOpenChange={(next, details) => {
204 + if (next || details.event?.target === element) return;
205 + if (trigger !== null) setDismissedAt(trigger.rangeStart);
206 + }}
207 + >
208 + <PopoverPopup
209 + anchor={element}
210 + side={side}
211 + align="start"
212 + padding="compact"
213 + width="sm"
214 + initialFocus={false}
215 + finalFocus={false}
216 + >
217 + {candidates.length > 0 ? (
218 + <div id={listId} role="listbox" aria-label="Mention a user" className="-mx-1.5">
219 + {candidates.map((actor, index) => (
220 + <div
221 + key={actor.login}
222 + id={optionId(actor.login)}
223 + role="option"
224 + aria-selected={index === activeIndex}
225 + className={cn(
226 + "flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm",
227 + index === activeIndex && "bg-accent text-accent-foreground",
228 + )}
229 + onMouseMove={() => {
230 + if (index !== activeIndex) setHighlight({ query: trigger?.query ?? "", index });
231 + }}
232 + // Keeps focus, and the caret, in the textarea.
233 + onMouseDown={(event) => event.preventDefault()}
234 + onClick={() => select(actor)}
235 + >
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}
241 + </div>
242 + ))}
243 + </div>
244 + ) : (
245 + <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"}
251 + </p>
252 + )}
253 + </PopoverPopup>
254 + </Popover>
255 + </>
256 + );
257 +}
apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+10 -3
@@ -19,7 +19,6 @@ import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldS
19 import { Button } from "../ui/button";
20 import { MorphIcon } from "~/components/MorphIcon";
21 import { PullRequestEditButton } from "./PullRequestEditButton";
22 -import { Textarea } from "../ui/textarea";
22 import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
23 import {
24 editPullRequestThreadComment,
@@ -30,6 +29,10 @@ import { PullRequestMarkdown } from "./PullRequestMarkdown";
29 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
30 import { PullRequestReactionBar } from "./PullRequestReactions";
31 import type { PendingReviewComment } from "./pullRequestReviewStore";
32 +import {
33 + PullRequestMarkdownTextarea,
34 + type PullRequestMentionScope,
35 +} from "./PullRequestMarkdownTextarea";
36
37 const CARD_CLASS =
38 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
@@ -113,6 +116,7 @@ export function ReviewThreadCard({
116 canReact,
117 environmentId,
118 reference,
119 + mentionScope,
120 pending,
121 fixPending,
122 fixLabel = "Fix in a thread",
@@ -131,6 +135,7 @@ export function ReviewThreadCard({
135 canReact: boolean;
136 environmentId: EnvironmentId;
137 reference: PullRequestRef;
138 + mentionScope: PullRequestMentionScope | null;
139 pending: boolean;
140 fixPending?: boolean;
141 fixLabel?: string;
@@ -287,6 +292,7 @@ export function ReviewThreadCard({
292 value={comment.body}
293 cwd={workspaceRoot}
294 environmentId={environmentId}
295 + mentionScope={mentionScope}
296 label="Edit comment"
297 saving={savingEdit}
298 onSave={(body) => void saveEdit(comment.id, body)}
@@ -337,15 +343,16 @@ export function ReviewThreadCard({
343 >
344 {(speech) => (
345 <div className="mt-2">
340 - <Textarea
346 + <PullRequestMarkdownTextarea
347 ref={replyRef}
348 readOnly={speech.freezesEditor}
349 autoFocus
350 size="sm"
351 + mentionScope={mentionScope}
352 value={reply}
353 placeholder="Reply"
354 aria-label="Reply to this conversation"
348 - onChange={(event) => setReply(event.target.value)}
355 + onValueChange={setReply}
356 onKeyDown={submitKeys({
357 value: reply,
358 pending,
apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx
+5 -1
@@ -14,7 +14,10 @@ vi.mock("~/speech/useTextFieldSpeech", () => ({
14 useTextFieldSpeech: () => ({ blocksSubmission: true, submitAfterDictation: mocks.queue }),
15 }));
16 vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => mocks.submit }));
17 -vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: { submitReview: {} } }));
17 +vi.mock(import("~/state/pullRequests"), async (original) => ({
18 + ...(await original()),
19 + pullRequestEnvironment: { submitReview: {} } as never,
20 +}));
21
22 it("submits only the line comments still in the draft when dictation finishes", async () => {
23 mocks.submit.mockClear();
@@ -34,6 +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}
41 term="pull request"
42 verdicts={["comment"]}
43 requestChangesSummaryRequired={false}
apps/web/src/components/pullRequest/PullRequestReviewForm.tsx
+9 -3
@@ -11,7 +11,6 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"
11 import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
12 import { Button } from "../ui/button";
13 import { Select, SelectItem, SelectPopup, SelectTrigger } from "../ui/select";
14 -import { Textarea } from "../ui/textarea";
14 import { toastManager } from "../ui/toast";
15 import { readableFailure } from "./pullRequestDetail.logic";
16 import {
@@ -19,6 +18,10 @@ import {
18 usePendingReviewComments,
19 usePullRequestReviewStore,
20 } from "./pullRequestReviewStore";
21 +import {
22 + PullRequestMarkdownTextarea,
23 + type PullRequestMentionScope,
24 +} from "./PullRequestMarkdownTextarea";
25
26 const VERDICTS: ReadonlyArray<{
27 readonly value: PullRequestReviewVerdict;
@@ -50,6 +53,7 @@ export function PullRequestReviewForm({
53 environmentId,
54 active,
55 reference,
56 + mentionScope,
57 term,
58 verdicts,
59 requestChangesSummaryRequired,
@@ -62,6 +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;
70 /** The host's word for a change request, as in "pull request". */
71 term: string;
72 verdicts: ReadonlyArray<PullRequestReviewVerdict>;
@@ -150,14 +155,15 @@ export function PullRequestReviewForm({
155
156 return (
157 <>
153 - <Textarea
158 + <PullRequestMarkdownTextarea
159 ref={textareaRef}
160 + mentionScope={mentionScope}
161 rows={3}
162 readOnly={speech.freezesEditor}
163 value={body}
164 placeholder={placeholder}
165 aria-label="Review summary"
160 - onChange={(event) => setSummary(reviewKey, event.target.value)}
166 + onValueChange={(next) => setSummary(reviewKey, next)}
167 onKeyDown={(event) => {
168 if (event.nativeEvent.isComposing || event.keyCode === 229 || event.repeat) return;
169 if (
apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+9
@@ -84,6 +84,10 @@ import { PullRequestMarkdown } from "./PullRequestMarkdown";
84 import { PullRequestCommentBody } from "./PullRequestCommentBody";
85 import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
86 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
87 +import {
88 + type PullRequestMentionScope,
89 + pullRequestMentionScope,
90 +} from "./PullRequestMarkdownTextarea";
91 import { PullRequestReactionBar } from "./PullRequestReactions";
92 import { PullRequestConversationGhost } from "./PullRequestGhosts";
93 import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
@@ -163,6 +167,7 @@ function reviewStateLabel(state: string): string {
167 interface CommentEditing {
168 readonly cwd: string;
169 readonly environmentId: EnvironmentId;
170 + readonly mentionScope: PullRequestMentionScope | null;
171 readonly threadRef: ScopedThreadRef | null;
172 readonly canEdit: (comment: PullRequestComment) => boolean;
173 readonly editingId: string | null;
@@ -187,6 +192,7 @@ function CommentBody({
192 value={comment.body}
193 cwd={editing.cwd}
194 environmentId={editing.environmentId}
195 + mentionScope={editing.mentionScope}
196 threadRef={editing.threadRef}
197 label="Edit comment"
198 saving={editing.saving}
@@ -542,9 +548,11 @@ export function PullRequestSummaryTab({
548 if (body !== description) void saveDescription(body);
549 };
550
551 + const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
552 const commentEditing: CommentEditing = {
553 cwd: detail.workspaceRoot,
554 environmentId,
555 + mentionScope,
556 threadRef,
557 canEdit: (comment) => canEditPullRequestComment(detail, comment),
558 editingId: editingCommentId,
@@ -794,6 +802,7 @@ export function PullRequestSummaryTab({
802 value={bodyScope.body}
803 cwd={detail.workspaceRoot}
804 environmentId={environmentId}
805 + mentionScope={mentionScope}
806 threadRef={threadRef}
807 label={`${capitalizeTerm(terminology.singular)} description`}
808 placeholder={`Describe this ${terminology.singular}`}
apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+7
@@ -57,6 +57,10 @@ import {
57 pullRequestReviewOutcomeToneClassName,
58 } from "./pullRequestPresentation";
59 import { PullRequestGlyph } from "./pullRequestIcons";
60 +import {
61 + type PullRequestMentionScope,
62 + pullRequestMentionScope,
63 +} from "./PullRequestMarkdownTextarea";
64 import { LegendList, type LegendListRef } from "@legendapp/list/react";
65
66 interface ReactionSurface {
@@ -64,6 +68,7 @@ interface ReactionSurface {
68 readonly environmentId: EnvironmentId;
69 readonly threadRef: ScopedThreadRef | null;
70 readonly reference: PullRequestRef;
71 + readonly mentionScope: PullRequestMentionScope | null;
72 readonly onRefresh: () => void;
73 }
74
@@ -263,6 +268,7 @@ function ConversationCard({
268 value={editable.body}
269 cwd={cwd}
270 environmentId={reactions.environmentId}
271 + mentionScope={reactions.mentionScope}
272 threadRef={reactions.threadRef}
273 label="Edit comment"
274 saving={saving}
@@ -653,6 +659,7 @@ export function PullRequestTimelineTab({
659 environmentId,
660 threadRef,
661 reference,
662 + mentionScope: pullRequestMentionScope(detail, environmentId, reference),
663 onRefresh,
664 };
665 const editable = new Map(
apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
+3
@@ -37,6 +37,7 @@ import {
37 fileDiffRows,
38 rowsToPatch,
39 } from "@t3tools/client-runtime/review-guide-tour";
40 +import type { PullRequestMentionScope } from "../PullRequestMarkdownTextarea";
41 import { GuideNoteMarker } from "./GuideNotes";
42 import { GuideProse } from "./GuideProse";
43
@@ -55,6 +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;
60 readonly pending: ReadonlyArray<PendingReviewComment>;
61 readonly onComment: (comment: {
62 readonly path: string;
@@ -323,6 +325,7 @@ function ExcerptDiff({
325 kind="draft"
326 rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
327 text=""
328 + mentionScope={commenting.canComment ? commenting.mentionScope : null}
329 placeholder={
330 commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"
331 }
packages/contracts/src/pullRequest.ts
+2
@@ -277,6 +277,8 @@ export const PullRequestCapabilities = Schema.Struct({
277 stacks: Schema.optional(Schema.Boolean),
278 stackActions: Schema.optional(Schema.Boolean),
279 labels: Schema.optional(Schema.Boolean),
280 + /** The host searches the repository's users, so composers can complete `@login`. */
281 + mentions: Schema.optional(Schema.Boolean),
282 /**
283 * Every head gets at least one check, so a head that has gone a while without any means none
284 * reported rather than that the repository runs none. Absent means an empty list says nothing.
packages/shared/package.json
+4
@@ -263,6 +263,10 @@
263 "types": "./src/composerTrigger.ts",
264 "import": "./src/composerTrigger.ts"
265 },
266 + "./pullRequestComposerTrigger": {
267 + "types": "./src/pullRequestComposerTrigger.ts",
268 + "import": "./src/pullRequestComposerTrigger.ts"
269 + },
270 "./composerInlineTokens": {
271 "types": "./src/composerInlineTokens.ts",
272 "import": "./src/composerInlineTokens.ts"
packages/shared/src/pullRequestComposerTrigger.test.ts new
+70
@@ -0,0 +1,70 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import {
4 + detectPullRequestMention,
5 + insertPullRequestMention,
6 + narrowPullRequestMentions,
7 +} from "./pullRequestComposerTrigger.ts";
8 +
9 +describe("detectPullRequestMention", () => {
10 + 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) => {
16 + const cursor = rangeStart + 1 + query.length;
17 + expect(detectPullRequestMention(text, cursor)).toEqual({
18 + query,
19 + rangeStart,
20 + rangeEnd: cursor,
21 + });
22 + });
23 +
24 + it.each([
25 + ["mail me at jane@example.com", "mail me at jane@example.com".length],
26 + ["@jane done", "@jane done".length],
27 + ["@-jane", "@-jane".length],
28 + ["`@decorator`", "`@decorator".length],
29 + ["@jane", 3],
30 + ])("ignores %j", (text, cursor) => {
31 + expect(detectPullRequestMention(text, cursor)).toBeNull();
32 + });
33 +});
34 +
35 +describe("insertPullRequestMention", () => {
36 + it.each(["", "\nnext line", "\r\nnext line"])(
37 + "replaces the partial login and adds a space before %j",
38 + (suffix) => {
39 + const text = `thanks @ju${suffix}`;
40 + const trigger = detectPullRequestMention(text, "thanks @ju".length)!;
41 + expect(insertPullRequestMention(text, trigger, "julius")).toEqual({
42 + text: `thanks @julius ${suffix}`,
43 + cursor: "thanks @julius ".length,
44 + });
45 + },
46 + );
47 +
48 + 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();
54 + });
55 +});
56 +
57 +describe("narrowPullRequestMentions", () => {
58 + it("matches login or name, case-insensitively, up to the limit", () => {
59 + const users = [
60 + { login: "TonybynMp4", name: null },
61 + { login: "16g", name: "Tom" },
62 + { login: "theo", name: "Theo" },
63 + ];
64 + expect(narrowPullRequestMentions(users, "to", 5).map((u) => u.login)).toEqual([
65 + "TonybynMp4",
66 + "16g",
67 + ]);
68 + expect(narrowPullRequestMentions(users, "", 2)).toHaveLength(2);
69 + });
70 +});
packages/shared/src/pullRequestComposerTrigger.ts new
+53
@@ -0,0 +1,53 @@
1 +import { replaceTextRange } from "./composerTrigger.ts";
2 +
3 +export interface PullRequestMentionTrigger {
4 + readonly query: string;
5 + readonly rangeStart: number;
6 + readonly rangeEnd: number;
7 +}
8 +
9 +// Covers GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).
10 +const MENTION_TOKEN = /^@([A-Za-z0-9_][A-Za-z0-9_.-]*)?$/;
11 +
12 +/** The `@login` being typed at the caret, when the caret sits at its end. */
13 +export function detectPullRequestMention(
14 + text: string,
15 + cursor: number,
16 +): PullRequestMentionTrigger | null {
17 + const end = Math.max(0, Math.min(text.length, cursor));
18 + const next = text[end];
19 + if (next !== undefined && !/\s/.test(next)) return null;
20 + let start = end;
21 + while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;
22 + const match = MENTION_TOKEN.exec(text.slice(start, end));
23 + if (!match) return null;
24 + return { query: match[1] ?? "", rangeStart: start, rangeEnd: end };
25 +}
26 +
27 +export function insertPullRequestMention(
28 + text: string,
29 + trigger: PullRequestMentionTrigger,
30 + login: string,
31 +): { text: string; cursor: number } {
32 + const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? "");
33 + if (!followedBySpace) {
34 + return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login} `);
35 + }
36 + const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login}`);
37 + return { ...inserted, cursor: inserted.cursor + 1 };
38 +}
39 +
40 +export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(
41 + users: ReadonlyArray<A>,
42 + typed: string,
43 + limit: number,
44 +): A[] {
45 + const needle = typed.toLowerCase();
46 + return users
47 + .filter(
48 + (user) =>
49 + user.login.toLowerCase().includes(needle) ||
50 + (user.name?.toLowerCase().includes(needle) ?? false),
51 + )
52 + .slice(0, limit);
53 +}
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+1
@@ -52,6 +52,7 @@ const CAPABILITIES: PullRequestCapabilities = {
52 // `az repos pr list` has no text filter.
53 search: false,
54 reactions: false,
55 + mentions: false,
56 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
57 // Reviewer candidates require separate identity/graph APIs and permissions.
58 reviewers: { request: true, listCandidates: false },
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+1
@@ -23,6 +23,7 @@ const CAPABILITIES: PullRequestCapabilities = {
23 mergeMethods: ["merge", "squash", "rebase"],
24 search: true,
25 reactions: false,
26 + mentions: false,
27 review: {
28 inlineComment: true,
29 reply: true,
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+1
@@ -48,6 +48,7 @@ const CAPABILITIES: PullRequestCapabilities = {
48 updateMethods: ["merge", "rebase"],
49 search: false,
50 reactions: true,
51 + mentions: true,
52 labels: true,
53 // Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
54 review: {
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+1
@@ -34,6 +34,7 @@ const CAPABILITIES: PullRequestCapabilities = {
34 stacks: true,
35 stackActions: true,
36 reactions: true,
37 + mentions: true,
38 labels: true,
39 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
40 review: {
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+1
@@ -41,6 +41,7 @@ const CAPABILITIES: PullRequestCapabilities = {
41 updateMethods: ["merge", "rebase"],
42 search: true,
43 reactions: true,
44 + mentions: true,
45 viewedFiles: "host",
46 review: {
47 inlineComment: true,
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+14
@@ -1844,6 +1844,20 @@ layer("GitLabPullRequestCli.layer", (it) => {
1844 }),
1845 );
1846
1847 + it.effect.each([
1848 + ["th", "projects/acme%2Fweb/users?per_page=100"],
1849 + ["tho", "projects/acme%2Fweb/users?per_page=100&search=tho"],
1850 + ] as const)("searches project users only from three characters (%s)", ([search, path]) =>
1851 + Effect.gen(function* () {
1852 + mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify([author]))));
1853 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1854 +
1855 + yield* cli.listProjectUsers({ cwd: "/w", repository: "acme/web", search });
1856 +
1857 + expect(argsOfCall(0)[1]).toBe(path);
1858 + }),
1859 + );
1860 +
1861 it.effect("reads who has access to the project and who is already on the merge request", () =>
1862 Effect.gen(function* () {
1863 mockedExecute
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+3 -1
@@ -1287,7 +1287,9 @@ export const make = Effect.gen(function* () {
1287 host: input.host,
1288 path: `projects/${projectPath(input.repository)}/users?${query([
1289 ["per_page", String(MAX_PAGE_SIZE)],
1290 - ...searchParams(input.search),
1290 + // GitLab answers nothing for a user search under three characters; callers narrow the
1291 + // unsearched page instead.
1292 + ...((input.search?.trim().length ?? 0) >= 3 ? searchParams(input.search) : []),
1293 ])}`,
1294 }).pipe(
1295 Effect.flatMap((result) => {
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+1
@@ -32,6 +32,7 @@ const CAPABILITIES: PullRequestCapabilities = {
32 updateMethods: ["rebase"],
33 search: true,
34 reactions: true,
35 + mentions: true,
36 // GitLab's viewed marks live in browser-local storage.
37 viewedFiles: "environment",
38 review: {