#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix waiting-for-author label application (#8583)
James Bruntonc85a1475339a
diff --git a/.github/scripts/github.ts b/.github/scripts/github.tsindex 2929a1cb07..050e2ff476 100644--- a/.github/scripts/github.ts+++ b/.github/scripts/github.ts@@ -26,8 +26,6 @@ export type IssueRef = Repo & { issue_number: number };export interface PullData {mergeable: boolean | null;mergeable_state: string;- labels: { name: string }[];- head: { ref: string; repo: { full_name: string } | null };}/** The parts of github-script's `github` client these scripts call. */diff --git a/.github/scripts/pr-turn.test.ts b/.github/scripts/pr-turn.test.tsindex 47c2241771..97ab45e85f 100644--- a/.github/scripts/pr-turn.test.ts+++ b/.github/scripts/pr-turn.test.ts@@ -2,32 +2,22 @@ import assert from "node:assert/strict";import { describe, it } from "node:test";import { type GitHubClient, LABELS } from "./github.ts";-import {- clearStaleTurnLabel,- type ReviewNode,- type TimelineItem,- turnChangeForEvent,- type TurnPayload,- updateTurnLabel,-} from "./pr-turn.ts";+import { answeredPull, type ReviewNode, syncTurnLabel, type TimelineItem, type TurnPayload, updateTurnLabel } from "./pr-turn.ts";type TurnItem = ReviewNode | TimelineItem;const AUTHOR = "contributor";const HEAD = "head-sha";-const FORK = "contributor/r";-const BRANCH = "feature";const NOW = Date.parse("2026-10-01T12:00:00Z");const repo = { owner: "o", repo: "r" };+const issue = { ...repo, issue_number: 7 };interface FakeOptions {- labelled?: boolean;alreadyRemoved?: boolean;- missing?: boolean;pageSize?: number;}-function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved = false, missing = false, pageSize = 100 }: FakeOptions = {}) {+function fakeGitHub(items: TurnItem[] = [], { alreadyRemoved = false, pageSize = 100 }: FakeOptions = {}) {const calls: string[] = [];const reads = { pages: 0 };const github: GitHubClient = {@@ -58,11 +48,7 @@ function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved =updateComment: async () => assert.fail("no comment edits"),},pulls: {- get: async () => {- if (missing) throw Object.assign(new Error("Not Found"), { status: 404 });- const labels = labelled ? [{ name: LABELS.waitingOnAuthor }] : [];- return { data: { mergeable: null, mergeable_state: "unknown", labels, head: { ref: BRANCH, repo: { full_name: FORK } } } };- },+ get: async () => assert.fail("no PR reads"),update: async () => assert.fail("no closes"),listFiles: async () => assert.fail("no file lists"),},@@ -98,144 +84,122 @@ const commentBy = (login: string, onPullRequest = true): TurnPayload => ({issue: { number: 7, user: { login: AUTHOR }, ...(onPullRequest ? { pull_request: {} } : {}) },comment: { user: { login } },});-const relayRun = ({ title = "Review on #7", event = "pull_request_review", headRepo = FORK, headBranch = BRANCH } = {}): TurnPayload => ({- workflow_run: { event, display_title: title, head_branch: headBranch, head_repository: { full_name: headRepo } },-});-const changeFor = (payload: TurnPayload, items: TurnItem[] = [], options: FakeOptions = {}) =>- turnChangeForEvent(fakeGitHub(items, options).github, { repo, payload });+async function sync(items: TurnItem[], { labelled = false, live = true } = {}) {+ const { github, calls } = fakeGitHub(items);+ return { waiting: await syncTurnLabel(github, issue, labelled, live), calls };+}++const ADDED = ["label #7 waiting-on-author"];+const REMOVED = ["unlabel #7 waiting-on-author"];-describe("turn change for an author's event", () => {- it("hands the turn back when the author pushes, re-requests review or marks it ready", async () => {- assert.deepEqual(await changeFor(pushBy(AUTHOR)), { number: 7, add: false });+describe("answered pull", () => {+ it("hands the turn back when the author pushes, re-requests review or marks it ready", () => {+ assert.equal(answeredPull(pushBy(AUTHOR)), 7);});- it("ignores a maintainer's push, such as Update branch", async () => {- assert.equal(await changeFor(pushBy("maintainer")), null);+ it("ignores a maintainer's push, such as Update branch", () => {+ assert.equal(answeredPull(pushBy("maintainer")), null);});- it("hands the turn back when the author comments", async () => {- assert.deepEqual(await changeFor(commentBy(AUTHOR)), { number: 7, add: false });+ it("hands the turn back when the author comments", () => {+ assert.equal(answeredPull(commentBy(AUTHOR)), 7);});- it("ignores someone else's comment, and comments on issues", async () => {- assert.equal(await changeFor(commentBy("maintainer")), null);- assert.equal(await changeFor(commentBy(AUTHOR, false)), null);+ it("ignores someone else's comment, and comments on issues", () => {+ assert.equal(answeredPull(commentBy("maintainer")), null);+ assert.equal(answeredPull(commentBy(AUTHOR, false)), null);});});-describe("turn change for a relayed review", () => {+describe("update turn label", () => {+ const core = { info: () => {} };++ it("removes the label, and does not mind when it is not there", async () => {+ const present = fakeGitHub();+ await updateTurnLabel({ github: present.github, context: { repo, payload: pushBy(AUTHOR) }, core });+ assert.deepEqual(present.calls, REMOVED);++ const absent = fakeGitHub([], { alreadyRemoved: true });+ await updateTurnLabel({ github: absent.github, context: { repo, payload: pushBy(AUTHOR) }, core });+ assert.deepEqual(absent.calls, []);+ });++ it("leaves the label for an event that is not the author's", async () => {+ const { github, calls } = fakeGitHub();+ await updateTurnLabel({ github, context: { repo, payload: commentBy("maintainer") }, core });+ assert.deepEqual(calls, []);+ });+});++describe("sync turn label", () => {it("gives the author the turn on a changes-requested review from someone who can push", async () => {- assert.deepEqual(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 1)]), { number: 7, add: true });+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "maintainer", true, 1)]), { waiting: true, calls: ADDED });});it("ignores changes requested by someone who cannot push, or by a bot", async () => {- assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "passer-by", false, 1)]), null);- assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "review-bot", true, 1, HEAD, "Bot")]), null);+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "passer-by", false, 1)]), { waiting: false, calls: [] });+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "review-bot", true, 1, HEAD, "Bot")]), { waiting: false, calls: [] });});it("hands the turn back on an approval from someone who can push", async () => {const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("APPROVED", "maintainer", true, 1)];- assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ assert.deepEqual(await sync(items, { labelled: true }), { waiting: false, calls: REMOVED });});it("ignores approvals from someone who cannot push, and comment-only reviews", async () => {const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9)];- assert.equal(await changeFor(relayRun(), [...items, review("APPROVED", "passer-by", false, 1)], { labelled: true }), null);- assert.equal(await changeFor(relayRun(), [...items, review("COMMENTED", "maintainer", true, 1)], { labelled: true }), null);+ const stillWaiting = { waiting: true, calls: [] };+ assert.deepEqual(await sync([...items, review("APPROVED", "passer-by", false, 1)], { labelled: true }), stillWaiting);+ assert.deepEqual(await sync([...items, review("COMMENTED", "maintainer", true, 1)], { labelled: true }), stillWaiting);});- it("hands the turn back when the author replies in a review", async () => {+ it("hands the turn back when the author replies in a review or a review thread", async () => {const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];- assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ assert.deepEqual(await sync(items, { labelled: true }), { waiting: false, calls: REMOVED });});it("hands the turn back when a changes-requested review is dismissed", async () => {const items = [review("DISMISSED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), dismissal(1)];- assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ assert.deepEqual(await sync(items, { labelled: true }), { waiting: false, calls: REMOVED });});- it("goes by the latest review, whichever run arrives first", async () => {+ it("goes by the latest review", async () => {const items = [review("CHANGES_REQUESTED", "maintainer", true, 2), review("APPROVED", "other-maintainer", true, 1)];- assert.equal(await changeFor(relayRun(), items), null);+ assert.deepEqual(await sync(items), { waiting: false, calls: [] });});- it("does not add the label when the author answered before the run", async () => {- assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 2, "older-sha")]), null);- assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 2), comment(AUTHOR, 1)]), null);+ it("does not add the label when the author answered before the triage ran", async () => {+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "maintainer", true, 2, "older-sha")]), { waiting: false, calls: [] });+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "maintainer", true, 2), comment(AUTHOR, 1)]), { waiting: false, calls: [] });});it("keeps a label added by hand", async () => {- assert.equal(await changeFor(relayRun(), [review("APPROVED", "maintainer", true, 10), labelEvent("LabeledEvent", 1)], { labelled: true }), null);+ const items = [review("APPROVED", "maintainer", true, 10), labelEvent("LabeledEvent", 1)];+ assert.deepEqual(await sync(items, { labelled: true }), { waiting: true, calls: [] });+ });++ it("does not re-add a label removed by hand", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), labelEvent("UnlabeledEvent", 1)];+ assert.deepEqual(await sync(items), { waiting: false, calls: [] });});it("reads further back in the timeline when the newest page moves nothing", async () => {const noise = Array.from({ length: 5 }, (_, index) => comment("maintainer", 5 - index));const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), comment(AUTHOR, 8), ...noise];const { github, reads } = fakeGitHub(items, { pageSize: 2 });- assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun() }), null);+ assert.equal(await syncTurnLabel(github, issue, false, true), false);assert.ok(reads.pages > 2);});- it("hands the turn back when the author replies to a review thread", async () => {- const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];- const payload = relayRun({ event: "pull_request_review_comment" });- assert.deepEqual(await changeFor(payload, items, { labelled: true }), { number: 7, add: false });- });-- it("ignores a run built from another PR, whatever its title says", async () => {- const { github, reads } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 1)]);- assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ headRepo: "attacker/r" }) }), null);- assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ headBranch: "other" }) }), null);- assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ event: "pull_request" }) }), null);- assert.equal(reads.pages, 0);- });-- it("ignores runs it did not relay, and PRs that do not exist", async () => {- assert.equal(await changeFor(relayRun({ title: "Something else" })), null);- assert.equal(await changeFor(relayRun(), [], { missing: true }), null);- });-});--describe("update turn label", () => {- const core = { info: () => {} };-- it("adds the label", async () => {- const { github, calls } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 1)]);- await updateTurnLabel({ github, context: { repo, payload: relayRun() }, core });- assert.deepEqual(calls, ["label #7 waiting-on-author"]);- });-- it("removes the label, and does not mind when it is not there", async () => {- const present = fakeGitHub();- await updateTurnLabel({ github: present.github, context: { repo, payload: pushBy(AUTHOR) }, core });- assert.deepEqual(present.calls, ["unlabel #7 waiting-on-author"]);-- const absent = fakeGitHub([], { alreadyRemoved: true });- await updateTurnLabel({ github: absent.github, context: { repo, payload: pushBy(AUTHOR) }, core });- assert.deepEqual(absent.calls, []);- });-});--describe("clear stale turn label", () => {- const issue = { ...repo, issue_number: 7 };- const answered = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];-- it("removes a label whose turn has moved on", async () => {- const { github, calls } = fakeGitHub(answered);- assert.equal(await clearStaleTurnLabel(github, issue, true), true);- assert.deepEqual(calls, ["unlabel #7 waiting-on-author"]);- });-- it("keeps a label that still stands", async () => {- const { github, calls } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9)]);- assert.equal(await clearStaleTurnLabel(github, issue, true), false);- assert.deepEqual(calls, []);+ it("reads no timeline for an unlabelled PR no review hands to the author", async () => {+ const { github, reads } = fakeGitHub([review("APPROVED", "maintainer", true, 2), comment(AUTHOR, 1)]);+ assert.equal(await syncTurnLabel(github, issue, false, true), false);+ assert.equal(reads.pages, 1);});it("changes nothing in a dry run", async () => {- const { github, calls } = fakeGitHub(answered);- assert.equal(await clearStaleTurnLabel(github, issue, false), true);- assert.deepEqual(calls, []);+ assert.deepEqual(await sync([review("CHANGES_REQUESTED", "maintainer", true, 1)], { live: false }), { waiting: true, calls: [] });+ assert.deepEqual(await sync([], { labelled: true, live: false }), { waiting: false, calls: [] });});});diff --git a/.github/scripts/pr-turn.ts b/.github/scripts/pr-turn.tsindex bd2b293c2a..c29458b00d 100644--- a/.github/scripts/pr-turn.ts+++ b/.github/scripts/pr-turn.ts@@ -1,33 +1,25 @@-// Keeps waiting-on-author current. pr-turn-labels.yml runs it as each event happens, and-// the daily triage re-checks every ready PR that has the label, because the review relay-// does not always run: a conflicted PR has no merge ref to run it on. This file owns-// waiting-on-author and no other label.+// Keeps waiting-on-author current. The daily triage adds and removes it from each ready+// PR's history, because no event a review raises can label a fork's PR: GitHub runs it+// from the fork, so it waits for a maintainer to approve the run, and fails outright+// once the PR conflicts. pr-turn-labels.yml removes it as soon as the author responds,+// from events that run without approval. This file owns waiting-on-author and no other+// label.//// The author's turn starts with a changes-requested review from someone who can push, or// the label added by hand. It ends when the author pushes, comments, replies to a review,// re-requests review or marks the PR ready, when someone who can push approves, when a// changes-requested review is dismissed, or when the label is removed.-import { type Core, type GitHubClient, type IssueRef, isNotFound, LABELS, type PullData, type Repo, removeLabel } from "./github.ts";+import { type Core, type GitHubClient, type IssueRef, LABELS, type Repo, removeLabel } from "./github.ts";-/** The parts of a github-script `context.payload` the turn events carry. */+/** The parts of a github-script `context.payload` the author's responses carry. */export interface TurnPayload {sender?: { login: string };pull_request?: { number: number; user: { login: string } };issue?: { number: number; user: { login: string }; pull_request?: unknown };comment?: { user: { login: string } };- workflow_run?: { event: string; display_title: string; head_branch: string; head_repository: { full_name: string } };}-export interface TurnChange {- number: number;- add: boolean;-}--// Must match the run-name and the events in pr-review-events.yml.-const REVIEW_RUN_TITLE = /^Review on #(\d+)$/;-const RELAYED_EVENTS = ["pull_request_review", "pull_request_review_comment"];-// Reviews come from `reviews`, not the timeline: a reply to a review thread is a review// of its own, and the timeline leaves those out.const REVIEWS_QUERY = `@@ -164,53 +156,30 @@ async function latestTimelineMove(github: GitHubClient, repo: Repo, number: numb* Whether the PR is waiting on its author. Read from the PR's history rather than the* event at hand, so runs that overlap, arrive late or are re-run all agree.*/-export async function authorHasTurn(github: GitHubClient, { owner, repo }: Repo, number: number): Promise<boolean> {+async function authorHasTurn(github: GitHubClient, { owner, repo }: Repo, number: number, labelled: boolean): Promise<boolean> {const page = await github.graphql<ReviewsPage>(REVIEWS_QUERY, { owner, repo, number });const pr = page.repository.pullRequest;if (pr === null) return false;const author = pr.author?.login;- const fromReviews = pr.reviews.nodes.flatMap((review) => move(review.submittedAt, reviewTurn(review, author, pr.headRefOid)));+ const fromReviews = latestMove(pr.reviews.nodes.flatMap((review) => move(review.submittedAt, reviewTurn(review, author, pr.headRefOid))));+ // Without the label, each time it went on it came off again later, so only a review+ // can have given the author the turn.+ if (!labelled && fromReviews?.turn !== "author") return false;const fromTimeline = await latestTimelineMove(github, { owner, repo }, number, author);- return latestMove(fromTimeline === null ? fromReviews : [...fromReviews, fromTimeline])?.turn === "author";+ return latestMove([fromReviews, fromTimeline].filter((latest) => latest !== null))?.turn === "author";}-async function relayedPull(github: GitHubClient, repo: Repo, run: NonNullable<TurnPayload["workflow_run"]>) {- const match = REVIEW_RUN_TITLE.exec(run.display_title);- if (!RELAYED_EVENTS.includes(run.event) || !match) return null;- const number = Number(match[1]);- const pull = await github.rest.pulls.get({ ...repo, pull_number: number }).then(- ({ data }): PullData | null => data,- (error: unknown) => {- if (isNotFound(error)) return null;- throw error;- },- );- // Any PR can name a run, by editing pr-review-events.yml or adding a workflow of the- // same name, so the title is only trusted for the PR the run was built from.- const builtFrom = pull?.head.repo?.full_name === run.head_repository.full_name && pull.head.ref === run.head_branch;- return builtFrom ? { number, pull } : null;-}--/** How the triggering event moves waiting-on-author, or null when it does not. */-export async function turnChangeForEvent(- github: GitHubClient,- { repo, payload }: { repo: Repo; payload: TurnPayload },-): Promise<TurnChange | null> {+/** The PR whose author the triggering event shows responding, or null. */+export function answeredPull(payload: TurnPayload): number | null {if (payload.pull_request) {const { number, user } = payload.pull_request;- return payload.sender?.login === user.login ? { number, add: false } : null;- }- if (payload.issue) {- const { number, user, pull_request } = payload.issue;- return pull_request && payload.comment?.user.login === user.login ? { number, add: false } : null;+ return payload.sender?.login === user.login ? number : null;}- const relayed = payload.workflow_run ? await relayedPull(github, repo, payload.workflow_run) : null;- if (relayed === null) return null;- const add = await authorHasTurn(github, repo, relayed.number);- const labelled = relayed.pull.labels.some((label) => label.name === LABELS.waitingOnAuthor);- return add === labelled ? null : { number: relayed.number, add };+ const { issue, comment } = payload;+ return issue?.pull_request && comment?.user.login === issue.user.login ? issue.number : null;}+/** pr-turn-labels.yml's entry point: hands the turn back as soon as the author responds. */export async function updateTurnLabel({github,context,@@ -220,23 +189,20 @@ export async function updateTurnLabel({context: { repo: Repo; payload: TurnPayload };core: Pick<Core, "info">;}) {- const change = await turnChangeForEvent(github, context);- if (change === null) return;- const issue = { ...context.repo, issue_number: change.number };- if (change.add) {- await github.rest.issues.addLabels({ ...issue, labels: [LABELS.waitingOnAuthor] });- } else {- await removeLabel(github, issue, LABELS.waitingOnAuthor);- }- core.info(`#${change.number}: ${change.add ? "+" : "-"}${LABELS.waitingOnAuthor}`);+ const number = answeredPull(context.payload);+ if (number === null) return;+ await removeLabel(github, { ...context.repo, issue_number: number }, LABELS.waitingOnAuthor);+ core.info(`#${number}: -${LABELS.waitingOnAuthor}`);}/**- * Removes waiting-on-author from a PR whose history says the turn has moved on. Returns- * whether the label was stale; changes nothing unless `live`.+ * Adds or removes waiting-on-author to match the PR's history, given whether it carries+ * the label now. Returns whether the PR is waiting on its author; changes nothing unless+ * `live`.*/-export async function clearStaleTurnLabel(github: GitHubClient, issue: IssueRef, live: boolean) {- if (await authorHasTurn(github, issue, issue.issue_number)) return false;- if (live) await removeLabel(github, issue, LABELS.waitingOnAuthor);- return true;+export async function syncTurnLabel(github: GitHubClient, issue: IssueRef, labelled: boolean, live: boolean) {+ const waiting = await authorHasTurn(github, issue, issue.issue_number, labelled);+ if (live && waiting && !labelled) await github.rest.issues.addLabels({ ...issue, labels: [LABELS.waitingOnAuthor] });+ if (live && !waiting && labelled) await removeLabel(github, issue, LABELS.waitingOnAuthor);+ return waiting;}diff --git a/.github/scripts/stale-prs.test.ts b/.github/scripts/stale-prs.test.tsindex f29eed76d6..b62a28a256 100644--- a/.github/scripts/stale-prs.test.ts+++ b/.github/scripts/stale-prs.test.ts@@ -386,7 +386,7 @@ interface FakeOptions {failFor?: number;failWrite?: string;alreadyRemoved?: string[];- /** The history pr-turn.ts reads to re-check waiting-on-author. */+ /** The history pr-turn.ts reads for waiting-on-author; the PR's own label events by default. */turnItems?: TurnItem[];/** What pulls.listFiles returns, for a PR over the size limit in total. */files?: ChangedFile[];@@ -405,7 +405,7 @@ function fakeGitHub(failFor,failWrite,alreadyRemoved = [],- turnItems = STILL_WAITING,+ turnItems,files = [],comments = [],writers = [],@@ -419,17 +419,24 @@ function fakeGitHub(calls.push(call);writeTimes.push(Date.now());};+ const turnHistory = (number: unknown): TurnItem[] =>+ turnItems ??+ (prs.find((pr) => pr.number === number)?.timeline ?? []).flatMap((event) =>+ event.__typename === "LabeledEvent" || event.__typename === "UnlabeledEvent"+ ? [{ __typename: event.__typename, createdAt: event.createdAt, label: event.label }]+ : [],+ );const graphql = async (query: string, variables: Record<string, unknown>) => {if (query.includes("pullRequests(states: OPEN")) {const nodes = prs.map((pr) => ({ number: pr.number }));return { repository: { pullRequests: { pageInfo: { hasNextPage: false, endCursor: null }, nodes } } };}if (query.includes("reviews(last")) {- const reviews = { nodes: turnItems.filter((item) => item.__typename === "PullRequestReview") };+ const reviews = { nodes: turnHistory(variables.number).filter((item) => item.__typename === "PullRequestReview") };return { repository: { pullRequest: { author: { login: "contributor" }, headRefOid: "head-sha", reviews } } };}if (query.includes("REVIEW_DISMISSED_EVENT")) {- const nodes = turnItems.filter((item) => item.__typename !== "PullRequestReview");+ const nodes = turnHistory(variables.number).filter((item) => item.__typename !== "PullRequestReview");return { repository: { pullRequest: { timelineItems: { pageInfo: { hasPreviousPage: false, startCursor: null }, nodes } } } };}if (variables.number === failFor) throw new Error("boom");@@ -457,7 +464,7 @@ function fakeGitHub(pulls: {get: async () => {reads.mergeable += 1;- return { data: { mergeable, mergeable_state: mergeableState, labels: [], head: { ref: "feature", repo: null } } };+ return { data: { mergeable, mergeable_state: mergeableState } };},update: async ({ pull_number }) => write(`close #${pull_number}`),listFiles: async ({ page }) => ({ data: page === 1 ? files : [] }),@@ -584,6 +591,35 @@ describe("triage run", () => {assert.deepEqual(calls, ["unlabel #1 waiting-on-author", "unlabel #1 Stale PR"]);});+ describe("waiting-on-author from a review", () => {+ const changesRequested: TurnItem = {+ __typename: "PullRequestReview",+ submittedAt: daysAgo(10),+ state: "CHANGES_REQUESTED",+ authorCanPushToRepository: true,+ author: PERSON,+ commit: { oid: "head-sha" },+ };++ it("adds the label, and dates the turn from then rather than warning at once", async () => {+ const { github, calls } = fakeGitHub([pullRequest()], { turnItems: [changesRequested] });+ await triage(github);+ assert.deepEqual(calls, ["label #1 waiting-on-author"]);+ });++ it("only reports it in a dry run", async () => {+ const { github, calls } = fakeGitHub([pullRequest()], { turnItems: [changesRequested] });+ await triage(github, { live: false });+ assert.deepEqual(calls, []);+ });++ it("leaves a draft alone", async () => {+ const { github, calls } = fakeGitHub([pullRequest({ isDraft: true })], { turnItems: [changesRequested] });+ await triage(github);+ assert.deepEqual(calls, []);+ });+ });+it("reads a timeline longer than one page", async () => {const pr = conflicted(40);for (let day = 39; day > 0; day -= 1) label(pr, `noise-${day}`, day);diff --git a/.github/scripts/stale-prs.ts b/.github/scripts/stale-prs.tsindex 5ff87cd0dd..01d720284a 100644--- a/.github/scripts/stale-prs.ts+++ b/.github/scripts/stale-prs.ts@@ -14,7 +14,7 @@ import {removeLabel,} from "./github.ts";import { enforceSizeLimit, MAX_LINES, type SizedPullRequest } from "./pr-size.ts";-import { clearStaleTurnLabel } from "./pr-turn.ts";+import { syncTurnLabel } from "./pr-turn.ts";const DAY_MS = 24 * 60 * 60 * 1000;@@ -628,7 +628,8 @@ export interface TriageInputs {}/**- * Triages every open PR, holding each to the size limit first, and writes a job summary.+ * Triages every open PR, first bringing waiting-on-author up to date on a ready one and+ * holding each to the size limit, and writes a job summary.* A PR that cannot be read or updated is logged and skipped, and the job is failed at* the end. Throws if the open PRs cannot be listed.*/@@ -653,9 +654,13 @@ export default async function triageStalePullRequests({try {let pr = await fetchPullRequest(github, repo, number);if (pr === null) continue;- if (!pr.isDraft && hasLabel(pr, LABELS.waitingOnAuthor) && (await clearStaleTurnLabel(github, issue, live))) {- core.info(`#${number}: -${LABELS.waitingOnAuthor} (the turn had already moved on)`);- pr = withLabel(pr, LABELS.waitingOnAuthor, false, now);+ if (!pr.isDraft) {+ const turnLabelled = hasLabel(pr, LABELS.waitingOnAuthor);+ const waiting = await syncTurnLabel(github, issue, turnLabelled, live);+ if (waiting !== turnLabelled) {+ core.info(`#${number}: ${waiting ? "+" : "-"}${LABELS.waitingOnAuthor}`);+ pr = withLabel(pr, LABELS.waitingOnAuthor, waiting, now);+ }}const size = await enforceSizeLimit(github, repo, sizedPullRequest(pr), sizeLive, canPush);if (size.held !== hasLabel(pr, LABELS.tooLarge)) {diff --git a/.github/workflows/pr-review-events.yml b/.github/workflows/pr-review-events.ymldeleted file mode 100644index 0fe2a8719c..0000000000--- a/.github/workflows/pr-review-events.yml+++ /dev/null@@ -1,38 +0,0 @@-name: PR review events--# Lets pr-turn-labels.yml react to reviews. A review on a fork PR only gets a-# read-only token here, but the workflow_run it triggers gets a write token.-# Relays every review: pr-turn.ts decides which ones move the turn.--# Carries the PR to pr-turn-labels.yml: must match REVIEW_RUN_TITLE in pr-turn.ts.-run-name: "Review on #${{ github.event.pull_request.number }}"--on:- pull_request_review:- types: [submitted, dismissed]- # A reply to a review thread is not guaranteed a review event of its own.- pull_request_review_comment:- types: [created]--permissions: {}--jobs:- relay:- name: Relay review event- # Every inline comment raises this, but only the author's can move the turn.- if: >-- github.event_name != 'pull_request_review_comment' ||- github.event.comment.user.login == github.event.pull_request.user.login- runs-on: ubuntu-latest- steps:- - name: Harden Runner- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1- with:- egress-policy: audit-- - name: Record the event- env:- EVENT: ${{ github.event_name }}- PR_NUMBER: ${{ github.event.pull_request.number }}- run: |- echo "$EVENT on #$PR_NUMBER"diff --git a/.github/workflows/pr-turn-labels.yml b/.github/workflows/pr-turn-labels.ymlindex b055c9d79f..58326e097e 100644--- a/.github/workflows/pr-turn-labels.yml+++ b/.github/workflows/pr-turn-labels.yml@@ -1,14 +1,11 @@name: PR turn labels-# Adds waiting-on-author on a changes-requested review and removes it on an approval-# or when the PR author responds. The rules live in .github/scripts/pr-turn.ts.-# Reviews arrive through pr-review-events.yml. Runs whatever STALE_PR_BOT_LIVE says:-# a label left stale while the triage is off would date its warning from before.+# Removes waiting-on-author as soon as the PR author responds. The daily triage in+# stale-prs.yml adds it, and removes it on approvals and review replies; the rules live+# in .github/scripts/pr-turn.ts. Runs whatever STALE_PR_BOT_LIVE says: a label left+# stale while the triage is off would date its warning from before.on:- workflow_run:- workflows: ["PR review events"]- types: [completed]pull_request_target:types: [synchronize, ready_for_review, review_requested]issue_comment:@@ -22,10 +19,9 @@ jobs:name: Update the turn label# Skips only events pr-turn.ts would do nothing with: a push, ready, re-request or comment# that is not the author's, or on a PR without the label. Must not skip anything- # turnChangeForEvent acts on.+ # answeredPull acts on.if: >-vars.CI_PROFILE != 'lite' && (- (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success') ||(github.event.pull_request && github.event.sender.login == github.event.pull_request.user.login &&contains(github.event.pull_request.labels.*.name, 'waiting-on-author')) ||(github.event.issue.pull_request && github.event.comment.user.login == github.event.issue.user.login &&diff --git a/.github/workflows/stale-prs.yml b/.github/workflows/stale-prs.ymlindex 5f3bda6412..60a1060090 100644--- a/.github/workflows/stale-prs.yml+++ b/.github/workflows/stale-prs.yml@@ -18,7 +18,6 @@ on:- ".github/workflows/stale-prs.yml"- ".github/scripts/*.ts"- ".github/workflows/pr-turn-labels.yml"- - ".github/workflows/pr-review-events.yml"- ".github/scripts/package.json"- ".github/scripts/package-lock.json"- ".github/scripts/tsconfig.json"