diff --git a/design/github.md b/design/github.md index a1986db7f8..a9f7c1b659 100644 --- a/design/github.md +++ b/design/github.md @@ -35,11 +35,13 @@ also wake a Conversation or run an Event automation. - Images in PRs, issues, and comments are links to public Junior images. - Junior can review a PR and request changes. - When the requester requests changes on a Junior PR, the PR asks for - their review again, in the Inbox and on GitHub, when Junior acts after - them and the required checks pass. Junior acts when it pushes commits, - comments, replies to a review comment, or marks the change request - addressed. When the requester comments or reviews, Junior acts next, and - the Inbox stops asking. A requester who approved since is not asked. + their review again, in the Inbox and on GitHub, only when Junior marks + each comment of that change request addressed or declined and the + required checks pass. Pushes, merges of the base branch, comments, and + replies do not ask. When the requester comments or reviews, Junior acts + next, and the Inbox stops asking. A requester who approved since is not + asked. The Inbox item says why it asks: every comment is handled, or the + checks now pass. - Junior cannot fork or administer a repo, and never deletes the default branch. - Junior reaches only repos where its App is installed. @@ -53,9 +55,6 @@ also wake a Conversation or run an Event automation. ## Gaps -- Junior asks the requester to review again as soon as it acts after their - change request, before the required checks pass. This breaks "asks for a - review only when the required checks pass" (Attention). - A pull request that Junior opens ready for review asks for a review at once, before the required checks pass. This breaks "asks for a review only when the required checks pass" (Attention). diff --git a/packages/junior-github/src/events/pull-request.ts b/packages/junior-github/src/events/pull-request.ts index b276d490d8..5ba319d8bd 100644 --- a/packages/junior-github/src/events/pull-request.ts +++ b/packages/junior-github/src/events/pull-request.ts @@ -43,7 +43,7 @@ const STACK_CONFLICT_STEPS = * sets comment_id only when it has a body. */ const PULL_REQUEST_FEEDBACK = - 'When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status "addressed" or "declined".'; + 'When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback or answering a question, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status "addressed" or "declined".'; const GITHUB_PULL_REQUEST_EVENT_GUIDANCE: Partial< Record diff --git a/packages/junior-github/src/graphql-documents.ts b/packages/junior-github/src/graphql-documents.ts index 66bef4aa08..b935aacd75 100644 --- a/packages/junior-github/src/graphql-documents.ts +++ b/packages/junior-github/src/graphql-documents.ts @@ -232,16 +232,15 @@ export const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(` /** * Read what decides the requester's next action on one pull request: its - * state, merge state, review requests, latest reviews, head commit, and - * latest comments and review requests. A review comment reply is a review, - * so `reviews` holds it too. + * state, merge state, review requests, latest reviews, and latest comments + * and review requests. A review comment reply is a review, so `reviews` + * holds it too. */ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(` query PullRequestNextAction($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { autoMergeRequest { enabledAt } - headRefOid isDraft mergeStateStatus state @@ -254,7 +253,6 @@ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(` pageInfo { hasPreviousPage startCursor } nodes { ...NextActionReview } } - commits(last: 1) { nodes { commit { committedDate } } } timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) { nodes { __typename @@ -273,7 +271,61 @@ export const PULL_REQUEST_NEXT_ACTION = githubGraphql(` state submittedAt author { __typename login } - commit { oid } + } +`); + +/** + * Read what decides whether a reviewer's change request is ready for their + * review again: whether GitHub asks them, their latest review with the + * reactors of its body and each of its comments, the checks of the head + * commit, and the branch protection's required checks of the base branch. + */ +export const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(` + query PullRequestReviewAgain($owner: String!, $name: String!, $number: Int!, $reviewer: String!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + baseRefName + baseRef { refUpdateRule { requiredStatusCheckContexts } } + reviewRequests(first: 100) { + nodes { requestedReviewer { __typename ... on User { login } } } + } + reviews(last: 1, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, DISMISSED]) { + nodes { + databaseId + state + body + ...FeedbackReactors + comments(first: 100) { + totalCount + nodes { databaseId ...FeedbackReactors } + } + } + } + commits(last: 1) { + nodes { + commit { + statusCheckRollup { + contexts(first: 100) { + pageInfo { hasNextPage } + nodes { + __typename + ... on CheckRun { name status conclusion } + ... on StatusContext { context state } + } + } + } + } + } + } + } + } + } + + fragment FeedbackReactors on Reactable { + reactionGroups { + content + reactors(first: 100) { nodes { ... on Bot { databaseId } } } + } } `); @@ -294,7 +346,6 @@ export const PULL_REQUEST_REVIEWS_BEFORE = githubGraphql(` state submittedAt author { __typename login } - commit { oid } } `); diff --git a/packages/junior-github/src/pull-request-review-again.ts b/packages/junior-github/src/pull-request-review-again.ts new file mode 100644 index 0000000000..1775c5aa7d --- /dev/null +++ b/packages/junior-github/src/pull-request-review-again.ts @@ -0,0 +1,409 @@ +/** + * Whether a reviewer's change request on a Junior pull request is ready for + * their review again. + * + * Only an explicit signal asks again: Junior marks every comment of the + * reviewer's latest change request addressed or declined with the feedback + * tool. Pushes, base-branch syncs, comments, and replies never ask on their + * own. The ask also waits until the required checks of the head commit pass. + * GitHub sends no webhook for a reaction, so the feedback tool reads this + * when it marks a comment. When the checks have not passed yet, it saves a + * held ask, and the check suite webhook reads this again. + */ +import type { PluginState } from "@sentry/junior-plugin-api"; +import * as z from "zod"; +import { PULL_REQUEST_REVIEW_AGAIN } from "./graphql-documents.js"; + +/** + * One GitHub API read: a GraphQL query when `body` is set, else a REST GET. + * It returns the response body and throws when GitHub rejects the read. + */ +export type GitHubRead = (request: { + body?: unknown; + operation: string; + path: string; +}) => Promise; + +/** + * `ready`: ask the reviewer again now. `checks`: every comment is marked, + * but the required checks have not passed. `none`: do not ask, because + * GitHub already asks them, their latest review is not a change request, or + * a comment of it is not marked. + */ +export type ReviewAgainReadiness = "checks" | "none" | "ready"; + +const reactorsSchema = z.object({ + reactionGroups: z.array( + z.object({ + content: z.string(), + reactors: z.object({ + nodes: z.array( + z.object({ databaseId: z.number().optional() }).nullable(), + ), + }), + }), + ), +}); + +const checkContextSchema = z.discriminatedUnion("__typename", [ + z.object({ + __typename: z.literal("CheckRun"), + conclusion: z.string().nullable(), + name: z.string(), + status: z.string(), + }), + z.object({ + __typename: z.literal("StatusContext"), + context: z.string(), + state: z.string(), + }), +]); + +const reviewAgainSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ + baseRef: z + .object({ + refUpdateRule: z + .object({ + requiredStatusCheckContexts: z + .array(z.string().nullable()) + .nullable(), + }) + .nullable(), + }) + .nullable(), + baseRefName: z.string().min(1), + commits: z.object({ + nodes: z.array( + z.object({ + commit: z.object({ + statusCheckRollup: z + .object({ + contexts: z.object({ + nodes: z.array(checkContextSchema.nullable()), + pageInfo: z.object({ hasNextPage: z.boolean() }), + }), + }) + .nullable(), + }), + }), + ), + }), + reviewRequests: z.object({ + nodes: z.array( + z + .object({ + requestedReviewer: z + .object({ + __typename: z.string(), + login: z.string().optional(), + }) + .nullable(), + }) + .nullable(), + ), + }), + reviews: z.object({ + nodes: z.array( + reactorsSchema + .extend({ + body: z.string(), + comments: z.object({ + nodes: z.array( + reactorsSchema + .extend({ databaseId: z.number().nullable() }) + .nullable(), + ), + totalCount: z.number(), + }), + databaseId: z.number().nullable(), + state: z.string(), + }) + .nullable(), + ), + }), + }), + }), + }), +}); + +// Rulesets that apply to a branch. Only status check rules matter here. +const branchRulesSchema = z.array( + z.object({ + parameters: z + .object({ + required_status_checks: z + .array(z.object({ context: z.string() })) + .optional(), + }) + .optional(), + type: z.string(), + }), +); + +// The reactions that mark a comment addressed or declined, by GraphQL name. +const MARKED_CONTENTS = new Set(["THUMBS_DOWN", "THUMBS_UP"]); + +// A check run that completed with one of these conclusions does not block a +// merge. Every other conclusion does. +const PASSING_CONCLUSIONS = new Set(["NEUTRAL", "SKIPPED", "SUCCESS"]); + +type CheckContext = z.output; + +/** Return whether one check run or commit status passes, fails, or waits. */ +export function checkContextState( + context: CheckContext, +): "failing" | "passing" | "pending" { + if (context.__typename === "CheckRun") { + if (context.status !== "COMPLETED") return "pending"; + return PASSING_CONCLUSIONS.has(context.conclusion ?? "") + ? "passing" + : "failing"; + } + if (context.state === "SUCCESS") return "passing"; + return context.state === "PENDING" || context.state === "EXPECTED" + ? "pending" + : "failing"; +} + +function markedBy( + reactable: z.output, + botUserId: number, +): boolean { + return reactable.reactionGroups.some( + (group) => + MARKED_CONTENTS.has(group.content) && + group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId), + ); +} + +/** + * Return whether every required check passes. A required check that has + * not reported yet waits, so the ask does not go out before CI starts. + */ +function requiredChecksPass( + required: Set, + contexts: CheckContext[], + incomplete: boolean, +): boolean { + for (const name of required) { + const states = contexts + .filter( + (context) => + (context.__typename === "CheckRun" + ? context.name + : context.context) === name, + ) + .map(checkContextState); + // More than 100 checks hide some, so a missing check can still exist. + if (states.length === 0 && incomplete) return false; + if (states.length === 0 || states.some((state) => state !== "passing")) { + return false; + } + } + return true; +} + +/** + * Read whether `reviewer`'s latest change request on a pull request is + * ready for their review again. The comments of a change request are its + * inline comments and its body. An empty body counts only when the review + * has no inline comments. + */ +export async function readReviewAgainReadiness( + read: GitHubRead, + target: { + botUserId: number; + /** + * The comment that the caller just marked. It counts as marked, because + * GitHub's GraphQL read can lag behind a reaction that was just added. + */ + marked?: { id: number; kind: "review" | "review_body" } | undefined; + name: string; + number: number; + owner: string; + reviewer: string; + }, +): Promise { + const { name, number, owner, reviewer } = target; + const pull = reviewAgainSchema.parse( + await read({ + body: { + ...PULL_REQUEST_REVIEW_AGAIN, + variables: { name, number, owner, reviewer }, + }, + operation: "github.pull.review-again.get", + path: "/graphql", + }), + ).data.repository.pullRequest; + const lower = reviewer.toLowerCase(); + const requested = pull.reviewRequests.nodes.some( + (request) => request?.requestedReviewer?.login?.toLowerCase() === lower, + ); + const review = pull.reviews.nodes[0]; + if (requested || review?.state !== "CHANGES_REQUESTED") return "none"; + const comments = review.comments.nodes.filter((comment) => comment !== null); + // A comment past the first 100 cannot be read, so it counts as open. + if (comments.length < review.comments.totalCount) return "none"; + const { marked } = target; + const justMarked = (id: number | null, kind: "review" | "review_body") => + marked?.kind === kind && marked.id === id; + const bodyMarked = + justMarked(review.databaseId, "review_body") || + markedBy(review, target.botUserId); + const bodyCounts = review.body.trim() !== "" || comments.length === 0; + if (bodyCounts && !bodyMarked) return "none"; + const commentsMarked = comments.every( + (comment) => + justMarked(comment.databaseId, "review") || + markedBy(comment, target.botUserId), + ); + if (!commentsMarked) return "none"; + + const rules = branchRulesSchema.parse( + await read({ + operation: "github.repo.branch-rules.get", + path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`, + }), + ); + const required = new Set([ + ...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter( + (context): context is string => Boolean(context), + ), + ...rules.flatMap((rule) => + rule.type === "required_status_checks" + ? (rule.parameters?.required_status_checks ?? []).map( + (check) => check.context, + ) + : [], + ), + ]); + const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup; + const contexts = (rollup?.contexts.nodes ?? []).filter( + (context) => context !== null, + ); + return requiredChecksPass( + required, + contexts, + rollup?.contexts.pageInfo.hasNextPage ?? false, + ) + ? "ready" + : "checks"; +} + +// A held ask waits for the checks of one fix, which take hours at most. +// After this time, only a new mark asks. +const HELD_ASK_TTL_MS = 3 * 24 * 60 * 60 * 1000; + +const heldAskSchema = z.object({ + at: z.iso.datetime(), + // `handled`: the checks passed, but GitHub did not take the request. + reason: z.enum(["checks", "handled"]), + reviewer: z.string().min(1), + // The comment whose mark made the ask, so a lagging read still counts it. + marked: z + .object({ id: z.number(), kind: z.enum(["review", "review_body"]) }) + .optional(), +}); + +/** A review ask that waits for the required checks to pass. */ +export type GitHubHeldReviewAsk = z.output; + +function heldAskKey(target: { + number: number; + repositoryFullName: string; +}): string { + return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`; +} + +/** Save the review ask that waits for the checks of one pull request. */ +export async function holdGitHubReviewAsk( + state: PluginState, + target: { number: number; repositoryFullName: string }, + ask: GitHubHeldReviewAsk, +): Promise { + await state.set( + heldAskKey(target), + heldAskSchema.parse(ask), + HELD_ASK_TTL_MS, + ); +} + +/** Return the review ask that waits for the checks of one pull request. */ +export async function readHeldGitHubReviewAsk( + state: PluginState, + target: { number: number; repositoryFullName: string }, +): Promise { + const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target))); + return saved.success ? saved.data : undefined; +} + +/** + * Drop the held review ask of one pull request. With `reviewer`, drop it + * only when it is for that reviewer. + */ +export async function dropHeldGitHubReviewAsk( + state: PluginState, + target: { number: number; repositoryFullName: string }, + reviewer?: string, +): Promise { + if (reviewer !== undefined) { + const held = await readHeldGitHubReviewAsk(state, target); + if (held?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return; + } + await state.delete(heldAskKey(target)); +} + +/** + * Why Junior asked a reviewer again: `handled` when the last comment was + * marked and the checks already passed, `checks` when passing checks + * released a held ask. + */ +export type GitHubReviewAskReason = "checks" | "handled"; + +// The tool asks on GitHub, and GitHub's review request webhook shows the +// item. The mark only needs to outlive that delivery. +const ASKED_TTL_MS = 60 * 60 * 1000; + +const askedSchema = z.object({ + at: z.iso.datetime(), + reviewer: z.string().min(1), +}); + +/** A review that the feedback tool asked for, until the item shows it. */ +export type GitHubReviewAsked = z.output; + +function askedKey(target: { + number: number; + repositoryFullName: string; +}): string { + return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`; +} + +/** Record that the feedback tool asked `reviewer` again on one pull request. */ +export async function markGitHubReviewAsked( + state: PluginState, + target: { number: number; repositoryFullName: string }, + asked: GitHubReviewAsked, +): Promise { + await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS); +} + +/** Return the review that the feedback tool asked for on one pull request. */ +export async function readGitHubReviewAsked( + state: PluginState, + target: { number: number; repositoryFullName: string }, +): Promise { + const saved = askedSchema.safeParse(await state.get(askedKey(target))); + return saved.success ? saved.data : undefined; +} + +/** Drop the record of a review that the feedback tool asked for. */ +export async function dropGitHubReviewAsked( + state: PluginState, + target: { number: number; repositoryFullName: string }, +): Promise { + await state.delete(askedKey(target)); +} diff --git a/packages/junior-github/src/pull-request-reviews.ts b/packages/junior-github/src/pull-request-reviews.ts deleted file mode 100644 index a84b8651a6..0000000000 --- a/packages/junior-github/src/pull-request-reviews.ts +++ /dev/null @@ -1,44 +0,0 @@ -import * as z from "zod"; - -const REVIEWS_PAGE_SIZE = 100; - -const reviewsSchema = z.array( - z.object({ - commit_id: z.string().nullable().optional(), - state: z.string(), - user: z.object({ login: z.string() }).nullable(), - }), -); - -/** One review of a pull request, as GitHub lists it. */ -export type GitHubPullRequestReview = z.infer[number]; - -/** - * Read every page of a pull request's reviews, and return the latest - * approval, change request, or dismissal of each reviewer by lowercase - * login. Comments do not count. `readPage` reads the reviews with the given - * query string. - */ -export async function loadLatestReviews( - readPage: (query: string) => Promise, -): Promise> { - const latest = new Map(); - // A later page can hold a newer review, so read every page. GitHub lists - // reviews oldest first. - for (let page = 1; ; page++) { - const batch = reviewsSchema.parse( - // oxlint-disable-next-line no-await-in-loop -- Stop paging at the first short page. - await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`), - ); - for (const review of batch) { - if ( - review.user && - review.state !== "COMMENTED" && - review.state !== "PENDING" - ) { - latest.set(review.user.login.toLowerCase(), review); - } - } - if (batch.length < REVIEWS_PAGE_SIZE) return latest; - } -} diff --git a/packages/junior-github/src/tools/get-pull-request.ts b/packages/junior-github/src/tools/get-pull-request.ts index b9cb788a5d..ce4108c2b8 100644 --- a/packages/junior-github/src/tools/get-pull-request.ts +++ b/packages/junior-github/src/tools/get-pull-request.ts @@ -13,6 +13,7 @@ import * as z from "zod"; import { subscribableResourceSchema } from "@sentry/junior-plugin-api"; import { gitHubPullRequestSubscribable } from "../events/pull-request.js"; import { PULL_REQUEST_CHECKS } from "../graphql-documents.js"; +import { checkContextState } from "../pull-request-review-again.js"; import { githubApi, parseRepo, repoPath } from "../tool-support/github-api.js"; const commitShaSchema = z.string().regex(/^[0-9a-f]{40}$/i); @@ -156,26 +157,6 @@ const checksResponseSchema = z.object({ }), }), }); -type CheckContext = z.output; - -// A check run that completed with one of these conclusions does not block a -// merge. Every other conclusion does. -const PASSING_CONCLUSIONS = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]); - -function contextState( - context: CheckContext, -): "passing" | "failing" | "pending" { - if (context.__typename === "CheckRun") { - if (context.status !== "COMPLETED") return "pending"; - return PASSING_CONCLUSIONS.has(context.conclusion ?? "") - ? "passing" - : "failing"; - } - if (context.state === "SUCCESS") return "passing"; - return context.state === "PENDING" || context.state === "EXPECTED" - ? "pending" - : "failing"; -} /** Read the required checks and merge state of one pull request. */ async function readPullRequestChecks( @@ -206,7 +187,7 @@ async function readPullRequestChecks( >; for (const context of rollup?.contexts.nodes ?? []) { if (!context.isRequired) continue; - checks[contextState(context)].push( + checks[checkContextState(context)].push( context.__typename === "CheckRun" ? context.name : context.context, ); } diff --git a/packages/junior-github/src/tools/update-pull-request-feedback.ts b/packages/junior-github/src/tools/update-pull-request-feedback.ts index 4a708d4133..ec22ec6c6c 100644 --- a/packages/junior-github/src/tools/update-pull-request-feedback.ts +++ b/packages/junior-github/src/tools/update-pull-request-feedback.ts @@ -2,6 +2,7 @@ import pLimit from "p-limit"; import { type PluginEgress, type PluginLogger, + type PluginState, type PluginToolOutput, definePluginTool, PluginToolInputError, @@ -25,7 +26,12 @@ import { pullRequestReviewPath, REST_REACTION_CONTENT, } from "../pull-request-feedback.js"; -import { loadLatestReviews } from "../pull-request-reviews.js"; +import { + dropHeldGitHubReviewAsk, + holdGitHubReviewAsk, + markGitHubReviewAsked, + readReviewAgainReadiness, +} from "../pull-request-review-again.js"; import { botUserIdFromEmail } from "../webhooks/ownership.js"; import { type GitHubApiResponse, @@ -87,13 +93,14 @@ const reactionSchema = z.object({ }); /** - * Return the issue or pull request number of one comment in `repo`. A - * conversation comment is an issue comment, so its issue can be a plain issue. + * Return the issue or pull request number of one comment in `repo`, and its + * author. A conversation comment is an issue comment, so its issue can be a + * plain issue. */ -async function commentParentNumber( +async function readComment( egress: PluginEgress, input: PullRequestCommentRef, -): Promise { +): Promise<{ author?: string; number: string }> { const commentResponse = await githubApi(egress, { operation: "github.pull.comment.get", path: pullRequestCommentPath(input), @@ -108,6 +115,10 @@ async function commentParentNumber( .object({ issue_url: z.string().optional(), pull_request_url: z.string().optional(), + user: z + .object({ login: z.string().min(1) }) + .nullable() + .optional(), }) .safeParse(commentPayload); const parentUrl = comment.success @@ -120,7 +131,8 @@ async function commentParentNumber( if (!number) { throw new Error("GitHub comment did not name its issue or pull request."); } - return number; + const author = comment.success ? comment.data.user?.login : undefined; + return { ...(author ? { author } : undefined), number }; } /** @@ -184,10 +196,12 @@ interface BotReaction { } /** - * The reactions on one pull request comment or review body. Each kind has its - * own GitHub API, but the feedback rules are the same for both. + * The reactions on one pull request comment or review body, and its author. + * Each kind has its own GitHub API, but the feedback rules are the same for + * both. */ interface FeedbackReactions { + author?: string; list(): Promise; botReactions(body: unknown): BotReaction[]; remove(reaction: BotReaction): Promise; @@ -199,14 +213,15 @@ async function commentReactions( egress: PluginEgress, input: PullRequestCommentRef & { botUserId: number; pullRequest: number }, ): Promise { - const parentNumber = await commentParentNumber(egress, input); - if (parentNumber !== String(input.pullRequest)) { + const comment = await readComment(egress, input); + if (comment.number !== String(input.pullRequest)) { throw new PluginToolInputError( `GitHub comment ${input.commentId} is not on pull request ${input.pullRequest}.`, ); } const path = pullRequestCommentReactionsPath(input); return { + ...(comment.author ? { author: comment.author } : undefined), list: () => githubApi(egress, { operation: "github.pull.comment-reaction.list", @@ -233,10 +248,7 @@ async function commentReactions( }; } -/** - * Return the GraphQL reactions of a review on `pullRequest`, and the login of - * its author when the review requests changes. - */ +/** Return the GraphQL reactions of a review on `pullRequest`. */ async function reviewBodyReactions( egress: PluginEgress, input: { @@ -246,7 +258,7 @@ async function reviewBodyReactions( pullRequest: number; reviewId: number; }, -): Promise { +): Promise { // The path names the pull request, so GitHub returns 404 for a review on // another pull request. const reviewResponse = await githubApi(egress, { @@ -261,7 +273,6 @@ async function reviewBodyReactions( const review = z .object({ node_id: z.string().min(1), - state: z.string().optional(), user: z .object({ login: z.string().min(1) }) .nullable() @@ -283,9 +294,7 @@ async function reviewBodyReactions( const update = `github.pull.review-reaction.update:${input.owner}/${input.name}`.toLowerCase(); return { - ...(review.state === "CHANGES_REQUESTED" && review.user - ? { changesRequestedBy: review.user.login } - : undefined), + ...(review.user ? { author: review.user.login } : undefined), list: () => graphql("github.pull.review-reaction.list", REVIEW_REACTIONS, { subjectId, @@ -315,51 +324,113 @@ async function reviewBodyReactions( } /** - * Ask the reviewer who requested changes to review again, while their latest - * review still requests changes. GitHub stops asking a reviewer once they - * review, so the fixed pull request would not wait on them. A reviewer who - * approved since then is not asked. The request is optional, so a failure is - * logged and does not fail the tool. + * Ask the reviewer to review again when every comment of their latest + * change request is marked and the required checks pass. GitHub stops + * asking a reviewer once they review, so the fixed pull request would not + * wait on them. While the checks have not passed, the ask is held, and the + * check suite webhook asks when they pass. The ask is optional, so a failure + * is logged and does not fail the tool. */ -async function requestReviewAgain( +async function askForReviewAgain( + ctx: { + egress: PluginEgress; + log: Pick; + state: PluginState; + }, + input: { + botUserId: number; + marked?: { id: number; kind: "review" | "review_body" }; + name: string; + owner: string; + pullRequest: number; + reviewer: string; + }, +): Promise { + const target = { + number: input.pullRequest, + repositoryFullName: `${input.owner}/${input.name}`, + }; + const fields = { number: target.number, repo: target.repositoryFullName }; + try { + const readiness = await readReviewAgainReadiness( + async (request) => { + const response = await githubApi(ctx.egress, { + ...request, + ...(request.body === undefined ? undefined : { method: "POST" }), + }); + // GraphQL can return partial data with errors, such as for a + // field the token cannot read, so only the schema rejects it. + if (!response.ok) { + throw new Error( + `GitHub ${request.operation} failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`, + ); + } + return response.body; + }, + { ...input, number: input.pullRequest }, + ); + // A read can lag behind another comment's new mark, so "none" drops + // nothing. Each webhook checks a held ask again. + if (readiness === "none") return; + const at = new Date().toISOString(); + if (readiness === "checks") { + await holdGitHubReviewAsk(ctx.state, target, { + at, + ...(input.marked ? { marked: input.marked } : undefined), + reason: "checks", + reviewer: input.reviewer, + }); + return; + } + // GitHub's review request webhook shows the item. This record gives it + // the reason. + await markGitHubReviewAsked(ctx.state, target, { + at, + reviewer: input.reviewer, + }); + if (await requestReviewer(ctx, input)) { + await dropHeldGitHubReviewAsk(ctx.state, target, input.reviewer); + return; + } + // The next webhook asks again. + await holdGitHubReviewAsk(ctx.state, target, { + at, + ...(input.marked ? { marked: input.marked } : undefined), + reason: "handled", + reviewer: input.reviewer, + }); + } catch (error) { + ctx.log.warn( + "github.pull_request.request_reviewers_after_feedback.failed", + { + ...fields, + errorType: error instanceof Error ? error.name : "UnknownError", + }, + ); + } +} + +/** Ask the reviewer on GitHub, and return whether GitHub took the request. */ +async function requestReviewer( ctx: { egress: PluginEgress; log: Pick }, input: { name: string; owner: string; pullRequest: number; reviewer: string }, -): Promise { +): Promise { const fields = { number: input.pullRequest, repo: `${input.owner}/${input.name}`, }; try { - const pullPath = `${repoPath(input)}/pulls/${input.pullRequest}`; - let rejectedStatus: number | undefined; - const latest = await loadLatestReviews(async (query) => { - const page = await githubApi(ctx.egress, { - operation: "github.pull.review.list", - path: `${pullPath}/reviews?${query}`, - }); - // An empty page ends the read. - if (page.ok) return page.body; - rejectedStatus = page.status; - return []; + const response = await githubApi(ctx.egress, { + operation: "github.pull.request_reviewers", + method: "POST", + path: `${repoPath(input)}/pulls/${input.pullRequest}/requested_reviewers`, + body: { reviewers: [input.reviewer] }, }); - if ( - rejectedStatus === undefined && - latest.get(input.reviewer.toLowerCase())?.state === "CHANGES_REQUESTED" - ) { - const response = await githubApi(ctx.egress, { - operation: "github.pull.request_reviewers", - method: "POST", - path: `${pullPath}/requested_reviewers`, - body: { reviewers: [input.reviewer] }, - }); - if (!response.ok) rejectedStatus = response.status; - } - if (rejectedStatus !== undefined) { - ctx.log.warn( - "github.pull_request.request_reviewers_after_feedback.rejected", - { ...fields, status: rejectedStatus }, - ); - } + if (response.ok) return true; + ctx.log.warn( + "github.pull_request.request_reviewers_after_feedback.rejected", + { ...fields, status: response.status }, + ); } catch (error) { ctx.log.warn( "github.pull_request.request_reviewers_after_feedback.failed", @@ -369,6 +440,7 @@ async function requestReviewAgain( }, ); } + return false; } // GraphQL reports errors with HTTP 200, so a failed reply can be `ok`. @@ -381,7 +453,8 @@ function failed(response: GitHubApiResponse): boolean { /** * Set Junior's feedback reaction on a pull request comment or review body. * Replace only state reactions Junior previously added to the same comment. - * Addressed change requests ask their reviewer to review again. + * When the comments of a change request are all marked, ask its reviewer to + * review again. */ export function createGitHubUpdatePullRequestFeedbackTool( botEmail: string | undefined, @@ -397,14 +470,18 @@ export function createGitHubUpdatePullRequestFeedbackTool( readOnlyHint: false, }, description: - "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.", + "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. When every comment of the author's latest change request is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.", exposure: "direct", inputSchema, outputSchema, async execute( input, _options, - ctx: { egress: PluginEgress; log: Pick }, + ctx: { + egress: PluginEgress; + log: Pick; + state: PluginState; + }, ): Promise { const parsedInput = inputSchema.safeParse(input); if (!parsedInput.success) { @@ -430,7 +507,7 @@ export function createGitHubUpdatePullRequestFeedbackTool( number: pullRequest, botUserId, }); - const reactions: FeedbackReactions & { changesRequestedBy?: string } = + const reactions: FeedbackReactions = commentKind === "review_body" ? await reviewBodyReactions(ctx.egress, { owner: repo.owner, @@ -484,12 +561,16 @@ export function createGitHubUpdatePullRequestFeedbackTool( ); } } - if (status === "addressed" && reactions.changesRequestedBy) { - await requestReviewAgain(ctx, { - owner: repo.owner, + if (reactions.author) { + await askForReviewAgain(ctx, { + botUserId, name: repo.name, + owner: repo.owner, + ...(commentKind === "conversation" + ? undefined + : { marked: { id: commentId, kind: commentKind } }), pullRequest, - reviewer: reactions.changesRequestedBy, + reviewer: reactions.author, }); } return { diff --git a/packages/junior-github/src/webhooks/handler.ts b/packages/junior-github/src/webhooks/handler.ts index 05986f26b8..4b814cc1af 100644 --- a/packages/junior-github/src/webhooks/handler.ts +++ b/packages/junior-github/src/webhooks/handler.ts @@ -477,6 +477,7 @@ export function createGitHubWebhookRoute(args: { loadGitHubLogin: args.loadGitHubLogin, log: args.log, inboxItems: args.inboxItems, + state: args.state, targets: pullRequestActionTargets(eventName, body), }); await requestGitHubReviewersWhenReady({ diff --git a/packages/junior-github/src/webhooks/installation-requests.ts b/packages/junior-github/src/webhooks/installation-requests.ts index 7dd7768f67..525106944b 100644 --- a/packages/junior-github/src/webhooks/installation-requests.ts +++ b/packages/junior-github/src/webhooks/installation-requests.ts @@ -26,6 +26,7 @@ import { PULL_REQUEST_REVIEWS_BEFORE, pullRequestLifecycles, } from "../graphql-documents.js"; +import type { GitHubRead } from "../pull-request-review-again.js"; import { githubErrorMessage } from "../tool-support/github-api.js"; /** Environment variable names for the GitHub App installation. */ @@ -240,6 +241,34 @@ export async function requestPullRequestReviewers( ); } +/** + * Return a read-only GitHub reader for one repository, for the review-again + * check: GraphQL for the pull request, and REST for the branch rules. + */ +export async function loadReviewAgainReader( + env: GitHubInstallationEnv, + repositoryFullName: string, +): Promise { + const { name } = splitRepository(repositoryFullName, "review again"); + const token = await issueInstallationToken({ + ...env, + permissions: { + checks: "read", + contents: "read", + metadata: "read", + pull_requests: "read", + }, + repositories: [name], + }); + return async (request) => + await githubRequest("https://api.github.com", request.path, { + ...(request.body === undefined + ? { responses: env.responses } + : { body: request.body, method: "POST" }), + token: token.token, + }); +} + /** Add the "reviewing" reaction to one pull request comment or review body. */ export async function markPullRequestFeedbackReviewing( env: GitHubInstallationEnv, @@ -376,7 +405,6 @@ const reviewsSchema = z.object({ nodes: nodesSchema( z.object({ author: actorSchema, - commit: z.object({ oid: z.string().min(1) }).nullable(), state: z.string(), submittedAt: timestampSchema.nullable(), }), @@ -391,12 +419,6 @@ const nextActionSchema = z.object({ repository: z.object({ pullRequest: z.object({ autoMergeRequest: z.object({}).nullable(), - commits: z.object({ - nodes: nodesSchema( - z.object({ commit: z.object({ committedDate: timestampSchema }) }), - ), - }), - headRefOid: z.string().min(1), isDraft: z.boolean(), mergeStateStatus: z.string(), reviewRequests: z.object({ @@ -437,20 +459,20 @@ const reviewsPageSchema = z.object({ /** * One thing that a person or an App did on a pull request: `author` wrote a - * comment or review, `push` is the head commit, and `reviewRequest` asked - * `login` for a review. `login` is the REST login, so a bot ends in `[bot]`. + * comment or review, and `reviewRequest` asked `login` for a review. `login` + * is the REST login, so a bot ends in `[bot]`. */ export interface GitHubPullRequestActivity { at: Date; - kind: "author" | "push" | "reviewRequest"; + kind: "author" | "reviewRequest"; login: string; } /** The pull request facts that decide its next action. */ export interface GitHubPullRequestMergeState { /** - * The latest comments, reviews, review requests, and head commit, in no - * order. GitHub returns the latest 100 comments and review requests. + * The latest comments, reviews, and review requests, in no order. GitHub + * returns the latest 100 comments and review requests. */ activity: GitHubPullRequestActivity[]; /** @@ -461,15 +483,11 @@ export interface GitHubPullRequestMergeState { /** A person turned on auto-merge, so GitHub merges it without them. */ autoMerge: boolean; /** - * The commit of the requester's latest change request, when that is their - * latest review. Read only when the pull request is open and not a draft. + * The requester's latest review requests changes. Read only when the pull + * request is open and not a draft. */ - changesRequestedCommit?: string; - /** When the requester submitted that change request. */ - changesRequestedAt?: Date; + changesRequested: boolean; draft: boolean; - /** The commit at the head of the pull request. */ - headSha: string; /** * GitHub's merge state, such as `clean` or `blocked`. `clean` means that * the required reviews and every check and status passed, and there are @@ -545,14 +563,6 @@ export async function loadPullRequestMergeState( } const activity: GitHubPullRequestActivity[] = []; - const head = pull.commits.nodes.at(-1); - if (head) { - activity.push({ - at: new Date(head.commit.committedDate), - kind: "push", - login: "", - }); - } for (const item of pull.timelineItems.nodes) { if (item.__typename === "IssueComment" && item.author) { activity.push({ @@ -588,8 +598,8 @@ export async function loadPullRequestMergeState( activity, approved: false, autoMerge: Boolean(pull.autoMergeRequest), + changesRequested: false, draft: pull.isDraft, - headSha: pull.headRefOid, ...(mergeableState ? { mergeableState } : undefined), requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && @@ -627,14 +637,6 @@ export async function loadPullRequestMergeState( } const login = requesterLogin?.toLowerCase(); const requesterReview = login ? latest.get(login) : undefined; - if ( - requesterReview?.state === "CHANGES_REQUESTED" && - requesterReview.commit - ) { - state.changesRequestedCommit = requesterReview.commit.oid; - if (requesterReview.submittedAt) { - state.changesRequestedAt = new Date(requesterReview.submittedAt); - } - } + state.changesRequested = requesterReview?.state === "CHANGES_REQUESTED"; return state; } diff --git a/packages/junior-github/src/webhooks/pull-request-action.ts b/packages/junior-github/src/webhooks/pull-request-action.ts index 3bbb103dd2..1280f6b3e1 100644 --- a/packages/junior-github/src/webhooks/pull-request-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-action.ts @@ -4,17 +4,23 @@ * * The action derives from GitHub state. It is "merge" when the pull request * is open, not a draft, approved, auto-merge is off, and GitHub's merge state - * is `clean`. Otherwise it is "review" when GitHub still asks the requester - * for a review, or when the requester's latest review requests changes and - * Junior acted after the requester: it pushed, its App commented or - * reviewed, or GitHub asked for the requester's review again. GitHub stops - * asking a reviewer once they review, so without the second case a fixed or - * answered pull request never asks the requester again. Then Junior also - * asks for their review on GitHub, so GitHub notifies them. When the - * requester comments or reviews after that, the action ends, even while - * GitHub still asks them, because Junior acts next. One GitHub read gives - * the state and each side's latest activity. A comment by another person - * needs no read. + * is `clean`. Otherwise it is "review" while GitHub asks the requester for a + * review. When the requester still requests changes and comments or reviews + * after GitHub last asked them, the action ends, even while GitHub still + * asks them, because Junior acts next. + * + * After a change request, only an explicit signal asks the requester again: + * Junior marks every comment of it addressed or declined, and the required + * checks pass (`pull-request-review-again.ts`). Pushes, base-branch syncs, + * comments, and replies never ask on their own. When the checks had not + * passed at the last mark, the ask is held. A later webhook, such as a + * completed check suite, then asks on GitHub once they pass, so GitHub + * notifies the requester, and shows the item. A comment or review by the + * reviewer after the hold drops it, because Junior acts next. The item text + * says why it asks: every comment is handled, or the checks now pass. Other + * review requests from GitHub get a general text. One GitHub read gives the + * state and each side's latest activity. A comment by another person needs + * no read. * * The requester takes one action, not both, so one item per pull request * shows it. Each webhook that can change one of these facts reads them @@ -30,6 +36,7 @@ import type { PluginConversationInboxItems, PluginLogger, PluginInboxItems, + PluginState, InboxItemSubjectTitleParts, } from "@sentry/junior-plugin-api"; import pLimit from "p-limit"; @@ -47,16 +54,25 @@ import { gitHubConflictItemKey, } from "../merge-conflict-checks/policy.js"; import { listGitHubPullRequestOpeners } from "../pull-request-requesters/store.js"; +import { + dropGitHubReviewAsked, + dropHeldGitHubReviewAsk, + type GitHubReviewAskReason, + readGitHubReviewAsked, + readHeldGitHubReviewAsk, + readReviewAgainReadiness, +} from "../pull-request-review-again.js"; import { checkSuitePullRequests } from "./check-suite.js"; import { logFailOpenFailure } from "./fail-open-log.js"; import { loadPullRequestMergeState, + loadReviewAgainReader, requestPullRequestReviewers, type GitHubInstallationEnv, type GitHubPullRequestActivity, type GitHubPullRequestMergeState, } from "./installation-requests.js"; -import { isBotLogin } from "./ownership.js"; +import { botUserIdFromEmail } from "./ownership.js"; import type { GitHubPullRequestTarget } from "./pull-request-people.js"; // Pull requests that one delivery syncs at once, under GitHub rate limits. @@ -121,8 +137,8 @@ async function closeLegacyItems( export interface GitHubPullRequestActionTarget extends GitHubPullRequestTarget { /** * The login of a comment's author. A comment changes the next action only - * when Junior or the requester wrote it, so the check skips comments by - * other people with no GitHub read. + * when the requester wrote it, so the check skips comments by other + * people and by Junior with no GitHub read. */ commentBy?: string; } @@ -164,7 +180,7 @@ export function pullRequestActionTargets( if (!parsed.success) return []; const { comment, repository } = parsed.data; const number = (parsed.data.issue ?? parsed.data.pull_request)?.number; - // A comment by a deleted account is by neither Junior nor the requester. + // A comment by a deleted account is not by the requester. if (number === undefined || !comment.user) return []; return [ { @@ -187,46 +203,27 @@ export function pullRequestActionTargets( ]; } -/** - * Who did one thing on a pull request. A push counts as Junior's, as new - * commits do. A request for the requester's review hands the pull request - * to them, so it counts as Junior's too. - */ -function actor( - activity: Pick, - requesterLogin: string | undefined, - botEmail: string | undefined, -): "junior" | "requester" | undefined { - const byRequester = - requesterLogin !== undefined && - activity.login.toLowerCase() === requesterLogin.toLowerCase(); - switch (activity.kind) { - case "push": - return "junior"; - case "reviewRequest": - return byRequester ? "junior" : undefined; - case "author": - if (isBotLogin(activity.login, botEmail)) return "junior"; - return byRequester ? "requester" : undefined; - } +function sameLogin(a: string, b: string | undefined): boolean { + return b !== undefined && a.toLowerCase() === b.toLowerCase(); } -/** When Junior and the requester last acted on a pull request. */ +/** + * When GitHub last asked the requester for a review, and when the requester + * last commented or reviewed. + */ interface LatestActivity { - juniorAt?: Date; + askedAt?: Date; requesterAt?: Date; } function latestActivity( activity: GitHubPullRequestActivity[], requesterLogin: string | undefined, - botEmail: string | undefined, ): LatestActivity { const latest: LatestActivity = {}; for (const entry of activity) { - const by = actor(entry, requesterLogin, botEmail); - if (!by) continue; - const key = by === "junior" ? "juniorAt" : "requesterAt"; + if (!sameLogin(entry.login, requesterLogin)) continue; + const key = entry.kind === "reviewRequest" ? "askedAt" : "requesterAt"; const saved = latest[key]; if (!saved || entry.at > saved) latest[key] = entry.at; } @@ -238,35 +235,6 @@ function timeOf(at: Date | undefined): number { return at ? at.getTime() : Number.NEGATIVE_INFINITY; } -/** Why the requester's review is wanted again after their change request. */ -type ReviewAgainReason = "commits" | "reply"; - -/** - * Return why the requester's review is wanted again after their change - * request, or undefined while Junior acts next. - */ -function reviewAgainReason( - state: GitHubPullRequestMergeState, - activity: LatestActivity, -): ReviewAgainReason | undefined { - if (!state.changesRequestedCommit) return undefined; - const newCommits = state.changesRequestedCommit !== state.headSha; - const changesRequestedAt = timeOf(state.changesRequestedAt); - const requesterAt = Math.max( - timeOf(activity.requesterAt), - changesRequestedAt, - ); - if (timeOf(activity.juniorAt) > requesterAt) { - return newCommits ? "commits" : "reply"; - } - // GitHub gives the time of a commit, not of its push, so a commit made - // before the change request can come later. New commits with no later - // requester activity still count as Junior's. - return newCommits && !(timeOf(activity.requesterAt) > changesRequestedAt) - ? "commits" - : undefined; -} - /** * Derive the requester's next action. Return undefined when it cannot be * known yet, so a later event decides. @@ -274,14 +242,12 @@ function reviewAgainReason( function nextAction( state: GitHubPullRequestMergeState, requester: { - activity: LatestActivity; actedLast: boolean; + askedAgain: boolean; login: string | undefined; }, saved: GitHubPullRequestAction | undefined, -): - | { action?: GitHubPullRequestAction; reason?: ReviewAgainReason } - | undefined { +): { action?: GitHubPullRequestAction } | undefined { if (state.state !== "open") return {}; // With auto-merge on, GitHub merges it, so no person needs to. const canMerge = !state.draft && !state.autoMerge; @@ -291,13 +257,13 @@ function nextAction( // GitHub has not computed the merge state yet, such as after a push. The // merge can still be the action, so it stays until a later event decides. if (canMerge && !state.mergeableState && saved === "merge") return undefined; + if (requester.askedAgain) return { action: "review" }; const requested = isRequested(state, requester.login); - if (requested && !requester.actedLast) return { action: "review" }; - const reason = reviewAgainReason(state, requester.activity); - if (reason) return { action: "review", reason }; // A reply to the change request ends the review that Junior asked for, // though GitHub still asks for it, because Junior acts next. - if (requested && !state.changesRequestedCommit) return { action: "review" }; + if (requested && (!requester.actedLast || !state.changesRequested)) { + return { action: "review" }; + } if (canMerge && !state.mergeableState) return undefined; return {}; } @@ -312,13 +278,6 @@ function isRequested( ); } -const REVIEW_AGAIN_TEXT: Record string> = - { - commits: (number) => - `#${number} has new commits since you requested changes.`, - reply: (number) => `#${number} has a reply since you requested changes.`, - }; - type CloseReason = { reason: string; status: "done" | "dismissed" }; type EndedState = Exclude; @@ -356,6 +315,12 @@ function closeReason( }; } +/** The item text that says why Junior asked for the review again. */ +const REVIEW_AGAIN_TEXT: Record = { + checks: "Checks now pass, and every comment is handled.", + handled: "Every comment on your change request is handled.", +}; + async function showAction( items: PluginInboxItems, args: { @@ -364,7 +329,7 @@ async function showAction( identityId: string; number: number; previous: GitHubPullRequestAction | undefined; - reason: ReviewAgainReason | undefined; + reason: GitHubReviewAskReason | undefined; state: GitHubPullRequestMergeState; titleParts: InboxItemSubjectTitleParts | undefined; }, @@ -380,7 +345,7 @@ async function showAction( body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` - : `${args.reason ? REVIEW_AGAIN_TEXT[args.reason](number) : `GitHub asks you to review #${number}.`}\n\n${state.url}`, + : `${args.reason ? REVIEW_AGAIN_TEXT[args.reason] : `GitHub asks you to review #${number}.`}\n\n${state.url}`, dedupeKey: args.dedupeKey, // The number stays visible where a view shows only the subject. subject: { @@ -443,8 +408,9 @@ export async function closeEndedGitHubPullRequestItems(args: { } /** - * Ask for the requester's review on GitHub, so GitHub notifies them. The - * item already asks, so a failure is logged and the item stays. + * Ask for a reviewer's review on GitHub, so GitHub notifies them, and return + * whether GitHub took the request. The item already asks, so a failure is + * logged and the item stays. */ async function requestReviewAgain( args: { @@ -453,18 +419,102 @@ async function requestReviewAgain( }, target: GitHubPullRequestTarget, login: string, -): Promise { +): Promise { try { await requestPullRequestReviewers(args.env, { ...target, reviewers: [login], }); + return true; } catch (error) { logFailOpenFailure(args.log, "GitHub review request again failed", error, { number: target.number, repository: target.repositoryFullName, }); + return false; + } +} + +/** + * Ask the reviewer of a held review ask again once the required checks + * pass, and return their login and the reason. Keep the hold while the + * checks have not passed, or while GitHub does not take the request, so a + * later webhook asks again. Drop it when the pull request ended, when the + * reviewer commented or reviewed since, or when their change request is no + * longer ready. + */ +async function askHeldReview( + args: { + botEmail: string | undefined; + env: GitHubInstallationEnv; + log?: Pick | undefined; + state: PluginState; + }, + target: GitHubPullRequestTarget, + state: GitHubPullRequestMergeState, +): Promise<{ reason: GitHubReviewAskReason; reviewer: string } | undefined> { + const held = await readHeldGitHubReviewAsk(args.state, target); + if (!held) return undefined; + const heldAt = new Date(held.at); + const botUserId = botUserIdFromEmail(args.botEmail); + const actedSince = state.activity.some( + (entry) => + entry.kind === "author" && + sameLogin(entry.login, held.reviewer) && + entry.at > heldAt, + ); + if (state.state !== "open" || actedSince || botUserId === undefined) { + await dropHeldGitHubReviewAsk(args.state, target); + return undefined; } + const [owner = "", name = ""] = target.repositoryFullName.split("/"); + const readiness = await readReviewAgainReadiness( + await loadReviewAgainReader(args.env, target.repositoryFullName), + { + botUserId, + marked: held.marked, + name, + number: target.number, + owner, + reviewer: held.reviewer, + }, + ); + if (readiness === "checks") return undefined; + if (readiness === "ready") { + if (await requestReviewAgain(args, target, held.reviewer)) { + await dropHeldGitHubReviewAsk(args.state, target); + } + return { reason: held.reason, reviewer: held.reviewer }; + } + await dropHeldGitHubReviewAsk(args.state, target); + return undefined; +} + +/** + * Return why Junior asked the requester again, if it did: the reason of the + * held ask that this sync released, or `handled` when the feedback tool + * asked them and they have not acted since. + */ +async function askReason( + state: PluginState, + target: GitHubPullRequestTarget, + args: { + asked: { reason: GitHubReviewAskReason; reviewer: string } | undefined; + requesterAt: Date | undefined; + requesterLogin: string | undefined; + }, +): Promise { + if (args.asked !== undefined) { + return sameLogin(args.asked.reviewer, args.requesterLogin) + ? args.asked.reason + : undefined; + } + const asked = await readGitHubReviewAsked(state, target); + return asked && + sameLogin(asked.reviewer, args.requesterLogin) && + timeOf(args.requesterAt) <= Date.parse(asked.at) + ? "handled" + : undefined; } async function syncOne( @@ -477,6 +527,7 @@ async function syncOne( | undefined; log?: Pick | undefined; inboxItems: PluginConversationInboxItems; + state: PluginState; }, target: GitHubPullRequestActionTarget, ): Promise { @@ -495,11 +546,7 @@ async function syncOne( const requesterLogin = await args.loadGitHubLogin?.(opener.identityId); if ( target.commentBy !== undefined && - !actor( - { kind: "author", login: target.commentBy }, - requesterLogin, - args.botEmail, - ) + !sameLogin(target.commentBy, requesterLogin) ) { return; } @@ -526,15 +573,20 @@ async function syncOne( target, requesterLogin, ); - const activity = latestActivity( - state.activity, + const activity = latestActivity(state.activity, requesterLogin); + const asked = await askHeldReview(args, target, state); + const reason = await askReason(args.state, target, { + asked, + requesterAt: activity.requesterAt, requesterLogin, - args.botEmail, - ); - const actedLast = timeOf(activity.requesterAt) > timeOf(activity.juniorAt); + }); const next = nextAction( state, - { activity, actedLast, login: requesterLogin }, + { + actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt), + askedAgain: asked !== undefined && reason !== undefined, + login: requesterLogin, + }, previous, ); // Act only on a change. So repeat events add no second item, and an @@ -548,7 +600,7 @@ async function syncOne( identityId: opener.identityId, number: target.number, previous, - reason: next.reason, + reason, state, titleParts: next.action ? await loadGitHubTitleParts( @@ -561,13 +613,6 @@ async function syncOne( ) : undefined, }); - if ( - next.reason && - requesterLogin && - !isRequested(state, requesterLogin) - ) { - await requestReviewAgain(args, target, requesterLogin); - } } // Close the old items only after the new one shows, so a failed show // does not leave the Inbox with no next-action item. @@ -586,6 +631,9 @@ async function syncOne( }) : undefined, ]); + if (changed && next.action === "review" && reason === "handled") { + await dropGitHubReviewAsked(args.state, target); + } if (!changed) return previous; // Save after the items change, so a failure leaves the old action and // the next event tries again. @@ -626,6 +674,8 @@ export async function syncGitHubPullRequestActions(args: { | undefined; log?: Pick | undefined; inboxItems: PluginConversationInboxItems; + /** Holds the review asks that wait for the required checks. */ + state: PluginState; targets: GitHubPullRequestActionTarget[]; }): Promise { await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map( diff --git a/packages/junior-github/tests/pull-request-action-harness.ts b/packages/junior-github/tests/pull-request-action-harness.ts index c6f18fcbd0..9330cbd3ed 100644 --- a/packages/junior-github/tests/pull-request-action-harness.ts +++ b/packages/junior-github/tests/pull-request-action-harness.ts @@ -6,6 +6,7 @@ import { createHmac, generateKeyPairSync } from "node:crypto"; import type { PluginConversationInboxItems, PluginRoute, + PluginState, } from "@sentry/junior-plugin-api"; import { bindPluginTool } from "@sentry/junior-testing/plugin-tool"; import { http, HttpResponse } from "msw"; @@ -52,12 +53,12 @@ export const repository = { owner: { login: "getsentry" }, }; -export function checkSuiteCompleted() { +export function checkSuiteCompleted(conclusion = "success") { return signedRequest( { action: "completed", check_suite: { - conclusion: "success", + conclusion, head_sha: "abcdef1234567890", id: 77, pull_requests: [ @@ -188,12 +189,28 @@ export interface GitHubState { /** The review requests on the pull request's timeline. */ reviewRequests?: Array<{ at: string; login: string }>; reviews: Array<{ + body?: string; commit_id?: string; + /** The ids of the review's inline comments. */ + comments?: number[]; id?: number; state: string; submitted_at?: string; user: { login: string }; }>; + /** + * Junior's feedback reactions, by `review:` for a review body and + * `comment:` for an inline comment. + */ + feedback?: Record; + /** Feedback keys that GitHub's GraphQL read does not show yet. */ + laggingFeedback?: string[]; + /** GitHub rejects review requests, such as during an outage. */ + rejectReviewRequests?: boolean; + /** The checks of the head commit. */ + checks?: Array<{ conclusion: string | null; name: string; status: string }>; + /** The checks that a ruleset of the base branch requires. */ + requiredChecks?: string[]; state: "closed" | "open"; /** The pull request title. */ title?: string; @@ -232,7 +249,93 @@ function reviewsPage(github: GitHubState, before: number) { }; } +// The bot's reactions in GraphQL, as reaction groups. +function graphqlReactionGroups(github: GitHubState, key: string) { + return github.laggingFeedback?.includes(key) + ? [] + : botReactionGroups(github, key); +} + +function botReactionGroups(github: GitHubState, key: string) { + const content = github.feedback?.[key]; + return content + ? [ + { + content: { "+1": "THUMBS_UP", "-1": "THUMBS_DOWN", eyes: "EYES" }[ + content + ], + reactors: { nodes: [{ databaseId: BOT_USER_ID }] }, + }, + ] + : []; +} + +// What the feedback tool and the check suite webhook read to decide +// whether to ask a reviewer again. +function reviewAgainPull(github: GitHubState, reviewer: string) { + const review = github.reviews + .filter( + (item) => + item.user.login.toLowerCase() === reviewer.toLowerCase() && + item.state !== "COMMENTED", + ) + .at(-1); + return { + baseRef: { refUpdateRule: null }, + baseRefName: "main", + commits: { + nodes: [ + { + commit: { + statusCheckRollup: { + contexts: { + nodes: (github.checks ?? []).map((check) => ({ + __typename: "CheckRun", + ...check, + })), + pageInfo: { hasNextPage: false }, + }, + }, + }, + }, + ], + }, + reviewRequests: { + nodes: (github.requestedReviewers ?? []).map((login) => ({ + requestedReviewer: { __typename: "User", login }, + })), + }, + reviews: { + nodes: review + ? [ + { + body: review.body ?? "Please change this.", + databaseId: review.id ?? null, + comments: { + nodes: (review.comments ?? []).map((id) => ({ + databaseId: id, + reactionGroups: graphqlReactionGroups( + github, + `comment:${id}`, + ), + })), + totalCount: review.comments?.length ?? 0, + }, + reactionGroups: graphqlReactionGroups( + github, + `review:${review.id}`, + ), + state: review.state, + }, + ] + : [], + }, + }; +} + export function mockGitHub(github: GitHubState, requests: string[]) { + const reviewOfComment = (id: number) => + github.reviews.find((review) => review.comments?.includes(id)); mswServer.use( http.post( "https://api.github.com/app/installations/456/access_tokens", @@ -295,11 +398,98 @@ export function mockGitHub(github: GitHubState, requests: string[]) { return HttpResponse.json({ ...review, node_id: `PRR_${review?.id}` }); }, ), + // The feedback tool reads one inline comment, and sets its reaction. + http.get( + "https://api.github.com/repos/getsentry/junior/pulls/comments/:id", + ({ params }) => + HttpResponse.json({ + pull_request_url: + "https://api.github.com/repos/getsentry/junior/pulls/946", + user: reviewOfComment(Number(params["id"]))?.user ?? null, + }), + ), + http.get( + "https://api.github.com/repos/getsentry/junior/pulls/comments/:id/reactions", + ({ params }) => { + const content = github.feedback?.[`comment:${String(params["id"])}`]; + return HttpResponse.json( + content ? [{ content, id: 1, user: { id: BOT_USER_ID } }] : [], + ); + }, + ), + http.delete( + "https://api.github.com/repos/getsentry/junior/pulls/comments/:id/reactions/:reaction", + ({ params }) => { + delete github.feedback?.[`comment:${String(params["id"])}`]; + return new HttpResponse(null, { status: 204 }); + }, + ), + http.post( + "https://api.github.com/repos/getsentry/junior/pulls/comments/:id/reactions", + async ({ params, request }) => { + const { content } = (await request.json()) as { content: string }; + (github.feedback ??= {})[`comment:${String(params["id"])}`] = content; + return HttpResponse.json({ content, id: 1 }, { status: 201 }); + }, + ), + http.get( + "https://api.github.com/repos/getsentry/junior/rules/branches/main", + () => { + requests.push("rules"); + return HttpResponse.json( + github.requiredChecks + ? [ + { + parameters: { + required_status_checks: github.requiredChecks.map( + (context) => ({ context }), + ), + }, + type: "required_status_checks", + }, + ] + : [], + ); + }, + ), http.post("https://api.github.com/graphql", async ({ request }) => { const { operationName, variables } = (await request.json()) as { operationName: string; - variables: { before?: string }; + variables: { + before?: string; + content?: string; + reviewer?: string; + subjectId?: string; + }; }; + const reviewKey = `review:${variables.subjectId?.replace("PRR_", "")}`; + if (operationName === "PullRequestReviewAgain") { + requests.push("review again"); + return HttpResponse.json({ + data: { + repository: { + pullRequest: reviewAgainPull(github, variables.reviewer ?? ""), + }, + }, + }); + } + if (operationName === "ReviewReactions") { + return HttpResponse.json({ + data: { + node: { reactionGroups: botReactionGroups(github, reviewKey) }, + }, + }); + } + if (operationName === "AddReviewReaction") { + (github.feedback ??= {})[reviewKey] = + { THUMBS_DOWN: "-1", THUMBS_UP: "+1" }[variables.content ?? ""] ?? + "eyes"; + return HttpResponse.json({ data: { addReaction: {} } }); + } + if (operationName === "RemoveReviewReaction") { + delete github.feedback?.[reviewKey]; + return HttpResponse.json({ data: { removeReaction: {} } }); + } if (operationName === "PullRequestNextAction") { requests.push("pull"); const mergeableState = await readPull(github); @@ -366,6 +556,10 @@ export function mockGitHub(github: GitHubState, requests: string[]) { "https://api.github.com/repos/getsentry/junior/pulls/946/requested_reviewers", async ({ request }) => { const { reviewers } = (await request.json()) as { reviewers: string[] }; + if (github.rejectReviewRequests) { + requests.push(`rejected ${reviewers.join(",")}`); + return HttpResponse.json({}, { status: 503 }); + } requests.push(`request ${reviewers.join(",")}`); github.requestedReviewers = [ ...(github.requestedReviewers ?? []), @@ -377,8 +571,15 @@ export function mockGitHub(github: GitHubState, requests: string[]) { ); } -/** Mark one review body addressed with the feedback tool, as Junior does. */ -export async function markReviewAddressed(reviewId: number): Promise { +/** + * Mark one review body or inline review comment with the feedback tool, as + * Junior does. `state` is the plugin state that the webhook route reads. + */ +export async function markFeedback( + state: PluginState, + target: { id: number; kind: "review" | "review_body" }, + status: "addressed" | "declined" = "addressed", +): Promise { const tool = bindPluginTool( githubPlugin().hooks!.tools!()["updatePullRequestFeedback"], { @@ -387,18 +588,19 @@ export async function markReviewAddressed(reviewId: number): Promise { await fetch(request), }, log: { error() {}, info() {}, warn() {} }, + state, users: { replaceSlackMentions: async (value: unknown) => value }, } as never, ); await tool.execute( { - comment_id: reviewId, - comment_kind: "review_body", + comment_id: target.id, + comment_kind: target.kind, pull_request: 946, repo: "getsentry/junior", - status: "addressed", + status, }, - { toolCallId: `addressed-${reviewId}` }, + { toolCallId: `${status}-${target.kind}-${target.id}` }, ); } @@ -413,6 +615,8 @@ export function route( failures = { close: 0 }, /** Keys of the other closed items, such as from before one item per pull request. */ otherCloses: string[] = [], + /** The plugin state, shared with the feedback tool. */ + state: PluginState = memoryState(), ): PluginRoute { const isReady = (dedupeKey: string) => dedupeKey === DEDUPE_KEY; const inboxItems: PluginConversationInboxItems = { @@ -471,7 +675,7 @@ export function route( events: { hasMatch: async () => false, async publish() {} }, cache: { getOrLoad: unused }, inboxItems, - state: memoryState(), + state, // The requester linked the GitHub account `Requester`. users: { readIdentity: async (identityId: string) => diff --git a/packages/junior-github/tests/pull-request-review-again.test.ts b/packages/junior-github/tests/pull-request-review-again.test.ts index 5df9e4b4c4..21f657c0b0 100644 --- a/packages/junior-github/tests/pull-request-review-again.test.ts +++ b/packages/junior-github/tests/pull-request-review-again.test.ts @@ -1,10 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createGitHubFixture } from "./github-db"; +import { memoryState } from "./plugin-harness"; import { DEDUPE_KEY, PULL_URL, + checkSuiteCompleted, commented, - markReviewAddressed, + markFeedback, mockGitHub, pullRequestAction, reviewRequested, @@ -65,10 +67,11 @@ describe("review again after a change request", () => { } }); - it("asks the requester again after a push that follows their change request", async () => { + it("asks the requester again only after Junior marks every comment of their change request, not after a push", async () => { const fixture = await createGitHubFixture(); const calls: InboxItemCall[] = []; const requests: string[] = []; + const state = memoryState(); const github: GitHubState = { draft: false, mergeableStates: ["blocked"], @@ -80,7 +83,7 @@ describe("review again after a change request", () => { mockGitHub(github, requests); try { await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); - const webhook = route(fixture, calls); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); await webhook.handler(pullRequestAction("review_requested")); expect(calls.at(-1)).toMatchObject({ kind: "upsert", @@ -91,6 +94,7 @@ describe("review again after a change request", () => { github.requestedReviewers = []; github.reviews = [ { + comments: [401], commit_id: "head-1", id: 301, state: "CHANGES_REQUESTED", @@ -109,18 +113,28 @@ describe("review again after a change request", () => { }; expect(calls.at(-1)).toEqual(ended); - // Junior pushes the fix. The requester's change request is on an older - // commit, so the review is wanted again, and GitHub asks for it. + // Junior pushes the fix. A push alone does not ask. github.headSha = "head-2"; requests.length = 0; await webhook.handler(pullRequestAction("synchronize")); - expect(requests).toContain("request Requester"); + expect(requests).not.toContain("request requester"); + expect(calls.at(-1)).toEqual(ended); + + // Junior marks the body. The inline comment is still open. + await markFeedback(state, { id: 301, kind: "review_body" }); + expect(requests).not.toContain("request requester"); + + // Junior marks the last comment, and asks its author to review again. + // GitHub then asks for the review, so the item comes back. + await markFeedback(state, { id: 401, kind: "review" }); + expect(requests).toContain("request requester"); + await webhook.handler(pullRequestAction("review_requested")); expect(calls.at(-1)).toEqual({ conversationId: "slack:C123:1712345.0001", kind: "upsert", notice: { assigneeIdentityIds: ["identity-requester"], - body: `#946 has new commits since you requested changes.\n\n${PULL_URL}`, + body: `Every comment on your change request is handled.\n\n${PULL_URL}`, dedupeKey: DEDUPE_KEY, subject: { id: PULL_URL, @@ -132,14 +146,6 @@ describe("review again after a change request", () => { }, }); - // Junior marks the change request addressed, and asks its author to - // review again. GitHub then asks for the review, so the item stays. - requests.length = 0; - await markReviewAddressed(301); - expect(requests).toEqual(["pull", "reviews", "request requester"]); - await webhook.handler(pullRequestAction("review_requested")); - expect(calls).toHaveLength(3); - // The approval ends the review. github.requestedReviewers = []; github.reviews.push({ @@ -155,10 +161,11 @@ describe("review again after a change request", () => { } }); - it("asks the requester again when Junior replies to their change request with no push, until they reply", async () => { + it("asks the requester again when Junior answers their change request and marks it addressed, until they reply", async () => { const fixture = await createGitHubFixture(); const calls: InboxItemCall[] = []; const requests: string[] = []; + const state = memoryState(); const github: GitHubState = { draft: false, mergeableStates: ["blocked"], @@ -166,6 +173,7 @@ describe("review again after a change request", () => { requestedReviewers: [], reviews: [ { + body: "Why does this need a new table?", commit_id: "head-1", id: 301, state: "CHANGES_REQUESTED", @@ -178,7 +186,7 @@ describe("review again after a change request", () => { mockGitHub(github, requests); try { await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); - const webhook = route(fixture, calls); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); // The requester asks a question with a change request. await webhook.handler( reviewSubmitted("changes_requested", { @@ -188,7 +196,8 @@ describe("review again after a change request", () => { ); expect(calls).toEqual([]); - // A comment by another person changes nothing, and reads nothing. + // Comments by another person and by Junior change nothing, and read + // nothing. A reply alone does not ask. requests.length = 0; await webhook.handler( commented(github, "issue_comment", { @@ -196,36 +205,29 @@ describe("review again after a change request", () => { login: "someone-else", }), ); - expect(requests).toEqual([]); - - // Junior answers in a comment and pushes nothing. The requester's - // review is wanted again, in the Inbox and on GitHub. await webhook.handler( commented(github, "issue_comment", { at: "2026-07-02T11:00:00Z", login: "sentry-junior[bot]", }), ); - expect(requests).toEqual(["pull", "request Requester"]); + expect(requests).toEqual([]); + expect(calls).toEqual([]); + + // Junior marks the answered change request addressed. The requester's + // review is wanted again, on GitHub and in the Inbox. + await markFeedback(state, { id: 301, kind: "review_body" }); + expect(requests).toContain("request requester"); const asked = { conversationId: "slack:C123:1712345.0001", kind: "upsert", - notice: { - assigneeIdentityIds: ["identity-requester"], - body: `#946 has a reply since you requested changes.\n\n${PULL_URL}`, - dedupeKey: DEDUPE_KEY, - subject: { - id: PULL_URL, - title: "Add the Inbox notice (#946)", - url: PULL_URL, - }, + notice: expect.objectContaining({ + body: `Every comment on your change request is handled.\n\n${PULL_URL}`, title: "Review requested · #946", - waitsOnAssignees: true, - }, + }), }; - expect(calls).toEqual([asked]); await webhook.handler( - reviewRequested(github, "Requester", "2026-07-02T11:00:01Z"), + reviewRequested(github, "requester", "2026-07-02T11:00:01Z"), ); expect(calls).toEqual([asked]); @@ -247,21 +249,74 @@ describe("review again after a change request", () => { kind: "close", }); - // Junior replies in the review thread, so the review is wanted again. - // GitHub already asks for it, so Junior does not ask twice. - requests.length = 0; + // Junior's reply in the review thread alone does not ask again. await webhook.handler( commented(github, "pull_request_review_comment", { at: "2026-07-02T13:00:00Z", login: "sentry-junior[bot]", }), ); - expect(calls.at(-1)).toMatchObject({ - kind: "upsert", - notice: { title: "Review requested · #946" }, - }); - expect(calls).toHaveLength(3); - expect(requests).not.toContain("request Requester"); + expect(calls).toHaveLength(2); + } finally { + await fixture.close(); + } + }); + + it("asks once the last inline comment is marked though GitHub's read lags, and retries a rejected request", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const state = memoryState(); + const github: GitHubState = { + checks: [{ conclusion: "SUCCESS", name: "test", status: "COMPLETED" }], + draft: false, + mergeableStates: ["blocked"], + merged: false, + requestedReviewers: [], + requiredChecks: ["test"], + reviews: [ + { + body: "", + comments: [401, 402], + commit_id: "head-1", + id: 301, + state: "CHANGES_REQUESTED", + user: { login: "requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); + await webhook.handler(reviewSubmitted("changes_requested")); + await markFeedback(state, { id: 401, kind: "review" }); + expect(requests).not.toContain("request requester"); + + // GitHub's read does not show the last mark yet, and GitHub rejects + // the request. Nothing asks, and the ask waits. + github.laggingFeedback = ["comment:402"]; + github.rejectReviewRequests = true; + await markFeedback(state, { id: 402, kind: "review" }); + expect(requests).toContain("rejected requester"); + expect(requests).not.toContain("request requester"); + + // The next webhook asks again, though the read still lags, and the + // item says why. + github.rejectReviewRequests = false; + await webhook.handler(checkSuiteCompleted()); + expect(requests).toContain("request requester"); + expect(calls).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + kind: "upsert", + notice: expect.objectContaining({ + body: `Every comment on your change request is handled.\n\n${PULL_URL}`, + title: "Review requested · #946", + }), + }, + ]); } finally { await fixture.close(); } @@ -270,6 +325,7 @@ describe("review again after a change request", () => { it("asks the requester again when a change request is addressed with no push", async () => { const fixture = await createGitHubFixture(); const calls: InboxItemCall[] = []; + const state = memoryState(); const github: GitHubState = { draft: false, mergeableStates: ["blocked"], @@ -288,21 +344,21 @@ describe("review again after a change request", () => { mockGitHub(github, []); try { await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); - const webhook = route(fixture, calls); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); // The change request is on the head commit, so nothing is new yet. await webhook.handler(reviewSubmitted("changes_requested")); expect(calls).toEqual([]); // Junior answers without a push, such as when the code was already // right. GitHub asks the requester again, and the item comes back. - await markReviewAddressed(301); + await markFeedback(state, { id: 301, kind: "review_body" }); await webhook.handler(pullRequestAction("review_requested")); expect(calls).toEqual([ { conversationId: "slack:C123:1712345.0001", kind: "upsert", notice: expect.objectContaining({ - body: `GitHub asks you to review #946.\n\n${PULL_URL}`, + body: `Every comment on your change request is handled.\n\n${PULL_URL}`, title: "Review requested · #946", }), }, @@ -312,6 +368,197 @@ describe("review again after a change request", () => { } }); + it("replays getsentry/junior#3941: asks again only when every comment of the latest change request is marked and the required checks pass", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const at = (time: string) => `2026-11-21T${time}Z`; + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const state = memoryState(); + const passing = [ + { conclusion: "SUCCESS", name: "test", status: "COMPLETED" }, + ]; + const pending = [{ conclusion: null, name: "test", status: "IN_PROGRESS" }]; + const github: GitHubState = { + checks: passing, + draft: false, + headSha: "head-1", + mergeableStates: ["blocked"], + merged: false, + requestedReviewers: [], + requiredChecks: ["test"], + reviews: [], + state: "open", + }; + mockGitHub(github, requests); + const asks = () => + requests.filter((request) => request.startsWith("request ")); + const push = async (headSha: string, time: string) => { + vi.setSystemTime(new Date(at(time))); + github.headSha = headSha; + github.checks = pending; + await webhook.handler(pullRequestAction("synchronize")); + }; + const requestChanges = async ( + review: Omit, + time: string, + ) => { + vi.setSystemTime(new Date(at(time))); + github.reviews.push({ + ...review, + state: "CHANGES_REQUESTED", + submitted_at: at(time), + user: { login: "Requester" }, + }); + await webhook.handler( + reviewSubmitted("changes_requested", { + at: at(time), + login: "Requester", + }), + ); + }; + const mark = async ( + target: { id: number; kind: "review" | "review_body" }, + time: string, + status: "addressed" | "declined" = "addressed", + ) => { + vi.setSystemTime(new Date(at(time))); + await markFeedback(state, target, status); + }; + const webhook = route(fixture, calls, [], { close: 0 }, [], state); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + + // 17:48 The requester requests changes in a body and two comments. + await requestChanges( + { + body: "A few things.", + comments: [401, 402], + commit_id: "head-1", + id: 301, + }, + "17:48:00", + ); + // 17:50 Junior merges main into the branch. A sync push asks nothing. + await push("head-2", "17:50:00"); + expect(asks()).toEqual([]); + expect(calls).toEqual([]); + + // Junior marks the body and one comment. One comment is still open. + await mark({ id: 301, kind: "review_body" }, "17:58:00"); + await mark({ id: 401, kind: "review" }, "17:59:00"); + expect(asks()).toEqual([]); + + // 18:01:20 A commit lands. 18:02:01 The requester requests changes + // again, on the older head that they reviewed. + await push("head-3", "18:01:20"); + await requestChanges( + { body: "", comments: [403], commit_id: "head-2", id: 302 }, + "18:02:01", + ); + expect(asks()).toEqual([]); + + // Junior finishes the first change request. It is no longer the + // latest, so the new comment is still open. + await mark({ id: 402, kind: "review" }, "18:05:00"); + expect(asks()).toEqual([]); + + // 18:34 A fix lands. Junior declines the last comment while the + // checks run, so the ask waits for them. + await push("head-4", "18:34:00"); + await mark({ id: 403, kind: "review" }, "18:34:30", "declined"); + expect(asks()).toEqual([]); + + // 18:36 Junior merges main again, and the checks fail. + await push("head-5", "18:36:00"); + github.checks = [ + { conclusion: "FAILURE", name: "test", status: "COMPLETED" }, + ]; + await webhook.handler(checkSuiteCompleted("failure")); + expect(asks()).toEqual([]); + expect(calls).toEqual([]); + + // Junior fixes the checks. When they pass, the requester is asked. + await push("head-6", "18:45:00"); + expect(asks()).toEqual([]); + vi.setSystemTime(new Date(at("18:50:00"))); + github.checks = passing; + await webhook.handler(checkSuiteCompleted()); + expect(asks()).toEqual(["request Requester"]); + expect(calls).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + kind: "upsert", + notice: expect.objectContaining({ + body: `Checks now pass, and every comment is handled.\n\n${PULL_URL}`, + title: "Review requested · #946", + }), + }, + ]); + + // GitHub's review request keeps the item, and asks nothing twice. + await webhook.handler( + reviewRequested(github, "Requester", at("18:50:01")), + ); + await webhook.handler(checkSuiteCompleted()); + expect(asks()).toEqual(["request Requester"]); + expect(calls).toHaveLength(1); + } finally { + vi.useRealTimers(); + await fixture.close(); + } + }); + + it("drops an ask that waits for the checks when the requester comments first", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const state = memoryState(); + const github: GitHubState = { + checks: [{ conclusion: null, name: "test", status: "QUEUED" }], + draft: false, + mergeableStates: ["blocked"], + merged: false, + requestedReviewers: [], + requiredChecks: ["test"], + reviews: [ + { + commit_id: "head-1", + id: 301, + state: "CHANGES_REQUESTED", + submitted_at: "2026-07-02T10:00:00Z", + user: { login: "requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); + vi.setSystemTime(new Date("2026-07-02T11:00:00Z")); + await markFeedback(state, { id: 301, kind: "review_body" }); + // The requester asks something more before the checks pass. Junior + // acts next, so the waiting ask ends. + await webhook.handler( + commented(github, "issue_comment", { + at: "2026-07-02T11:05:00Z", + login: "Requester", + }), + ); + github.checks = [ + { conclusion: "SUCCESS", name: "test", status: "COMPLETED" }, + ]; + await webhook.handler(checkSuiteCompleted()); + expect(requests).not.toContain("request requester"); + expect(calls).toEqual([]); + } finally { + vi.useRealTimers(); + await fixture.close(); + } + }); + it.each([ { name: "an approval", @@ -340,6 +587,7 @@ describe("review again after a change request", () => { const fixture = await createGitHubFixture(); const calls: InboxItemCall[] = []; const requests: string[] = []; + const state = memoryState(); const github: GitHubState = { autoMerge, draft: false, @@ -356,9 +604,9 @@ describe("review again after a change request", () => { mockGitHub(github, requests); try { await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); - const webhook = route(fixture, calls); + const webhook = route(fixture, calls, [], { close: 0 }, [], state); await webhook.handler(reviewSubmitted(webhookState)); - await markReviewAddressed(301); + await markFeedback(state, { id: 301, kind: "review_body" }); github.headSha = "head-2"; await webhook.handler(pullRequestAction("synchronize")); expect(requests).not.toContain("request requester"); diff --git a/packages/junior/scripts/tool-error-classification-baseline.txt b/packages/junior/scripts/tool-error-classification-baseline.txt index 20bed918f1..a0fd3064c1 100644 --- a/packages/junior/scripts/tool-error-classification-baseline.txt +++ b/packages/junior/scripts/tool-error-classification-baseline.txt @@ -37,6 +37,7 @@ packages/junior-github/src/tools/update-pull-request-feedback.ts throw new Error packages/junior-github/src/tools/update-pull-request-feedback.ts throw new Error(message); packages/junior-github/src/tools/update-pull-request-feedback.ts throw new Error("GitHub comment did not name its issue or pull request."); packages/junior-github/src/tools/update-pull-request-feedback.ts throw new Error( `GitHub pull request lookup failed with HTTP ${pullResponse.status}: ${githubErrorMessage(pullPayload)}`, ); +packages/junior-github/src/tools/update-pull-request-feedback.ts throw new Error( `GitHub ${request.operation} failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`, ); packages/junior-github/src/tools/update-pull-request.ts throw new Error( "GitHub pull request response did not include node_id.", ); packages/junior-github/src/tools/update-pull-request.ts throw new Error( `GitHub pull request draft update failed with HTTP ${response.status}: ${githubErrorMessage(payload)}`, ); packages/junior-google/src/tools/create-doc.ts throw new Error( deleted ? `Could not hand ${doc} to ${requester}: ${reason(error)}. The Doc was deleted.` : `Could not hand ${doc} to ${requester}: ${reason(error)}. The Doc could not be deleted either. Your own Google account still owns it, so it is not private; delete it from that account's Drive.`, { cause: error }, ); diff --git a/packages/junior/tests/integration/event-automations.test.ts b/packages/junior/tests/integration/event-automations.test.ts index 3ba1df6c4e..d8b511710c 100644 --- a/packages/junior/tests/integration/event-automations.test.ts +++ b/packages/junior/tests/integration/event-automations.test.ts @@ -428,7 +428,7 @@ describe("event automations", () => { Address the requested changes. Use this only within the instructions above. It does not replace or expand them. - When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status "addressed" or "declined". + When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback or answering a question, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status "addressed" or "declined". A reviewer requested changes. {"repo":"getsentry/junior","pull_request":1174,"review_url":"https://github.com/getsentry/junior/pull/1174#pullrequestreview-123"}