TypeScript
feat(web): filter PR comments by bots and resolved threads (#17645)
Julius Marminge6cd02e98f7ed
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsxindex 57033b67154..27191a970b3 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx@@ -9,6 +9,14 @@ vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));vi.mock("./PullRequestMarkdown", () => ({PullRequestMarkdown: ({ text }: { text: string }) => <p>{text}</p>,}));+vi.mock("../ui/menu", () => ({+ Menu: "div",+ MenuCheckboxItem: "div",+ MenuGroup: "div",+ MenuGroupLabel: "div",+ MenuPopup: "div",+ MenuTrigger: "div",+}));vi.mock("../ui/tooltip", () => ({Tooltip: ({ children }: { children: ReactNode }) => children,TooltipTrigger: ({ children }: { children: ReactNode }) => children,@@ -70,7 +78,20 @@ const detail: PullRequestDetailView = {};let renderer: ReactTestRenderer;-beforeEach(() => vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true));+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const store = new Map<string, string>();+ vi.stubGlobal(+ "window",+ Object.assign(new EventTarget(), {+ localStorage: {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => store.set(key, value),+ removeItem: (key: string) => store.delete(key),+ },+ }),+ );+});afterEach(() => {act(() => renderer?.unmount());vi.unstubAllGlobals();@@ -145,70 +166,80 @@ it("keeps an unsaved description when collapsed and reopened", () => {expect(renderer.root.findByType("textarea").props.value).toBe("Unsaved description");});-it("opens bot reports in pages without hiding human comments", () => {+function texts() {+ return renderer.root+ .findAllByType("p")+ .map((p) => p.children.join(""))+ .filter((text) => text !== detail.body);+}++function filterItem(label: string) {+ return renderer.root.find(+ (node) => typeof node.props.onCheckedChange === "function" && node.children.includes(label),+ );+}++it("hides bot and resolved comments until the filter shows them, and remembers the choice", () => {+ const comment = (index: number, login: string, body: string, isBot = false) => ({+ id: `comment-${index}`,+ kind: "issue-comment" as const,+ author: { login, name: null, avatarUrl: null, isBot },+ body,+ createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,+ url: null,+ path: null,+ reviewState: null,+ });+ const resolved = {+ ...comment(13, "reviewer", "Resolved remark"),+ kind: "review-comment" as const,+ };const value: PullRequestDetailView = {...detail,- commentCount: 13,- comments: Array.from({ length: 13 }, (_, index) => ({- id: `comment-${index}`,- kind: "issue-comment",- author: {- login: index === 12 ? "human" : "review-app",- name: null,- avatarUrl: null,- isBot: index !== 12,+ commentCount: 14,+ comments: [+ ...Array.from({ length: 12 }, (_, index) =>+ comment(index, "review-app", `Bot report ${index}`, true),+ ),+ comment(12, "human", "Human comment"),+ resolved,+ ],+ reviewThreads: [+ {+ id: "thread",+ path: "src/index.ts",+ line: 1,+ side: "right",+ isResolved: true,+ isOutdated: false,+ comments: [resolved],},- body: index === 12 ? "Human comment" : `Bot report ${index}`,- createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,- url: null,- path: null,- reviewState: null,- })),+ ],};act(() => {renderer = create(render(value));});- expect(renderer.root.findAllByType("p").map((p) => p.children.join(""))).toContain(- "Human comment",- );- expect(- renderer.root.findAllByType("p").some((p) => p.children.join("").startsWith("Bot report")),- ).toBe(false);- const group = renderer.root- .findAllByType("button")- .find((button) => button.props["aria-label"] === "12 bot comments")!;- act(() => group.props.onClick({ nativeEvent: {}, preventDefault() {}, stopPropagation() {} }));+ expect(texts()).toEqual(["Human comment"]);expect(- renderer.root.findAllByType("p").filter((p) => p.children.join("").startsWith("Bot report")),- ).toHaveLength(10);- expect(renderer.root.findAllByType("p").map((p) => p.children.join(""))).not.toContain(- "Bot report 0",- );- act(() =>- renderer.root- .findAllByType("button")- .find((button) => button.children.includes(" older bot comment"))!- .props.onClick(),- );- expect(- renderer.root.findAllByType("p").filter((p) => p.children.join("").startsWith("Bot report")),- ).toHaveLength(12);- act(() => group.props.onClick({ nativeEvent: {}, preventDefault() {}, stopPropagation() {} }));- act(() => group.props.onClick({ nativeEvent: {}, preventDefault() {}, stopPropagation() {} }));- expect(renderer.root.findAllByType("p").map((p) => p.children.join(""))).toContain(- "Bot report 0",- );- act(() =>- renderer.root- .findAllByType("button")- .find((button) => button.children.includes(" recent bot comments"))!- .props.onClick(),- );- expect(- renderer.root.findAllByType("p").filter((p) => p.children.join("").startsWith("Bot report")),- ).toHaveLength(10);- act(() => renderer.update(render({ ...value, url: `${value.url}0`, number: 10 })));+ renderer.root.findByProps({ "aria-label": "Filter comments" }).children.join(""),+ ).toContain("13 hidden");++ act(() => filterItem("Bot comments").props.onCheckedChange(true));+ // Bots now share the human comment's pages: the ten most recent, the oldest left behind.+ expect(texts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);+ expect(texts()).toContain("Human comment");+ expect(texts()).not.toContain("Bot report 0");++ act(() => filterItem("Resolved or dismissed").props.onCheckedChange(true));expect(- renderer.root.findAllByType("p").some((p) => p.children.join("").startsWith("Bot report")),- ).toBe(false);+ renderer.root.findAllByType("button").some((button) => button.children.includes("Resolved")),+ ).toBe(true);++ // Another pull request, or the same one opened again, keeps the reader's choice.+ act(() => renderer.unmount());+ act(() => {+ renderer = create(render({ ...value, url: `${value.url}0`, number: 10 }));+ });+ expect(filterItem("Bot comments").props.checked).toBe(true);+ expect(texts()).toContain("Bot report 11");});diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsxindex 581c4d0741d..9fae094ce56 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx@@ -12,12 +12,15 @@ import {ChevronDownIcon,ChevronRightIcon,HammerIcon,+ ListFilterIcon,TagIcon,UsersIcon,} from "lucide-react";+import * as Schema from "effect/Schema";import { useRef, useState, type ReactNode } from "react";import { pullRequestEnvironment } from "~/state/pullRequests";+import { useLocalStorage } from "~/hooks/useLocalStorage";import { cn } from "~/lib/utils";import { useOpenLink } from "~/browser/useOpenLink";import { formatRelativeTimeLabel } from "~/timestampFormat";@@ -25,6 +28,14 @@ import { formatRelativeTimeLabel } from "~/timestampFormat";import { Button } from "../ui/button";import { PullRequestEditButton } from "./PullRequestEditButton";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";+import {+ Menu,+ MenuCheckboxItem,+ MenuGroup,+ MenuGroupLabel,+ MenuPopup,+ MenuTrigger,+} from "../ui/menu";import { toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import {@@ -349,111 +360,21 @@ function Section({);}-function CommentGroup({- label,- comments,- detail,- children,- onOpenChange,-}: {- label: string;- comments: readonly PullRequestComment[];- detail: PullRequestDetailView;- children: ReactNode;- onOpenChange?: (open: boolean) => void;-}) {- const authors = [- ...new Map(- comments.map((comment) => [reviewerKey(comment.author?.login ?? "ghost"), comment.author]),- ).values(),- ];- const fileCount = new Set(comments.flatMap((comment) => (comment.path ? [comment.path] : [])))- .size;- const latest = comments.reduce<string | null>(- (date, comment) => (date === null || comment.createdAt > date ? comment.createdAt : date),- null,- );- return (- <div className="overflow-hidden rounded-lg border border-border bg-background">- <Collapsible onOpenChange={onOpenChange}>- <div className="flex items-center gap-3 pl-3">- <div className="flex shrink-0 -space-x-1.5">- {authors.slice(0, 3).map((actor) => (- // The ring separates the overlapping faces; it belongs to the stack, not the actor.- <span- key={actor?.login ?? "ghost"}- className="relative flex rounded-full ring-2 ring-background hover:z-10 focus-within:z-10"- >- <PullRequestActorLabel- actor={actor}- profileUrl={- detail.provider === "github" && actor- ? new URL(- actor.isBot || actor.login.endsWith("[bot]")- ? `/apps/${encodeURIComponent(actor.login.replace(/\[bot\]$/, ""))}`- : `/${encodeURIComponent(actor.login)}`,- detail.url,- ).toString()- : null- }- variant="avatar"- />- </span>- ))}- {authors.length > 3 ? (- <span className="relative flex size-6 items-center justify-center rounded-full bg-muted text-3xs text-muted-foreground ring-2 ring-background">- +{authors.length - 3}- </span>- ) : null}- </div>- <CollapsibleTrigger- aria-label={label}- className="group flex min-w-0 flex-1 items-center gap-3 rounded-md py-3 pr-3 text-left hover:bg-muted/30"- >- <span className="min-w-0 flex-1 space-y-1">- <span className="block text-xs font-medium text-foreground/90">{label}</span>- <span className="flex flex-wrap gap-x-1.5 text-2xs text-muted-foreground">- <span>- {authors.length} {authors.length === 1 ? "author" : "authors"}- </span>- {fileCount > 0 ? (- <span>- · {fileCount} {fileCount === 1 ? "file" : "files"}- </span>- ) : null}- {latest ? (- <span>- · Latest{" "}- <Tooltip>- <TooltipTrigger render={<time dateTime={latest} />}>- {formatRelativeTimeLabel(latest)}- </TooltipTrigger>- <TooltipPopup>{new Date(latest).toLocaleString()}</TooltipPopup>- </Tooltip>- </span>- ) : null}- </span>- </span>- <ChevronRightIcon- aria-hidden- className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90"- />- </CollapsibleTrigger>- </div>- <CollapsiblePanel keepMounted>- <div className="border-t border-border/60 px-3 pb-3">{children}</div>- </CollapsiblePanel>- </Collapsible>- </div>- );-}-/*** What a first render of the conversation carries. A pull request with two hundred comments is* two hundred markdown documents, and the ones worth arriving for are the recent ones.*/const COMMENT_PAGE = 10;+/**+ * Which kinds of comment the conversation shows. Kept per browser rather than per pull request:+ * whether a reader wants bot reports and finished threads in front of them is a habit, not a+ * property of one change.+ */+const COMMENT_FILTER_STORAGE_KEY = "t3code:pull-request-comment-filter:v1";+const CommentFilterSchema = Schema.Struct({ bots: Schema.Boolean, resolved: Schema.Boolean });+const DEFAULT_COMMENT_FILTER: typeof CommentFilterSchema.Type = { bots: false, resolved: false };+export function PullRequestSummaryTab({environmentId,threadRef,@@ -487,10 +408,12 @@ export function PullRequestSummaryTab({// Keyed by the pull request, so opening another one starts at the end of its conversation// rather than wherever the last one had been read back to.const [shown, setShown] = useState({ url: detail.url, count: COMMENT_PAGE });- const [openedBotGroup, setOpenedBotGroup] = useState<string | null>(null);- const [shownBots, setShownBots] = useState({ url: detail.url, count: COMMENT_PAGE });- const shownBotComments = shownBots.url === detail.url ? shownBots.count : COMMENT_PAGE;const shownComments = shown.url === detail.url ? shown.count : COMMENT_PAGE;+ const [commentFilter, setCommentFilter] = useLocalStorage(+ COMMENT_FILTER_STORAGE_KEY,+ DEFAULT_COMMENT_FILTER,+ CommentFilterSchema,+ );// A comment that already lives on a review thread is that thread: the thread carries the line// and side the bare comment has lost, and a resolved one is finished work nobody should be// invited to fix again — the same call the whole-review hand-off makes.@@ -500,22 +423,24 @@ export function PullRequestSummaryTab({),);- const activeComments: PullRequestComment[] = [];- const finishedComments: PullRequestComment[] = [];- const botComments: PullRequestComment[] = [];- for (const comment of detail.comments) {- const finished =- threadByCommentId.get(comment.id)?.isResolved ||- pullRequestReviewOutcome(comment.reviewState) === "dismissed";- const bot = comment.author?.isBot === true || comment.author?.login.endsWith("[bot]");- (finished ? finishedComments : bot ? botComments : activeComments).push(comment);- }+ const isFinished = (comment: PullRequestComment) =>+ threadByCommentId.get(comment.id)?.isResolved === true ||+ pullRequestReviewOutcome(comment.reviewState) === "dismissed";+ const isBot = (comment: PullRequestComment) =>+ comment.author?.isBot === true || comment.author?.login.endsWith("[bot]") === true;+ const filteredComments = detail.comments.filter(+ (comment) =>+ (commentFilter.bots || !isBot(comment)) && (commentFilter.resolved || !isFinished(comment)),+ );+ // The one count the filter shows. Per-kind counts would overlap, since a resolved bot comment+ // is both kinds and needs both shown.+ const filteredOutCount = detail.comments.length - filteredComments.length;// Windowed by recency regardless of display order: expanding always reaches further back in// time, whether the newest comment currently reads first or last.- const recentComments = activeComments.slice(Math.max(0, activeComments.length - shownComments));- const hiddenCommentCount = activeComments.length - recentComments.length;- const recentBotComments = botComments.slice(Math.max(0, botComments.length - shownBotComments));- const hiddenBotCommentCount = botComments.length - recentBotComments.length;+ const recentComments = filteredComments.slice(+ Math.max(0, filteredComments.length - shownComments),+ );+ const hiddenCommentCount = filteredComments.length - recentComments.length;const [commentOrder, setCommentOrder] = useState<"newest" | "oldest">("newest");const visibleComments = orderPullRequestComments(recentComments, commentOrder);const showOldestCommentsButton =@@ -638,6 +563,30 @@ export function PullRequestSummaryTab({const renderComment = (comment: PullRequestComment) => {const thread = threadByCommentId.get(comment.id);const body = visibleBody(comment.body);+ if (isFinished(comment)) {+ return (+ <CollapsedComment+ key={`${detail.url}:${comment.id}`}+ comment={comment}+ editing={commentEditing}+ detail={detail}+ thread={thread}+ label={thread?.isResolved ? "Resolved" : "Review dismissed"}+ body={body}+ reactionBar={+ <PullRequestReactionBar+ className="ml-auto justify-end"+ reactions={comment.reactions ?? []}+ canReact={detail.capabilities.reactions === true}+ subjectId={comment.id}+ environmentId={environmentId}+ reference={reference}+ onRefresh={onRefresh}+ />+ }+ />+ );+ }const outcome = pullRequestReviewOutcome(comment.reviewState);// An approval is a verdict, not a finding: there is nothing in it to fix.const finding: PullRequestFinding | null =@@ -920,20 +869,51 @@ export function PullRequestSummaryTab({<Sectiontitle={`Comments (${detail.commentCount})`}actions={- <Button- size="xs"- variant="ghost-muted"- className="shrink-0"- aria-label={- commentOrder === "newest"- ? "Show oldest comments first"- : "Show newest comments first"- }- onClick={() => setCommentOrder((value) => (value === "newest" ? "oldest" : "newest"))}- >- <ArrowDownUpIcon aria-hidden className="size-3" />- {commentOrder === "newest" ? "Newest first" : "Oldest first"}- </Button>+ <div className="flex shrink-0 items-center gap-1">+ <Menu>+ <MenuTrigger+ render={<Button size="xs" variant="ghost-muted" />}+ aria-label="Filter comments"+ >+ <ListFilterIcon aria-hidden className="size-3" />+ {filteredOutCount > 0 ? `${filteredOutCount} hidden` : "Filter"}+ </MenuTrigger>+ <MenuPopup align="end">+ <MenuGroup>+ <MenuGroupLabel>Show</MenuGroupLabel>+ <MenuCheckboxItem+ checked={commentFilter.bots}+ closeOnClick={false}+ onCheckedChange={(bots) => setCommentFilter((value) => ({ ...value, bots }))}+ >+ Bot comments+ </MenuCheckboxItem>+ <MenuCheckboxItem+ checked={commentFilter.resolved}+ closeOnClick={false}+ onCheckedChange={(resolved) =>+ setCommentFilter((value) => ({ ...value, resolved }))+ }+ >+ Resolved or dismissed+ </MenuCheckboxItem>+ </MenuGroup>+ </MenuPopup>+ </Menu>+ <Button+ size="xs"+ variant="ghost-muted"+ aria-label={+ commentOrder === "newest"+ ? "Show oldest comments first"+ : "Show newest comments first"+ }+ onClick={() => setCommentOrder((value) => (value === "newest" ? "oldest" : "newest"))}+ >+ <ArrowDownUpIcon aria-hidden className="size-3" />+ {commentOrder === "newest" ? "Newest first" : "Oldest first"}+ </Button>+ </div>}>{activityPending ? (@@ -950,6 +930,12 @@ export function PullRequestSummaryTab({) : null}{detail.comments.length === 0 ? (<p className="py-2 text-xs text-muted-foreground">No comments yet.</p>+ ) : filteredComments.length === 0 ? (+ <p className="py-2 text-xs text-muted-foreground">+ {filteredOutCount === 1+ ? "The only comment is hidden by the filter."+ : `All ${filteredOutCount} comments are hidden by the filter.`}+ </p>) : (<div className="space-y-3">{commentOrder === "oldest" ? showOldestCommentsButton : null}@@ -965,87 +951,6 @@ export function PullRequestSummaryTab({Show only {COMMENT_PAGE} recent comments</Button>) : null}- {botComments.length > 0 ? (- <CommentGroup- key={`bots:${detail.url}`}- label={`${botComments.length} bot comment${botComments.length === 1 ? "" : "s"}`}- comments={botComments}- detail={detail}- onOpenChange={(open) => {- if (open) setOpenedBotGroup(detail.url);- }}- >- <div className="space-y-3 pt-2">- {openedBotGroup === detail.url- ? orderPullRequestComments(recentBotComments, commentOrder).map(- renderComment,- )- : null}- {hiddenBotCommentCount > 0 ? (- <Button- size="sm"- variant="outline"- className="w-full"- onClick={() =>- setShownBots({- url: detail.url,- count: shownBotComments + COMMENT_PAGE,- })- }- >- Show {Math.min(hiddenBotCommentCount, COMMENT_PAGE)} older bot comment- {hiddenBotCommentCount === 1 ? "" : "s"} ({hiddenBotCommentCount} hidden)- </Button>- ) : null}- {shownBotComments > COMMENT_PAGE ? (- <Button- size="sm"- variant="ghost"- className="w-full"- onClick={() => setShownBots({ url: detail.url, count: COMMENT_PAGE })}- >- Show only {COMMENT_PAGE} recent bot comments- </Button>- ) : null}- </div>- </CommentGroup>- ) : null}- {finishedComments.length > 0 ? (- <CommentGroup- key={detail.url}- label={`${finishedComments.length} resolved or dismissed comment${finishedComments.length === 1 ? "" : "s"}`}- comments={finishedComments}- detail={detail}- >- <div className="space-y-2 pt-2">- {orderPullRequestComments(finishedComments, commentOrder).map((comment) => {- const thread = threadByCommentId.get(comment.id);- return (- <CollapsedComment- key={comment.id}- comment={comment}- editing={commentEditing}- detail={detail}- thread={thread}- label={thread?.isResolved ? "Resolved" : "Review dismissed"}- body={visibleBody(comment.body)}- reactionBar={- <PullRequestReactionBar- className="ml-auto justify-end"- reactions={comment.reactions ?? []}- canReact={detail.capabilities.reactions === true}- subjectId={comment.id}- environmentId={environmentId}- reference={reference}- onRefresh={onRefresh}- />- }- />- );- })}- </div>- </CommentGroup>- ) : null}</div>)}</>