Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions .github/actions/publish-calls/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ name: 'Publish the calls'
description: >
Makes the calls that an agent left in calls.json in its output directory, from a job that has
write credentials and never runs the agent's code: open a draft pull request, push to the branch
of a pull request, file an issue, comment on an issue or a pull request, reply in a review thread.
of a pull request, file an issue, comment on an issue or a pull request, reply in a review thread,
post a review.
Everything that is posted comes from the calls. To catch mistakes, every call is checked before
any of them runs: its shape, and its repo, which must be microsoft/playwright or
microsoft/playwright-<name>. A scope-* input limits the calls more. When one call fails a check,
none of them runs. The calls run in a fixed order: pull request, push, issue, comment, reply.
none of them runs. The calls run in a fixed order: pull request, push, issue, comment, reply,
review.
calls.d.ts has the types of the file, and the agent reads it too: run-agent copies it to the
guides. publish-calls.ts has the checks. The job checks out the repo of the run at the commit
that the patch of a pull-request or push call is against. A pull request in another Playwright
Expand All @@ -28,7 +30,7 @@ inputs:
required: false
default: ''
scope-pull-request:
description: 'Number of the only pull request in this repo that the push, the replies and the comments may target'
description: 'Number of the only pull request in this repo that the push, the replies, the review and the comments may target'
required: false
default: ''
outputs:
Expand All @@ -44,6 +46,9 @@ outputs:
comment:
description: 'true when a comment was posted'
value: ${{ steps.publish.outputs.comment }}
review:
description: 'URL of the review, when one was posted'
value: ${{ steps.publish.outputs.review }}
runs:
using: composite
steps:
Expand Down
31 changes: 27 additions & 4 deletions .github/actions/publish-calls/calls.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@
// regular file in $OUTPUT_DIR, not a link.
// - A title is one line of at most 256 characters. A text has at most 65536 characters.
// - A label that the repo does not have is dropped.
// - At most one call of each kind `pull-request`, `push` and `issue`, at most one comment on each
// issue, and at most one reply to each comment.
// - At most one call of each kind `pull-request`, `push`, `issue` and `review`, at most one comment
// on each issue, and at most one reply to each comment.
//
// What the job does with the calls:
// - It makes them in this order, whatever their order in the file: pull-request, push, issue,
// comment, reply.
// comment, reply, review.
// - In a comment, it replaces `{{pull-request}}` with the URL of the PR that the pull-request call
// opened, and `{{issue}}` with the URL of the issue that the issue call filed or found. When that
// call failed, or there is none, it puts a note that says so instead. You cannot know these URLs
Expand Down Expand Up @@ -70,7 +70,7 @@
// publish-calls.ts in microsoft/playwright/.github/actions/publish-calls/ imports these types and
// makes the checks.

export type Call = PullRequest | Push | Issue | Comment | Reply;
export type Call = PullRequest | Push | Issue | Comment | Reply | Review;

export type Kind = Call['call'];

Expand Down Expand Up @@ -149,3 +149,26 @@ export type Reply = Text & {
/** The id of a comment in the thread, from review.json. */
comment: number;
};

/** Posts a review of a PR: a text, and comments on lines of its diff. A review from the bot never
* approves a PR or requests changes. The text has the footer, and the comments need none. */
export type Review = Text & {
call: 'review';
repo: string;
pullRequest: number;
/** The commit that you reviewed, as a full sha. The lines of the comments are in its diff. */
commit: string;
/** At most 50. GitHub refuses a review with a line outside the diff of the PR. The job then posts
* the review without them, and with these comments at the end of the text. */
comments?: ReviewComment[];
};

/** A comment on one line of the diff of a PR. */
export type ReviewComment = {
/** The path of the file in the repo. */
path: string;
/** The line number in the file at the commit of the review: an added line or a context line. */
line: number;
/** The markdown of the comment. */
body: string;
};
64 changes: 58 additions & 6 deletions .github/actions/publish-calls/publish-calls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// Node can remove: no enum, no namespace, no parameter properties, no `import x = require()`. An
// `import type` is removed too, and the file stays CommonJS.

import type { Call as FileCall, Comment, Issue, Kind, PullRequest, Push, Reply } from './calls';
import type { Call as FileCall, Comment, Issue, Kind, PullRequest, Push, Reply, Review, ReviewComment } from './calls';

const fs: typeof import('fs') = require('fs');
const path: typeof import('path') = require('path');
Expand All @@ -22,7 +22,7 @@ const { execFileSync }: typeof import('child_process') = require('child_process'
// A call after the checks: the text read from its file, the patch as an absolute path, and the
// repo in lower case.
type Checked<T> = Omit<T, 'body' | 'bodyFile'> & { body: string };
type Call = Checked<PullRequest> | Push | Checked<Issue> | Checked<Comment> | Checked<Reply>;
type Call = Checked<PullRequest> | Push | Checked<Issue> | Checked<Comment> | Checked<Reply> | Checked<Review>;

// The keys of a kind in calls.json, other than call and the text.
type KeysOf<K extends Kind> = Exclude<keyof Extract<FileCall, { call: K }>, 'call'>;
Expand Down Expand Up @@ -55,6 +55,7 @@ type GitHub = {
get(params: Repo & { pull_number: number }): Promise<{ data: { state: string, head: { ref: string, repo: { full_name: string } | null } } }>,
getReviewComment(params: Repo & { comment_id: number }): Promise<{ data: { id: number, in_reply_to_id?: number, pull_request_url: string, html_url: string } }>,
createReplyForReviewComment(params: Repo & { pull_number: number, comment_id: number, body: string }): Promise<unknown>,
createReview(params: Repo & { pull_number: number, commit_id: string, event: string, body: string, comments: (ReviewComment & { side: string })[] }): Promise<{ data: { html_url: string } }>,
},
issues: {
addLabels(params: Repo & { issue_number: number, labels: string[] }): Promise<unknown>,
Expand All @@ -79,7 +80,7 @@ type Context = { repo: Repo };

// The order in which the calls run, whatever their order in the file: a comment links the pull
// request and the issue that were opened before it, and a reply comes after the push it explains.
const KINDS: Kind[] = ['pull-request', 'push', 'issue', 'comment', 'reply'];
const KINDS: Kind[] = ['pull-request', 'push', 'issue', 'comment', 'reply', 'review'];

// The keys of each kind. A kind with text takes exactly one of body and bodyFile.
const SCHEMA: { [K in Kind]: { required: KeysOf<K>[], optional: KeysOf<K>[], text: boolean } } = {
Expand All @@ -88,6 +89,7 @@ const SCHEMA: { [K in Kind]: { required: KeysOf<K>[], optional: KeysOf<K>[], tex
'issue': { required: ['repo', 'title'], optional: ['labels', 'filedFor'], text: true },
'comment': { required: ['repo', 'issue'], optional: [], text: true },
'reply': { required: ['repo', 'pullRequest', 'comment'], optional: [], text: true },
'review': { required: ['repo', 'pullRequest', 'commit'], optional: ['comments'], text: true },
};

// The links that a comment can have, to what the calls before it opened.
Expand All @@ -99,6 +101,7 @@ const MAX_CALLS = 100;
const MAX_TITLE = 256;
const MAX_TEXT = 65536;
const MAX_LABELS = 10;
const MAX_REVIEW_COMMENTS = 50;

const BOT_NAME = 'microsoft-playwright-automation[bot]';
const BOT_EMAIL = '203992400+microsoft-playwright-automation[bot]@users.noreply.github.com';
Expand Down Expand Up @@ -215,6 +218,12 @@ async function publish({ github, context, core }: { github: GitHub, context: Con
summary.push(`- Replied to ${target.html_url}`);
break;
}
case 'review': {
const url = await postReview(github, core, call);
core.setOutput('review', url);
summary.push(`- Posted the review ${url}`);
break;
}
}
} catch (error) {
core.error(`${what} failed: ${(error as Error).message}`);
Expand Down Expand Up @@ -296,7 +305,7 @@ function parse(item: unknown, dir: string): Call {
return call as Call;
}

function check(key: Key, value: unknown, dir: string): string | number | string[] {
function check(key: Key, value: unknown, dir: string): string | number | string[] | ReviewComment[] {
switch (key) {
case 'repo': {
if (typeof value !== 'string' || !FAMILY.test(value.toLowerCase()))
Expand All @@ -321,11 +330,17 @@ function check(key: Key, value: unknown, dir: string): string | number | string[
throw new Error(`${key} must be a branch name, such as triage/123/456-1, got ${JSON.stringify(value)}`);
return value;
}
case 'commit':
case 'onto': {
if (typeof value !== 'string' || !/^[0-9a-f]{40}$/.test(value))
throw new Error(`onto must be a full commit sha, got ${JSON.stringify(value)}`);
throw new Error(`${key} must be a full commit sha, got ${JSON.stringify(value)}`);
return value;
}
case 'comments': {
if (!Array.isArray(value) || value.length > MAX_REVIEW_COMMENTS)
throw new Error(`comments must be an array of at most ${MAX_REVIEW_COMMENTS} comments`);
return value.map(reviewComment);
}
case 'patch':
return resolveFile(dir, value);
case 'commitBody':
Expand All @@ -342,6 +357,20 @@ function check(key: Key, value: unknown, dir: string): string | number | string[
}
}

function reviewComment(item: unknown): ReviewComment {
if (!item || typeof item !== 'object' || Array.isArray(item))
throw new Error('a comment of a review must be an object');
const { path: file, line, body, ...rest } = item as Record<string, unknown>;
const unknownKey = Object.keys(rest)[0];
if (unknownKey !== undefined)
throw new Error(`a comment of a review has an unknown key ${JSON.stringify(unknownKey)}`);
if (typeof file !== 'string' || !file || file.includes('\\') || file.startsWith('/') || file.split('/').some(part => !part || part === '.' || part === '..'))
throw new Error(`a comment of a review needs a path in the repo, got ${JSON.stringify(file)}`);
if (!isId(line))
throw new Error(`a comment of a review needs a line, got ${JSON.stringify(line)}`);
return { path: file, line, body: text(body, 'body') };
}

function text(value: unknown, key: string): string {
if (typeof value !== 'string' || !value.trim() || value.length > MAX_TEXT)
throw new Error(`${key} must be a text of 1 to ${MAX_TEXT} characters`);
Expand Down Expand Up @@ -380,6 +409,7 @@ function checkScope(call: Call, scope: Scope): void {
break;
case 'push':
case 'reply':
case 'review':
if (call.call === 'push' && call.repo !== repository)
throw new Error(`a push can only go to ${repository}, the repo of the run`);
if (pullRequest !== undefined && !(call.repo === repository && call.pullRequest === pullRequest))
Expand Down Expand Up @@ -422,6 +452,26 @@ async function fileIssue(github: GitHub, core: Core, call: Checked<Issue>): Prom
return issue.html_url;
}

// Posts the review as a comment, so that it never approves or blocks a PR. GitHub refuses the whole
// review when one comment is not on a line of the diff, which the agent cannot check. The comments
// then go at the end of the text, because the findings matter more than where they are shown.
async function postReview(github: GitHub, core: Core, call: Checked<Review>): Promise<string> {
const [owner, repo] = call.repo.split('/');
const params = { owner, repo, pull_number: call.pullRequest, commit_id: call.commit, event: 'COMMENT' };
const comments = call.comments ?? [];
try {
const { data } = await github.rest.pulls.createReview({ ...params, body: call.body, comments: comments.map(comment => ({ ...comment, side: 'RIGHT' })) });
return data.html_url;
} catch (error) {
if (!comments.length || (error as { status?: number }).status !== 422)
throw error;
core.warning(`GitHub refused the comments of the review, so they go in its text: ${(error as Error).message}`);
}
const body = [call.body, ...comments.map(comment => `**\`${comment.path}:${comment.line}\`**\n\n${comment.body}`)].join('\n\n');
const { data } = await github.rest.pulls.createReview({ ...params, body, comments: [] });
return data.html_url;
}

// Applies the patch to the checkout, commits it on the checkout as the app, and pushes it to the
// branch. With lease set to '', the branch must not exist yet. Without a lease, the push fails when
// the branch moved since the checkout.
Expand Down Expand Up @@ -498,7 +548,8 @@ function targetOf(call: Call): number | undefined {
switch (call.call) {
case 'comment': return call.issue;
case 'push':
case 'reply': return call.pullRequest;
case 'reply':
case 'review': return call.pullRequest;
}
return undefined;
}
Expand All @@ -510,6 +561,7 @@ function describe(call: Call): string {
case 'issue': return `issue in ${call.repo}`;
case 'comment': return `comment on ${call.repo}#${call.issue}`;
case 'reply': return `reply to comment ${call.comment} on ${call.repo}#${call.pullRequest}`;
case 'review': return `review of ${call.repo}#${call.pullRequest}`;
}
}

Expand Down
10 changes: 6 additions & 4 deletions .github/workflows/bots.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ the moment it lands on `main`.
| [`ci-env`](../actions/ci-env/action.yml) | Exports `CI_ENV_EXEC`, a wrapper that runs a command under xvfb on Linux and at normal I/O priority on Windows, and `CI_ENV_WINDOWS_NORMAL_IO`, the PowerShell script behind it. The test workflows use it too. | none |
| [`run-agent`](../actions/run-agent/action.yml) | Copies the guides and `calls.d.ts` to `$AGENT_GUIDES_DIR`, runs the Copilot CLI with the prompt, puts the agent's `summary.md` into the run summary, uploads the output directory as an artifact and reports whether the result file exists. | the workflow token, for the Copilot requests and, when `github-tools` is `true`, for the GitHub tools |
| [`collect-review`](../actions/collect-review/action.yml) | Writes the context of the revision to `review.json` and uploads it: the issue that the PR closes, or that its branch names, with its comments; the PR, with its description and commits; and the comments, reviews and unresolved threads on the PR. Only the comments of people with write access and of the bot get through. Fails when the maintainers left nothing to address. | the workflow token, to read the PR, the issue and the collaborators |
| [`publish-calls`](../actions/publish-calls/action.yml) | Reads the agent's `calls.json`, checks every call against the schema and the Playwright repos, and makes none of them when one fails. Then opens the draft PR, pushes to the branch of a PR, files an issue, comments and replies in review threads, in that order, with the texts as the agent wrote them. See [The calls](#the-calls). | the app token |
| [`publish-calls`](../actions/publish-calls/action.yml) | Reads the agent's `calls.json`, checks every call against the schema and the Playwright repos, and makes none of them when one fails. Then opens the draft PR, pushes to the branch of a PR, files an issue, comments, replies in review threads and posts a review, in that order, with the texts as the agent wrote them. See [The calls](#the-calls). | the app token |

`run-agent` runs the Copilot CLI with all tools and paths allowed and no questions to the user, with
a model and a credit budget that the workflow can override. `github-tools: true` gives the agent
Expand Down Expand Up @@ -96,6 +96,7 @@ checks in `publish-calls.ts` are written by hand; keep them in line with `calls.
| `issue` | `repo`, `title`, `body` or `bodyFile`, `labels`, `filedFor` | Uses an open issue whose text has the `filedFor` URL, or files one with the labels that the repo has. |
| `comment` | `repo`, `issue`, `body` or `bodyFile` | Posts the text, with `{{pull-request}}` and `{{issue}}` replaced by the URLs of what the calls before it opened, or by a note when they failed. |
| `reply` | `repo`, `pullRequest`, `comment`, `body` or `bodyFile` | Checks that the comment is in a review thread of that PR, and replies to the thread. One reply per thread. |
| `review` | `repo`, `pullRequest`, `commit`, `body` or `bodyFile`, `comments` | Posts a review with the state `COMMENT`, which never approves or blocks the PR, with the comments on lines of the diff at `commit`. When GitHub refuses a line, it posts the comments at the end of the text. The PR review workflow of `playwright-browsers` uses it. |

The agent writes every text that is posted, with the footer that names the bot and links the run,
and the branch, the commit body, the labels and `onto`. The guides and the skills say what to put
Expand All @@ -105,19 +106,20 @@ The checks, before any call runs:

- **The shape.** Only the keys above, with the right types. Titles are one line of at most 256
characters. A file is a regular file inside the output directory, named by a relative path
without `..`. At most one `pull-request`, one `push` and one `issue`, one comment per issue, one
without `..`. At most one `pull-request`, one `push`, one `issue` and one `review`, one comment per issue, one
reply per comment.
- **The family.** `repo` is `microsoft/playwright` or `microsoft/playwright-<name>`, so that a
mistake files nothing on someone else's repo. A pull request and a push go only to the repo of
the run, which is the checkout.
- **The scope, when the workflow gives one.** `scope-kinds` lists the kinds that the run may make.
`scope-issue` is the one issue that comments may target. `scope-pull-request` is the one PR that
the push, the replies and the comments may target. The workflows give none today.
the push, the replies, the review and the comments may target. Only the PR review workflow of
`playwright-browsers` gives them today.

The checks are there to catch mistakes, not to stop an agent that wants to do harm: what the calls
do is visible and can be undone. When a check fails, no call runs, and the job fails. The calls run
in a fixed order, whatever the order in the file: `pull-request`, `push`, `issue`, `comment`,
`reply`. When a call fails at run time, the others still run, except that a failed push skips the
`reply`, `review`. When a call fails at run time, the others still run, except that a failed push skips the
comments and replies on its PR, and the job fails at the end.

## The Issue triage workflow
Expand Down
Loading