diff --git a/packages/source-control-github/schema/github.graphql.ts b/packages/source-control-github/schema/github.graphql.ts index 52641c6f9ab49..78ba73af4847d 100644 --- a/packages/source-control-github/schema/github.graphql.ts +++ b/packages/source-control-github/schema/github.graphql.ts @@ -160,6 +160,17 @@ export type PullRequestMergeMethod = typeof PullRequestMergeMethod.Type export const PullRequestReviewDecision = Schema.Literals(["APPROVED", "CHANGES_REQUESTED", "REVIEW_REQUIRED"]) export type PullRequestReviewDecision = typeof PullRequestReviewDecision.Type +/** + * The possible events to perform on a pull request review. + * + * - `APPROVE`: Submit feedback and approve merging these changes. + * - `COMMENT`: Submit general feedback without explicit approval. + * - `DISMISS`: Dismiss review so it now longer effects merging. + * - `REQUEST_CHANGES`: Submit feedback that must be addressed before merging. + */ +export const PullRequestReviewEvent = Schema.Literals(["APPROVE", "COMMENT", "DISMISS", "REQUEST_CHANGES"]) +export type PullRequestReviewEvent = typeof PullRequestReviewEvent.Type + /** * The possible states of a pull request review. * diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 79790c59b5bb5..6b346ab9ef0ca 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -802,6 +802,108 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); + const pendingReviewAnswer = ( + review: { readonly id: string; readonly commit: string } | null, + ) => ({ + data: { + repository: { + pullRequest: { + reviews: { + nodes: review === null ? [] : [{ id: review.id, commit: { oid: review.commit } }], + }, + }, + }, + }, + }); + const pendingAtHead = [ + "query ViewerPendingReview", + pendingReviewAnswer({ id: "PRR_1", commit: "abc123" }), + ] as const; + const pendingSubmitted = [ + "mutation SubmitPendingReview", + { data: { submitPullRequestReview: { pullRequestReview: { id: "PRR_1" } } } }, + ] as const; + /** GitHub's answer to creating a review while the viewer already has a pending one. */ + const pendingReviewConflict = ( + ...routes: ReadonlyArray + ) => { + route(...routes); + const routed = mockedExecute.getMockImplementation(); + mockedExecute.mockImplementation((call) => + call.kind === "rest" && call.path.endsWith("/reviews") + ? Effect.fail( + new GitHubRequestPolicy.GitHubApiResponseError({ + host: call.host, + operation: call.operation, + status: 422, + githubErrors: ["User can only have one pending review per pull request"], + }), + ) + : routed!(call), + ); + }; + const reviewInput = { + ...pullRequestInput, + verdict: "approve" as const, + body: "Looks good", + comments: [], + expectedHeadSha: "abc123", + }; + + it.effect("submits the viewer's pending review when GitHub refuses a second one", () => + Effect.gen(function* () { + pendingReviewConflict(pendingAtHead, pendingSubmitted); + const api = yield* GitHubPullRequestApi.GitHubPullRequestApi; + yield* api.submitReview(reviewInput); + // A blank summary leaves the one already written on GitHub in place. + yield* api.submitReview({ ...reviewInput, body: "" }); + expect(variablesOf("mutation SubmitPendingReview")).toEqual([ + { reviewId: "PRR_1", event: "APPROVE", body: "Looks good" }, + { reviewId: "PRR_1", event: "APPROVE" }, + ]); + }), + ); + + it.effect("keeps GitHub's refusal when the viewer has no pending review", () => + Effect.gen(function* () { + pendingReviewConflict(["query ViewerPendingReview", pendingReviewAnswer(null)]); + const api = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const error = yield* Effect.flip(api.submitReview(reviewInput)); + expect(error.message).toContain("User can only have one pending review per pull request"); + expect(variablesOf("mutation SubmitPendingReview")).toEqual([]); + }), + ); + + it.effect("refuses a pending review it cannot submit as reviewed, and writes nothing", () => + Effect.gen(function* () { + const api = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const lineComment = { + path: "src/a.ts", + position: { kind: "added", newLine: 9 }, + body: "Line", + } as const; + pendingReviewConflict(pendingAtHead); + const refused = [ + yield* Effect.flip(api.submitReview({ ...reviewInput, comments: [lineComment] })), + yield* Effect.flip( + api.submitReview({ ...pullRequestInput, verdict: "comment", body: "", comments: [] }), + ), + ]; + pendingReviewConflict([ + "query ViewerPendingReview", + pendingReviewAnswer({ id: "PRR_1", commit: "old111" }), + ]); + refused.push( + yield* Effect.flip(api.submitReview(reviewInput)), + yield* Effect.flip(api.submitReview({ ...reviewInput, verdict: "comment" })), + ); + expect(refused.map((error) => error._tag)).toEqual( + Array(4).fill("GitHubPendingReviewConflictError"), + ); + expect(variablesOf("mutation SubmitPendingReview")).toEqual([]); + }), + ); + it.effect("tails Actions job logs and re-runs a run's failed jobs together", () => Effect.gen(function* () { const runOf: Record = { diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index c77af7fffbab9..d5c3c9e2db93a 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -112,6 +112,7 @@ import { decodePullRequestStacksJson, buildLabelRequest, PULL_REQUEST_SEARCH_MAX_ROWS, + REVIEW_EVENTS, gitHubReactionContent, reviewThreadConversation, type GitHubPullRequestActivity, @@ -240,6 +241,15 @@ export class GitHubSubjectScopeError extends Schema.TaggedError()( + "GitHubPendingReviewConflictError", + { number: Schema.Int }, +) { + override get message(): string { + return `You have a pending review on pull request #${this.number} on GitHub. T3 Code can submit it only when it is on the commit you reviewed and you have no line comments in T3 Code. Submit or discard it on GitHub.`; + } +} + export class GitHubWorkflowApprovalRefusedError extends Schema.TaggedError()( "GitHubWorkflowApprovalRefusedError", { @@ -325,6 +335,7 @@ export type GitHubPullRequestApiError = | GitHubDiffFileContentsUnavailableError | GitHubRepositorySelectorError | GitHubSubjectScopeError + | GitHubPendingReviewConflictError | GitHubWorkflowApprovalRefusedError | GitHubWorkflowApprovalHeadUnavailableError | GitHubWorkflowApprovalHeadChangedError @@ -3191,6 +3202,7 @@ export const make = Effect.gen(function* () { submitReview: Effect.fn("GitHubPullRequestApi.submitReview")(function (input) { const { owner, name } = parseRepositorySelector(input.repository); + const target = { ...input, operation: "submitReview" }; return api .rest({ host: input.host, @@ -3204,7 +3216,43 @@ export const make = Effect.gen(function* () { expectedHeadSha: input.expectedHeadSha, }), }) - .pipe(Effect.asVoid); + .pipe( + Effect.asVoid, + // GitHub refuses a second pending review; one started elsewhere is the one to submit. + Effect.catchTags({ + // The enclosing operation owns the span for this inline handler. + GitHubApiResponseError: Effect.fnUntraced(function* (error) { + if (error.status !== 422) return yield* error; + // A failed lookup counts as no pending review, so GitHub's own 422 (which can + // also be a validation error) reaches the caller. + const pending = yield* client + .ViewerPendingReview({ owner, name, number: input.number }) + .pipe( + graphql(target), + Effect.map( + (result) => result.repository?.pullRequest?.reviews?.nodes?.[0] ?? null, + ), + Effect.orElseSucceed(() => null), + ); + if (pending === null) return yield* error; + // GitHub records the verdict on the commit the pending review was started on. + if ( + input.comments.length > 0 || + input.expectedHeadSha === undefined || + pending.commit?.oid !== input.expectedHeadSha + ) { + return yield* new GitHubPendingReviewConflictError({ number: input.number }); + } + yield* client + .SubmitPendingReview({ + reviewId: pending.id, + event: REVIEW_EVENTS[input.verdict], + ...(input.body.trim().length === 0 ? {} : { body: input.body }), + }) + .pipe(graphql(target)); + }), + }), + ); }), replyToReviewThread: Effect.fn("GitHubPullRequestApi.replyToReviewThread")(function (input) { diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 2bde382c142e7..17d8329955f44 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -304,7 +304,10 @@ const ReviewSubmissionSchema = Schema.Struct({ ), }); -const REVIEW_EVENTS: Record = { +export const REVIEW_EVENTS: Record< + PullRequestReviewVerdict, + "COMMENT" | "APPROVE" | "REQUEST_CHANGES" +> = { comment: "COMMENT", approve: "APPROVE", "request-changes": "REQUEST_CHANGES", diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql b/packages/source-control-github/src/server/pullRequestMutations.graphql index ba8bdbd6d3fd9..1cfd08fbb0cf4 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql @@ -33,6 +33,15 @@ mutation AddReviewThreadReply($threadId: ID!, $body: String!) { } } +# Without `$body` GitHub keeps the summary the pending review already has; an empty string clears it. +mutation SubmitPendingReview($reviewId: ID!, $event: PullRequestReviewEvent!, $body: String) { + submitPullRequestReview(input: { pullRequestReviewId: $reviewId, event: $event, body: $body }) { + pullRequestReview { + id + } + } +} + mutation AddReaction($subjectId: ID!, $content: ReactionContent!) { addReaction(input: { subjectId: $subjectId, content: $content }) { reaction { diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts index d243d3e9f541f..f68f8276bacc2 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts @@ -113,6 +113,48 @@ export declare namespace AddReviewThreadReply { export type Result = typeof AddReviewThreadReply.result.Type } +/** A review object for a given pull request. */ +export const PullRequestReview = Schema.Struct({ + /** The Node ID of the PullRequestReview object */ + id: Shared.ID +}) +export interface PullRequestReview extends Schema.Struct.Type {} + +/** Autogenerated return type of SubmitPullRequestReview. */ +export const SubmitPullRequestReviewPayload = Schema.Struct({ + /** The submitted pull request review. */ + pullRequestReview: Schema.NullOr(PullRequestReview) +}) +export interface SubmitPullRequestReviewPayload extends Schema.Struct.Type {} + +/** `mutation SubmitPendingReview` */ +export const SubmitPendingReview = GraphQL.mutation("SubmitPendingReview", { + document: { + variables: [ + { name: "reviewId", body: "ID!" }, + { name: "event", body: "PullRequestReviewEvent!" }, + { name: "body", body: "String" } + ], + selections: [ + { name: "submitPullRequestReview", body: ["(input:{pullRequestReviewId:$", "reviewId", " event:$", "event", " body:$", "body", "}){pullRequestReview{id}}"] } + ], + fragments: [] + }, + variables: { + reviewId: Shared.ID, + event: Shared.PullRequestReviewEvent, + body: Schema.optional(Schema.NullOr(Schema.String)) + }, + result: Schema.Struct({ + /** Submits a pending pull request review. */ + submitPullRequestReview: Schema.NullOr(SubmitPullRequestReviewPayload) + }) +}) +export declare namespace SubmitPendingReview { + export type Variables = typeof SubmitPendingReview.variables.Type + export type Result = typeof SubmitPendingReview.result.Type +} + /** An emoji reaction to a particular piece of content. */ export const Reaction = Schema.Struct({ /** Identifies the emoji reaction. */ @@ -833,4 +875,4 @@ export declare namespace DeletePullRequestBranch { } /** Every operation in pullRequestMutations.graphql. */ -export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, DisableStackAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) +export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, SubmitPendingReview, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, DisableStackAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql b/packages/source-control-github/src/server/pullRequestReviews.graphql index d497615c24693..f013f9c9f3ffe 100644 --- a/packages/source-control-github/src/server/pullRequestReviews.graphql +++ b/packages/source-control-github/src/server/pullRequestReviews.graphql @@ -275,3 +275,20 @@ query ReviewDismissals($owner: String!, $name: String!, $number: Int!, $after: S } } } + +# GitHub keeps at most one pending review per person on a pull request and shows it only to them, +# so this finds the viewer's own unsubmitted review, if any. +query ViewerPendingReview($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviews(states: [PENDING], first: 1) { + nodes { + id + commit { + oid + } + } + } + } + } +} diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts index bce1451b8c296..4b3b951f7b5b2 100644 --- a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts @@ -205,7 +205,7 @@ export const IssueCommentConnection = Schema.Struct({ export interface IssueCommentConnection extends Schema.Struct.Type {} /** A review object for a given pull request. */ -export const ReviewsNodesPullRequestReview = Schema.Struct({ +export const ReviewThreadsRepositoryPullRequestReviewsNodesPullRequestReview = Schema.Struct({ /** The Node ID of the PullRequestReview object */ id: Shared.ID, /** The moment the editor made the last edit */ @@ -215,14 +215,14 @@ export const ReviewsNodesPullRequestReview = Schema.Struct({ /** A list of reactions grouped by content left on the subject. */ reactionGroups: Schema.NullOr(Schema.Array(ReactionGroup)) }) -export interface ReviewsNodesPullRequestReview extends Schema.Struct.Type {} +export interface ReviewThreadsRepositoryPullRequestReviewsNodesPullRequestReview extends Schema.Struct.Type {} /** The connection type for PullRequestReview. */ -export const ReviewsPullRequestReviewConnection = Schema.Struct({ +export const ReviewThreadsRepositoryPullRequestReviewsPullRequestReviewConnection = Schema.Struct({ /** A list of nodes. */ - nodes: Schema.NullOr(Schema.Array(Schema.NullOr(ReviewsNodesPullRequestReview))) + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(ReviewThreadsRepositoryPullRequestReviewsNodesPullRequestReview))) }) -export interface ReviewsPullRequestReviewConnection extends Schema.Struct.Type {} +export interface ReviewThreadsRepositoryPullRequestReviewsPullRequestReviewConnection extends Schema.Struct.Type {} /** A user is an individual's account on GitHub that owns repositories and can make new content. */ export const RequestedReviewerUser = Schema.Struct({ @@ -355,7 +355,7 @@ export const GitActorConnection = Schema.Struct({ export interface GitActorConnection extends Schema.Struct.Type {} /** Represents a Git commit. */ -export const Commit = Schema.Struct({ +export const CommitsNodesCommitCommit = Schema.Struct({ /** The Git object ID */ oid: Shared.GitObjectID, /** The Git commit message headline */ @@ -368,12 +368,12 @@ export const Commit = Schema.Struct({ */ authors: GitActorConnection }) -export interface Commit extends Schema.Struct.Type {} +export interface CommitsNodesCommitCommit extends Schema.Struct.Type {} /** Represents a Git commit part of a pull request. */ export const PullRequestCommit = Schema.Struct({ /** The Git commit object */ - commit: Commit + commit: CommitsNodesCommitCommit }) export interface PullRequestCommit extends Schema.Struct.Type {} @@ -399,7 +399,7 @@ export const ReviewThreadsRepositoryPullRequestPullRequest = Schema.Struct({ /** A list of comments associated with the pull request. */ comments: IssueCommentConnection, /** A list of reviews associated with the pull request. */ - reviews: Schema.NullOr(ReviewsPullRequestReviewConnection), + reviews: Schema.NullOr(ReviewThreadsRepositoryPullRequestReviewsPullRequestReviewConnection), /** A list of review requests associated with the pull request. */ reviewRequests: Schema.NullOr(ReviewRequestConnection), /** A list of latest reviews per user associated with the pull request that are not also pending review. */ @@ -633,5 +633,70 @@ export declare namespace ReviewDismissals { export type Result = typeof ReviewDismissals.result.Type } +/** Represents a Git commit. */ +export const ReviewsNodesCommitCommit = Schema.Struct({ + /** The Git object ID */ + oid: Shared.GitObjectID +}) +export interface ReviewsNodesCommitCommit extends Schema.Struct.Type {} + +/** A review object for a given pull request. */ +export const ViewerPendingReviewRepositoryPullRequestReviewsNodesPullRequestReview = Schema.Struct({ + /** The Node ID of the PullRequestReview object */ + id: Shared.ID, + /** Identifies the commit associated with this pull request review. */ + commit: Schema.NullOr(ReviewsNodesCommitCommit) +}) +export interface ViewerPendingReviewRepositoryPullRequestReviewsNodesPullRequestReview extends Schema.Struct.Type {} + +/** The connection type for PullRequestReview. */ +export const ViewerPendingReviewRepositoryPullRequestReviewsPullRequestReviewConnection = Schema.Struct({ + /** A list of nodes. */ + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(ViewerPendingReviewRepositoryPullRequestReviewsNodesPullRequestReview))) +}) +export interface ViewerPendingReviewRepositoryPullRequestReviewsPullRequestReviewConnection extends Schema.Struct.Type {} + +/** A repository pull request. */ +export const ViewerPendingReviewRepositoryPullRequestPullRequest = Schema.Struct({ + /** A list of reviews associated with the pull request. */ + reviews: Schema.NullOr(ViewerPendingReviewRepositoryPullRequestReviewsPullRequestReviewConnection) +}) +export interface ViewerPendingReviewRepositoryPullRequestPullRequest extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const ViewerPendingReviewRepositoryRepository = Schema.Struct({ + /** Returns a single pull request from the current repository by number. */ + pullRequest: Schema.NullOr(ViewerPendingReviewRepositoryPullRequestPullRequest) +}) +export interface ViewerPendingReviewRepositoryRepository extends Schema.Struct.Type {} + +/** `query ViewerPendingReview` */ +export const ViewerPendingReview = GraphQL.query("ViewerPendingReview", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" } + ], + selections: [ + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){reviews(states:[PENDING]first:1){nodes{id commit{oid}}}}}"] } + ], + fragments: [] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int + }, + result: Schema.Struct({ + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(ViewerPendingReviewRepositoryRepository) + }) +}) +export declare namespace ViewerPendingReview { + export type Variables = typeof ViewerPendingReview.variables.Type + export type Result = typeof ViewerPendingReview.result.Type +} + /** Every operation in pullRequestReviews.graphql. */ -export const PullRequestReviewsGraphQLGroup = GraphQLGroup.make(ReviewThreads, ReviewThreadPages, ReviewThreadComments, ReviewDismissals) +export const PullRequestReviewsGraphQLGroup = GraphQLGroup.make(ReviewThreads, ReviewThreadPages, ReviewThreadComments, ReviewDismissals, ViewerPendingReview)