Skip to content

Commit c354c60

Browse files
fix(github): Do not ask a reviewer again after they approve
Marking an older change request addressed asked its author to review again even when they had approved since. The tool now asks only while the reviewer's latest review still requests changes. Co-Authored-By: BYK <[email protected]>
1 parent aaa18d6 commit c354c60

5 files changed

Lines changed: 111 additions & 58 deletions

File tree

‎design/github.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ also wake a Conversation or run an Event automation.
3636
- Junior can review a PR and request changes.
3737
- When the requester requests changes on a Junior PR, the PR asks for
3838
their review again after Junior pushes new commits or marks the change
39-
request addressed.
39+
request addressed. A requester who approved since is not asked.
4040
- Junior cannot fork or administer a repo, and never pushes to or deletes
4141
the default branch.
4242
- Junior reaches only repos where its App is installed.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import * as z from "zod";
2+
3+
const REVIEWS_PAGE_SIZE = 100;
4+
5+
const reviewsSchema = z.array(
6+
z.object({
7+
commit_id: z.string().nullable().optional(),
8+
state: z.string(),
9+
user: z.object({ login: z.string() }).nullable(),
10+
}),
11+
);
12+
13+
/** One review of a pull request, as GitHub lists it. */
14+
export type GitHubPullRequestReview = z.infer<typeof reviewsSchema>[number];
15+
16+
/**
17+
* Read every page of a pull request's reviews, and return the latest
18+
* approval, change request, or dismissal of each reviewer by lowercase
19+
* login. Comments do not count. `readPage` reads the reviews with the given
20+
* query string.
21+
*/
22+
export async function loadLatestReviews(
23+
readPage: (query: string) => Promise<unknown>,
24+
): Promise<Map<string, GitHubPullRequestReview>> {
25+
const latest = new Map<string, GitHubPullRequestReview>();
26+
// A later page can hold a newer review, so read every page. GitHub lists
27+
// reviews oldest first.
28+
for (let page = 1; ; page++) {
29+
const batch = reviewsSchema.parse(
30+
// oxlint-disable-next-line no-await-in-loop -- Stop paging at the first short page.
31+
await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`),
32+
);
33+
for (const review of batch) {
34+
if (
35+
review.user &&
36+
review.state !== "COMMENTED" &&
37+
review.state !== "PENDING"
38+
) {
39+
latest.set(review.user.login.toLowerCase(), review);
40+
}
41+
}
42+
if (batch.length < REVIEWS_PAGE_SIZE) return latest;
43+
}
44+
}

‎packages/junior-github/src/tools/update-pull-request-feedback.ts‎

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
REMOVE_REVIEW_REACTION,
1515
REVIEW_REACTIONS,
1616
} from "../graphql-documents.js";
17+
import { loadLatestReviews } from "../pull-request-reviews.js";
1718
import { botUserIdFromEmail } from "../webhooks/ownership.js";
1819
import {
1920
type GitHubApiResponse,
@@ -375,10 +376,11 @@ async function reviewBodyReactions(
375376
}
376377

377378
/**
378-
* Ask the reviewer who requested changes to review again. GitHub stops asking
379-
* a reviewer once they review, so the fixed pull request would not wait on
380-
* them. The request is optional, so a failure is logged and does not fail the
381-
* tool.
379+
* Ask the reviewer who requested changes to review again, while their latest
380+
* review still requests changes. GitHub stops asking a reviewer once they
381+
* review, so the fixed pull request would not wait on them. A reviewer who
382+
* approved since then is not asked. The request is optional, so a failure is
383+
* logged and does not fail the tool.
382384
*/
383385
async function requestReviewAgain(
384386
ctx: { egress: PluginEgress; log: Pick<PluginLogger, "warn"> },
@@ -389,16 +391,34 @@ async function requestReviewAgain(
389391
repo: `${input.owner}/${input.name}`,
390392
};
391393
try {
392-
const response = await githubApi(ctx.egress, {
393-
operation: "github.pull.request_reviewers",
394-
method: "POST",
395-
path: `${repoPath(input)}/pulls/${input.pullRequest}/requested_reviewers`,
396-
body: { reviewers: [input.reviewer] },
394+
const pullPath = `${repoPath(input)}/pulls/${input.pullRequest}`;
395+
let rejectedStatus: number | undefined;
396+
const latest = await loadLatestReviews(async (query) => {
397+
const page = await githubApi(ctx.egress, {
398+
operation: "github.pull.review.list",
399+
path: `${pullPath}/reviews?${query}`,
400+
});
401+
// An empty page ends the read.
402+
if (page.ok) return page.body;
403+
rejectedStatus = page.status;
404+
return [];
397405
});
398-
if (!response.ok) {
406+
if (
407+
rejectedStatus === undefined &&
408+
latest.get(input.reviewer.toLowerCase())?.state === "CHANGES_REQUESTED"
409+
) {
410+
const response = await githubApi(ctx.egress, {
411+
operation: "github.pull.request_reviewers",
412+
method: "POST",
413+
path: `${pullPath}/requested_reviewers`,
414+
body: { reviewers: [input.reviewer] },
415+
});
416+
if (!response.ok) rejectedStatus = response.status;
417+
}
418+
if (rejectedStatus !== undefined) {
399419
ctx.log.warn(
400420
"github.pull_request.request_reviewers_after_feedback.rejected",
401-
{ ...fields, status: response.status },
421+
{ ...fields, status: rejectedStatus },
402422
);
403423
}
404424
} catch (error) {
@@ -438,7 +458,7 @@ export function createGitHubUpdatePullRequestFeedbackTool(
438458
readOnlyHint: false,
439459
},
440460
description:
441-
"Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. Addressed on a review that requested changes also asks its reviewer to review again. Only works on pull requests the bot authored.",
461+
"Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. Addressed on a change request asks its reviewer to review again, unless they approved since. Only works on pull requests the bot authored.",
442462
exposure: "direct",
443463
inputSchema,
444464
outputSchema,

‎packages/junior-github/src/webhooks/installation-requests.ts‎

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
PULL_REQUEST_CONFLICT_HISTORY,
1818
pullRequestLifecycles,
1919
} from "../graphql-documents.js";
20+
import { loadLatestReviews } from "../pull-request-reviews.js";
2021
import { githubErrorMessage } from "../tool-support/github-api.js";
2122
import {
2223
graphqlReactionContent,
@@ -361,14 +362,6 @@ const pullRequestSchema = z.object({
361362
title: z.string(),
362363
});
363364

364-
const reviewsSchema = z.array(
365-
z.object({
366-
commit_id: z.string().nullable().optional(),
367-
state: z.string(),
368-
user: z.object({ login: z.string() }).nullable(),
369-
}),
370-
);
371-
372365
/** The pull request facts that decide its next action. */
373366
export interface GitHubPullRequestMergeState {
374367
/**
@@ -464,30 +457,9 @@ export async function loadPullRequestMergeState(
464457
const readsApproval = canMerge && state.mergeableState === "clean";
465458
if (!readsApproval && !readsChanges) return state;
466459

467-
// A later page can hold a newer review, so read every page. GitHub lists
468-
// reviews oldest first.
469-
const reviews: z.infer<typeof reviewsSchema> = [];
470-
for (let page = 1; ; page++) {
471-
const batch = reviewsSchema.parse(
472-
// oxlint-disable-next-line no-await-in-loop -- Stop paging at the first short page.
473-
await read(`/reviews?per_page=100&page=${page}`),
474-
);
475-
reviews.push(...batch);
476-
if (batch.length < 100) break;
477-
}
478-
const latestReviews = new Map<
479-
string,
480-
z.infer<typeof reviewsSchema>[number]
481-
>();
482-
for (const review of reviews) {
483-
if (
484-
review.user &&
485-
review.state !== "COMMENTED" &&
486-
review.state !== "PENDING"
487-
) {
488-
latestReviews.set(review.user.login.toLowerCase(), review);
489-
}
490-
}
460+
const latestReviews = await loadLatestReviews(
461+
async (query) => await read(`/reviews?${query}`),
462+
);
491463
const reviewStates = [...latestReviews.values()].map(
492464
(review) => review.state,
493465
);

‎packages/junior-github/tests/pull-request-action.test.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -692,7 +692,7 @@ describe("next action item", () => {
692692
// review again. GitHub then asks for the review, so the item stays.
693693
requests.length = 0;
694694
await markReviewAddressed(301);
695-
expect(requests).toEqual(["pull", "request requester"]);
695+
expect(requests).toEqual(["pull", "reviews", "request requester"]);
696696
await webhook.handler(pullRequestAction("review_requested"));
697697
expect(calls).toHaveLength(3);
698698

@@ -757,27 +757,44 @@ describe("next action item", () => {
757757
});
758758

759759
it.each([
760-
{ reviewState: "APPROVED", webhookState: "approved" as const },
761-
{ reviewState: "COMMENTED", webhookState: "commented" as const },
760+
{
761+
name: "an approval",
762+
reviews: [{ id: 301, state: "APPROVED" }],
763+
webhookState: "approved" as const,
764+
},
765+
{
766+
name: "a comment",
767+
reviews: [{ id: 301, state: "COMMENTED" }],
768+
webhookState: "commented" as const,
769+
},
770+
{
771+
// With auto-merge on, a push after the approval can merge with no
772+
// other person, so asking again would only bother the requester.
773+
autoMerge: true,
774+
name: "an approval that follows a change request",
775+
reviews: [
776+
{ id: 301, state: "CHANGES_REQUESTED" },
777+
{ id: 302, state: "APPROVED" },
778+
],
779+
webhookState: "approved" as const,
780+
},
762781
])(
763-
"does not ask the requester again after an $webhookState review",
764-
async ({ reviewState, webhookState }) => {
782+
"does not ask the requester again after $name",
783+
async ({ autoMerge, reviews, webhookState }) => {
765784
const fixture = await createGitHubFixture();
766785
const calls: ReviewItemCall[] = [];
767786
const requests: string[] = [];
768787
const github: GitHubState = {
788+
autoMerge,
769789
draft: false,
770790
mergeableStates: ["blocked"],
771791
merged: false,
772792
requestedReviewers: [],
773-
reviews: [
774-
{
775-
commit_id: "head-1",
776-
id: 301,
777-
state: reviewState,
778-
user: { login: "requester" },
779-
},
780-
],
793+
reviews: reviews.map((review) => ({
794+
...review,
795+
commit_id: "head-1",
796+
user: { login: "requester" },
797+
})),
781798
state: "open",
782799
};
783800
mockGitHub(github, requests);

0 commit comments

Comments
 (0)