Skip to content
TypeScript

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

Antony7bc2a40ced90
diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
index f80e9a5a093..e3ed028b592 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
@@ -26,6 +26,8 @@ import { PullRequestCommentFooter } from "./PullRequestReactions";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
import { usePullRequestPermissions } from "./usePullRequestPermissions";
import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
+import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
+import { usePullRequestMentions } from "./usePullRequestMentions";
export function PullRequestDiscussionScreen({
route,
@@ -55,6 +57,13 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false });
const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId);
const [body, setBody] = useState("");
+ const mentions = usePullRequestMentions({
+ environmentId: params.environmentId,
+ projectId: params.projectId,
+ value: body,
+ onChangeValue: setBody,
+ enabled: detail.data?.capabilities.mentions === true,
+ });
const [extra, setExtra] = useState<readonly PullRequestThreadComment[]>([]);
const [cursor, setCursor] = useState<string | null | undefined>();
const [busy, setBusy] = useState(false);
@@ -222,7 +231,11 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
</ScrollView>
</ScrollViewMarker>
{canReply ? (
- <View className="absolute inset-x-4 bottom-0" style={{ paddingBottom: bottomInset }}>
+ <View
+ className="absolute inset-x-4 bottom-0 gap-2"
+ style={{ paddingBottom: bottomInset }}
+ >
+ <PullRequestMentionSuggestions mentions={mentions} />
<GlassSurface
chrome="none"
onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)}
@@ -230,6 +243,9 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
>
<TextInput
accessibilityLabel="Discussion reply"
+ selection={mentions.selection}
+ onSelectionChange={mentions.onSelectionChange}
+ onBlur={mentions.onBlur}
multiline
maxLength={65536}
placeholder="Reply…"
diff --git a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx
index 8546302b7cf..1d6eb374e54 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx
@@ -16,6 +16,8 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { PullRequestSheetContent } from "./PullRequestSheetContent";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
import { usePullRequestPermissions } from "./usePullRequestPermissions";
+import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
+import { usePullRequestMentions } from "./usePullRequestMentions";
export type PullRequestEditParams = PullRequestParams &
(
@@ -49,6 +51,13 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd
: (pr?.body ?? null);
const [draft, setDraft] = useState<string | null>(null);
const value = draft ?? original ?? "";
+ const mentions = usePullRequestMentions({
+ environmentId: params.environmentId,
+ projectId: params.projectId,
+ value: value,
+ onChangeValue: setDraft,
+ enabled: params.field !== "title" && pr?.capabilities.mentions === true,
+ });
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
@@ -131,8 +140,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps<PullRequestEd
/>
}
>
+ <PullRequestMentionSuggestions mentions={mentions} />
<TextInput
multiline={params.field !== "title"}
+ selection={mentions.selection}
+ onSelectionChange={mentions.onSelectionChange}
+ onBlur={mentions.onBlur}
editable={!busy && original !== null}
autoFocus
accessibilityLabel={
diff --git a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
index d0b7a5ae880..68de1a2f2f3 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
@@ -15,6 +15,8 @@ import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
import { reviewPositionLabel } from "./pullRequestDiffComments";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
import { usePullRequestPermissions } from "./usePullRequestPermissions";
+import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
+import { usePullRequestMentions } from "./usePullRequestMentions";
export type InlineCommentParams = PullRequestParams & {
readonly draftId?: string;
@@ -33,6 +35,13 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
const body = editedBody ?? saved?.body ?? "";
const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params)));
const { refresh: refreshDetail } = detail;
+ const mentions = usePullRequestMentions({
+ environmentId: params.environmentId,
+ projectId: params.projectId,
+ value: body,
+ onChangeValue: setBody,
+ enabled: detail.data?.capabilities.mentions === true,
+ });
useFocusEffect(refreshDetail);
const permissions = usePullRequestPermissions(params, detail.data);
const stale = detail.data && detail.data.headSha !== params.headSha;
@@ -101,8 +110,12 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
{params.code}
</Text>
</View>
+ <PullRequestMentionSuggestions mentions={mentions} />
<TextInput
multiline
+ selection={mentions.selection}
+ onSelectionChange={mentions.onSelectionChange}
+ onBlur={mentions.onBlur}
editable={store.ready && !busy}
autoFocus
accessibilityLabel="Inline review comment"
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx b/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx
new file mode 100644
index 00000000000..d91dcde9968
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx
@@ -0,0 +1,65 @@
+import { Pressable, ScrollView, StyleSheet, View } from "react-native";
+
+import { AppText as Text } from "../../components/ui/AppText";
+import { GlassSurface } from "../../components/ui/GlassSurface";
+import { PullRequestAvatar } from "./PullRequestPresentation";
+import type { usePullRequestMentions } from "./usePullRequestMentions";
+
+/** The `@` suggestions for a pull request text input, rendered just above it. */
+export function PullRequestMentionSuggestions({
+ mentions,
+}: {
+ readonly mentions: ReturnType<typeof usePullRequestMentions>;
+}) {
+ if (!mentions.open) return null;
+ return (
+ <GlassSurface
+ glassEffectStyle="clear"
+ tintColorClassName="accent-glass-surface"
+ style={{ borderRadius: 16, overflow: "hidden" }}
+ >
+ {mentions.candidates.length > 0 ? (
+ <ScrollView
+ className="max-h-[180px]"
+ keyboardShouldPersistTaps="always"
+ showsVerticalScrollIndicator={false}
+ accessibilityLabel="Mention a user"
+ >
+ {mentions.candidates.map((actor, index) => (
+ <Pressable
+ key={actor.login}
+ accessibilityRole="button"
+ accessibilityLabel={`Mention ${actor.login}`}
+ onPress={() => mentions.select(actor)}
+ className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60"
+ style={{
+ borderBottomWidth:
+ index === mentions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth,
+ }}
+ >
+ <PullRequestAvatar actor={actor} size={20} />
+ <Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
+ {actor.login}
+ </Text>
+ {actor.name && actor.name !== actor.login ? (
+ <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
+ {actor.name}
+ </Text>
+ ) : null}
+ </Pressable>
+ ))}
+ </ScrollView>
+ ) : (
+ <View className="px-3.5 py-2.5">
+ <Text className="text-xs text-foreground-tertiary">
+ {mentions.isLoading
+ ? "Searching users..."
+ : mentions.failed
+ ? "Couldn't search users on the host"
+ : "No matching users"}
+ </Text>
+ </View>
+ )}
+ </GlassSurface>
+ );
+}
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
index bb923689d42..3b5fa30d181 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
@@ -19,6 +19,8 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetContent";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
import { usePullRequestPermissions } from "./usePullRequestPermissions";
+import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions";
+import { usePullRequestMentions } from "./usePullRequestMentions";
function useActionSubmission(params: PullRequestParams) {
const navigation = useNavigation();
@@ -81,6 +83,13 @@ export function PullRequestReviewSheet({
...draft,
...(params.mode === "review" ? { summary: body } : { comment: body }),
}));
+ const mentions = usePullRequestMentions({
+ environmentId: params.environmentId,
+ projectId: params.projectId,
+ value: body,
+ onChangeValue: setBody,
+ enabled: result.data?.capabilities.mentions === true,
+ });
const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha);
const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");
const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value));
@@ -169,8 +178,12 @@ export function PullRequestReviewSheet({
<Text className="px-4 text-xs text-foreground-muted">
{reviewing ? "Summary" : "Comment"}
</Text>
+ <PullRequestMentionSuggestions mentions={mentions} />
<TextInput
multiline
+ selection={mentions.selection}
+ onSelectionChange={mentions.onSelectionChange}
+ onBlur={mentions.onBlur}
accessibilityLabel={reviewing ? "Review summary" : "Comment"}
placeholder={
reviewing
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts b/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts
new file mode 100644
index 00000000000..8c2a759bef8
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts
@@ -0,0 +1,73 @@
+import { EnvironmentId, ProjectId, type PullRequestActor } from "@t3tools/contracts";
+import {
+ detectPullRequestMention,
+ insertPullRequestMention,
+ narrowPullRequestMentions,
+} from "@t3tools/shared/pullRequestComposerTrigger";
+import { useState } from "react";
+import type { TextInputSelectionChangeEvent } from "react-native";
+
+import { composerPullRequests } from "../../state/pull-requests";
+import { useEnvironmentQuery } from "../../state/query";
+import { useDebouncedValue } from "../../state/queries";
+
+const MENTION_SUGGESTION_LIMIT = 6;
+
+/** Completes `@login` in a pull request text input from the repository's users. */
+export function usePullRequestMentions(input: {
+ readonly environmentId: string;
+ readonly projectId: string;
+ readonly value: string;
+ readonly onChangeValue: (value: string) => void;
+ /** The pull request's host completes mentions (`capabilities.mentions`), and the field takes them. */
+ readonly enabled: boolean;
+}) {
+ const [selection, setSelection] = useState<{ start: number; end: number } | null>(null);
+ // Set only right after an insertion, so the native input keeps its own caret otherwise.
+ const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null);
+ const trigger =
+ !input.enabled || selection === null || selection.start !== selection.end
+ ? null
+ : detectPullRequestMention(input.value, selection.start);
+ const typed = trigger?.query ?? "";
+ const search = typed === "" ? undefined : typed.slice(0, 100);
+ const sent = useDebouncedValue(search, 250);
+ const hosted = useEnvironmentQuery(
+ trigger === null
+ ? null
+ : composerPullRequests.filterOptions({
+ environmentId: EnvironmentId.make(input.environmentId),
+ input: {
+ kind: "authors",
+ projectId: ProjectId.make(input.projectId),
+ ...(sent ? { query: sent } : {}),
+ },
+ }),
+ );
+ // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
+ const candidates = narrowPullRequestMentions(
+ hosted.data?.authors ?? [],
+ typed,
+ MENTION_SUGGESTION_LIMIT,
+ );
+
+ return {
+ open: trigger !== null,
+ candidates,
+ isLoading: hosted.isPending || sent !== search,
+ failed: hosted.error !== null,
+ selection: placed ?? undefined,
+ onSelectionChange: (event: TextInputSelectionChangeEvent) => {
+ setSelection(event.nativeEvent.selection);
+ setPlaced(null);
+ },
+ onBlur: () => setSelection(null),
+ select: (actor: PullRequestActor) => {
+ if (trigger === null) return;
+ const next = insertPullRequestMention(input.value, trigger, actor.login);
+ input.onChangeValue(next.text);
+ setSelection({ start: next.cursor, end: next.cursor });
+ setPlaced({ start: next.cursor, end: next.cursor });
+ },
+ };
+}
diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx
index fb2fc81bae8..874118daf30 100644
--- a/apps/web/src/components/DiffPanel.browser.test.tsx
+++ b/apps/web/src/components/DiffPanel.browser.test.tsx
@@ -79,6 +79,7 @@ vi.mock("~/hooks/useTheme", () => ({
vi.mock("~/state/queries", () => ({
useCheckpointDiff: () => ({ data: null, error: null, isPending: false }),
useTurnItemDetail: () => ({ data: null, error: null, isPending: false }),
+ useDebouncedValue: <A,>(value: A) => value,
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} }));
vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} }));
diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx
index a73b631a888..f012daf098d 100644
--- a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx
+++ b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx
@@ -3,7 +3,10 @@ import { MessageCircle, Trash2 } from "lucide-react";
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { Button } from "~/components/ui/button";
-import { Textarea } from "~/components/ui/textarea";
+import {
+ PullRequestMarkdownTextarea,
+ type PullRequestMentionScope,
+} from "~/components/pullRequest/PullRequestMarkdownTextarea";
import {
SpeechTextField,
TextFieldSpeechControls,
@@ -37,6 +40,8 @@ interface DiffCommentAnnotationProps {
pending?: boolean;
secondaryAction?: DiffCommentSecondaryAction;
focusOnMount?: boolean;
+ /** Set only for pull request comments, where `@` completes the repository's users. */
+ mentionScope?: PullRequestMentionScope | null;
}
export function DiffCommentAnnotation({
@@ -55,6 +60,7 @@ export function DiffCommentAnnotation({
pending = false,
secondaryAction,
focusOnMount = true,
+ mentionScope = null,
}: DiffCommentAnnotationProps) {
const [localDraftText, setLocalDraftText] = useState("");
const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
@@ -121,8 +127,9 @@ export function DiffCommentAnnotation({
contentEditable={false}
onPointerDown={(event) => event.stopPropagation()}
>
- <Textarea
+ <PullRequestMarkdownTextarea
ref={textareaRef}
+ mentionScope={mentionScope}
readOnly={speech?.freezesEditor}
autoFocus={focusOnMount}
size="sm"
@@ -130,7 +137,7 @@ export function DiffCommentAnnotation({
dir={textDirection(displayedText)}
placeholder={placeholder}
aria-label={`Comment on lines ${rangeLabel}`}
- onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}
+ onValueChange={onTextChange ?? setLocalDraftText}
onFocus={(event) => {
const end = event.currentTarget.value.length;
event.currentTarget.setSelectionRange(end, end);
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
index b8f46cd513b..39c57012999 100644
--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
@@ -109,6 +109,7 @@ import {
ReviewThreadCard,
toViewerSide,
} from "./PullRequestReviewAnnotation";
+import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
import {
getFileViewedRange,
isFileDiffCollapsed,
@@ -550,6 +551,7 @@ function PullRequestCodeTab({
commit,
cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
});
+ const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
const hostReview = detail.capabilities.review;
const review = {
inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -960,6 +962,7 @@ function PullRequestCodeTab({
canReact={detail.capabilities.reactions === true}
environmentId={environmentId}
reference={reference}
+ mentionScope={mentionScope}
pending={threadPending}
fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
fixLabel={fixFindingLabel}
@@ -1031,6 +1034,7 @@ function PullRequestCodeTab({
kind="draft"
rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
text=""
+ mentionScope={canCommentOnLines ? mentionScope : null}
submitLabel={canCommentOnLines ? "Add to review" : "Add to agent"}
{...(canCommentOnLines && onAddToAgentSelection
? {
diff --git a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx
index 0bb17925164..f108ddd918f 100644
--- a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx
@@ -8,9 +8,12 @@ import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFie
import { pullRequestEnvironment } from "~/state/pullRequests";
import { Button } from "../ui/button";
-import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
import { PullRequestGlyph } from "./pullRequestIcons";
+import {
+ PullRequestMarkdownTextarea,
+ pullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
import { pullRequestReviewKey } from "./pullRequestReviewStore";
import { useInlineActionConfirm } from "./useInlineActionConfirm";
@@ -108,8 +111,9 @@ export function PullRequestCommentForm({
return (
<div className="space-y-2">
- <Textarea
+ <PullRequestMarkdownTextarea
ref={textareaRef}
+ mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
// Lock while posting because success clears the draft.
disabled={locked}
readOnly={speech.freezesEditor}
@@ -117,7 +121,7 @@ export function PullRequestCommentForm({
rows={3}
placeholder="Leave a comment"
aria-label={`Comment on this ${sourceControlClients.get(detail.provider).changeRequest.singular}`}
- onChange={(event) => setBody(event.target.value)}
+ onValueChange={setBody}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (
diff --git a/apps/web/src/components/pullRequest/PullRequestComposer.tsx b/apps/web/src/components/pullRequest/PullRequestComposer.tsx
index e787e02c022..0c9f8f95e30 100644
--- a/apps/web/src/components/pullRequest/PullRequestComposer.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestComposer.tsx
@@ -16,6 +16,7 @@ import {
usePendingReviewComments,
usePullRequestReviewStore,
} from "./pullRequestReviewStore";
+import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
export function PullRequestComposer({
environmentId,
@@ -154,6 +155,7 @@ export function PullRequestComposer({
active={open && mode === "review"}
environmentId={environmentId}
reference={reference}
+ mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
term={term}
verdicts={verdicts}
requestChangesSummaryRequired={sourceControlClients
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index bee7266aeeb..f272c2df81d 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -66,6 +66,7 @@ import { useLiveRefresh } from "~/hooks/useLiveRefresh";
import { pullRequestEnvironment, usePullRequestTurnRefresh } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { PullRequestStackMenu } from "./PullRequestStackMenu";
+import { pullRequestMentionScope } from "./PullRequestMarkdownTextarea";
import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
import {
capitalizeTerm,
@@ -1737,6 +1738,7 @@ export function PullRequestDetailPanel({
detail.capabilities.review.inlineComment && detail.viewerPermissions.comment
}
rangeComments={detail.capabilities.review.rangeComment === true}
+ mentionScope={pullRequestMentionScope(detail, environmentId, reference)}
onAskAboutLines={(comment, request) =>
addSelectionToAgent({ comment, request }, { keepGuide: true })
}
diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx
index 0b746725e62..d1a1a249d78 100644
--- a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx
@@ -55,6 +55,7 @@ it("keeps Try again inside a short panel when a failed guide has long diagnostic
active
canComment={false}
rangeComments={false}
+ mentionScope={null}
onAskAboutLines={null}
onAskAboutStop={null}
onFinishReview={null}
diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx
index c7a032f6ffd..8952c785a96 100644
--- a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx
@@ -17,6 +17,7 @@ import {
usePendingReviewComments,
usePullRequestReviewStore,
} from "./pullRequestReviewStore";
+import type { PullRequestMentionScope } from "./PullRequestMarkdownTextarea";
export function PullRequestGuideTab({
environmentId,
@@ -26,6 +27,7 @@ export function PullRequestGuideTab({
active,
canComment,
rangeComments,
+ mentionScope,
onAskAboutLines,
onAskAboutStop,
onFinishReview,
@@ -39,6 +41,7 @@ export function PullRequestGuideTab({
active: boolean;
canComment: boolean;
rangeComments: boolean;
+ mentionScope: PullRequestMentionScope | null;
onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null;
onAskAboutStop:
| ((stop: PullRequestReviewGuideStop, index: number, question: string) => void)
@@ -62,6 +65,7 @@ export function PullRequestGuideTab({
: {
canComment,
rangeComments,
+ mentionScope,
pending,
onComment: ({ path, oldPath, position, startPosition, body }) =>
addComment(reviewKey, {
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
index faf7057f97b..31dfb68338d 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx
@@ -1,7 +1,7 @@
import { act, render, type Screen } from "../../../test/render";
-import { AuthSourceControlWriteScope, EnvironmentId } from "@t3tools/contracts";
+import { AuthSourceControlWriteScope, EnvironmentId, ProjectId } from "@t3tools/contracts";
import { expect, it, vi } from "vite-plus/test";
-import { userEvent } from "vite-plus/test/browser";
+import { page, userEvent } from "vite-plus/test/browser";
const permissions = vi.hoisted(() => ({
allowed: new Set<string>(),
@@ -26,6 +26,22 @@ vi.mock(import("~/state/session"), async (original) => {
};
});
+vi.mock(import("~/state/pullRequests"), async (original) => ({
+ ...(await original()),
+ usePullRequestFilterOptions: (targets: ReadonlyArray<unknown>) => ({
+ labels: [],
+ authors:
+ targets.length === 0
+ ? []
+ : [
+ { login: "julius", name: "Julius", avatarUrl: null },
+ { login: "theo", name: "Theo", avatarUrl: null },
+ ],
+ error: null,
+ isPending: false,
+ }),
+}));
+
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
const secondary = EnvironmentId.make("secondary");
@@ -45,6 +61,7 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
value={options?.value ?? "Original description"}
cwd="/repo"
environmentId={secondary}
+ mentionScope={{ environmentId: secondary, projectId: ProjectId.make("project") }}
label="Pull request description"
saving={false}
allowEmpty={options?.allowEmpty ?? false}
@@ -88,3 +105,26 @@ it("keeps an edited draft through revocation and saves it after access returns w
await clickSave(screen);
expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
});
+
+it("completes an @mention on Enter and closes the list on Escape until the next keystroke", async () => {
+ setup();
+ permissions.allowed.add(secondary);
+ await using screen = await openEditor({ value: "" });
+ const textarea = screen.container.querySelector("textarea")!;
+ await userEvent.type(textarea, "Thanks @ju");
+ await expect.element(page.getByRole("option", { name: /julius/ })).toBeVisible();
+
+ await userEvent.keyboard("{Enter}");
+ expect(textarea.value).toBe("Thanks @julius ");
+ await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
+
+ await userEvent.type(textarea, "and @");
+ await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
+ await userEvent.keyboard("{Escape}");
+ await expect.element(page.getByRole("listbox")).not.toBeInTheDocument();
+ expect(onCancel).not.toHaveBeenCalled();
+
+ await userEvent.type(textarea, "t");
+ await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible();
+ expect(onSave).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
index cb649ee5270..aeb834ae312 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
@@ -9,14 +9,18 @@ import { cn } from "~/lib/utils";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { Button } from "../ui/button";
-import { Textarea } from "../ui/textarea";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
+import {
+ PullRequestMarkdownTextarea,
+ type PullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
export function PullRequestMarkdownEditor({
value,
cwd,
environmentId,
+ mentionScope,
threadRef = null,
placeholder,
label,
@@ -29,6 +33,7 @@ export function PullRequestMarkdownEditor({
readonly value: string;
readonly cwd: string;
readonly environmentId: EnvironmentId;
+ readonly mentionScope: PullRequestMentionScope | null;
readonly threadRef?: ScopedThreadRef | null;
readonly placeholder?: string | undefined;
readonly label: string;
@@ -102,14 +107,15 @@ export function PullRequestMarkdownEditor({
)}
</div>
) : (
- <Textarea
+ <PullRequestMarkdownTextarea
autoFocus
disabled={saving}
+ mentionScope={mentionScope}
value={draft}
rows={6}
placeholder={placeholder}
aria-label={label}
- onChange={(event) => setDraft(event.target.value)}
+ onValueChange={setDraft}
/>
)}
<div className="flex justify-end gap-2">
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx
new file mode 100644
index 00000000000..3029059f229
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownTextarea.tsx
@@ -0,0 +1,257 @@
+import type {
+ EnvironmentId,
+ ProjectId,
+ PullRequestActor,
+ PullRequestDetailView,
+ PullRequestRef,
+} from "@t3tools/contracts";
+import {
+ detectPullRequestMention,
+ insertPullRequestMention,
+ narrowPullRequestMentions,
+} from "@t3tools/shared/pullRequestComposerTrigger";
+import { useId, useState, type Ref } from "react";
+import { flushSync } from "react-dom";
+
+import { cn } from "~/lib/utils";
+import { usePullRequestFilterOptions } from "~/state/pullRequests";
+import { useDebouncedValue } from "~/state/queries";
+
+import { Popover, PopoverPopup } from "../ui/popover";
+import { Textarea, type TextareaProps } from "../ui/textarea";
+import { PullRequestActorAvatar } from "./pullRequestPresentation";
+
+/** The repository whose users an `@` completes. */
+export interface PullRequestMentionScope {
+ readonly environmentId: EnvironmentId;
+ readonly projectId: ProjectId;
+}
+
+/** Null on hosts that cannot search their users, so `@` never opens a list that cannot fill. */
+export function pullRequestMentionScope(
+ detail: Pick<PullRequestDetailView, "capabilities">,
+ environmentId: EnvironmentId,
+ reference: PullRequestRef,
+): PullRequestMentionScope | null {
+ return detail.capabilities.mentions === true
+ ? { environmentId, projectId: reference.projectId }
+ : null;
+}
+
+const MENTION_SEARCH_DEBOUNCE_MS = 200;
+const MENTION_SUGGESTION_LIMIT = 8;
+// About a full list of suggestions. The popup fits itself to the space it opens into, so it never
+// flips once results grow it; the side is picked up front from the room a full list needs.
+const SUGGESTION_LIST_HEIGHT = 320;
+
+function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" {
+ const rect = target.getBoundingClientRect();
+ const below = window.innerHeight - rect.bottom;
+ return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom";
+}
+
+function useMentionCandidates(scope: PullRequestMentionScope | null, query: string | null) {
+ const typed = query ?? "";
+ const search = typed === "" ? undefined : typed.slice(0, 100);
+ const sent = useDebouncedValue(search, MENTION_SEARCH_DEBOUNCE_MS);
+ const hosted = usePullRequestFilterOptions(
+ scope === null || query === null
+ ? []
+ : [
+ {
+ environmentId: scope.environmentId,
+ input: {
+ kind: "authors",
+ projectId: scope.projectId,
+ ...(sent ? { query: sent } : {}),
+ },
+ },
+ ],
+ );
+ // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
+ return {
+ candidates: narrowPullRequestMentions(hosted.authors, typed, MENTION_SUGGESTION_LIMIT),
+ isPending: hosted.isPending || sent !== search,
+ failed: hosted.error !== null,
+ };
+}
+
+function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
+ if (typeof ref === "function") ref(value);
+ else if (ref) ref.current = value;
+}
+
+/** A markdown textarea for pull request text that completes `@login` from the repository's users. */
+export function PullRequestMarkdownTextarea({
+ ref,
+ value,
+ onValueChange,
+ mentionScope,
+ onKeyDown,
+ onSelect,
+ onFocus,
+ onBlur,
+ ...props
+}: Omit<TextareaProps, "value" | "onChange"> & {
+ readonly value: string;
+ readonly onValueChange: (value: string) => void;
+ readonly mentionScope: PullRequestMentionScope | null;
+}) {
+ const listId = useId();
+ const [element, setElement] = useState<HTMLTextAreaElement | null>(null);
+ const [caret, setCaret] = useState<number | null>(null);
+ const [side, setSide] = useState<"top" | "bottom">("bottom");
+ const [dismissedAt, setDismissedAt] = useState<number | null>(null);
+ const [highlight, setHighlight] = useState({ query: "", index: 0 });
+
+ const trigger =
+ mentionScope === null || caret === null || props.readOnly
+ ? null
+ : detectPullRequestMention(value, caret);
+ const open = trigger !== null && trigger.rangeStart !== dismissedAt;
+ const { candidates, isPending, failed } = useMentionCandidates(
+ mentionScope,
+ open ? trigger.query : null,
+ );
+ const activeIndex =
+ trigger !== null && highlight.query === trigger.query
+ ? Math.min(highlight.index, Math.max(0, candidates.length - 1))
+ : 0;
+ const active = open ? candidates[activeIndex] : undefined;
+ const optionId = (login: string) => `${listId}-${login}`;
+
+ const syncCaret = (target: HTMLTextAreaElement) => {
+ setSide(suggestionSide(target));
+ setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null);
+ };
+
+ const select = (actor: PullRequestActor) => {
+ if (trigger === null || element === null) return;
+ const next = insertPullRequestMention(value, trigger, actor.login);
+ flushSync(() => onValueChange(next.text));
+ element.setSelectionRange(next.cursor, next.cursor);
+ setCaret(next.cursor);
+ };
+
+ return (
+ <>
+ <Textarea
+ {...props}
+ ref={(node) => {
+ setElement(node);
+ assignRef(ref, node);
+ }}
+ value={value}
+ role={mentionScope === null ? undefined : "combobox"}
+ aria-autocomplete={mentionScope === null ? undefined : "list"}
+ aria-expanded={mentionScope === null ? undefined : open}
+ aria-controls={open && candidates.length > 0 ? listId : undefined}
+ aria-activedescendant={active ? optionId(active.login) : undefined}
+ onChange={(event) => {
+ onValueChange(event.target.value);
+ syncCaret(event.target);
+ setDismissedAt(null);
+ }}
+ onSelect={(event) => {
+ syncCaret(event.currentTarget);
+ onSelect?.(event);
+ }}
+ onFocus={(event) => {
+ syncCaret(event.currentTarget);
+ onFocus?.(event);
+ }}
+ onBlur={(event) => {
+ setCaret(null);
+ onBlur?.(event);
+ }}
+ onKeyDown={(event) => {
+ // Some IMEs confirm a composition with an Enter that reports keyCode 229 but not isComposing.
+ if (open && !event.nativeEvent.isComposing && event.nativeEvent.keyCode !== 229) {
+ const handled = (() => {
+ if (event.key === "Escape") {
+ setDismissedAt(trigger.rangeStart);
+ return true;
+ }
+ if (candidates.length === 0) return false;
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ setHighlight({
+ query: trigger.query,
+ index: (activeIndex + step + candidates.length) % candidates.length,
+ });
+ return true;
+ }
+ const plain = !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey;
+ if ((event.key === "Enter" || event.key === "Tab") && plain && active) {
+ select(active);
+ return true;
+ }
+ return false;
+ })();
+ if (handled) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ }
+ onKeyDown?.(event);
+ }}
+ />
+ <Popover
+ open={open}
+ modal={false}
+ onOpenChange={(next, details) => {
+ if (next || details.event?.target === element) return;
+ if (trigger !== null) setDismissedAt(trigger.rangeStart);
+ }}
+ >
+ <PopoverPopup
+ anchor={element}
+ side={side}
+ align="start"
+ padding="compact"
+ width="sm"
+ initialFocus={false}
+ finalFocus={false}
+ >
+ {candidates.length > 0 ? (
+ <div id={listId} role="listbox" aria-label="Mention a user" className="-mx-1.5">
+ {candidates.map((actor, index) => (
+ <div
+ key={actor.login}
+ id={optionId(actor.login)}
+ role="option"
+ aria-selected={index === activeIndex}
+ className={cn(
+ "flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm",
+ index === activeIndex && "bg-accent text-accent-foreground",
+ )}
+ onMouseMove={() => {
+ if (index !== activeIndex) setHighlight({ query: trigger?.query ?? "", index });
+ }}
+ // Keeps focus, and the caret, in the textarea.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => select(actor)}
+ >
+ <PullRequestActorAvatar actor={actor} className="size-5" />
+ <span className="truncate font-medium">{actor.login}</span>
+ {actor.name && actor.name !== actor.login ? (
+ <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="px-1 text-xs text-muted-foreground">
+ {isPending
+ ? "Searching users..."
+ : failed
+ ? "Couldn't search users on the host"
+ : "No matching users"}
+ </p>
+ )}
+ </PopoverPopup>
+ </Popover>
+ </>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
index 6bd09260875..a98a660cdbc 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
@@ -19,7 +19,6 @@ import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldS
import { Button } from "../ui/button";
import { MorphIcon } from "~/components/MorphIcon";
import { PullRequestEditButton } from "./PullRequestEditButton";
-import { Textarea } from "../ui/textarea";
import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
import {
editPullRequestThreadComment,
@@ -30,6 +29,10 @@ import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
import { PullRequestReactionBar } from "./PullRequestReactions";
import type { PendingReviewComment } from "./pullRequestReviewStore";
+import {
+ PullRequestMarkdownTextarea,
+ type PullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
const CARD_CLASS =
"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({
canReact,
environmentId,
reference,
+ mentionScope,
pending,
fixPending,
fixLabel = "Fix in a thread",
@@ -131,6 +135,7 @@ export function ReviewThreadCard({
canReact: boolean;
environmentId: EnvironmentId;
reference: PullRequestRef;
+ mentionScope: PullRequestMentionScope | null;
pending: boolean;
fixPending?: boolean;
fixLabel?: string;
@@ -287,6 +292,7 @@ export function ReviewThreadCard({
value={comment.body}
cwd={workspaceRoot}
environmentId={environmentId}
+ mentionScope={mentionScope}
label="Edit comment"
saving={savingEdit}
onSave={(body) => void saveEdit(comment.id, body)}
@@ -337,15 +343,16 @@ export function ReviewThreadCard({
>
{(speech) => (
<div className="mt-2">
- <Textarea
+ <PullRequestMarkdownTextarea
ref={replyRef}
readOnly={speech.freezesEditor}
autoFocus
size="sm"
+ mentionScope={mentionScope}
value={reply}
placeholder="Reply"
aria-label="Reply to this conversation"
- onChange={(event) => setReply(event.target.value)}
+ onValueChange={setReply}
onKeyDown={submitKeys({
value: reply,
pending,
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx
index d8901b6db6c..23c82d5c38d 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx
@@ -14,7 +14,10 @@ vi.mock("~/speech/useTextFieldSpeech", () => ({
useTextFieldSpeech: () => ({ blocksSubmission: true, submitAfterDictation: mocks.queue }),
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => mocks.submit }));
-vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: { submitReview: {} } }));
+vi.mock(import("~/state/pullRequests"), async (original) => ({
+ ...(await original()),
+ pullRequestEnvironment: { submitReview: {} } as never,
+}));
it("submits only the line comments still in the draft when dictation finishes", async () => {
mocks.submit.mockClear();
@@ -34,6 +37,7 @@ it("submits only the line comments still in the draft when dictation finishes",
active
environmentId={EnvironmentId.make("test")}
reference={reference}
+ mentionScope={null}
term="pull request"
verdicts={["comment"]}
requestChangesSummaryRequired={false}
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx
index b70b59f9d69..edf718d8489 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx
@@ -11,7 +11,6 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"
import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
import { Button } from "../ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger } from "../ui/select";
-import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
import { readableFailure } from "./pullRequestDetail.logic";
import {
@@ -19,6 +18,10 @@ import {
usePendingReviewComments,
usePullRequestReviewStore,
} from "./pullRequestReviewStore";
+import {
+ PullRequestMarkdownTextarea,
+ type PullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
const VERDICTS: ReadonlyArray<{
readonly value: PullRequestReviewVerdict;
@@ -50,6 +53,7 @@ export function PullRequestReviewForm({
environmentId,
active,
reference,
+ mentionScope,
term,
verdicts,
requestChangesSummaryRequired,
@@ -62,6 +66,7 @@ export function PullRequestReviewForm({
/** False while the form stays mounted but hidden; dictation is cancelled then. */
active: boolean;
reference: PullRequestRef;
+ mentionScope: PullRequestMentionScope | null;
/** The host's word for a change request, as in "pull request". */
term: string;
verdicts: ReadonlyArray<PullRequestReviewVerdict>;
@@ -150,14 +155,15 @@ export function PullRequestReviewForm({
return (
<>
- <Textarea
+ <PullRequestMarkdownTextarea
ref={textareaRef}
+ mentionScope={mentionScope}
rows={3}
readOnly={speech.freezesEditor}
value={body}
placeholder={placeholder}
aria-label="Review summary"
- onChange={(event) => setSummary(reviewKey, event.target.value)}
+ onValueChange={(next) => setSummary(reviewKey, next)}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing || event.keyCode === 229 || event.repeat) return;
if (
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index 2ffef724ab7..617aa887080 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -84,6 +84,10 @@ import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestCommentBody } from "./PullRequestCommentBody";
import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
+import {
+ type PullRequestMentionScope,
+ pullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
import { PullRequestReactionBar } from "./PullRequestReactions";
import { PullRequestConversationGhost } from "./PullRequestGhosts";
import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
@@ -163,6 +167,7 @@ function reviewStateLabel(state: string): string {
interface CommentEditing {
readonly cwd: string;
readonly environmentId: EnvironmentId;
+ readonly mentionScope: PullRequestMentionScope | null;
readonly threadRef: ScopedThreadRef | null;
readonly canEdit: (comment: PullRequestComment) => boolean;
readonly editingId: string | null;
@@ -187,6 +192,7 @@ function CommentBody({
value={comment.body}
cwd={editing.cwd}
environmentId={editing.environmentId}
+ mentionScope={editing.mentionScope}
threadRef={editing.threadRef}
label="Edit comment"
saving={editing.saving}
@@ -542,9 +548,11 @@ export function PullRequestSummaryTab({
if (body !== description) void saveDescription(body);
};
+ const mentionScope = pullRequestMentionScope(detail, environmentId, reference);
const commentEditing: CommentEditing = {
cwd: detail.workspaceRoot,
environmentId,
+ mentionScope,
threadRef,
canEdit: (comment) => canEditPullRequestComment(detail, comment),
editingId: editingCommentId,
@@ -794,6 +802,7 @@ export function PullRequestSummaryTab({
value={bodyScope.body}
cwd={detail.workspaceRoot}
environmentId={environmentId}
+ mentionScope={mentionScope}
threadRef={threadRef}
label={`${capitalizeTerm(terminology.singular)} description`}
placeholder={`Describe this ${terminology.singular}`}
diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
index 1f41f238114..88f14347ab1 100644
--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
@@ -57,6 +57,10 @@ import {
pullRequestReviewOutcomeToneClassName,
} from "./pullRequestPresentation";
import { PullRequestGlyph } from "./pullRequestIcons";
+import {
+ type PullRequestMentionScope,
+ pullRequestMentionScope,
+} from "./PullRequestMarkdownTextarea";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
interface ReactionSurface {
@@ -64,6 +68,7 @@ interface ReactionSurface {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef | null;
readonly reference: PullRequestRef;
+ readonly mentionScope: PullRequestMentionScope | null;
readonly onRefresh: () => void;
}
@@ -263,6 +268,7 @@ function ConversationCard({
value={editable.body}
cwd={cwd}
environmentId={reactions.environmentId}
+ mentionScope={reactions.mentionScope}
threadRef={reactions.threadRef}
label="Edit comment"
saving={saving}
@@ -653,6 +659,7 @@ export function PullRequestTimelineTab({
environmentId,
threadRef,
reference,
+ mentionScope: pullRequestMentionScope(detail, environmentId, reference),
onRefresh,
};
const editable = new Map(
diff --git a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
index d336bb789e7..e419a165002 100644
--- a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
+++ b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
@@ -37,6 +37,7 @@ import {
fileDiffRows,
rowsToPatch,
} from "@t3tools/client-runtime/review-guide-tour";
+import type { PullRequestMentionScope } from "../PullRequestMarkdownTextarea";
import { GuideNoteMarker } from "./GuideNotes";
import { GuideProse } from "./GuideProse";
@@ -55,6 +56,7 @@ export interface ExcerptCommenting {
readonly canComment: boolean;
/** The host anchors a comment to a range of lines rather than to its last one. */
readonly rangeComments: boolean;
+ readonly mentionScope: PullRequestMentionScope | null;
readonly pending: ReadonlyArray<PendingReviewComment>;
readonly onComment: (comment: {
readonly path: string;
@@ -323,6 +325,7 @@ function ExcerptDiff({
kind="draft"
rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
text=""
+ mentionScope={commenting.canComment ? commenting.mentionScope : null}
placeholder={
commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"
}
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index ad18ee6303e..e96d1f3dfdb 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -277,6 +277,8 @@ export const PullRequestCapabilities = Schema.Struct({
stacks: Schema.optional(Schema.Boolean),
stackActions: Schema.optional(Schema.Boolean),
labels: Schema.optional(Schema.Boolean),
+ /** The host searches the repository's users, so composers can complete `@login`. */
+ mentions: Schema.optional(Schema.Boolean),
/**
* Every head gets at least one check, so a head that has gone a while without any means none
* reported rather than that the repository runs none. Absent means an empty list says nothing.
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 6dfe675900e..5d9a87ac771 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -263,6 +263,10 @@
"types": "./src/composerTrigger.ts",
"import": "./src/composerTrigger.ts"
},
+ "./pullRequestComposerTrigger": {
+ "types": "./src/pullRequestComposerTrigger.ts",
+ "import": "./src/pullRequestComposerTrigger.ts"
+ },
"./composerInlineTokens": {
"types": "./src/composerInlineTokens.ts",
"import": "./src/composerInlineTokens.ts"
diff --git a/packages/shared/src/pullRequestComposerTrigger.test.ts b/packages/shared/src/pullRequestComposerTrigger.test.ts
new file mode 100644
index 00000000000..0aa786a581a
--- /dev/null
+++ b/packages/shared/src/pullRequestComposerTrigger.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ detectPullRequestMention,
+ insertPullRequestMention,
+ narrowPullRequestMentions,
+} from "./pullRequestComposerTrigger.ts";
+
+describe("detectPullRequestMention", () => {
+ it.each([
+ ["@", 0, ""],
+ ["cc @ju", 3, "ju"],
+ ["line one\[email protected]", 9, "first.last"],
+ ["@jane-doe more", 0, "jane-doe"],
+ ])("finds the mention in %j", (text, rangeStart, query) => {
+ const cursor = rangeStart + 1 + query.length;
+ expect(detectPullRequestMention(text, cursor)).toEqual({
+ query,
+ rangeStart,
+ rangeEnd: cursor,
+ });
+ });
+
+ it.each([
+ ["mail me at [email protected]", "mail me at [email protected]".length],
+ ["@jane done", "@jane done".length],
+ ["@-jane", "@-jane".length],
+ ["`@decorator`", "`@decorator".length],
+ ["@jane", 3],
+ ])("ignores %j", (text, cursor) => {
+ expect(detectPullRequestMention(text, cursor)).toBeNull();
+ });
+});
+
+describe("insertPullRequestMention", () => {
+ it.each(["", "\nnext line", "\r\nnext line"])(
+ "replaces the partial login and adds a space before %j",
+ (suffix) => {
+ const text = `thanks @ju${suffix}`;
+ const trigger = detectPullRequestMention(text, "thanks @ju".length)!;
+ expect(insertPullRequestMention(text, trigger, "julius")).toEqual({
+ text: `thanks @julius ${suffix}`,
+ cursor: "thanks @julius ".length,
+ });
+ },
+ );
+
+ it("reuses the space that already follows and moves past it", () => {
+ const text = "@ju please look";
+ const trigger = detectPullRequestMention(text, 3)!;
+ const inserted = insertPullRequestMention(text, trigger, "julius");
+ expect(inserted).toEqual({ text: "@julius please look", cursor: "@julius ".length });
+ expect(detectPullRequestMention(inserted.text, inserted.cursor)).toBeNull();
+ });
+});
+
+describe("narrowPullRequestMentions", () => {
+ it("matches login or name, case-insensitively, up to the limit", () => {
+ const users = [
+ { login: "TonybynMp4", name: null },
+ { login: "16g", name: "Tom" },
+ { login: "theo", name: "Theo" },
+ ];
+ expect(narrowPullRequestMentions(users, "to", 5).map((u) => u.login)).toEqual([
+ "TonybynMp4",
+ "16g",
+ ]);
+ expect(narrowPullRequestMentions(users, "", 2)).toHaveLength(2);
+ });
+});
diff --git a/packages/shared/src/pullRequestComposerTrigger.ts b/packages/shared/src/pullRequestComposerTrigger.ts
new file mode 100644
index 00000000000..a2e64f924c9
--- /dev/null
+++ b/packages/shared/src/pullRequestComposerTrigger.ts
@@ -0,0 +1,53 @@
+import { replaceTextRange } from "./composerTrigger.ts";
+
+export interface PullRequestMentionTrigger {
+ readonly query: string;
+ readonly rangeStart: number;
+ readonly rangeEnd: number;
+}
+
+// Covers GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`).
+const MENTION_TOKEN = /^@([A-Za-z0-9_][A-Za-z0-9_.-]*)?$/;
+
+/** The `@login` being typed at the caret, when the caret sits at its end. */
+export function detectPullRequestMention(
+ text: string,
+ cursor: number,
+): PullRequestMentionTrigger | null {
+ const end = Math.max(0, Math.min(text.length, cursor));
+ const next = text[end];
+ if (next !== undefined && !/\s/.test(next)) return null;
+ let start = end;
+ while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;
+ const match = MENTION_TOKEN.exec(text.slice(start, end));
+ if (!match) return null;
+ return { query: match[1] ?? "", rangeStart: start, rangeEnd: end };
+}
+
+export function insertPullRequestMention(
+ text: string,
+ trigger: PullRequestMentionTrigger,
+ login: string,
+): { text: string; cursor: number } {
+ const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? "");
+ if (!followedBySpace) {
+ return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login} `);
+ }
+ const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login}`);
+ return { ...inserted, cursor: inserted.cursor + 1 };
+}
+
+export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(
+ users: ReadonlyArray<A>,
+ typed: string,
+ limit: number,
+): A[] {
+ const needle = typed.toLowerCase();
+ return users
+ .filter(
+ (user) =>
+ user.login.toLowerCase().includes(needle) ||
+ (user.name?.toLowerCase().includes(needle) ?? false),
+ )
+ .slice(0, limit);
+}
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
index 17aaed9a930..7f3aa0561fc 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
@@ -52,6 +52,7 @@ const CAPABILITIES: PullRequestCapabilities = {
// `az repos pr list` has no text filter.
search: false,
reactions: false,
+ mentions: false,
review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
// Reviewer candidates require separate identity/graph APIs and permissions.
reviewers: { request: true, listCandidates: false },
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
index 087d3b9dc8f..9123f34c7ef 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
@@ -23,6 +23,7 @@ const CAPABILITIES: PullRequestCapabilities = {
mergeMethods: ["merge", "squash", "rebase"],
search: true,
reactions: false,
+ mentions: false,
review: {
inlineComment: true,
reply: true,
diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
index d9b0054fe02..f41dbe0d0d8 100644
--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
@@ -48,6 +48,7 @@ const CAPABILITIES: PullRequestCapabilities = {
updateMethods: ["merge", "rebase"],
search: false,
reactions: true,
+ mentions: true,
labels: true,
// Forgejo's public API has no thread replies/resolution or draft conversion endpoint.
review: {
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
index ad60b486840..f465da71a41 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
@@ -34,6 +34,7 @@ const CAPABILITIES: PullRequestCapabilities = {
stacks: true,
stackActions: true,
reactions: true,
+ mentions: true,
labels: true,
// Line comments go through GitCafe's review drafts, which arrive with revision fencing.
review: {
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
index 14936af269d..6e0f0af0cad 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
@@ -41,6 +41,7 @@ const CAPABILITIES: PullRequestCapabilities = {
updateMethods: ["merge", "rebase"],
search: true,
reactions: true,
+ mentions: true,
viewedFiles: "host",
review: {
inlineComment: true,
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index 8c55e786c7e..d51d952f310 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -1844,6 +1844,20 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect.each([
+ ["th", "projects/acme%2Fweb/users?per_page=100"],
+ ["tho", "projects/acme%2Fweb/users?per_page=100&search=tho"],
+ ] as const)("searches project users only from three characters (%s)", ([search, path]) =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify([author]))));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.listProjectUsers({ cwd: "/w", repository: "acme/web", search });
+
+ expect(argsOfCall(0)[1]).toBe(path);
+ }),
+ );
+
it.effect("reads who has access to the project and who is already on the merge request", () =>
Effect.gen(function* () {
mockedExecute
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index f3a0c2cd391..2572fcd0253 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -1287,7 +1287,9 @@ export const make = Effect.gen(function* () {
host: input.host,
path: `projects/${projectPath(input.repository)}/users?${query([
["per_page", String(MAX_PAGE_SIZE)],
- ...searchParams(input.search),
+ // GitLab answers nothing for a user search under three characters; callers narrow the
+ // unsearched page instead.
+ ...((input.search?.trim().length ?? 0) >= 3 ? searchParams(input.search) : []),
])}`,
}).pipe(
Effect.flatMap((result) => {
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index ec3f46f0ac2..6839e7febd0 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -32,6 +32,7 @@ const CAPABILITIES: PullRequestCapabilities = {
updateMethods: ["rebase"],
search: true,
reactions: true,
+ mentions: true,
// GitLab's viewed marks live in browser-local storage.
viewedFiles: "environment",
review: {