diff --git a/.github/actions/collect-review/action.yml b/.github/actions/collect-review/action.yml new file mode 100644 index 0000000000000..f76c333c8d0ef --- /dev/null +++ b/.github/actions/collect-review/action.yml @@ -0,0 +1,129 @@ +name: 'Collect the review' +description: > + Collects a pull request and the maintainers' comments on it into review.json in the directory, + for the revision agent, and uploads the directory as an artifact. Only people with write access + count as maintainers: nobody else's comments get through, and no resolved threads. Fails when + there is nothing to address. +inputs: + pull-request: + description: 'Number of the pull request' + required: true + dir: + description: 'Directory to write review.json to; uploaded as the artifact' + required: false + default: ${{ runner.temp }}/review + artifact-name: + description: 'Name of the uploaded artifact' + required: false + default: 'review' + token: + description: 'Token that reads the pull request and the collaborators' + required: false + default: ${{ github.token }} +outputs: + head: + description: 'Head commit of the pull request' + value: ${{ steps.collect.outputs.head }} + base: + description: 'Merge base of the pull request with its base branch' + value: ${{ steps.collect.outputs.base }} + branch: + description: 'Head branch of the pull request' + value: ${{ steps.collect.outputs.branch }} +runs: + using: composite + steps: + - name: Collect the pull request and the maintainers' comments + id: collect + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + PULL_NUMBER: ${{ inputs.pull-request }} + DIR: ${{ inputs.dir }} + with: + github-token: ${{ inputs.token }} + script: | + const fs = require('fs'); + const path = require('path'); + const { PULL_NUMBER, DIR } = process.env; + const { owner, repo } = context.repo; + const pull_number = Number(PULL_NUMBER); + fs.mkdirSync(DIR, { recursive: true }); + + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }); + const { data: { merge_base_commit: base } } = await github.rest.repos.compareCommitsWithBasehead({ owner, repo, basehead: `${pr.base.ref}...${pr.head.sha}` }); + const commits = await github.paginate(github.rest.pulls.listCommits, { owner, repo, pull_number, per_page: 100 }); + const { repository: { pullRequest: data } } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + comments(last: 100) { totalCount nodes { author { __typename login } body createdAt url } } + reviews(last: 100) { totalCount nodes { author { __typename login } body state createdAt url } } + reviewThreads(last: 100) { + totalCount + nodes { + isResolved isOutdated path line originalLine + comments(first: 100) { totalCount nodes { author { __typename login } body createdAt url diffHunk } } + } + } + } + } + }`, { owner, repo, number: pull_number }); + for (const [name, connection] of [['comments', data.comments], ['reviews', data.reviews], ['review threads', data.reviewThreads], ...data.reviewThreads.nodes.map(t => [`comments in a thread on ${t.path}`, t.comments])]) { + if (connection.totalCount > connection.nodes.length) + core.warning(`Read only ${connection.nodes.length} of ${connection.totalCount} ${name}`); + } + + // Only people with write access count as maintainers. The agent never sees anyone else's comments. + const maintainers = new Map(); + const isMaintainer = async author => { + if (author?.__typename !== 'User') + return false; + if (!maintainers.has(author.login)) { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username: author.login }).catch(() => ({ data: {} })); + maintainers.set(author.login, ['admin', 'write'].includes(data.permission)); + } + return maintainers.get(author.login); + }; + const comment = c => ({ author: c.author.login, createdAt: c.createdAt, url: c.url, body: c.body }); + + const comments = []; + for (const c of data.comments.nodes) { + if (await isMaintainer(c.author)) + comments.push({ kind: 'comment', ...comment(c) }); + } + for (const r of data.reviews.nodes) { + if (r.body.trim() && await isMaintainer(r.author)) + comments.push({ kind: 'review', state: r.state, ...comment(r) }); + } + for (const t of data.reviewThreads.nodes) { + if (t.isResolved) + continue; + const thread = []; + for (const c of t.comments.nodes) { + if (await isMaintainer(c.author)) + thread.push(comment(c)); + } + if (thread.length) + comments.push({ kind: 'thread', path: t.path, line: t.line ?? t.originalLine, outdated: t.isOutdated, diffHunk: t.comments.nodes[0].diffHunk, createdAt: thread[0].createdAt, comments: thread }); + } + comments.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + if (!comments.length) + throw new Error('There are no comments from maintainers to address, other than in resolved threads'); + + fs.writeFileSync(path.join(DIR, 'review.json'), JSON.stringify({ + url: pr.html_url, + title: pr.title, + body: pr.body, + head: pr.head.sha, + base: base.sha, + commits: commits.map(c => ({ sha: c.sha, date: c.commit.committer.date, message: c.commit.message })), + comments, + }, null, 2)); + core.setOutput('head', pr.head.sha); + core.setOutput('base', base.sha); + core.setOutput('branch', pr.head.ref); + - name: Upload the review + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.artifact-name }} + path: ${{ inputs.dir }} diff --git a/.github/actions/publish-patch/action.yml b/.github/actions/publish-patch/action.yml new file mode 100644 index 0000000000000..e7d74f7bf1e5d --- /dev/null +++ b/.github/actions/publish-patch/action.yml @@ -0,0 +1,110 @@ +name: 'Publish a patch' +description: > + Publishes the patch an agent left in its output directory, from a job that has write credentials + and never runs the agent's code. Applies the patch to the checkout, rejects one that changes + anything under .github/, commits it as the Playwright automation app with the title and body from + the metadata file, pushes it to the branch and, when asked, opens the branch as a draft pull + request with the body file as its description. +inputs: + token: + description: 'Token with write access to contents and pull requests, from the app' + required: true + dir: + description: 'Directory with the patch, the metadata and the body file' + required: true + patch: + description: 'File name of the patch in dir' + required: true + metadata: + description: 'File name of the JSON in dir with the commit title and, optionally, body' + required: true + branch: + description: 'Branch to push to; created when it does not exist, never force-pushed' + required: true + commit-body: + description: 'Commit body when the metadata has none, such as the Fixes: line' + required: false + default: '' + pull-request: + description: 'true opens a draft pull request from the branch; false only pushes' + required: false + default: 'false' + base: + description: 'Base branch of the pull request' + required: false + default: 'main' + body-file: + description: 'File name of the pull request description in dir' + required: false + default: '' + workflow-name: + description: 'How the pull request footer names the workflow' + required: false + default: 'triage workflow' +outputs: + commit: + description: 'The pushed commit' + value: ${{ steps.publish.outputs.commit }} + pull-request: + description: 'URL of the pull request, when one was opened' + value: ${{ steps.publish.outputs.pull-request }} + number: + description: 'Number of the pull request, when one was opened' + value: ${{ steps.publish.outputs.number }} +runs: + using: composite + steps: + - name: Validate, commit, push and open + id: publish + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + DIR: ${{ inputs.dir }} + PATCH: ${{ inputs.patch }} + METADATA: ${{ inputs.metadata }} + BRANCH: ${{ inputs.branch }} + COMMIT_BODY: ${{ inputs.commit-body }} + PULL_REQUEST: ${{ inputs.pull-request }} + BASE: ${{ inputs.base }} + BODY_FILE: ${{ inputs.body-file }} + WORKFLOW_NAME: ${{ inputs.workflow-name }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + with: + github-token: ${{ inputs.token }} + script: | + const fs = require('fs'); + const path = require('path'); + const { execFileSync } = require('child_process'); + const { DIR, PATCH, METADATA, BRANCH, COMMIT_BODY, PULL_REQUEST, BASE, BODY_FILE, WORKFLOW_NAME, RUN_URL } = process.env; + const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim(); + const { owner, repo } = context.repo; + git('apply', '--index', path.join(DIR, PATCH)); + + // Workflow and action changes would run with this repo's secrets in PR CI. + const workflowFiles = git('diff', '--cached', '--name-only', '--no-renames', '-z').split('\0').filter(file => file.startsWith('.github/')); + if (workflowFiles.length) + throw new Error(`Patch changes workflow files, treating it as compromised: ${workflowFiles.join(', ')}`); + + const { title, body } = JSON.parse(fs.readFileSync(path.join(DIR, METADATA), 'utf8')); + if (typeof title !== 'string' || !title.trim()) + throw new Error(`${METADATA} needs a title`); + const commitBody = typeof body === 'string' && body.trim() ? body : COMMIT_BODY; + git('config', 'user.name', 'microsoft-playwright-automation[bot]'); + git('config', 'user.email', '203992400+microsoft-playwright-automation[bot]@users.noreply.github.com'); + git('commit', '-m', title, ...(commitBody ? ['-m', commitBody] : [])); + // Not a force push: it fails if an existing branch moved after the agent started. + git('push', 'origin', `HEAD:refs/heads/${BRANCH}`); + const commit = git('rev-parse', 'HEAD'); + core.setOutput('commit', commit); + if (PULL_REQUEST !== 'true') { + await core.summary.addRaw(`Pushed https://github.com/${owner}/${repo}/commit/${commit}\n`).write(); + return; + } + const description = BODY_FILE ? fs.readFileSync(path.join(DIR, BODY_FILE), 'utf8').trim() : ''; + const { data: pr } = await github.rest.pulls.create({ + owner, repo, head: BRANCH, base: BASE, title, + body: `${description}\n\nPrepared by the [${WORKFLOW_NAME}](${RUN_URL}).`, + draft: true, + }); + core.setOutput('pull-request', pr.html_url); + core.setOutput('number', pr.number); + await core.summary.addRaw(`Draft pull request: ${pr.html_url}\n`).write(); diff --git a/.github/actions/run-agent/action.yml b/.github/actions/run-agent/action.yml new file mode 100644 index 0000000000000..494dd5e82e47a --- /dev/null +++ b/.github/actions/run-agent/action.yml @@ -0,0 +1,106 @@ +name: 'Run the agent' +description: > + Runs the Copilot CLI unattended with the prompt, the way the triage and revision workflows do: all + tools and paths allowed, no questions, the session transcript in the output directory. The agent + leaves its results as files in the output directory. The action reports whether the result file + is there, writes the agent's summary.md into the run summary and uploads the output directory as + an artifact, also when the session failed or ran out of budget. The Copilot CLI has to be + installed already. +inputs: + prompt: + description: 'The prompt' + required: true + output-dir: + description: 'Directory the agent writes its results to; uploaded as the artifact' + required: true + result-file: + description: 'Path in the output directory the agent writes last when it has a result, such as fix/proposal.json' + required: true + artifact-name: + description: 'Name of the uploaded artifact' + required: true + github-tools: + description: 'true gives the agent the GitHub MCP tools with the token; false gives it no built-in MCP servers and no URL access' + required: false + default: 'false' + exec: + description: 'Command the Copilot CLI runs through, such as a wrapper that enters a container or sets the I/O priority' + required: false + default: '' + working-directory: + description: 'Directory the agent runs in' + required: false + default: '.' + model: + description: 'Model for the Copilot CLI' + required: false + default: 'gpt-6.1-sol' + max-ai-credits: + description: 'Budget for the session' + required: false + default: '5000' + token: + description: 'Token for the Copilot CLI and its GitHub tools' + required: false + default: ${{ github.token }} +outputs: + outcome: + description: 'success or failure of the Copilot session' + value: ${{ steps.agent.outcome }} + has-result: + description: 'true when the result file exists' + value: ${{ steps.save.outputs.has-result }} +runs: + using: composite + steps: + - name: Run the Copilot CLI + id: agent + # A finished result is still useful if the session exhausts its budget. + continue-on-error: true + shell: bash + working-directory: ${{ inputs.working-directory }} + env: + COPILOT_GITHUB_TOKEN: ${{ inputs.token }} + PROMPT: ${{ inputs.prompt }} + OUTPUT_DIR: ${{ inputs.output-dir }} + WRAPPER: ${{ inputs.exec }} + TOOLS: ${{ inputs.github-tools == 'true' && '--enable-all-github-mcp-tools' || '--disable-builtin-mcps' }} + MODEL: ${{ inputs.model }} + MAX_AI_CREDITS: ${{ inputs.max-ai-credits }} + run: | + mkdir -p "$OUTPUT_DIR" + $WRAPPER copilot \ + --allow-all-tools \ + --allow-all-paths \ + --no-ask-user \ + "$TOOLS" \ + --share="$OUTPUT_DIR/copilot-session.md" \ + --model "$MODEL" \ + --max-ai-credits "$MAX_AI_CREDITS" \ + -p "$PROMPT" + - name: Save the outcome + id: save + shell: bash + env: + OUTPUT_DIR: ${{ inputs.output-dir }} + RESULT_FILE: ${{ inputs.result-file }} + AGENT_OUTCOME: ${{ steps.agent.outcome }} + run: | + mkdir -p "$OUTPUT_DIR" + if [[ -f "$OUTPUT_DIR/$RESULT_FILE" ]]; then + echo "has-result=true" >> "$GITHUB_OUTPUT" + else + echo "has-result=false" >> "$GITHUB_OUTPUT" + fi + echo "Copilot step: $AGENT_OUTCOME" >> "$GITHUB_STEP_SUMMARY" + if [[ -f "$OUTPUT_DIR/summary.md" ]]; then + cat "$OUTPUT_DIR/summary.md" >> "$GITHUB_STEP_SUMMARY" + else + echo "No summary was produced; see the session artifact." >> "$GITHUB_STEP_SUMMARY" + fi + - name: Upload the output directory + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.artifact-name }} + path: ${{ inputs.output-dir }} + if-no-files-found: warn diff --git a/.github/actions/triage-comment/action.yml b/.github/actions/triage-comment/action.yml new file mode 100644 index 0000000000000..0346e642989c2 --- /dev/null +++ b/.github/actions/triage-comment/action.yml @@ -0,0 +1,99 @@ +name: 'Post the triage comment' +description: > + Posts the agent's investigation note, comment.md in the directory, on the issue, with the draft + pull request appended when one was opened and any extra text after it, then hides the comment + with the run link. Without a note, when the run failed or ran out of budget first, posts that the + bot couldn't finish and why, from the outcomes of the triage job. +inputs: + issue: + description: 'Number of the issue' + required: true + dir: + description: 'Directory the triage artifact was downloaded to' + required: true + footer: + description: 'The footer, such as "Triaged on Linux by the Playwright bot"; the run link follows' + required: true + job-result: + description: 'Result of the triage job' + required: true + setup-outcome: + description: 'Outcome of the setup step of the triage job' + required: false + default: '' + agent-outcome: + description: 'Outcome of the Copilot session' + required: false + default: '' + setup-failure-reason: + description: 'Why a failed setup step failed, for the comment' + required: false + default: 'installing dependencies, building or downloading browsers failed' + pull-request: + description: 'URL of the draft pull request, when one was opened' + required: false + default: '' + publish-result: + description: 'Result of the publish job' + required: false + default: '' + extra: + description: 'Markdown appended after the pull request line' + required: false + default: '' + start-comment: + description: 'Node id of the comment with the run link, hidden afterwards' + required: false + default: '' + token: + description: 'Token that writes issue comments' + required: false + default: ${{ github.token }} +runs: + using: composite + steps: + - name: Post the comment + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + GH_REPO: ${{ github.repository }} + ISSUE: ${{ inputs.issue }} + DIR: ${{ inputs.dir }} + FOOTER: ${{ inputs.footer }} + JOB_RESULT: ${{ inputs.job-result }} + SETUP_OUTCOME: ${{ inputs.setup-outcome }} + AGENT_OUTCOME: ${{ inputs.agent-outcome }} + SETUP_FAILURE_REASON: ${{ inputs.setup-failure-reason }} + PR_URL: ${{ inputs.pull-request }} + PUBLISH_RESULT: ${{ inputs.publish-result }} + EXTRA: ${{ inputs.extra }} + START_COMMENT: ${{ inputs.start-comment }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + mkdir -p "$DIR" + if [[ ! -s "$DIR/comment.md" ]]; then + if [[ "$SETUP_OUTCOME" == "failure" ]]; then + reason="$SETUP_FAILURE_REASON" + elif [[ "$AGENT_OUTCOME" == "failure" ]]; then + reason="the Copilot session failed or ran out of budget before it wrote a result" + elif [[ "$JOB_RESULT" != "success" ]]; then + reason="the triage job ended with result \`$JOB_RESULT\`, for example after a timeout" + else + reason="the Copilot session ended without writing a result" + fi + echo "Hi, I'm the Playwright bot. I couldn't finish triaging this issue: $reason. The agent run has the details." > "$DIR/comment.md" + fi + if [[ -n "$PR_URL" ]]; then + printf '\n\nDraft fix: %s\n' "$PR_URL" >> "$DIR/comment.md" + elif [[ "$PUBLISH_RESULT" == "failure" ]]; then + printf '\n\nThe bot proposed a fix, but opening the pull request failed. The agent run has the details.\n' >> "$DIR/comment.md" + fi + if [[ -n "$EXTRA" ]]; then + printf '\n\n%s\n' "$EXTRA" >> "$DIR/comment.md" + fi + printf '\n\n%s - [agent run](%s)\n\n' "$FOOTER" "$RUN_URL" >> "$DIR/comment.md" + gh issue comment "$ISSUE" --body-file "$DIR/comment.md" + if [[ -n "$START_COMMENT" ]]; then + gh api graphql -f query='mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: OUTDATED }) { clientMutationId } }' -f id="$START_COMMENT" \ + || echo "::warning::Could not hide the comment with the run link" + fi diff --git a/.github/workflows/revision.yml b/.github/workflows/revision.yml index 162fb9ea9a343..f0f2165f64cd9 100644 --- a/.github/workflows/revision.yml +++ b/.github/workflows/revision.yml @@ -22,114 +22,35 @@ jobs: github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest permissions: + contents: read pull-requests: write + env: + PLATFORM: ${{ fromJSON('{"needs-revision":"linux","needs-revision-mac":"mac","needs-revision-win":"windows"}')[github.event.label.name] }} outputs: head: ${{ steps.collect.outputs.head }} base: ${{ steps.collect.outputs.base }} branch: ${{ steps.collect.outputs.branch }} - platform: ${{ steps.collect.outputs.platform }} + platform: ${{ env.PLATFORM }} steps: + # The base branch, for the actions: pull_request_target checks out the base, not the PR. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/actions + persist-credentials: false - name: Collect the PR and the maintainers' comments id: collect - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + uses: ./.github/actions/collect-review + with: + pull-request: ${{ github.event.pull_request.number }} + - name: Post the run link env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + PLATFORM_NAME: ${{ fromJSON('{"linux":"Linux","mac":"macOS","windows":"Windows"}')[env.PLATFORM] }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - with: - script: | - const fs = require('fs'); - const path = require('path'); - const { RUNNER_TEMP, RUN_URL } = process.env; - const { owner, repo } = context.repo; - const pull_number = context.payload.pull_request.number; - const platform = { 'needs-revision': 'linux', 'needs-revision-mac': 'mac', 'needs-revision-win': 'windows' }[context.payload.label.name]; - const dir = path.join(RUNNER_TEMP, 'review'); - fs.mkdirSync(dir, { recursive: true }); - - const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }); - const { data: { merge_base_commit: base } } = await github.rest.repos.compareCommitsWithBasehead({ owner, repo, basehead: `${pr.base.ref}...${pr.head.sha}` }); - const commits = await github.paginate(github.rest.pulls.listCommits, { owner, repo, pull_number, per_page: 100 }); - const { repository: { pullRequest: data } } = await github.graphql(` - query($owner: String!, $repo: String!, $number: Int!) { - repository(owner: $owner, name: $repo) { - pullRequest(number: $number) { - comments(last: 100) { totalCount nodes { author { __typename login } body createdAt url } } - reviews(last: 100) { totalCount nodes { author { __typename login } body state createdAt url } } - reviewThreads(last: 100) { - totalCount - nodes { - isResolved isOutdated path line originalLine - comments(first: 100) { totalCount nodes { author { __typename login } body createdAt url diffHunk } } - } - } - } - } - }`, { owner, repo, number: pull_number }); - for (const [name, connection] of [['comments', data.comments], ['reviews', data.reviews], ['review threads', data.reviewThreads], ...data.reviewThreads.nodes.map(t => [`comments in a thread on ${t.path}`, t.comments])]) { - if (connection.totalCount > connection.nodes.length) - core.warning(`Read only ${connection.nodes.length} of ${connection.totalCount} ${name}`); - } - - // Only people with write access count as maintainers. The agent never sees anyone else's comments. - const maintainers = new Map(); - const isMaintainer = async author => { - if (author?.__typename !== 'User') - return false; - if (!maintainers.has(author.login)) { - const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username: author.login }).catch(() => ({ data: {} })); - maintainers.set(author.login, ['admin', 'write'].includes(data.permission)); - } - return maintainers.get(author.login); - }; - const comment = c => ({ author: c.author.login, createdAt: c.createdAt, url: c.url, body: c.body }); - - const comments = []; - for (const c of data.comments.nodes) { - if (await isMaintainer(c.author)) - comments.push({ kind: 'comment', ...comment(c) }); - } - for (const r of data.reviews.nodes) { - if (r.body.trim() && await isMaintainer(r.author)) - comments.push({ kind: 'review', state: r.state, ...comment(r) }); - } - for (const t of data.reviewThreads.nodes) { - if (t.isResolved) - continue; - const thread = []; - for (const c of t.comments.nodes) { - if (await isMaintainer(c.author)) - thread.push(comment(c)); - } - if (thread.length) - comments.push({ kind: 'thread', path: t.path, line: t.line ?? t.originalLine, outdated: t.isOutdated, diffHunk: t.comments.nodes[0].diffHunk, createdAt: thread[0].createdAt, comments: thread }); - } - comments.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); - if (!comments.length) - throw new Error('There are no comments from maintainers to address, other than in resolved threads'); - - fs.writeFileSync(path.join(dir, 'review.json'), JSON.stringify({ - url: pr.html_url, - title: pr.title, - body: pr.body, - head: pr.head.sha, - base: base.sha, - commits: commits.map(c => ({ sha: c.sha, date: c.commit.committer.date, message: c.commit.message })), - comments, - }, null, 2)); - core.setOutput('head', pr.head.sha); - core.setOutput('base', base.sha); - core.setOutput('branch', pr.head.ref); - core.setOutput('platform', platform); - - const platformName = { linux: 'Linux', mac: 'macOS', windows: 'Windows' }[platform]; - await github.rest.issues.createComment({ - owner, repo, issue_number: pull_number, - body: `Hi, I'm the Playwright bot. I started to address the review comments on ${platformName}: [agent run](${RUN_URL})\n`, - }).catch(e => core.warning(`Could not post the run link: ${e.message}`)); - - name: Upload the review - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: review - path: ${{ runner.temp }}/review + run: | + body=$(printf "Hi, I'm the Playwright bot. I started to address the review comments on %s: [agent run](%s)\n" "$PLATFORM_NAME" "$RUN_URL") + gh pr comment "$PR" --body "$body" || echo "::warning::Could not post the run link" revise: name: Revise PR ${{ github.event.pull_request.number }} (${{ needs.prepare.outputs.platform }}) @@ -150,7 +71,7 @@ jobs: permissions: copilot-requests: write outputs: - has_revision: ${{ steps.save.outputs.has_revision }} + has_revision: ${{ steps.agent.outputs.has-result }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -179,48 +100,16 @@ jobs: npx playwright install --with-deps chromium firefox webkit - name: Revise with Copilot CLI id: agent - # A finished revision is still useful if the session exhausts its budget. - continue-on-error: true - env: - COPILOT_GITHUB_TOKEN: ${{ github.token }} # No GitHub tools and no URL access: the agent reads the PR only from the review the prepare job filtered. - run: | - copilot \ - --allow-all-tools \ - --allow-all-paths \ - --no-ask-user \ - --disable-builtin-mcps \ - --share="$OUTPUT_DIR/copilot-session.md" \ - --model gpt-6.1-sol \ - --max-ai-credits 5000 \ - -p "Follow .claude/skills/playwright-revision/SKILL.md. Read it in full before starting. - - Pull request: https://github.com/microsoft/playwright/pull/$PR" - - name: Save the outcome - id: save - if: always() - env: - AGENT_OUTCOME: ${{ steps.agent.outcome }} - run: | - mkdir -p "$OUTPUT_DIR" - if [[ -f "$OUTPUT_DIR/commit/commit.json" ]]; then - echo "has_revision=true" >> "$GITHUB_OUTPUT" - else - echo "has_revision=false" >> "$GITHUB_OUTPUT" - fi - echo "Copilot step: $AGENT_OUTCOME" >> "$GITHUB_STEP_SUMMARY" - if [[ -f "$OUTPUT_DIR/summary.md" ]]; then - cat "$OUTPUT_DIR/summary.md" >> "$GITHUB_STEP_SUMMARY" - else - echo "No summary was produced; see the session artifact." >> "$GITHUB_STEP_SUMMARY" - fi - - name: Upload the revision - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: ./.github/actions/run-agent with: - name: revision - path: ${{ env.OUTPUT_DIR }} - if-no-files-found: warn + prompt: | + Follow .claude/skills/playwright-revision/SKILL.md. Read it in full before starting. + + Pull request: https://github.com/microsoft/playwright/pull/${{ github.event.pull_request.number }} + output-dir: ${{ env.OUTPUT_DIR }} + result-file: commit/commit.json + artifact-name: revision push: name: Push the revision @@ -244,31 +133,10 @@ jobs: path: ${{ runner.temp }}/revision # Never execute code or scripts from the proposed changes in the app job. - name: Validate and push - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - BRANCH: ${{ needs.prepare.outputs.branch }} - PR: ${{ github.event.pull_request.number }} + uses: ./.github/actions/publish-patch with: - github-token: ${{ steps.app-token.outputs.token }} - script: | - const fs = require('fs'); - const path = require('path'); - const { execFileSync } = require('child_process'); - const { BRANCH, PR, RUNNER_TEMP } = process.env; - const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim(); - const dir = path.join(RUNNER_TEMP, 'revision', 'commit'); - const { owner, repo } = context.repo; - git('apply', '--index', path.join(dir, 'revision.patch')); - - // Workflow changes would run with this repo's secrets in PR CI. - const workflowFiles = git('diff', '--cached', '--name-only', '--no-renames', '-z').split('\0').filter(file => file.startsWith('.github/')); - if (workflowFiles.length) - throw new Error(`Patch changes workflow files, treating it as compromised: ${workflowFiles.join(', ')}`); - - const { title, body } = JSON.parse(fs.readFileSync(path.join(dir, 'commit.json'), 'utf8')); - git('config', 'user.name', 'microsoft-playwright-automation[bot]'); - git('config', 'user.email', '203992400+microsoft-playwright-automation[bot]@users.noreply.github.com'); - git('commit', '-m', title, ...(body ? ['-m', body] : [])); - // Not a force push: it fails if the branch moved after the review was collected. - git('push', 'origin', `HEAD:refs/heads/${BRANCH}`); - await core.summary.addRaw(`Pushed https://github.com/${owner}/${repo}/pull/${PR}/commits/${git('rev-parse', 'HEAD')}\n`).write(); + token: ${{ steps.app-token.outputs.token }} + dir: ${{ runner.temp }}/revision/commit + patch: revision.patch + metadata: commit.json + branch: ${{ needs.prepare.outputs.branch }} diff --git a/.github/workflows/triage.yml b/.github/workflows/triage.yml index be40507015a58..135d4b41d1fbf 100644 --- a/.github/workflows/triage.yml +++ b/.github/workflows/triage.yml @@ -84,9 +84,9 @@ jobs: outputs: base: ${{ steps.base.outputs.sha }} setup: ${{ steps.setup.outcome }} - agent: ${{ steps.agent.outcome }} - has_fix: ${{ steps.save.outputs.has_fix }} - browser: ${{ steps.save.outputs.browser }} + agent: ${{ steps.agent.outputs.outcome }} + has_fix: ${{ steps.agent.outputs.has-result }} + browser: ${{ steps.browser.outputs.browser }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -115,68 +115,43 @@ jobs: npm install -g @github/copilot npm run build npx playwright install --with-deps chromium firefox webkit + - name: Write the prompt + id: prompt + run: | + delimiter="PROMPT_$RANDOM$RANDOM" + { + echo "prompt<<$delimiter" + echo "Follow .claude/skills/playwright-triage/SKILL.md. Read it and the triage.md it" + echo "points to in full before starting." + if [[ -n "$ISSUE" ]]; then + printf '\nIssue: https://github.com/microsoft/playwright/issues/%s\n' "$ISSUE" + fi + if [[ -n "$TASK" ]]; then + printf '\nTask: %s\n' "$TASK" + fi + echo "$delimiter" + } >> "$GITHUB_OUTPUT" - name: Triage with Copilot CLI id: agent - # A finished proposal is still useful if the session exhausts its budget. - continue-on-error: true - env: - COPILOT_GITHUB_TOKEN: ${{ github.token }} - run: | - PROMPT="Follow .claude/skills/playwright-triage/SKILL.md. Read it and the triage.md it - points to in full before starting." - if [[ -n "$ISSUE" ]]; then - PROMPT="$PROMPT - - Issue: https://github.com/microsoft/playwright/issues/$ISSUE" - fi - if [[ -n "$TASK" ]]; then - PROMPT="$PROMPT - - Task: $TASK" - fi - copilot \ - --allow-all-tools \ - --allow-all-paths \ - --no-ask-user \ - --enable-all-github-mcp-tools \ - --share="$OUTPUT_DIR/copilot-session.md" \ - --model gpt-6.1-sol \ - --max-ai-credits 5000 \ - -p "$PROMPT" - - name: Save the outcome - id: save - if: always() - env: - AGENT_OUTCOME: ${{ steps.agent.outcome }} + uses: ./.github/actions/run-agent + with: + prompt: ${{ steps.prompt.outputs.prompt }} + output-dir: ${{ env.OUTPUT_DIR }} + result-file: fix/proposal.json + artifact-name: triage + github-tools: true + - name: Read the browser bug report + id: browser run: | - mkdir -p "$OUTPUT_DIR" - if [[ -f "$OUTPUT_DIR/fix/proposal.json" ]]; then - echo "has_fix=true" >> "$GITHUB_OUTPUT" - else - echo "has_fix=false" >> "$GITHUB_OUTPUT" - fi browser="" if [[ -f "$OUTPUT_DIR/browser/report.json" ]]; then browser=$(node -p 'String(JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).browser)' "$OUTPUT_DIR/browser/report.json" || true) [[ "$browser" =~ ^(chromium|firefox|webkit)$ ]] || { echo "::warning::browser/report.json does not name chromium, firefox or webkit"; browser=""; } fi echo "browser=$browser" >> "$GITHUB_OUTPUT" - echo "Copilot step: $AGENT_OUTCOME" >> "$GITHUB_STEP_SUMMARY" if [[ -n "$browser" ]]; then echo "Browser bug report: $browser" >> "$GITHUB_STEP_SUMMARY" fi - if [[ -f "$OUTPUT_DIR/summary.md" ]]; then - cat "$OUTPUT_DIR/summary.md" >> "$GITHUB_STEP_SUMMARY" - else - echo "No investigation summary was produced; see the session artifact." >> "$GITHUB_STEP_SUMMARY" - fi - - name: Upload investigation and fix - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: triage - path: ${{ env.OUTPUT_DIR }} - if-no-files-found: warn publish: name: Open draft pull request @@ -185,7 +160,7 @@ jobs: if: ${{ !cancelled() && needs.triage.outputs.has_fix == 'true' }} runs-on: ubuntu-latest outputs: - pr: ${{ steps.publish.outputs.pr }} + pr: ${{ steps.publish.outputs.pull-request }} steps: - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 id: app-token @@ -203,43 +178,16 @@ jobs: # Never execute code or scripts from the proposed changes in the app job. - name: Validate, push and open draft id: publish - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - BASE_SHA: ${{ needs.triage.outputs.base }} - ISSUE: ${{ github.event.issue.number || inputs.issue }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + uses: ./.github/actions/publish-patch with: - github-token: ${{ steps.app-token.outputs.token }} - script: | - const fs = require('fs'); - const path = require('path'); - const { execFileSync } = require('child_process'); - const { ISSUE, RUNNER_TEMP, RUN_URL } = process.env; - const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim(); - const dir = path.join(RUNNER_TEMP, 'triage', 'fix'); - const { owner, repo } = context.repo; - git('apply', '--index', path.join(dir, 'fix.patch')); - - // Workflow changes would run with this repo's secrets in PR CI. - const workflowFiles = git('diff', '--cached', '--name-only', '--no-renames', '-z').split('\0').filter(file => file.startsWith('.github/')); - if (workflowFiles.length) - throw new Error(`Patch changes workflow files, treating it as compromised: ${workflowFiles.join(', ')}`); - - const { title } = JSON.parse(fs.readFileSync(path.join(dir, 'proposal.json'), 'utf8')); - const description = fs.readFileSync(path.join(dir, 'pr-body.md'), 'utf8').trim(); - const branch = `triage/${ISSUE || 'task'}/${context.runId}-${process.env.GITHUB_RUN_ATTEMPT}`; - git('config', 'user.name', 'microsoft-playwright-automation[bot]'); - git('config', 'user.email', '203992400+microsoft-playwright-automation[bot]@users.noreply.github.com'); - git('switch', '-c', branch); - git('commit', '-m', title, ...(ISSUE ? ['-m', `Fixes: https://github.com/${owner}/${repo}/issues/${ISSUE}`] : [])); - git('push', 'origin', `HEAD:refs/heads/${branch}`); - const { data: pr } = await github.rest.pulls.create({ - owner, repo, head: branch, base: 'main', title, - body: `${description}\n\nPrepared by the [triage workflow](${RUN_URL}).`, - draft: true, - }); - core.setOutput('pr', pr.html_url); - await core.summary.addRaw(`Draft pull request: ${pr.html_url}\n`).write(); + token: ${{ steps.app-token.outputs.token }} + dir: ${{ runner.temp }}/triage/fix + patch: fix.patch + metadata: proposal.json + body-file: pr-body.md + branch: triage/${{ github.event.issue.number || inputs.issue || 'task' }}/${{ github.run_id }}-${{ github.run_attempt }} + commit-body: "${{ (github.event.issue.number || inputs.issue) && format('Fixes: https://github.com/{0}/issues/{1}', github.repository, github.event.issue.number || inputs.issue) || '' }}" + pull-request: true browser: name: File the browser issue @@ -321,64 +269,49 @@ jobs: if: ${{ !cancelled() && needs.triage.result != 'skipped' && (github.event_name == 'issues' || inputs.issue != '') }} runs-on: ubuntu-latest permissions: + contents: read issues: write env: - ISSUE: ${{ github.event.issue.number || inputs.issue }} - PLATFORM_NAME: ${{ fromJSON('{"linux":"Linux","mac":"macOS","windows":"Windows","needs-triage":"Linux","needs-triage-mac":"macOS","needs-triage-win":"Windows"}')[inputs.platform || github.event.label.name] }} - TRIAGE_RESULT: ${{ needs.triage.result }} - SETUP_OUTCOME: ${{ needs.triage.outputs.setup }} - AGENT_OUTCOME: ${{ needs.triage.outputs.agent }} - PUBLISH_RESULT: ${{ needs.publish.result }} - PR_URL: ${{ needs.publish.outputs.pr }} BROWSER: ${{ needs.triage.outputs.browser }} BROWSER_RESULT: ${{ needs.browser.result }} BROWSER_ISSUE_URL: ${{ needs.browser.outputs.url }} - START_COMMENT: ${{ needs.start.outputs.comment }} - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - WORKFLOW_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/actions + persist-credentials: false - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 # A failed triage run may not have uploaded anything. continue-on-error: true with: name: triage - path: output - - name: Post triage comment + path: ${{ runner.temp }}/triage + - name: Describe the browser bug report + id: browser + env: + OUTPUT_DIR: ${{ runner.temp }}/triage run: | - mkdir -p output - if [[ ! -s output/comment.md ]]; then - if [[ "$SETUP_OUTCOME" == "failure" ]]; then - reason="installing dependencies, building or downloading browsers failed" - elif [[ "$AGENT_OUTCOME" == "failure" ]]; then - reason="the Copilot session failed or ran out of budget before it wrote a result" - elif [[ "$TRIAGE_RESULT" != "success" ]]; then - reason="the triage job ended with result \`$TRIAGE_RESULT\`, for example after a timeout" - else - reason="the Copilot session ended without writing a result" - fi - echo "Hi, I'm the Playwright bot. I couldn't finish triaging this issue: $reason. The agent run has the details." > output/comment.md - fi - if [[ -n "$PR_URL" ]]; then - printf '\n\nDraft fix: %s\n' "$PR_URL" >> output/comment.md - elif [[ "$PUBLISH_RESULT" == "failure" ]]; then - printf '\n\nThe bot proposed a fix, but opening the pull request failed. The agent run has the details.\n' >> output/comment.md - fi - if [[ "$BROWSER" == "chromium" && -s output/browser/report.md ]]; then - title=$(jq -r '.title // empty' output/browser/report.json) - { - printf '\n\nChromium bug report, for a maintainer to file at https://crbug.com/new:\n\n**Title:** %s\n\n
\nBody\n\n````markdown\n' "$title" - cat output/browser/report.md - printf '\n````\n\n
\n' - } >> output/comment.md + extra="" + if [[ "$BROWSER" == "chromium" && -s "$OUTPUT_DIR/browser/report.md" ]]; then + title=$(jq -r '.title // empty' "$OUTPUT_DIR/browser/report.json") + extra=$(printf 'Chromium bug report, for a maintainer to file at https://crbug.com/new:\n\n**Title:** %s\n\n
\nBody\n\n````markdown\n%s\n````\n\n
' "$title" "$(cat "$OUTPUT_DIR/browser/report.md")") elif [[ -n "$BROWSER_ISSUE_URL" ]]; then - printf '\n\nBlocked-by: %s\n' "$BROWSER_ISSUE_URL" >> output/comment.md + extra="Blocked-by: $BROWSER_ISSUE_URL" elif [[ "$BROWSER_RESULT" == "failure" ]]; then - printf '\n\nThe bot wrote a %s bug report, but filing it in microsoft/playwright-browsers failed. The agent run has the details.\n' "$BROWSER" >> output/comment.md - fi - printf '\n\nTriaged on %s by the Playwright bot - [agent run](%s)\n\n' "$PLATFORM_NAME" "$WORKFLOW_URL" >> output/comment.md - gh issue comment "$ISSUE" --body-file output/comment.md - if [[ -n "$START_COMMENT" ]]; then - gh api graphql -f query='mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: OUTDATED }) { clientMutationId } }' -f id="$START_COMMENT" \ - || echo "::warning::Could not hide the comment with the run link" + extra="The bot wrote a $BROWSER bug report, but filing it in microsoft/playwright-browsers failed. The agent run has the details." fi + delimiter="EXTRA_$RANDOM$RANDOM" + { echo "extra<<$delimiter"; echo "$extra"; echo "$delimiter"; } >> "$GITHUB_OUTPUT" + - name: Post the triage comment + uses: ./.github/actions/triage-comment + with: + issue: ${{ github.event.issue.number || inputs.issue }} + dir: ${{ runner.temp }}/triage + footer: Triaged on ${{ fromJSON('{"linux":"Linux","mac":"macOS","windows":"Windows","needs-triage":"Linux","needs-triage-mac":"macOS","needs-triage-win":"Windows"}')[inputs.platform || github.event.label.name] }} by the Playwright bot + job-result: ${{ needs.triage.result }} + setup-outcome: ${{ needs.triage.outputs.setup }} + agent-outcome: ${{ needs.triage.outputs.agent }} + pull-request: ${{ needs.publish.outputs.pr }} + publish-result: ${{ needs.publish.result }} + extra: ${{ steps.browser.outputs.extra }} + start-comment: ${{ needs.start.outputs.comment }}