Skip to content

feat: automated PR review via GitHub webhook and Action#861

Open
Ruchitha1608 wants to merge 4 commits into
potpie-ai:mainfrom
Ruchitha1608:feat/github-pr-review-webhook
Open

feat: automated PR review via GitHub webhook and Action#861
Ruchitha1608 wants to merge 4 commits into
potpie-ai:mainfrom
Ruchitha1608:feat/github-pr-review-webhook

Conversation

@Ruchitha1608

Copy link
Copy Markdown

What this does

Wires Potpie's existing BlastRadiusAgent into a GitHub webhook so PRs
get reviewed automatically — no editor plugin required.

When a developer opens or updates a pull request:

  1. A GitHub Action sends a POST to /api/v1/github/webhook
  2. Potpie looks up the project for that repo + branch
  3. Runs code_changes_agent (BlastRadiusAgent) on the PR
  4. Posts the findings as a comment on the pull request

Why this matters

Cursor and Windsurf live inside the editor. This puts Potpie inside the
CI pipeline — a surface they cannot reach. Engineering teams get AI
analysis on every PR before a human reviewer even opens it.

Files changed

  • legacy/app/modules/code_provider/github/github_webhook_router.py
    webhook endpoint, signature verification, background agent execution
  • legacy/app/main.py — registers the new router
  • examples/potpie-pr-review.yml — drop-in GitHub Action template

Testing

14 unit tests, all passing. Covers signature verification, ignored events,
auth rejection, all trigger actions, and the full agent→comment flow.

End-to-end testing requires a running Potpie instance with a parsed
project and a GitHub token — covered in the setup instructions in the
Action template.

Wires the existing BlastRadiusAgent into a GitHub webhook endpoint so
pull requests get an automated Potpie review comment without any editor
plugin. Adds a drop-in GitHub Action template users copy into their repo.
@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 8668ad27-2ae3-43c7-b52a-269e7f12b091

📥 Commits

Reviewing files that changed from the base of the PR and between b1e78d0 and 8bf6879.

📒 Files selected for processing (1)
  • legacy/tests/unit/code_provider/test_github_webhook_router.py

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Automated pull request review: new webhook endpoint queues background reviews and posts results as PR comments.
    • Example CI workflow to forward PR events to the review service.
  • Security

    • Optional HMAC SHA-256 signature verification for incoming webhooks.
  • Tests

    • Comprehensive unit tests for signature validation, event handling, background review processing, and comment posting.

Walkthrough

Adds a GitHub webhook endpoint that verifies optional HMAC signatures, filters PR actions (opened, synchronize, reopened), enqueues a background task to run a code_changes_agent review, and posts the review as a PR comment. Includes app wiring, unit tests, and a GitHub Actions example workflow to send PR payloads.

Changes

GitHub Webhook PR Review Integration

Layer / File(s) Summary
Webhook handler, background task, and helpers
legacy/app/modules/code_provider/github/github_webhook_router.py
Implements POST /github/webhook with _verify_signature, _post_pr_comment, and _run_pr_review background task that resolves project from DB, builds ChatContext for code_changes_agent, runs AgentsService.execute, and posts results as a PR comment.
Unit tests for signature, endpoint, and background task
legacy/tests/unit/code_provider/test_github_webhook_router.py
Adds tests for _verify_signature, endpoint behavior (ignored events, action allowlist, signature enforcement), background task queuing, and async tests for _run_pr_review with and without a matching project.
FastAPI Application Wiring
legacy/app/main.py
Imports and registers github_webhook_router with the FastAPI app under the /api/v1 prefix with the Github tag.
Example Workflow Configuration
examples/potpie-pr-review.yml
Adds a GitHub Actions workflow triggered on PR opened, synchronize, and reopened that builds a JSON payload from GitHub context and POSTs it to POTPIE_WEBHOOK_URL (from repository secret) with X-GitHub-Event: pull_request.

Sequence Diagram(s)

sequenceDiagram
  participant GitHub
  participant Webhook
  participant Verify
  participant Background
  participant DB
  participant Agent
  participant GitHubAPI

  GitHub->>Webhook: POST /github/webhook (pull_request + X-Hub-Signature-256)
  Webhook->>Verify: verify signature (if GITHUB_WEBHOOK_SECRET set)
  alt signature ok or not required
    Webhook->>Background: enqueue _run_pr_review with repo/pr/branch
    Background->>DB: get_global_project_from_db(repo, branch)
    DB-->>Background: project or None
    alt project found
      Background->>Agent: AgentsService.execute(code_changes_agent ChatContext)
      Agent-->>Background: review result
      Background->>GitHubAPI: _post_pr_comment(token, repo, pr_number, comment)
      GitHubAPI-->>GitHub: comment created
    else project missing
      Background-->>Background: exit without posting
    end
  else signature invalid
    Webhook-->>GitHub: 400/401
  end
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: automated PR review via GitHub webhook and Action, which is the core feature added across all changed files.
Description check ✅ Passed The description comprehensively explains the feature, workflow, rationale, and testing coverage, directly addressing what the PR accomplishes and why it matters.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
legacy/app/modules/code_provider/github/github_webhook_router.py (1)

103-105: 💤 Low value

Handle case where result.response might be None or empty.

If agents_service.execute returns a result object with response=None or an empty string, the posted comment may contain "None" or be effectively blank. Consider a more explicit check.

♻️ Suggested improvement
-        review_body = result.response if result else "Potpie could not generate a review."
+        review_body = (result.response if result and result.response else
+                       "Potpie could not generate a review.")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@legacy/app/modules/code_provider/github/github_webhook_router.py` around
lines 103 - 105, The current code uses result.response directly which can be
None or an empty string and lead to posting "None" or blank comments; update the
handling after agents_service.execute so you compute review_body by checking
that result is truthy and result.response is a non-empty string (e.g., use a
truthy check or strip before fallback) and if not, set review_body to an
explicit message like "Potpie could not generate a review."; then call
_post_pr_comment(repo_name, pr_number, review_body). Ensure you reference
agents_service.execute, result.response and _post_pr_comment when making the
change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/potpie-pr-review.yml`:
- Around line 47-49: The curl call that posts "$payload" to POTPIE_WEBHOOK_URL
must include the GitHub event header expected by the router check
(x_github_event != "pull_request"); update the curl invocation to add the header
"X-GitHub-Event: pull_request" so the endpoint won't return
{"status":"ignored"}—modify the command that uses POTPIE_WEBHOOK_URL and payload
to include this header.

In `@legacy/app/modules/code_provider/github/github_webhook_router.py`:
- Around line 141-145: The handler in github_webhook_router.py currently does
direct dict access for pull_request, repository, number, head, etc. which can
raise KeyError on malformed payloads; change the extraction to validate the
payload and return a 400 with a clear message instead of allowing a 500: either
use safe access (dict.get) and check for missing keys for pr,
repository/full_name, pr["number"], pr["head"]["ref"], pr["title"] or wrap the
block that sets pr, repo_name, pr_number, branch, pr_title in a try/except
KeyError that logs the missing key(s) and returns a 400 response; ensure you
update the code paths that follow these variables to expect they may be absent
only when you return the error.
- Around line 46-58: The _post_pr_comment function currently calls the GitHub
API (Github(...), gh.get_repo, repo.get_pull, pr.create_issue_comment) without
targeted error handling; wrap the API interactions in a try/except that catches
github.GithubException (and optionally requests/IOError for network issues), and
log a clear, contextual error via logger.error including the repo_name,
pr_number and the exception details so failures to post a comment are
distinguishable from other errors in _run_pr_review; ensure the function still
returns gracefully after logging (no re-raise).

In `@legacy/tests/unit/code_provider/test_github_webhook_router.py`:
- Around line 98-108: The test currently patches
app.modules.code_provider.github.github_webhook_router._run_pr_review as
mock_task but never asserts it was queued; update
test_valid_pr_accepted_and_background_task_queued to assert the mock was called
(e.g., mock_task.assert_called_once()) after the response checks and, if
possible, validate the call arguments via mock_task.call_args to ensure it was
invoked with the expected PR and repo values (reference _run_pr_review and
mock_task in the test).

---

Nitpick comments:
In `@legacy/app/modules/code_provider/github/github_webhook_router.py`:
- Around line 103-105: The current code uses result.response directly which can
be None or an empty string and lead to posting "None" or blank comments; update
the handling after agents_service.execute so you compute review_body by checking
that result is truthy and result.response is a non-empty string (e.g., use a
truthy check or strip before fallback) and if not, set review_body to an
explicit message like "Potpie could not generate a review."; then call
_post_pr_comment(repo_name, pr_number, review_body). Ensure you reference
agents_service.execute, result.response and _post_pr_comment when making the
change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 40ec0054-82f8-4c3c-91a6-8f9bd39c661c

📥 Commits

Reviewing files that changed from the base of the PR and between af14184 and 8d9598d.

📒 Files selected for processing (4)
  • examples/potpie-pr-review.yml
  • legacy/app/main.py
  • legacy/app/modules/code_provider/github/github_webhook_router.py
  • legacy/tests/unit/code_provider/test_github_webhook_router.py

Comment thread examples/potpie-pr-review.yml
Comment thread legacy/app/modules/code_provider/github/github_webhook_router.py Outdated
Comment thread legacy/app/modules/code_provider/github/github_webhook_router.py Outdated
Comment thread legacy/tests/unit/code_provider/test_github_webhook_router.py
@Ruchitha1608

Copy link
Copy Markdown
Author

Hey @dhirenmathur @nndn — wanted to flag this PR directly. It wires the existing BlastRadiusAgent into a GitHub webhook so Potpie can review PRs automatically and post findings as comments — no editor plugin needed. It's the one thing Cursor/Windsurf can't do. Would love your feedback when you get a chance!

@Ruchitha1608 Ruchitha1608 left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 29225eb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant