Skip to content

fix: handle Ask GitHub rate limits#1476

Open
brendan-kellam wants to merge 2 commits into
mainfrom
brendan/fix-sou-1546-sou-1547
Open

fix: handle Ask GitHub rate limits#1476
brendan-kellam wants to merge 2 commits into
mainfrom
brendan/fix-sou-1546-sou-1547

Conversation

@brendan-kellam

@brendan-kellam brendan-kellam commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Fixes SOU-1546
Fixes SOU-1547

Summary

  • authenticate Ask GitHub repository lookups with the configured deployment token
  • return a distinct 429 response for GitHub primary and secondary rate limits
  • show a recoverable Ask GitHub client state with a retry action

Test plan

  • yarn workspace @sourcebot/backend test src/errors.test.ts
  • yarn workspace @sourcebot/backend build
  • yarn workspace @sourcebot/web test src/app/(app)/askgh/[owner]/[repo]/components/githubRateLimitExceeded.test.tsx
  • yarn workspace @sourcebot/web lint
  • yarn workspace @sourcebot/web build

Note

Low Risk
Changes are scoped to Ask GitHub repo onboarding and error handling; token use is via an existing env var and rate-limit detection is covered by unit tests.

Overview
Ask GitHub now uses EXPERIMENT_ASK_GH_GITHUB_TOKEN for experimental add-repo GitHub API calls instead of unauthenticated Octokit requests.

When GitHub returns primary or secondary rate limits, the backend maps them via isGitHubRateLimitError (429, or 403 with rate-limit headers/message) to HTTP 429 instead of a generic failure. The web layer surfaces GITHUB_RATE_LIMITED and the Ask GitHub page shows a recoverable “GitHub is temporarily busy” state with Try again (router.refresh()).

Reviewed by Cursor Bugbot for commit 6dd4ad0. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • Bug Fixes
    • GitHub repository lookups now use authentication, improving reliability and access to repositories.
    • GitHub API rate limits are detected and reported with a recoverable response instead of a generic error.
    • Added a clear “GitHub is temporarily busy” message with a Try again option.
  • Tests
    • Added coverage for rate-limit detection and retry behavior.

@github-actions

This comment has been minimized.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Authenticated GitHub repository lookups now classify rate-limit failures, return HTTP 429, propagate a dedicated web error code, and render a retryable busy state in the Ask GitHub page.

Changes

GitHub rate-limit flow

Layer / File(s) Summary
Backend detection and API response
packages/backend/src/api.ts, packages/backend/src/errors.ts, packages/backend/src/errors.test.ts, CHANGELOG.md
Authenticated Octokit requests now detect primary and secondary GitHub rate limits, return HTTP 429, and document the fix with coverage for recognized and unrelated errors.
Web error propagation
packages/web/src/lib/errorCodes.ts, packages/web/src/lib/serviceError.ts, packages/web/src/features/workerApi/actions.ts
HTTP 429 responses now map to GITHUB_RATE_LIMITED through a dedicated service-error factory.
Rate-limit page and retry UI
packages/web/src/app/(app)/askgh/[owner]/[repo]/page.tsx, packages/web/src/app/(app)/askgh/[owner]/[repo]/components/githubRateLimitExceeded.tsx, packages/web/src/app/(app)/askgh/[owner]/[repo]/components/githubRateLimitExceeded.test.tsx
The Ask GitHub page renders a busy message with a “Try again” button that refreshes the route, with component behavior tested.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AskGithubPage
  participant addGithubRepo
  participant experimental_addGithubRepo
  participant GitHub
  AskGithubPage->>addGithubRepo: add repository
  addGithubRepo->>experimental_addGithubRepo: repository lookup request
  experimental_addGithubRepo->>GitHub: authenticated API request
  GitHub-->>experimental_addGithubRepo: rate-limit failure
  experimental_addGithubRepo-->>addGithubRepo: HTTP 429
  addGithubRepo-->>AskGithubPage: GITHUB_RATE_LIMITED
  AskGithubPage->>AskGithubPage: render busy state
  AskGithubPage->>AskGithubPage: refresh on retry
Loading

Possibly related PRs

Suggested reviewers: msukkari

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: Ask GitHub rate-limit handling improvements.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch brendan/fix-sou-1546-sou-1547

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.

@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: 2

🤖 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 `@packages/backend/src/api.ts`:
- Around line 159-161: Protect the /api/experimental/add-github-repo endpoint
with mandatory authentication before constructing the Octokit client or
performing any GitHub lookup. Replace the optional-auth behavior with the
backend’s required-auth guard and reject unauthenticated requests; preserve the
existing authenticated repository persistence and indexing flow.

In `@packages/backend/src/errors.ts`:
- Around line 43-48: The rate-limit classifier must inspect wrapped errors
consistently with getStatus. Update the logic around the responseHeaders and
message extraction to read metadata from cause.response and the wrapped error
message as well as the top-level fields, preserving existing top-level handling;
add a regression test covering a wrapped GitHub 403 with rate-limit metadata and
verifying it is classified as HTTP 429.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5201e88a-275b-4c9e-9367-1697a360b466

📥 Commits

Reviewing files that changed from the base of the PR and between e1ce46b and 6dd4ad0.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • packages/backend/src/api.ts
  • packages/backend/src/errors.test.ts
  • packages/backend/src/errors.ts
  • packages/web/src/app/(app)/askgh/[owner]/[repo]/components/githubRateLimitExceeded.test.tsx
  • packages/web/src/app/(app)/askgh/[owner]/[repo]/components/githubRateLimitExceeded.tsx
  • packages/web/src/app/(app)/askgh/[owner]/[repo]/page.tsx
  • packages/web/src/features/workerApi/actions.ts
  • packages/web/src/lib/errorCodes.ts
  • packages/web/src/lib/serviceError.ts

Comment on lines +159 to +161
const octokit = new Octokit({
auth: env.EXPERIMENT_ASK_GH_GITHUB_TOKEN,
});

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant file with line numbers around the cited lines.
sed -n '120,220p' packages/backend/src/api.ts

# Locate addGithubRepo and auth wrapper usage.
rg -n "addGithubRepo|withOptionalAuth|Octokit|EXPERIMENT_ASK_GH_GITHUB_TOKEN|refresh" packages/backend/src -S

# Inspect withOptionalAuth definition if present in repo.
fd -a "withAuth.ts" "packages" "src" 2>/dev/null || true
rg -n "function withOptionalAuth|const withOptionalAuth|withOptionalAuth" packages -S

Repository: sourcebot-dev/sourcebot

Length of output: 30017


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the API route registration and any surrounding server-level middleware in packages/backend/src/api.ts.
sed -n '1,120p' packages/backend/src/api.ts

# Find who calls the experimental add-github-repo endpoint.
rg -n "/api/experimental/add-github-repo|addGithubRepo|experimental_addGithubRepo" packages -S

# Inspect the frontend page/api file that may call into this flow.
sed -n '1,160p' packages/web/src/app/\(app\)/askgh/\[owner\]/\[repo\]/api.ts

# Inspect the withOptionalAuth helper for context, but only from source.
sed -n '1,140p' packages/web/src/middleware/withAuth.ts

Repository: sourcebot-dev/sourcebot

Length of output: 10840


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '70,130p' packages/web/src/features/workerApi/actions.ts
sed -n '1,120p' packages/web/src/app/\(app\)/askgh/\[owner\]/\[repo\]/page.tsx

Repository: sourcebot-dev/sourcebot

Length of output: 5228


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the anonymous-access gate and the entitlement helper used by the page.
rg -n "isAnonymousAccessEnabled|hasEntitlement\\('ask'\\)|export const hasEntitlement|function hasEntitlement" packages/web/src packages/shared/src -S
sed -n '1,220p' packages/web/src/lib/entitlements.ts

Repository: sourcebot-dev/sourcebot

Length of output: 9447


Require auth before the GitHub lookup endpoint.
/api/experimental/add-github-repo is open, and the UI’s withOptionalAuth guard doesn’t protect the backend route. Any client that can reach the worker can probe arbitrary owner/repo pairs through the GitHub token and persist/index the result. If this must stay public, use a read-only public token and add abuse throttling.

🤖 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 `@packages/backend/src/api.ts` around lines 159 - 161, Protect the
/api/experimental/add-github-repo endpoint with mandatory authentication before
constructing the Octokit client or performing any GitHub lookup. Replace the
optional-auth behavior with the backend’s required-auth guard and reject
unauthenticated requests; preserve the existing authenticated repository
persistence and indexing flow.

Comment on lines +43 to +48
const responseHeaders = (err as { response?: { headers?: Record<string, string | undefined> } }).response?.headers;
const message = (err as { message?: unknown }).message;

return responseHeaders?.['x-ratelimit-remaining'] === '0'
|| responseHeaders?.['retry-after'] !== undefined
|| (typeof message === 'string' && /rate limit/i.test(message));

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Handle wrapped errors consistently with getStatus.

getStatus accepts cause.response.status, but the classifier only reads top-level response.headers and message. A wrapped GitHub 403 containing rate-limit metadata under cause.response can therefore fall through as a generic error instead of returning HTTP 429. Read headers/message from the same response shape, and add a regression test for the wrapped case.

🤖 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 `@packages/backend/src/errors.ts` around lines 43 - 48, The rate-limit
classifier must inspect wrapped errors consistently with getStatus. Update the
logic around the responseHeaders and message extraction to read metadata from
cause.response and the wrapped error message as well as the top-level fields,
preserving existing top-level handling; add a regression test covering a wrapped
GitHub 403 with rate-limit metadata and verifying it is classified as HTTP 429.

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