:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): show a GitHub settings link when a PR repo is out of reach (#129334)
Dylan Martin53b7d13867a2
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 289ce575bdc3..2fb0cad85040 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -232,6 +232,17 @@ const CONTENT_EXPIRED_SELF_HANDLED_BY_LOGIC_PATH: Record<string, string> = {generateSummary: 'products.ai_observability.frontend.summary-view.summaryViewLogic',}+/*+Loads whose owning logic renders a 404 with code `github_repository_inaccessible` inline, with a link+to the GitHub integration settings. The team's GitHub connection can't reach the PR's repository, so+the 404 is a setup state, not a defect. The backend raises the code in products/signals/backend/views.py.+*/+const GITHUB_REPOSITORY_INACCESSIBLE_SELF_HANDLED_BY_LOGIC_PATH: Record<string, string> = {+ loadReportDiff: 'scenes.inbox.logics.inboxReportDetailLogic',+ loadPrChecks: 'scenes.inbox.logics.inboxReportDetailLogic',+ loadPrComments: 'scenes.inbox.logics.inboxReportDetailLogic',+}+// projectLogic toasts a duplicate project name 409 from these actions.const CONFLICT_SELF_HANDLED_BY_LOGIC_PATH: Record<string, string> = {createProject: 'scenes.projectLogic',@@ -242,6 +253,9 @@ function isExpectedFailureOwnedByLogic(error: any, actionKey: string, logicPath:if (error?.status === 404 && error?.code === 'content_expired') {return isOwnedByLogic(CONTENT_EXPIRED_SELF_HANDLED_BY_LOGIC_PATH, actionKey, logicPath)}+ if (error?.status === 404 && error?.code === 'github_repository_inaccessible') {+ return isOwnedByLogic(GITHUB_REPOSITORY_INACCESSIBLE_SELF_HANDLED_BY_LOGIC_PATH, actionKey, logicPath)+ }return error?.status === 409 && isOwnedByLogic(CONFLICT_SELF_HANDLED_BY_LOGIC_PATH, actionKey, logicPath)}diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex d8e6cb09deb2..141cd0f7820a 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -3902,6 +3902,19 @@ class PullRequestChecksPermissionErrorSerializer(serializers.Serializer):)+class GitHubRepositoryInaccessibleErrorSerializer(serializers.Serializer):+ """Response when none of the team's GitHub integrations can access the repository."""++ code = serializers.CharField(+ read_only=True, help_text="Stable code for a repository no GitHub integration can access."+ )+ error = serializers.CharField(read_only=True, help_text="Which repository GitHub can't access, and who can fix it.")+ remediation_url = serializers.CharField(+ read_only=True,+ help_text="Project integrations settings where a project admin can reconnect GitHub.",+ )++class PullRequestCiStatus(TextChoices):"""Coarse rollup of a pull request's checks, as mapped from GitHub's status check rollup."""diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex bc746b87d8a5..9ae502c02a47 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -5829,11 +5829,20 @@ class TestSignalReportPrEndpoints(APIBaseTest):assert response.status_code == status.HTTP_404_NOT_FOUND- def test_pr_checks_404_when_no_integration_can_access_repo(self):+ @parameterized.expand([("checks", "_checks_url"), ("comments", "_comments_url")])+ def test_pr_detail_404_when_no_integration_can_access_repo(self, _name: str, url_method: str) -> None:report = self._create_report()with patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None):- response = self.client.get(self._checks_url(str(report.id)))+ response = self.client.get(getattr(self, url_method)(str(report.id)))assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.json() == {+ "code": "github_repository_inaccessible",+ "error": (+ "PostHog's GitHub connection can't access PostHog/posthog. A project admin must give the GitHub app "+ "access to this repository, or reconnect GitHub."+ ),+ "remediation_url": f"/project/{self.team.id}/settings/project-integrations",+ }def test_pr_checks_503_when_egress_budget_sheds_request(self):report = self._create_report()diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex be573b94b2b6..14934e0e82c9 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -2522,6 +2522,8 @@ class TestSignalReportCommitDiff(APIBaseTest):with patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None):response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.json()["code"] == "github_repository_inaccessible"+ assert response.json()["remediation_url"] == f"/project/{self.team.id}/settings/project-integrations"def _mock_github(self, result: dict):github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 8fdd81f23f16..bd9737238029 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -266,6 +266,7 @@ from products.signals.backend.scout_harness.views import emit_report_from_validafrom products.signals.backend.scout_report.trial_inbox import TrialInboxReads, private_report_artefactsfrom products.signals.backend.serializers import (CommitDiffResponseSerializer,+ GitHubRepositoryInaccessibleErrorSerializer,PersonalRankingQuerySerializer,PersonalRankingSerializer,PullRequestChecksPermissionErrorSerializer,@@ -375,6 +376,23 @@ _PULL_REQUEST_ID_PARAMETER = OpenApiParameter(description="Select a PR from the report's pull_requests collection. Omit for the compatibility primary PR (unfinished first).",)++def github_repository_inaccessible_response(team_id: int, repository: str) -> Response:+ return Response(+ GitHubRepositoryInaccessibleErrorSerializer(+ {+ "code": "github_repository_inaccessible",+ "error": (+ f"PostHog's GitHub connection can't access {repository}. A project admin must give the "+ "GitHub app access to this repository, or reconnect GitHub."+ ),+ "remediation_url": f"/project/{team_id}/settings/project-integrations",+ }+ ).data,+ status=status.HTTP_404_NOT_FOUND,+ )++# Reports one batch CI-status request may ask about. A report list page is 50 rows, so a full page# of pull requests fits, with room for a flat list that merges several sections.PR_CI_STATUS_MAX_REPORTS = 100@@ -5113,7 +5131,10 @@ class SignalReportViewSet(description="The CI checks on the report's implementation pull request.",),404: OpenApiResponse(- description="Report has no implementation PR, or no GitHub integration can access it."+ description=(+ "Report has no implementation PR, or no GitHub integration can access it "+ "(code `github_repository_inaccessible`, with a `remediation_url`)."+ )),403: OpenApiResponse(response=PullRequestChecksPermissionErrorSerializer,@@ -5220,7 +5241,10 @@ class SignalReportViewSet(description="Conversation and review comments on the report's implementation pull request.",),404: OpenApiResponse(- description="Report has no implementation PR, or no GitHub integration can access it."+ description=(+ "Report has no implementation PR, or no GitHub integration can access it "+ "(code `github_repository_inaccessible`, with a `remediation_url`)."+ )),502: OpenApiResponse(description="GitHub could not return the comments."),503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),@@ -5701,15 +5725,7 @@ class SignalReportViewSet(),)if github is None:- return (- None,- repository,- pr_number,- Response(- {"error": f"No GitHub integration can access '{repository}'."},- status=status.HTTP_404_NOT_FOUND,- ),- )+ return None, repository, pr_number, github_repository_inaccessible_response(self.team.id, repository)return github, repository, pr_number, None@@ -7105,7 +7121,12 @@ class SignalReportArtefactViewSet(description="The pull request diff, or the branch diff when no pull request is linked.",),400: OpenApiResponse(description="Artefact is not a commit, or is missing repository/branch."),- 404: OpenApiResponse(description="Artefact not found, or no GitHub integration can access the repository."),+ 404: OpenApiResponse(+ description=(+ "Artefact not found, or no GitHub integration can access the repository "+ "(code `github_repository_inaccessible`, with a `remediation_url`)."+ )+ ),502: OpenApiResponse(description="GitHub could not produce the diff (branch not found, fetch failed)."),},summary="Fetch the diff for a commit artefact",@@ -7152,10 +7173,7 @@ class SignalReportArtefactViewSet(except GitHubRateLimitError as e:return github_rate_limited_response(e)if github is None:- return Response(- {"error": f"No GitHub integration can access '{repository}'."},- status=status.HTTP_404_NOT_FOUND,- )+ return github_repository_inaccessible_response(self.team.id, str(repository))try:pull_request = _pull_request_ref_for_commit(artefact, str(repository), str(branch), github)except GitHubRateLimitError as e:diff --git a/products/signals/frontend/inbox/components/detail/PrCommentsSection.tsx b/products/signals/frontend/inbox/components/detail/PrCommentsSection.tsxindex d2400ea74afe..daf8abf15944 100644--- a/products/signals/frontend/inbox/components/detail/PrCommentsSection.tsx+++ b/products/signals/frontend/inbox/components/detail/PrCommentsSection.tsx@@ -89,7 +89,14 @@ export function PrCommentsSection({ report }: { report: SignalReport }): JSX.Ele}>{prCommentsError ? (- <p className="m-0 py-2 text-sm text-danger">{prCommentsError}</p>+ <p className="m-0 py-2 text-sm text-danger">+ {prCommentsError.message}+ {prCommentsError.remediationUrl ? (+ <Link to={prCommentsError.remediationUrl} className="ml-2">+ Open GitHub integration settings+ </Link>+ ) : null}+ </p>) : prComments === null ? (<div className="flex flex-col gap-3"><LemonSkeleton className="h-10 w-full" />diff --git a/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx b/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsxindex eebe346650da..4e08bd4179c5 100644--- a/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx+++ b/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'import { useCallback, useMemo, useState } from 'react'import { IconChat, IconGitBranch } from '@posthog/icons'-import { LemonSegmentedButton, LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'+import { LemonSegmentedButton, LemonSkeleton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { DraftThread, inboxReportDetailLogic, ReviewThread, threadKey } from '../../logics/inboxReportDetailLogic'import { SignalReport } from '../../types'@@ -170,7 +170,14 @@ export function PullRequestDiffPanel({ report, commit }: { report: SignalReport;/></div>{reportDiffError ? (- <p className="m-0 py-4 text-sm text-danger">{reportDiffError}</p>+ <p className="m-0 py-4 text-sm text-danger">+ {reportDiffError.message}+ {reportDiffError.remediationUrl ? (+ <Link to={reportDiffError.remediationUrl} className="ml-2">+ Open GitHub integration settings+ </Link>+ ) : null}+ </p>) : reportDiff ? (<><PullRequestDiffViewdiff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 409489419745..a535840b0244 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -1203,8 +1203,47 @@ describe('inboxReportDetailLogic', () => {message:"GitHub can't read pull request checks. A project admin must reconnect GitHub and grant the Checks permission.",remediationUrl: '/project/2/settings/project-integrations',+ code: 'github_checks_permission_missing',})})++ it('links an inaccessible repository to the GitHub settings and stops polling its checks', async () => {+ const inaccessible = {+ code: 'github_repository_inaccessible',+ error: "PostHog's GitHub connection can't access example/repo. A project admin must give the GitHub app access to this repository, or reconnect GitHub.",+ remediation_url: '/project/2/settings/project-integrations',+ }+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/pr_checks/': () => {+ prChecksRequests += 1+ return [404, inaccessible]+ },+ '/api/projects/:team_id/signals/reports/:id/pr_comments/': [404, inaccessible],+ },+ })+ logic.unmount()+ prChecksRequests = 0+ jest.useFakeTimers()+ logic = inboxReportDetailLogic({ reportId: PR_REPORT.id, report: PR_REPORT })+ logic.mount()+ try {+ await jest.advanceTimersByTimeAsync(1000)+ const expected = {+ message: inaccessible.error,+ remediationUrl: inaccessible.remediation_url,+ code: 'github_repository_inaccessible',+ }+ expect(logic.values.prChecksError).toEqual(expected)+ expect(logic.values.prCommentsError).toEqual(expected)+ expect(prChecksRequests).toBe(1)++ await jest.advanceTimersByTimeAsync(15000 * 20)+ expect(prChecksRequests).toBe(1)+ } finally {+ jest.useRealTimers()+ }+ })})describe('PR response races', () => {diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex 464ea6049ccd..4e3355870ff4 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -107,22 +107,26 @@ const SLOT_CLAIM_DISABLED_REASON: Record<ImplementationSlotClaim, string> = {shipped_pr: 'This report already has a pull request. Open it in the task log to continue it.',}-export type PrChecksError = {+export type GitHubLoadError = {message: stringremediationUrl: string | null+ code: string | null}-const GITHUB_CHECKS_PERMISSION_MISSING_CODE = 'github_checks_permission_missing'+export const GITHUB_REPOSITORY_INACCESSIBLE_CODE = 'github_repository_inaccessible'+// Errors a project admin fixes in the GitHub integration settings, so the server sends a link there.+const GITHUB_REMEDIABLE_ERROR_CODES = ['github_checks_permission_missing', GITHUB_REPOSITORY_INACCESSIBLE_CODE]-function prChecksErrorFrom(error: unknown): PrChecksError {- if (error instanceof ApiError && error.code === GITHUB_CHECKS_PERMISSION_MISSING_CODE) {+function githubLoadErrorFrom(error: unknown, fallbackMessage: string): GitHubLoadError {+ if (error instanceof ApiError && error.code && GITHUB_REMEDIABLE_ERROR_CODES.includes(error.code)) {const remediationUrl = (error.data as { remediation_url?: unknown } | null)?.remediation_urlreturn {message: error.message,remediationUrl: typeof remediationUrl === 'string' ? remediationUrl : null,+ code: error.code,}}- return { message: "Couldn't load the PR checks from GitHub.", remediationUrl: null }+ return { message: fallbackMessage, remediationUrl: null, code: null }}// The task↔report association is the `task_run` artefact log now (the legacy `/tasks/` endpoint is@@ -376,11 +380,11 @@ export interface inboxReportDetailLogicValues {prChecks: readonly PullRequestCheckApi[] | nullprChecksBackedOff: booleanprChecksConsecutiveFailures: number- prChecksError: PrChecksError | null+ prChecksError: GitHubLoadError | nullprChecksFailing: booleanprChecksLoading: booleanprComments: readonly PullRequestCommentApi[] | null- prCommentsError: string | null+ prCommentsError: GitHubLoadError | nullprCommentsLoading: booleanprimaryTask: ReportTaskEntry | nullpriorityExplanation: string | null@@ -394,7 +398,7 @@ export interface inboxReportDetailLogicValues {reportChecksLoading: booleanreportClaimant: _UserApi | nullreportDiff: CommitDiffResponseApi | null- reportDiffError: string | null+ reportDiffError: GitHubLoadError | nullreportDiffLoading: booleanreportReviewers: EnrichedReviewer[] | nullreportSignals: SignalNode[] | null@@ -1294,11 +1298,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([],// Human-readable diff-load failure (kea-loaders only exposes a boolean loading flag).reportDiffError: [- null as string | null,+ null as GitHubLoadError | null,{loadReportDiff: () => null,loadReportDiffSuccess: () => null,- loadReportDiffFailure: () => "Couldn't load the diff. Try again, or open the pull request on GitHub.",+ loadReportDiffFailure: (_, { errorObject }) =>+ githubLoadErrorFrom(+ errorObject,+ "Couldn't load the diff. Try again, or open the pull request on GitHub."+ ),},],// The commit artefact the current `reportDiff` was loaded for, so the artefact poll re-fetches@@ -1314,10 +1322,11 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// Cleared only on success (not on load start), so the section keeps showing the error while// a backed-off retry is in flight instead of flashing back to the loading skeleton.prChecksError: [- null as PrChecksError | null,+ null as GitHubLoadError | null,{loadPrChecksSuccess: () => null,- loadPrChecksFailure: (_, { errorObject }) => prChecksErrorFrom(errorObject),+ loadPrChecksFailure: (_, { errorObject }) =>+ githubLoadErrorFrom(errorObject, "Couldn't load the PR checks from GitHub."),},],// Consecutive failed checks fetches — feeds `prChecksBackedOff`.@@ -1329,11 +1338,12 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([},],prCommentsError: [- null as string | null,+ null as GitHubLoadError | null,{loadPrComments: () => null,loadPrCommentsSuccess: () => null,- loadPrCommentsFailure: () => "Couldn't load the PR comments from GitHub.",+ loadPrCommentsFailure: (_, { errorObject }) =>+ githubLoadErrorFrom(errorObject, "Couldn't load the PR comments from GitHub."),},],// Cleared only on success, so the error and its retry button stay visible while the retry runs.@@ -2368,7 +2378,8 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([let tick = 0const interval = setInterval(() => {tick += 1- if (!values.hasImplementationPr) {+ // Polling can't fix a repository the GitHub connection can't reach. Only an admin can.+ if (!values.hasImplementationPr || values.prChecksError?.code === GITHUB_REPOSITORY_INACCESSIBLE_CODE) {return}// While backed off, only every Nth tick retries — enough for a transient GitHub