: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
feat(integrations): expose GitHub installation status and install requests (#85114)
Charles Vien218733002c8c
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex f2ccfc47a30c..f7cdeecbb211 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4373,6 +4373,17 @@ export interface UserGitHubAccountApi {name?: string | null}+/**+ * * `connected` - connected+ * * `unavailable` - unavailable+ */+export type InstallationStatusEnumApi = (typeof InstallationStatusEnumApi)[keyof typeof InstallationStatusEnumApi]++export const InstallationStatusEnumApi = {+ Connected: 'connected',+ Unavailable: 'unavailable',+} as const+export interface UserGitHubIntegrationItemApi {/** PostHog UserIntegration row id. */id: string@@ -4394,6 +4405,13 @@ export interface UserGitHubIntegrationItemApi {github_login?: string | null/** True when this installation id matches a team-level GitHub integration on the active project. */uses_shared_installation: boolean+ /** Whether any other PostHog project or personal connection references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization. */+ installation_shared: boolean+ /** `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise.+ *+ * * `connected` - connected+ * * `unavailable` - unavailable */+ installation_status: InstallationStatusEnumApi/** When this integration row was created. */created_at: string}@@ -4449,11 +4467,18 @@ export interface GitHubReposResponseApi {repositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: boolean+ /** Total number of repositories matching the search query, across all pages. */+ total: number}export interface GitHubReposRefreshResponseApi {/** The refreshed repository cache. */repositories: GitHubRepoApi[]+ /** `unavailable` when GitHub reports the App installation as uninstalled or suspended, in which case `repositories` is the last cached list rather than a fresh one.+ *+ * * `connected` - connected+ * * `unavailable` - unavailable */+ installation_status: InstallationStatusEnumApi}/**@@ -4486,6 +4511,16 @@ export interface GitHubInstallRequestItemApi {* @nullable*/installation_id?: string | null+ /**+ * GitHub organization or user login the installation was approved under, once known.+ * @nullable+ */+ account_login?: string | null+ /**+ * GitHub account type (`Organization` or `User`) the installation was approved under, once known.+ * @nullable+ */+ account_type?: string | null/** When the install approval was requested. */requested_at: string/**@@ -4498,6 +4533,11 @@ export interface GitHubInstallRequestItemApi {export interface GitHubInstallRequestListResponseApi {/** The user's GitHub App install-approval requests, newest first. */results: GitHubInstallRequestItemApi[]+ /**+ * Shareable GitHub App install URL with no PostHog session state, for an org owner who needs to approve the install. Null when the GitHub App is not configured on this instance.+ * @nullable+ */+ install_url?: string | null}export interface UserGitHubPrepareCallbackRequestApi {diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex da9a83371790..2aed0839ec75 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -2643,6 +2643,27 @@ export const usersIntegrationsGithubInstallRequestsRetrieve = async (})}+export const getUsersIntegrationsGithubInstallRequestsDestroyUrl = (uuid: string, requestId: string) => {+ return `/api/users/${uuid}/integrations/github/install_requests/${requestId}/`+}++/**+ * Delete one of the requesting user's install-approval requests, whatever its status.+ *+ * User-facing bookkeeping only: a later connect attempt records a fresh row.+ * @summary Dismiss a GitHub install-approval request+ */+export const usersIntegrationsGithubInstallRequestsDestroy = async (+ uuid: string,+ requestId: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getUsersIntegrationsGithubInstallRequestsDestroyUrl(uuid, requestId), {+ ...options,+ method: 'DELETE',+ })+}+export const getUsersIntegrationsGithubPrepareCallbackCreateUrl = (uuid: string) => {return `/api/users/${uuid}/integrations/github/prepare_callback/`}diff --git a/posthog/api/github_callback/README.md b/posthog/api/github_callback/README.mdindex 6114c4689a8e..e968662eb4a0 100644--- a/posthog/api/github_callback/README.md+++ b/posthog/api/github_callback/README.md@@ -117,6 +117,24 @@ adoption.| `/complete/github-link/` | `personal_finish.github_link_complete` | personal user-link || `/webhooks/github` (+ `/pr`) | `posthog/urls.py:github_webhook` | inbound events |+Inbound `installation` events (`installation_events.py`) delete every row for an+uninstalled App and flip `GitHubInstallRequest` rows to approved when an org owner+accepts a member's install request. `installation_repositories` events mirror the+new `repository_selection` ("all" or "selected") onto every row for the+installation and drop their repository caches, so the UI can say "all+repositories" instead of listing them.++### Install requests (org owner approval)++A member installing the App gets `setup_action=request` back from GitHub, which+`install_requests.record_install_request` stores as a pending+`GitHubInstallRequest`. Clients read `GET /api/users/@me/integrations/github/install_requests/`+(rows plus a shareable `install_url` for the org owner) and poll it while a request+is pending; `DELETE .../install_requests/{id}/` dismisses one. The team and personal+integration serializers also expose `installation_shared` (whether disconnecting+leaves the App installed) and `installation_status` (`unavailable` once a token mint+404s), which the disconnect dialogs and status banners are built on.+The team code exchange (`team_services`) calls `github_user_from_code(code)`**without** a `redirect_uri`, so GitHub does not enforce a redirect_uri match onthe token exchange — only the browser landing URL (the App's Setup/Callback URL)diff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.pyindex 543beaa5ac5c..b323fdf4c85c 100644--- a/posthog/api/github_callback/installation_events.py+++ b/posthog/api/github_callback/installation_events.py@@ -16,14 +16,20 @@ silently pointed at a repository it can no longer reach.request (see ``posthog.api.github_callback.install_requests``). The payload's ``requester.id``is who asked, so matching pending ``GitHubInstallRequest`` rows on ``github_user_id`` flip toapproved, which is how the desktop learns the wait is over without polling GitHub itself.++The separate ``installation_repositories`` event fires when an owner changes which repositories+the App can see. It carries the new ``repository_selection`` ("all" or "selected"), which every+row for the installation mirrors so the UI can say "all repositories" instead of listing them."""+from typing import Any+from django.http import HttpResponsefrom django.utils import timezoneimport structlog-from posthog.models.integration import Integration+from posthog.models.integration import Integration, invalidate_github_repository_caches_for_installationfrom posthog.models.user_integration import GitHubInstallRequest, UserIntegrationlogger = structlog.get_logger(__name__)@@ -101,13 +107,20 @@ def _handle_installation_created(payload: dict) -> HttpResponse:)return HttpResponse(status=200)+ account = (payload.get("installation") or {}).get("account") or {}+ update_fields: dict[str, Any] = {+ "status": GitHubInstallRequest.Status.APPROVED,+ "installation_id": str(installation_id),+ "resolved_at": timezone.now(),+ }+ if account.get("login"):+ update_fields["account_login"] = str(account["login"])[:255]+ if account.get("type"):+ update_fields["account_type"] = str(account["type"])[:32]+resolved_count = GitHubInstallRequest.objects.filter(github_user_id=requester_id, status=GitHubInstallRequest.Status.PENDING- ).update(- status=GitHubInstallRequest.Status.APPROVED,- installation_id=str(installation_id),- resolved_at=timezone.now(),- )+ ).update(**update_fields)logger.info("github_installation_webhook_created",@@ -117,3 +130,52 @@ def _handle_installation_created(payload: dict) -> HttpResponse:)return HttpResponse(status=200)+++def handle_installation_repositories_event(payload: dict) -> HttpResponse:+ """Mirror a changed ``repository_selection`` onto every row for the installation and drop+ their repository caches so the next list reflects the new access."""+ installation_id = (payload.get("installation") or {}).get("id")+ repository_selection = payload.get("repository_selection")+ if installation_id is None or not isinstance(repository_selection, str):+ logger.warning(+ "github_installation_repositories_webhook_missing_fields",+ has_installation_id=installation_id is not None,+ repository_selection=repository_selection,+ )+ return HttpResponse(status=200)++ installation_id = str(installation_id)+ # Load only the columns we touch. The unbounded repository_cache blob and the encrypted+ # sensitive_config (decrypted eagerly on load) are skipped so a widely shared installation+ # can't spike a web worker's memory here. Writes go out as one bulk_update per model instead+ # of a save per row — which also skips the (no-op for github) push-config post_save signal,+ # avoiding a per-row lazy load of the deferred `kind`.+ team_changed = [+ row+ for row in Integration.objects.filter(kind="github", integration_id=installation_id).only("id", "config")+ if row.config.get("repository_selection") != repository_selection+ ]+ user_changed = [+ row+ for row in UserIntegration.objects.filter(kind="github", integration_id=installation_id).only("id", "config")+ if row.config.get("repository_selection") != repository_selection+ ]+ changed: list[Integration | UserIntegration] = [*team_changed, *user_changed]+ for row in changed:+ row.config = {**row.config, "repository_selection": repository_selection}+ if team_changed:+ Integration.objects.bulk_update(team_changed, ["config"])+ if user_changed:+ UserIntegration.objects.bulk_update(user_changed, ["config"])+ updated = len(changed)++ invalidate_github_repository_caches_for_installation(installation_id)++ logger.info(+ "github_installation_repositories_webhook_applied",+ installation_id=installation_id,+ repository_selection=repository_selection,+ rows_updated=updated,+ )+ return HttpResponse(status=200)diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.pyindex 22e298c6df93..04394881668d 100644--- a/posthog/api/github_callback/types.py+++ b/posthog/api/github_callback/types.py@@ -150,12 +150,18 @@ def github_oauth_redirect_uri() -> str:return f"{settings.SITE_URL.rstrip('/')}/complete/github-link/"-def github_app_install_url(state: str) -> str:+def github_app_install_url_shareable() -> str:+ """The App's install page with no PostHog state attached, safe to hand to a GitHub org owner+ who has no PostHog session to resume."""instance_settings = get_instance_settings(["GITHUB_APP_SLUG"])app_slug = instance_settings.get("GITHUB_APP_SLUG")if not app_slug:raise ApiValidationError("GitHub App is not configured on this instance (missing GITHUB_APP_SLUG).")- return f"https://github.com/apps/{app_slug}/installations/new?{urlencode({'state': state})}"+ return f"https://github.com/apps/{app_slug}/installations/new"+++def github_app_install_url(state: str) -> str:+ return f"{github_app_install_url_shareable()}?{urlencode({'state': state})}"def github_oauth_authorize_url(state: str) -> str:diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 8c6cf954a33b..a3ac758584c8 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -15,7 +15,7 @@ from django.utils import timezoneimport structlogfrom django_filters.rest_framework import DjangoFilterBackend-from drf_spectacular.utils import extend_schema, extend_schema_serializer+from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_serializerfrom prometheus_client import Counterfrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, PermissionDenied, ValidationError@@ -284,10 +284,23 @@ class GitHubReposQuerySerializer(serializers.Serializer):class GitHubReposResponseSerializer(serializers.Serializer):repositories = GitHubRepoSerializer(many=True)has_more = serializers.BooleanField(help_text="Whether more repositories are available beyond this page.")+ total = serializers.IntegerField(+ help_text="Total number of repositories matching the search query, across all pages."+ )+++GITHUB_INSTALLATION_STATUS_CHOICES = ["connected", "unavailable"]class GitHubReposRefreshResponseSerializer(serializers.Serializer):repositories = GitHubRepoSerializer(many=True, help_text="The refreshed repository cache.")+ installation_status = serializers.ChoiceField(+ choices=GITHUB_INSTALLATION_STATUS_CHOICES,+ help_text=(+ "`unavailable` when GitHub reports the App installation as uninstalled or suspended, in which "+ "case `repositories` is the last cached list rather than a fresh one."+ ),+ )class JiraProjectSerializer(serializers.Serializer):@@ -438,11 +451,60 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial"""Standard Integration serializer."""created_by = UserBasicSerializer(read_only=True)+ installation_shared = serializers.SerializerMethodField(+ help_text=(+ "GitHub only, null otherwise. Whether another project's GitHub integration references the same "+ "App installation. When false, disconnecting this integration also uninstalls the GitHub App from "+ "the connected account or organization and removes personal GitHub connections that share it."+ )+ )+ installation_status = serializers.SerializerMethodField(+ help_text=(+ "GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub "+ "and PostHog can no longer mint tokens for it; `connected` otherwise."+ )+ )class Meta:model = Integration- fields = ["id", "kind", "config", "created_at", "created_by", "errors", "display_name"]- read_only_fields = ["id", "created_at", "created_by", "errors", "display_name"]+ fields = [+ "id",+ "kind",+ "config",+ "created_at",+ "created_by",+ "errors",+ "display_name",+ "installation_shared",+ "installation_status",+ ]+ read_only_fields = [+ "id",+ "created_at",+ "created_by",+ "errors",+ "display_name",+ "installation_shared",+ "installation_status",+ ]++ @extend_schema_field(serializers.BooleanField(allow_null=True))+ def get_installation_shared(self, obj: Integration) -> bool | None:+ if obj.kind != "github" or not obj.integration_id:+ return None+ # Mirrors the check in IntegrationViewSet.perform_destroy: only other *team* rows keep the App+ # installed on GitHub. Personal rows don't count because destroy deletes them along with it.+ reference_counts = self.context.get("github_reference_counts")+ if reference_counts is not None:+ # List passes counts for the whole page, so the field costs one query however many rows there are.+ return reference_counts.get(obj.integration_id, 0) > 1+ return Integration.objects.filter(kind="github", integration_id=obj.integration_id).exclude(id=obj.id).exists()++ @extend_schema_field(serializers.ChoiceField(choices=GITHUB_INSTALLATION_STATUS_CHOICES, allow_null=True))+ def get_installation_status(self, obj: Integration) -> str | None:+ if obj.kind != "github":+ return None+ return "unavailable" if GitHubIntegration(obj).installation_unavailable() else "connected"def validate_kind(self, value: str) -> str:if value == Integration.IntegrationKind.SLACK_POSTHOG_CODE.value:@@ -1645,8 +1707,9 @@ class IntegrationViewSet(raise ValidationError("github_repos endpoint is only supported for GitHub integrations")github = GitHubIntegration(instance)repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)+ total = github.count_cached_repositories(search=search)- return Response({"repositories": repositories, "has_more": has_more})+ return Response({"repositories": repositories, "has_more": has_more, "total": total})@extend_schema(request=GitHubPrepareCallbackRequestSerializer, responses={204: None})@action(methods=["POST"], detail=False, url_path="github/prepare_callback")@@ -1777,11 +1840,26 @@ class IntegrationViewSet(if instance.kind != "github":raise ValidationError("refresh_github_repos endpoint is only supported for GitHub integrations")github = GitHubIntegration(instance)- repositories = github.sync_repository_cache(- min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS- )+ try:+ repositories = github.sync_repository_cache(+ min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS+ )+ except GitHubIntegrationError as err:+ # A refresh against an installation GitHub has since removed marks it unavailable; report+ # that as a state rather than a failure so the UI can offer removal instead of a retry loop.+ if not github.installation_unavailable():+ capture_exception(err)+ raise ValidationError(+ "Unable to refresh GitHub repositories. Please check integration settings and try again."+ ) from err+ repositories = github.list_all_cached_repositories(allow_refresh=False)- return Response({"repositories": repositories})+ return Response(+ {+ "repositories": repositories,+ "installation_status": "unavailable" if github.installation_unavailable() else "connected",+ }+ )@extend_schema(parameters=[GitHubTeamsQuerySerializer],@@ -1966,3 +2044,45 @@ class IntegrationViewSet(raise ValidationError("Error generating apply URL. Please try again later or contact support.")return Response({"url": url})++ # Defined last: a method named `list` shadows the builtin for the annotations of every method+ # declared after it in this class body.+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # A GitHub row connected while GitHub was flaky may still carry the numeric installation id+ # as its account name. Healing here (throttled inside ensure_account_name) fixes the display+ # everywhere the row is listed, including surfaces that never open the repository picker.+ # Inlined from ListModelMixin so the heal runs over the page being returned rather than the+ # whole queryset — each heal can spend a GitHub round trip, so rows nobody asked for mustn't+ # pay for one.+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)+ instances = page if page is not None else list(queryset)+ for instance in instances:+ if instance.kind == "github":+ GitHubIntegration(instance).ensure_account_name()+ # One grouped lookup for the whole page instead of an `exists()` per row, so+ # `installation_shared` stays a fixed one query however many GitHub rows there are.+ reference_counts = GitHubIntegration.installation_reference_counts(+ {+ instance.integration_id+ for instance in instances+ if instance.kind == "github" and instance.integration_id+ },+ include_personal=False,+ )+ serializer = self.get_serializer(+ instances,+ many=True,+ context={**self.get_serializer_context(), "github_reference_counts": reference_counts},+ )+ if page is not None:+ return self.get_paginated_response(serializer.data)+ return Response(serializer.data)++ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # Inlined from RetrieveModelMixin too: deferring to it would re-run `get_object`, paying a+ # second query and permission check for the row already in hand.+ instance = self.get_object()+ if instance.kind == "github":+ GitHubIntegration(instance).ensure_account_name()+ return Response(self.get_serializer(instance).data)diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.pyindex 4f7da9825bb1..2bd193961bc3 100644--- a/posthog/api/test/test_github_installation_webhook.py+++ b/posthog/api/test/test_github_installation_webhook.py@@ -5,6 +5,7 @@ import hashlibfrom unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.test import APIClient@@ -202,7 +203,7 @@ class TestGitHubInstallationWebhook(TestCase):response = self._post({"action": "created",- "installation": {"id": 55555},+ "installation": {"id": 55555, "account": {"login": "posthog-org", "type": "Organization"}},"requester": {"id": 4242, "login": "octocat-renamed"},})@@ -211,6 +212,8 @@ class TestGitHubInstallationWebhook(TestCase):matching.refresh_from_db()self.assertEqual(matching.status, GitHubInstallRequest.Status.APPROVED)self.assertEqual(matching.installation_id, "55555")+ self.assertEqual(matching.account_login, "posthog-org")+ self.assertEqual(matching.account_type, "Organization")self.assertIsNotNone(matching.resolved_at)someone_else.refresh_from_db()@@ -234,6 +237,39 @@ class TestGitHubInstallationWebhook(TestCase):pending.refresh_from_db()self.assertEqual(pending.status, GitHubInstallRequest.Status.PENDING)+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ def test_installation_repositories_updates_selection_and_invalidates_caches(self, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ team_row = self._team_integration("12345")+ user_row = self._user_integration("12345")+ untouched = self._team_integration("67890")+ for row in (team_row, user_row, untouched):+ row.config = {**row.config, "repository_selection": "selected"}+ row.repository_cache_updated_at = timezone.now()+ row.save()++ response = self._post(+ {+ "action": "added",+ "installation": {"id": 12345},+ "repository_selection": "all",+ "repositories_added": [{"full_name": "posthog/posthog"}],+ "repositories_removed": [],+ },+ event_type="installation_repositories",+ )++ self.assertEqual(response.status_code, 200)+ team_row.refresh_from_db()+ user_row.refresh_from_db()+ untouched.refresh_from_db()+ self.assertEqual(team_row.config["repository_selection"], "all")+ self.assertEqual(user_row.config["repository_selection"], "all")+ self.assertIsNone(team_row.repository_cache_updated_at)+ self.assertIsNone(user_row.repository_cache_updated_at)+ self.assertEqual(untouched.config["repository_selection"], "selected")+ self.assertIsNotNone(untouched.repository_cache_updated_at)+@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")def test_invalid_signature_returns_403_and_keeps_rows(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretdiff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 6acff66470e6..c6889664cbd6 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -10,8 +10,10 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import ANY, MagicMock, patchfrom django.core.cache import cache+from django.db import connectionfrom django.test import override_settingsfrom django.test.client import Client as HttpClient+from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport requests@@ -1305,6 +1307,10 @@ class TestIntegrationAPIKeyAccess:def test_github_repos_pagination(self, mock_list_repos, client: HttpClient):repos = [{"id": i, "name": f"repo{i}", "full_name": f"org/repo{i}"} for i in range(100)]mock_list_repos.return_value = (repos, True)+ self.github_integration.repository_cache = [+ {"id": i, "name": f"repo{i}", "full_name": f"org/repo{i}"} for i in range(250)+ ]+ self.github_integration.save()key_value = "test_key_123"PersonalAPIKey.objects.create(@@ -1323,6 +1329,7 @@ class TestIntegrationAPIKeyAccess:data = response.json()assert len(data["repositories"]) == 100assert data["has_more"] is True+ assert data["total"] == 250mock_list_repos.assert_called_once_with(search="", limit=100, offset=100)@patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")@@ -1602,6 +1609,42 @@ class TestIntegrationAPIKeyAccess:assert "integration:write" in response.json()["detail"]mock_sync_repository_cache.assert_not_called()+ @pytest.mark.parametrize(+ "installation_gone,expected_status",+ [(True, status.HTTP_200_OK), (False, status.HTTP_400_BAD_REQUEST)],+ )+ @patch("posthog.models.integration.github.GitHubIntegration.sync_repository_cache")+ def test_refresh_github_repos_distinguishes_uninstalled_from_transient_failure(+ self, mock_sync_repository_cache, installation_gone, expected_status, client: HttpClient+ ):+ self.github_integration.repository_cache = [{"id": 1, "name": "repo1", "full_name": "org/repo1"}]+ if installation_gone:+ self.github_integration.config = {+ **self.github_integration.config,+ "installation_unavailable_since": 1704110400,+ }+ self.github_integration.save()+ mock_sync_repository_cache.side_effect = GitHubIntegrationError("token refresh after 401 failed")++ key_value = "test_key_123"+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:write"],+ )++ response = client.post(+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_repos/refresh/",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )++ assert response.status_code == expected_status+ if installation_gone:+ data = response.json()+ assert data["installation_status"] == "unavailable"+ assert data["repositories"] == [{"id": 1, "name": "repo1", "full_name": "org/repo1"}]+def test_refresh_github_repos_is_mapped_as_write_action(self):assert "refresh_github_repos" in IntegrationViewSet.scope_object_write_actions@@ -3041,11 +3084,11 @@ class TestGitHubTeamIntegrationComplete:access_token_expires_in=28800,refresh_token_expires_in=15897600,)- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -3093,9 +3136,9 @@ class TestGitHubTeamIntegrationComplete:access_token_expires_in=28800,refresh_token_expires_in=15897600,)- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"}}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -3131,11 +3174,11 @@ class TestGitHubTeamIntegrationComplete:config={"installation_id": "12345", "repository_selection": "selected"},sensitive_config={"access_token": "ghs_old", "user_access_token": "gho_user"},)- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -5420,6 +5463,113 @@ class TestSlackPostHogCodeKindDeprecated:assert "kind" not in serializer.errors+class TestGitHubIntegrationListStatusFields:+ @pytest.fixture(autouse=True)+ def setup_integration(self, db):+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create_and_join(+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN+ )++ def _create_github_integration(self, team: Team, installation_id: str = "12345", **config) -> Integration:+ return Integration.objects.create(+ team=team,+ kind="github",+ config={+ "installation_id": installation_id,+ "account": {"name": "PostHog", "type": "Organization"},+ **config,+ },+ sensitive_config={"access_token": "ghs_token"},+ integration_id=installation_id,+ created_by=self.user,+ )++ def _list_github_row(self, client: HttpClient, integration_id: int) -> dict:+ client.force_login(self.user)+ response = client.get(f"/api/environments/{self.team.pk}/integrations/?kind=github")+ assert response.status_code == status.HTTP_200_OK+ return next(row for row in response.json()["results"] if row["id"] == integration_id)++ def test_installation_shared_false_when_this_is_the_only_team_row(self, client: HttpClient):+ integration = self._create_github_integration(self.team)+ # A personal row alone doesn't keep the App installed: destroy deletes it along with the team row.+ UserIntegration.objects.create(+ user=self.user, kind="github", integration_id="12345", config={}, sensitive_config={}+ )++ row = self._list_github_row(client, integration.id)++ assert row["installation_shared"] is False+ assert row["installation_status"] == "connected"++ def test_installation_shared_true_when_another_team_uses_the_installation(self, client: HttpClient):+ integration = self._create_github_integration(self.team)+ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ self._create_github_integration(other_team)++ row = self._list_github_row(client, integration.id)++ assert row["installation_shared"] is True++ def test_listing_more_github_rows_does_not_add_queries(self, client: HttpClient):+ self._create_github_integration(self.team, installation_id="1")+ client.force_login(self.user)+ url = f"/api/environments/{self.team.pk}/integrations/?kind=github"++ def integration_table_queries() -> int:+ with CaptureQueriesContext(connection) as captured:+ assert client.get(url).status_code == status.HTTP_200_OK+ return sum(1 for query in captured.captured_queries if "posthog_integration" in query["sql"])++ integration_table_queries() # warm the caches shared across requests+ with_one_row = integration_table_queries()+ for installation_id in ("2", "3", "4", "5"):+ self._create_github_integration(self.team, installation_id=installation_id)++ assert integration_table_queries() == with_one_row++ def test_installation_status_reports_unavailable_marker(self, client: HttpClient):+ integration = self._create_github_integration(self.team, installation_unavailable_since=1704110400)++ row = self._list_github_row(client, integration.id)++ assert row["installation_status"] == "unavailable"++ def test_status_fields_are_null_for_other_kinds(self, client: HttpClient):+ integration = Integration.objects.create(+ team=self.team, kind="databricks", integration_id="workspace-1", config={}, sensitive_config={}+ )++ client.force_login(self.user)+ response = client.get(f"/api/environments/{self.team.pk}/integrations/?kind=databricks")++ assert response.status_code == status.HTTP_200_OK+ row = next(row for row in response.json()["results"] if row["id"] == integration.id)+ assert row["installation_shared"] is None+ assert row["installation_status"] is None++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_list_heals_a_placeholder_account_name(self, mock_client_request, client: HttpClient):+ mock_client_request.return_value = MagicMock(+ status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}}+ )+ integration = Integration.objects.create(+ team=self.team,+ kind="github",+ config={"installation_id": "12345", "account": {"name": "12345", "type": None}},+ sensitive_config={"access_token": "ghs_token"},+ integration_id="12345",+ )++ row = self._list_github_row(client, integration.id)++ assert row["display_name"] == "PostHog"+ assert row["config"]["account"] == {"name": "PostHog", "type": "Organization"}+ mock_client_request.assert_called_once_with("installations/12345")++class TestGitHubIntegrationUninstall:@pytest.fixture(autouse=True)def setup_integration(self, db):diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex d1093b549c54..7dc7e3fa516c 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -16,8 +16,13 @@ from posthog.api.github_callback.state import (store_unified_authorize_state,)from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState-from posthog.models import OrganizationMembership, User-from posthog.models.integration import GitHubInstallationAccess, GitHubUserAuthorization, Integration+from posthog.models import OrganizationMembership, Team, User+from posthog.models.integration import (+ GitHubInstallationAccess,+ GitHubIntegrationError,+ GitHubUserAuthorization,+ Integration,+)from posthog.models.user_integration import (GitHubInstallRequest,ReauthorizationRequired,@@ -79,6 +84,84 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(len(results), 1)self.assertEqual(results[0]["installation_id"], "12345")self.assertFalse(results[0]["uses_shared_installation"])+ self.assertFalse(results[0]["installation_shared"])+ self.assertEqual(results[0]["installation_status"], "connected")++ @parameterized.expand(+ [+ ("team_row_on_another_project", "team"),+ ("another_users_personal_row", "user"),+ ]+ )+ def test_list_installation_shared_counts_any_other_reference(self, _name, other_kind):+ _create_user_integration(self.user)+ if other_kind == "team":+ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ Integration.objects.create(+ team=other_team, kind="github", integration_id="12345", config={}, sensitive_config={}+ )+ else:+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ _create_user_integration(other_user)++ response = self.client.get("/api/users/@me/integrations/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertTrue(results[0]["installation_shared"])+ # The active-project flag stays narrow: neither of these rows is on the current team.+ self.assertFalse(results[0]["uses_shared_installation"])++ def test_list_reports_unavailable_installation(self):+ integration = _create_user_integration(self.user)+ integration.config = {**integration.config, "installation_unavailable_since": 1704110400}+ integration.save()++ response = self.client.get("/api/users/@me/integrations/")++ self.assertEqual(response.json()["results"][0]["installation_status"], "unavailable")++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_list_heals_a_placeholder_account_name(self, mock_client_request):+ mock_client_request.return_value = MagicMock(+ status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}}+ )+ integration = _create_user_integration(self.user)+ integration.config = {**integration.config, "account": {"type": None, "name": "12345"}}+ integration.save()++ response = self.client.get("/api/users/@me/integrations/")++ self.assertEqual(response.json()["results"][0]["account"], {"type": "Organization", "name": "PostHog"})+ mock_client_request.assert_called_once_with("installations/12345")++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.list_all_repositories")+ def test_github_repos_returns_total_across_pages(self, mock_list_all):+ mock_list_all.return_value = [{"id": i, "name": f"repo{i}", "full_name": f"octocat/repo{i}"} for i in range(5)]+ _create_user_integration(self.user)++ response = self.client.get("/api/users/@me/integrations/github/12345/repos/?limit=2&offset=0")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(len(data["repositories"]), 2)+ self.assertTrue(data["has_more"])+ self.assertEqual(data["total"], 5)++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.sync_repository_cache")+ def test_github_repos_refresh_reports_unavailable_installation(self, mock_sync):+ mock_sync.side_effect = GitHubIntegrationError("token refresh after 401 failed")+ integration = _create_user_integration(self.user)+ integration.config = {**integration.config, "installation_unavailable_since": 1704110400}+ integration.repository_cache = [{"id": 1, "name": "repo1", "full_name": "octocat/repo1"}]+ integration.save()++ response = self.client.post("/api/users/@me/integrations/github/12345/repos/refresh/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["installation_status"], "unavailable")+ self.assertEqual(data["repositories"], [{"id": 1, "name": "repo1", "full_name": "octocat/repo1"}])def test_list_returns_multiple_github_integrations(self):_create_user_integration(self.user, integration_id="12345")@@ -139,6 +222,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):github_login="octocat-org",status=GitHubInstallRequest.Status.APPROVED,installation_id="55555",+ account_login="posthog-org",+ account_type="Organization",)GitHubInstallRequest.objects.create(user=other_user,@@ -155,9 +240,50 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(results[0]["id"], str(approved.id))self.assertEqual(results[0]["status"], "approved")self.assertEqual(results[0]["installation_id"], "55555")+ self.assertEqual(results[0]["account_login"], "posthog-org")+ self.assertEqual(results[0]["account_type"], "Organization")+ self.assertIsNone(results[1]["account_login"])logins = {r["github_login"] for r in results}self.assertEqual(logins, {"octocat", "octocat-org"})+ @parameterized.expand(+ [+ (+ "app_configured",+ {"GITHUB_APP_SLUG": "posthog-dev"},+ "https://github.com/apps/posthog-dev/installations/new",+ ),+ ("app_not_configured", {}, None),+ ]+ )+ def test_github_install_requests_includes_shareable_install_url(self, _name, instance_settings, expected):+ with patch("posthog.api.github_callback.types.get_instance_settings", return_value=instance_settings):+ response = self.client.get("/api/users/@me/integrations/github/install_requests/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["install_url"], expected)++ def test_dismiss_install_request_deletes_own_row(self):+ own = GitHubInstallRequest.objects.create(+ user=self.user, github_user_id=4242, github_login="octocat", status=GitHubInstallRequest.Status.PENDING+ )++ response = self.client.delete(f"/api/users/@me/integrations/github/install_requests/{own.id}/")++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(GitHubInstallRequest.objects.filter(id=own.id).exists())++ def test_dismiss_install_request_refuses_another_users_row(self):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ theirs = GitHubInstallRequest.objects.create(+ user=other_user, github_user_id=9999, github_login="someone", status=GitHubInstallRequest.Status.PENDING+ )++ response = self.client.delete(f"/api/users/@me/integrations/github/install_requests/{theirs.id}/")++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertTrue(GitHubInstallRequest.objects.filter(id=theirs.id).exists())+def test_delete_removes_specific_installation(self):_create_user_integration(self.user, integration_id="12345")_create_user_integration(self.user, integration_id="67890")@@ -365,11 +491,11 @@ class TestUserIntegrationEndpoints(APIBaseTest):"""OAuth-only flow: GET has code + state; installation_id is only in server state cache."""mock_verify_get.return_value = MagicMock(status_code=200)mock_user_from_code.return_value = _authorization()- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -427,9 +553,9 @@ class TestUserIntegrationEndpoints(APIBaseTest):# UserIntegration to a different installation.mock_verify_get.return_value = MagicMock(status_code=200)mock_user_from_code.return_value = _authorization()- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"}}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -486,11 +612,11 @@ class TestUserIntegrationEndpoints(APIBaseTest):status_code=200,json=lambda: {"installations": [{"id": 12345}]},)- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -569,11 +695,11 @@ class TestUserIntegrationEndpoints(APIBaseTest):):mock_verify_get.return_value = MagicMock(status_code=200)mock_user_from_code.return_value = _authorization()- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -621,11 +747,11 @@ class TestUserIntegrationEndpoints(APIBaseTest):"""First-party clients pass ``connect_from`` via start payload → cache; success redirects to their destination."""mock_verify_get.return_value = MagicMock(status_code=200)mock_user_from_code.return_value = _authorization()- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "User", "login": "octocat"},}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",@@ -797,9 +923,9 @@ class TestUserIntegrationEndpoints(APIBaseTest):# Verify-access call returns 200 → user has access to the installation.mock_verify_get.return_value = MagicMock(status_code=200)mock_user_from_code.return_value = _authorization()- mock_install_info = MagicMock()+ mock_install_info = MagicMock(status_code=200)mock_install_info.json.return_value = {"account": {"type": "Organization", "login": "acme"}}- mock_access_token = MagicMock()+ mock_access_token = MagicMock(status_code=201)mock_access_token.json.return_value = {"token": "ghs_install_token","expires_at": "2099-01-01T00:00:00Z",diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex 7ebfbe661e31..6747914e198d 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -32,9 +32,11 @@ from posthog.api.github_callback.types import (FlowKind,GitHubAuthorizeState,github_app_install_url,+ github_app_install_url_shareable,github_oauth_authorize_url,)from posthog.api.integration import (+ GITHUB_INSTALLATION_STATUS_CHOICES,GitHubBranchesQuerySerializer,GitHubBranchesResponseSerializer,GitHubReposQuerySerializer,@@ -46,7 +48,7 @@ from posthog.api.integration import (from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.exceptions_capture import capture_exception-from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integration+from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integrationfrom posthog.models.user import Userfrom posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegrationfrom posthog.permissions import APIScopePermission@@ -94,6 +96,20 @@ class UserGitHubIntegrationItemSerializer(serializers.Serializer):uses_shared_installation = serializers.BooleanField(help_text="True when this installation id matches a team-level GitHub integration on the active project.",)+ installation_shared = serializers.BooleanField(+ help_text=(+ "Whether any other PostHog project or personal connection references the same App installation. "+ "When false, disconnecting this integration also uninstalls the GitHub App from the connected "+ "account or organization."+ ),+ )+ installation_status = serializers.ChoiceField(+ choices=GITHUB_INSTALLATION_STATUS_CHOICES,+ help_text=(+ "`unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer "+ "mint tokens for it; `connected` otherwise."+ ),+ )created_at = serializers.DateTimeField(help_text="When this integration row was created.")@@ -149,6 +165,18 @@ class GitHubInstallRequestItemSerializer(serializers.Serializer):allow_null=True,help_text="GitHub App installation id, set once the request is approved.",)+ account_login = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="GitHub organization or user login the installation was approved under, once known.",+ )+ account_type = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="GitHub account type (`Organization` or `User`) the installation was approved under, once known.",+ )requested_at = serializers.DateTimeField(help_text="When the install approval was requested.")resolved_at = serializers.DateTimeField(required=False,@@ -162,6 +190,14 @@ class GitHubInstallRequestListResponseSerializer(serializers.Serializer):many=True,help_text="The user's GitHub App install-approval requests, newest first.",)+ install_url = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ "Shareable GitHub App install URL with no PostHog session state, for an org owner who needs to "+ "approve the install. Null when the GitHub App is not configured on this instance."+ ),+ )class UserSlackIntegrationItemSerializer(serializers.Serializer):@@ -261,6 +297,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"github_prepare_callback","github_destroy","github_repos_refresh",+ "github_install_requests_destroy","slack_start","slack_destroy",]@@ -347,16 +384,28 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):# the loop only sees that one shape, but the per-row dispatch keeps# the door open for dropping the kind default and returning github# + slack rows side-by-side in one response.- integrations = UserIntegration.objects.filter(user=user, kind=kind).order_by("created_at")- # Only compute the github-specific cross-team installation set when- # there could be github rows in the response; for `kind=slack` this- # would be an unused DB roundtrip on every settings page load.- team_installation_ids: set[str] = self._team_github_installation_ids(user) if kind == "github" else set()+ integrations = list(UserIntegration.objects.filter(user=user, kind=kind).order_by("created_at"))+ # Only compute the github-specific lookups when there could be github rows in the+ # response; for `kind=slack` these would be unused DB roundtrips on every settings page load.+ team_installation_ids: set[str] = set()+ reference_counts: dict[str, int] = {}+ if kind == "github":+ team_installation_ids = self._team_github_installation_ids(user)+ # One grouped lookup for the whole page instead of a count pair per row, so+ # `installation_shared` stays a fixed two queries however many rows there are.+ reference_counts = UserGitHubIntegration.installation_reference_counts(+ {integration.integration_id for integration in integrations if integration.integration_id}+ )results: list[dict[str, Any]] = []for integration in integrations:if integration.kind == "github":+ UserGitHubIntegration(integration).ensure_account_name()results.append(- _serialize_github_integration(integration, team_integration_installation_ids=team_installation_ids)+ _serialize_github_integration(+ integration,+ team_integration_installation_ids=team_installation_ids,+ installation_reference_counts=reference_counts,+ ))elif integration.kind == "slack":results.append(_serialize_slack_integration(integration))@@ -408,7 +457,8 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):github = UserGitHubIntegration(integration)repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)- return Response({"repositories": repositories, "has_more": has_more})+ total = github.count_cached_repositories(search=search)+ return Response({"repositories": repositories, "has_more": has_more, "total": total})@extend_schema(summary="Refresh repositories for a personal GitHub installation",@@ -425,10 +475,23 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):raise exceptions.NotFound("No GitHub integration found for this installation.")github = UserGitHubIntegration(integration)- repositories = github.sync_repository_cache(- min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS+ try:+ repositories = github.sync_repository_cache(+ min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS+ )+ except GitHubIntegrationError as err:+ if not github.installation_unavailable():+ capture_exception(err)+ raise exceptions.ValidationError(+ "Unable to refresh GitHub repositories. Please check integration settings and try again."+ ) from err+ repositories = github.list_all_cached_repositories(allow_refresh=False)+ return Response(+ {+ "repositories": repositories,+ "installation_status": "unavailable" if github.installation_unavailable() else "connected",+ })- return Response({"repositories": repositories})@extend_schema(summary="List branches for a personal GitHub installation repository",@@ -484,12 +547,34 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"github_login": install_request.github_login,"status": install_request.status,"installation_id": install_request.installation_id,+ "account_login": install_request.account_login,+ "account_type": install_request.account_type,"requested_at": install_request.requested_at,"resolved_at": install_request.resolved_at,}for install_request in install_requests]- return Response({"results": results})+ try:+ install_url: str | None = github_app_install_url_shareable()+ except exceptions.ValidationError:+ install_url = None+ return Response({"results": results, "install_url": install_url})++ @extend_schema(+ summary="Dismiss a GitHub install-approval request",+ responses={204: OpenApiResponse(description="Request dismissed.")},+ )+ @action(methods=["DELETE"], detail=False, url_path=r"github/install_requests/(?P<request_id>[0-9a-fA-F-]{36})")+ def github_install_requests_destroy(self, request: Request, request_id: str, **_kwargs) -> Response:+ """Delete one of the requesting user's install-approval requests, whatever its status.++ User-facing bookkeeping only: a later connect attempt records a fresh row.+ """+ user = self._get_user()+ deleted, _ = GitHubInstallRequest.objects.filter(user=user, id=request_id).delete()+ if not deleted:+ raise exceptions.NotFound("No GitHub install request found.")+ return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(summary="Start GitHub personal integration linking",@@ -821,8 +906,14 @@ def _serialize_github_integration(integration: UserIntegration,*,team_integration_installation_ids: set[str],+ installation_reference_counts: dict[str, int],) -> dict[str, Any]:"""Build the response payload for a single GitHub UserIntegration."""+ github = UserGitHubIntegration(integration)+ # Mirrors github_destroy's uninstall_if_last_reference: any other row, team or personal, keeps the+ # App installed on GitHub after this one is deleted. The precomputed map counts every reference+ # for the installation including this row, so more than one means another row still shares it.+ installation_shared = installation_reference_counts.get(integration.integration_id or "", 0) > 1return {"id": integration.id,"kind": "github",@@ -833,6 +924,8 @@ def _serialize_github_integration(# org/user). Lets the frontend tell which PR comments/reactions are the user's own."github_login": (integration.config.get("github_user") or {}).get("login"),"uses_shared_installation": integration.integration_id in team_integration_installation_ids,+ "installation_shared": installation_shared,+ "installation_status": "unavailable" if github.installation_unavailable() else "connected","created_at": integration.created_at,}diff --git a/posthog/migrations/1315_githubinstallrequest_account.py b/posthog/migrations/1315_githubinstallrequest_account.pynew file mode 100644index 000000000000..f1ffaa92d980--- /dev/null+++ b/posthog/migrations/1315_githubinstallrequest_account.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.17 on 2026-08-19 01:51++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1314_callable_choices"),+ ]++ operations = [+ migrations.AddField(+ model_name="githubinstallrequest",+ name="account_login",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ migrations.AddField(+ model_name="githubinstallrequest",+ name="account_type",+ field=models.CharField(blank=True, max_length=32, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex b5341a0a8773..2b22f030134a 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1314_callable_choices+1315_githubinstallrequest_accountdiff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 8f63eb86ad3f..bfd479c16625 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -5,9 +5,10 @@ operations that are shared between :class:`GitHubIntegration` (team-scoped) and:class:`UserGitHubIntegration` (user-scoped)."""+import jsonimport timeimport uuid-from collections.abc import Mapping+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetimefrom typing import Any, Literal, TypedDict, cast@@ -15,6 +16,8 @@ from urllib.parse import urlparsefrom django.conf import settingsfrom django.core.cache import cache+from django.db.models import Count, F, Func, JSONField, Value+from django.db.models.functions import Castfrom django.utils import timezoneimport jwt@@ -27,6 +30,7 @@ from posthog.egress.github.limiter import remember_observed_core_limitfrom posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limitedfrom posthog.egress.limiter.policies import Priorityfrom posthog.sync import database_sync_to_async_pool+from posthog.utils import safe_cache_add, safe_cache_deletelogger = structlog.get_logger(__name__)@@ -48,6 +52,12 @@ GITHUB_BRANCH_CACHE_TIMEOUT_SECONDS = 60 * 60 * 24INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY = "installation_unavailable_since"+ACCOUNT_NAME_HEAL_ATTEMPTED_AT_CONFIG_KEY = "account_name_heal_attempted_at"+GITHUB_ACCOUNT_NAME_HEAL_COOLDOWN_SECONDS = 5 * 60+# Held only while a heal is in flight, and released as soon as it finishes. The TTL is the backstop+# for a process that dies mid-heal, so it just has to outlast the 10s request timeout.+GITHUB_ACCOUNT_NAME_HEAL_CLAIM_TTL_SECONDS = 60+# Reactions cost one extra round trip per reacted comment, and GitHub offers no way to fetch them in# bulk, so bound the fan-out. Set high enough that a real pull request never reaches it: past this# point a comment renders without its pills, which is worse than the extra requests.@@ -120,6 +130,21 @@ class GitHubIntegrationError(Exception):self.status_code = status_code+def _jsonb_merge(column: str, patch: dict[str, Any]) -> Func:+ """Postgres ``column || patch``: a top-level key merge performed by the database.++ Lets a writer that owns a few keys of a shared JSON column update them without reading the+ column first, so keys it never looks at survive a concurrent write either way round.+ """+ return Func(+ F(column),+ Cast(Value(json.dumps(patch)), output_field=JSONField()),+ template="%(expressions)s",+ arg_joiner=" || ",+ output_field=JSONField(),+ )++def _github_repo_optional_fields(repo: dict) -> dict:"""Display fields for a repo, taken off the GitHub payload or a cached entry.@@ -247,6 +272,41 @@ class GitHubIntegrationBase:return team_qs.count() + user_qs.count()+ @staticmethod+ def installation_reference_counts(+ installation_ids: Iterable[str], *, include_personal: bool = True+ ) -> dict[str, int]:+ """PostHog rows referencing each GitHub App installation, keyed by installation id.++ Batched form of :meth:`installation_reference_count` for list endpoints: one grouped+ query per model for the whole page instead of a count pair per row. The returned count+ includes every reference, so a caller checking "is this shared besides the current row"+ tests ``> 1``. Pass ``include_personal=False`` to count team rows only — those are the+ ones that keep the App installed on GitHub, since disconnecting the last team row+ deletes the personal rows sharing it.+ """+ # Local imports: both model modules import this module at load time.+ from posthog.models.integration import Integration+ from posthog.models.user_integration import UserIntegration++ ids = {installation_id for installation_id in installation_ids if installation_id}+ counts: dict[str, int] = {}+ if not ids:+ return counts++ models: list[type[Integration] | type[UserIntegration]] = [Integration]+ if include_personal:+ models.append(UserIntegration)+ for model in models:+ grouped = (+ model.objects.filter(kind="github", integration_id__in=ids)+ .values("integration_id")+ .annotate(count=Count("id"))+ )+ for row in grouped:+ counts[row["integration_id"]] = counts.get(row["integration_id"], 0) + row["count"]+ return counts+@classmethoddef uninstall_app_installation(cls, installation_id: str) -> bool:"""Tell GitHub to uninstall the App via ``DELETE /app/installations/{id}``.@@ -413,6 +473,10 @@ class GitHubIntegrationBase:# refresh rewrites it, including for integrations connected before this key existed.if isinstance(data.get("permissions"), dict):config["permissions"] = data["permissions"]+ # Same reasoning for the "all" vs "selected" repository scope: an org owner can flip it on+ # GitHub at any time, and the UI uses it to decide whether to list repositories at all.+ if isinstance(data.get("repository_selection"), str):+ config["repository_selection"] = data["repository_selection"]config.pop(INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, None)self.integration.config = configself.integration.sensitive_config = {@@ -529,6 +593,71 @@ class GitHubIntegrationBase:stale — it survives disarming but GitHub will reject it once it expires server-side."""return bool(self.integration.config.get(INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY))+ def account_name_needs_heal(self) -> bool:+ """True when the stored account name is missing or is the numeric installation id, which is+ the placeholder written when ``GET /app/installations/{id}`` failed at connect time."""+ installation_id = self.github_installation_id+ account = self.integration.config.get("account")+ name = account.get("name") if isinstance(account, dict) else None+ return not name or str(name) == str(installation_id)++ def ensure_account_name(self) -> bool:+ """Replace a placeholder account name with the real GitHub login, at most once per cooldown.++ Skips installations already marked unavailable, since the lookup would fail the same way.+ Returns True when the name was healed. Persists the attempt timestamp either way so a broken+ installation costs one GitHub call per cooldown window, not one per list request.+ """+ installation_id = self.github_installation_id+ if not installation_id or self.installation_unavailable() or not self.account_name_needs_heal():+ return False+ now = int(time.time())+ last_attempt = self.integration.config.get(ACCOUNT_NAME_HEAL_ATTEMPTED_AT_CONFIG_KEY)+ if isinstance(last_attempt, int | float) and now - last_attempt < GITHUB_ACCOUNT_NAME_HEAL_COOLDOWN_SECONDS:+ return False+ # The attempt timestamp is only written once the request below returns, so a burst of+ # concurrent list requests would all clear the cooldown check and each spend a GitHub call+ # against the App-wide quota. Claim the row for the duration of the call so only the first+ # of the burst goes out. A cache outage falls back to the cooldown alone rather than+ # blocking the heal.+ claim_key = f"github_account_name_heal:{type(self.integration).__name__}:{self.integration.pk}"+ if not safe_cache_add(claim_key, True, GITHUB_ACCOUNT_NAME_HEAL_CLAIM_TTL_SECONDS):+ return False+ try:+ return self._fetch_and_store_account_name(installation_id, now)+ finally:+ safe_cache_delete(claim_key)++ def _fetch_and_store_account_name(self, installation_id: str, now: int) -> bool:+ healed_account: dict[str, Any] | None = None+ try:+ response = self.client_request(f"installations/{installation_id}")+ if response.status_code == 200:+ account = response.json().get("account") or {}+ login = account.get("login")+ if login:+ healed_account = {"type": account.get("type"), "name": login}+ except Exception:+ logger.warning(+ "GitHubIntegration: ensure_account_name failed",+ installation_id=installation_id,+ exc_info=True,+ )+ patch: dict[str, Any] = {ACCOUNT_NAME_HEAL_ATTEMPTED_AT_CONFIG_KEY: now}+ if healed_account is not None:+ patch["account"] = healed_account+ # `config` is one JSON column, so reading it here and writing the whole column back would drop+ # anything a concurrent token refresh or installation webhook commits in between — a window a+ # re-read narrows but never closes. Let Postgres merge the two keys this method owns into the+ # stored value instead, so every other key survives whichever write lands last.+ updated = (+ type(self.integration).objects.filter(pk=self.integration.pk).update(config=_jsonb_merge("config", patch))+ )+ if not updated:+ return False+ self.integration.config = {**self.integration.config, **patch}+ return healed_account is not None+def _on_token_refresh_failed(self, response: requests.Response) -> None:"""Called when the installation token refresh request fails.@@ -1917,6 +2046,13 @@ class GitHubIntegrationBase:has_more = offset + limit < len(filtered)return result, has_more+ def count_cached_repositories(self, *, search: str = "") -> int:+ """Size of the filtered set ``list_cached_repositories`` pages over. Call it right after+ ``list_cached_repositories`` on the same instance so it reads the just-synced in-memory+ cache rather than triggering a second sync."""+ cached_repositories = self._get_stored_repository_list() or []+ return len(self._filter_cached_repositories(cached_repositories, search))+def list_all_cached_repositories(self, max_repos: int | None = None, *, allow_refresh: bool = True) -> list[dict]:cached_repositories = self._get_stored_repository_list()has_cached_snapshot = self.integration.repository_cache_updated_at is not Nonediff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex 204603ce779b..ffd5af800556 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -124,16 +124,30 @@ class GitHubIntegration(GitHubIntegrationBase):@classmethoddef fetch_installation_access(cls, installation_id: str) -> GitHubInstallationAccess:try:- installation_info = cls.client_request(f"installations/{installation_id}").json()- access_token_response = cls.client_request(- f"installations/{installation_id}/access_tokens", method="POST"- ).json()+ installation_info_response = cls.client_request(f"installations/{installation_id}")+ access_token_response = cls.client_request(f"installations/{installation_id}/access_tokens", method="POST")except Exception as exc:raise GitHubInstallationAccessFetchError("installation_fetch_failed") from exc- installation_access_token = access_token_response.get("token")- token_expires_at = access_token_response.get("expires_at")- if not installation_access_token or not token_expires_at:+ # A non-200 body here is an error envelope without `account`, and callers persist+ # `account.login` as the display name; failing keeps the numeric installation id out of the UI.+ if installation_info_response.status_code != 200:+ logger.warning(+ "GitHubIntegration: failed to fetch installation info",+ installation_id=installation_id,+ status_code=installation_info_response.status_code,+ )+ raise GitHubInstallationAccessFetchError("installation_fetch_failed")++ try:+ installation_info = installation_info_response.json()+ access_token_data = access_token_response.json()+ except ValueError as exc:+ raise GitHubInstallationAccessFetchError("installation_fetch_failed") from exc++ installation_access_token = access_token_data.get("token")+ token_expires_at = access_token_data.get("expires_at")+ if access_token_response.status_code != 201 or not installation_access_token or not token_expires_at:raise GitHubInstallationAccessFetchError("installation_token_failed")return GitHubInstallationAccess(@@ -141,7 +155,7 @@ class GitHubIntegration(GitHubIntegrationBase):installation_info=installation_info,access_token=installation_access_token,token_expires_at=token_expires_at,- repository_selection=access_token_response.get("repository_selection", "selected"),+ repository_selection=access_token_data.get("repository_selection", "selected"),)@classmethoddiff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 483e771df26e..5d494bb07ad3 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -29,6 +29,7 @@ from posthog.models.github_integration_base import (GitHubIntegrationBase,)from posthog.models.integration import (+ GitHubInstallationAccessFetchError,GitHubIntegration,GitHubIntegrationError,Integration,@@ -927,6 +928,148 @@ class TestGitHubIntegrationModel(BaseTest):GitHubIntegration(integration).refresh_access_token()assert integration.config["permissions"] == {"contents": "read", "metadata": "read", "deployments": "read"}+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_integration_persists_repository_selection_on_refresh(self, mock_client_request):+ mock_client_request.side_effect = self.mock_github_client_request(repository_selection="all")+ integration = GitHubIntegration.integration_from_installation_id("INSTALLATION_ID", self.team.id, self.user)+ assert integration.config["repository_selection"] == "all"++ mock_client_request.side_effect = self.mock_github_client_request(repository_selection="selected")+ GitHubIntegration(integration).refresh_access_token()+ assert integration.config["repository_selection"] == "selected"++ @parameterized.expand(+ [+ ("installation_info_non_200", 503, 201, "installation_fetch_failed"),+ ("token_mint_non_201", 200, 400, "installation_token_failed"),+ ]+ )+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_fetch_installation_access_fails_on_bad_status(+ self, _name, info_status, token_status, expected_code, mock_client_request+ ):+ def _client_request(endpoint, method="GET"):+ response = MagicMock()+ if method == "POST":+ response.status_code = token_status+ response.json.return_value = (+ {"token": "TOKEN", "expires_at": "2099-01-01T00:00:00Z"} if token_status == 201 else {}+ )+ else:+ response.status_code = info_status+ response.json.return_value = (+ {"account": {"login": "PostHog", "type": "Organization"}}+ if info_status == 200+ else {"message": "Service unavailable"}+ )+ return response++ mock_client_request.side_effect = _client_request++ with pytest.raises(GitHubInstallationAccessFetchError) as exc_info:+ GitHubIntegration.fetch_installation_access("INSTALLATION_ID")++ assert exc_info.value.code == expected_code++ @parameterized.expand(+ [+ ("numeric_placeholder", {"type": None, "name": "INSTALL"}, True, "PostHog"),+ ("missing_account", None, True, "PostHog"),+ ("already_resolved", {"type": "Organization", "name": "PostHog"}, False, "PostHog"),+ ]+ )+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_ensure_account_name_only_fetches_for_placeholder_names(+ self, _name, account, expects_fetch, expected_name, mock_client_request+ ):+ mock_client_request.return_value = MagicMock(+ status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}}+ )+ config = {"installation_id": "INSTALL"}+ if account is not None:+ config["account"] = account+ integration = self.create_integration(config, {"access_token": "ACCESS_TOKEN"})++ healed = GitHubIntegration(integration).ensure_account_name()++ integration.refresh_from_db()+ assert healed is expects_fetch+ assert integration.config["account"]["name"] == expected_name+ assert mock_client_request.call_count == (1 if expects_fetch else 0)++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_ensure_account_name_backs_off_between_failed_attempts(self, mock_client_request):+ mock_client_request.return_value = MagicMock(status_code=503, json=lambda: {"message": "unavailable"})+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"type": None, "name": "INSTALL"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ with freeze_time("2024-01-01T12:00:00Z"):+ assert GitHubIntegration(integration).ensure_account_name() is False+ assert GitHubIntegration(integration).ensure_account_name() is False+ assert mock_client_request.call_count == 1++ with freeze_time("2024-01-01T12:06:00Z"):+ GitHubIntegration(integration).ensure_account_name()+ assert mock_client_request.call_count == 2+ integration.refresh_from_db()+ assert integration.config["account"]["name"] == "INSTALL"++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_ensure_account_name_skips_unavailable_installation(self, mock_client_request):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "INSTALL"}, "installation_unavailable_since": 1},+ {"access_token": "ACCESS_TOKEN"},+ )++ assert GitHubIntegration(integration).ensure_account_name() is False+ mock_client_request.assert_not_called()++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_ensure_account_name_keeps_config_written_during_the_github_call(self, mock_client_request):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"type": None, "name": "INSTALL"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ def _client_request(*_args, **_kwargs):+ # Stands in for a token refresh or installation webhook committing config mid-request.+ stored = Integration.objects.get(id=integration.id)+ Integration.objects.filter(id=integration.id).update(+ config={**stored.config, "repository_selection": "selected"}+ )+ return MagicMock(status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}})++ mock_client_request.side_effect = _client_request++ assert GitHubIntegration(integration).ensure_account_name() is True++ integration.refresh_from_db()+ assert integration.config["account"]["name"] == "PostHog"+ assert integration.config["repository_selection"] == "selected"++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_ensure_account_name_blocks_a_heal_that_lands_mid_call(self, mock_client_request):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"type": None, "name": "INSTALL"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ landed_mid_call = []++ def _client_request(*_args, **_kwargs):+ # Stands in for a second list request arriving before the first heal has recorded its attempt.+ reread = Integration.objects.get(id=integration.id)+ landed_mid_call.append(GitHubIntegration(reread).ensure_account_name())+ return MagicMock(status_code=200, json=lambda: {"account": {"login": "PostHog", "type": "Organization"}})++ mock_client_request.side_effect = _client_request++ assert GitHubIntegration(integration).ensure_account_name() is True++ assert landed_mid_call == [False]+ assert mock_client_request.call_count == 1+@patch("posthog.models.integration.github.reload_integrations_on_workers")@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")def test_github_refresh_access_token_handles_errors(self, mock_client_request, mock_reload):@@ -1397,6 +1540,27 @@ class TestGitHubIntegrationModel(BaseTest):assert has_more is expected_has_moremock_list_all.assert_called_once_with()+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_count_cached_repositories_counts_the_filtered_set_not_the_page(self, mock_list_all):+ mock_list_all.return_value = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ {"id": 3, "name": "code", "full_name": "Acme/code"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ github = GitHubIntegration(integration)++ repos, has_more = github.list_cached_repositories(search="posthog", limit=1, offset=0)++ assert len(repos) == 1+ assert has_more is True+ assert github.count_cached_repositories(search="posthog") == 2+ assert github.count_cached_repositories() == 3+ mock_list_all.assert_called_once_with()+@patch("posthog.models.integration.github.GitHubIntegration.list_branches")@patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")def test_list_cached_branches_uses_cached_data_when_fresh(self, mock_default_branch, mock_list_branches):diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex 3bd880eae8bc..97c395200980 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -130,6 +130,10 @@ class GitHubInstallRequest(UUIDModel):github_login = models.CharField(max_length=255, blank=True)status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)installation_id = models.CharField(max_length=64, null=True, blank=True)+ # The GitHub org or user the approved installation landed on, from the installation.created+ # payload. Only known once approved; the request itself doesn't say which org was targeted.+ account_login = models.CharField(max_length=255, null=True, blank=True)+ account_type = models.CharField(max_length=32, null=True, blank=True)requested_at = models.DateTimeField(auto_now_add=True)resolved_at = models.DateTimeField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)diff --git a/posthog/urls.py b/posthog/urls.pyindex 8f23249c744c..52625b069187 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -151,6 +151,14 @@ def _dispatch_installation_event(return handle_installation_event(payload)+def _dispatch_installation_repositories_event(+ request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str+) -> HttpResponse:+ from posthog.api.github_callback.installation_events import handle_installation_repositories_event++ return handle_installation_repositories_event(payload)++def _dispatch_loop_triggers(request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str) -> None:from products.tasks.backend.facade.webhooks import handle_github_event_for_loops@@ -181,6 +189,9 @@ GITHUB_WEBHOOK_HANDLERS: dict[str, list[tuple[str, GithubWebhookHandler]]] = {"installation": [("installation_lifecycle", _dispatch_installation_event),],+ "installation_repositories": [+ ("installation_repositories", _dispatch_installation_repositories_event),+ ],"push": [("loops", _dispatch_loop_triggers),],diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex fafdfdaa8ca4..b774b1a66425 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -251,6 +251,17 @@ export const IntegrationKindEnumApi = {YoutubeAnalytics: 'youtube-analytics',} as const+/**+ * * `connected` - connected+ * * `unavailable` - unavailable+ */+export type InstallationStatusEnumApi = (typeof InstallationStatusEnumApi)[keyof typeof InstallationStatusEnumApi]++export const InstallationStatusEnumApi = {+ Connected: 'connected',+ Unavailable: 'unavailable',+} as const+/*** Standard Integration serializer.*/@@ -262,6 +273,13 @@ export interface IntegrationConfigApi {readonly created_by: UserBasicApireadonly errors: stringreadonly display_name: string+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared: boolean | null+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status: InstallationStatusEnumApi | null}export interface PaginatedIntegrationConfigListApi {@@ -311,6 +329,13 @@ export interface PatchedIntegrationConfigApi {readonly created_by?: UserBasicApireadonly errors?: stringreadonly display_name?: string+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared?: boolean | null+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status?: InstallationStatusEnumApi | null}export interface GitHubBranchesResponseApi {@@ -350,11 +375,18 @@ export interface GitHubReposResponseApi {repositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: boolean+ /** Total number of repositories matching the search query, across all pages. */+ total: number}export interface GitHubReposRefreshResponseApi {/** The refreshed repository cache. */repositories: GitHubRepoApi[]+ /** `unavailable` when GitHub reports the App installation as uninstalled or suspended, in which case `repositories` is the last cached list rather than a fresh one.+ *+ * * `connected` - connected+ * * `unavailable` - unavailable */+ installation_status: InstallationStatusEnumApi}export interface GitHubTeamApi {diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 52a4b18d5856..ed5cd7d5a794 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -539,6 +539,9 @@ tools:users-integrations-github-destroy:operation: users_integrations_github_destroyenabled: false+ users-integrations-github-install-requests-destroy:+ operation: users_integrations_github_install_requests_destroy+ enabled: falseusers-integrations-github-install-requests-retrieve:operation: users_integrations_github_install_requests_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cb22fed7b23b..38d0103e46b6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39347,6 +39347,16 @@ export namespace Schemas {* @nullable*/installation_id?: string | null;+ /**+ * GitHub organization or user login the installation was approved under, once known.+ * @nullable+ */+ account_login?: string | null;+ /**+ * GitHub account type (`Organization` or `User`) the installation was approved under, once known.+ * @nullable+ */+ account_type?: string | null;/** When the install approval was requested. */requested_at: string;/**@@ -39359,6 +39369,11 @@ export namespace Schemas {export interface GitHubInstallRequestListResponse {/** The user's GitHub App install-approval requests, newest first. */results: GitHubInstallRequestItem[];+ /**+ * Shareable GitHub App install URL with no PostHog session state, for an org owner who needs to approve the install. Null when the GitHub App is not configured on this instance.+ * @nullable+ */+ install_url?: string | null;}export interface GitHubLinkExistingRequest {@@ -39415,15 +39430,34 @@ export namespace Schemas {can_push?: boolean;}+ /**+ * * `connected` - connected+ * * `unavailable` - unavailable+ */+ export type InstallationStatusEnum = typeof InstallationStatusEnum[keyof typeof InstallationStatusEnum];+++ export const InstallationStatusEnum = {+ Connected: 'connected',+ Unavailable: 'unavailable',+ } as const;+export interface GitHubReposRefreshResponse {/** The refreshed repository cache. */repositories: GitHubRepo[];+ /** `unavailable` when GitHub reports the App installation as uninstalled or suspended, in which case `repositories` is the last cached list rather than a fresh one.+ *+ * * `connected` - connected+ * * `unavailable` - unavailable */+ installation_status: InstallationStatusEnum;}export interface GitHubReposResponse {repositories: GitHubRepo[];/** Whether more repositories are available beyond this page. */has_more: boolean;+ /** Total number of repositories matching the search query, across all pages. */+ total: number;}export interface GitHubSource {@@ -44415,6 +44449,13 @@ export namespace Schemas {readonly created_by: UserBasic;readonly errors: string;readonly display_name: string;+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared: boolean | null;+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status: InstallationStatusEnum | null;}export interface RecommendedAction {@@ -56165,6 +56206,13 @@ export namespace Schemas {github_login?: string | null;/** True when this installation id matches a team-level GitHub integration on the active project. */uses_shared_installation: boolean;+ /** Whether any other PostHog project or personal connection references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization. */+ installation_shared: boolean;+ /** `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise.+ *+ * * `connected` - connected+ * * `unavailable` - unavailable */+ installation_status: InstallationStatusEnum;/** When this integration row was created. */created_at: string;}@@ -60499,6 +60547,13 @@ export namespace Schemas {readonly created_by?: UserBasic;readonly errors?: string;readonly display_name?: string;+ /**+ * GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.+ * @nullable+ */+ readonly installation_shared?: boolean | null;+ /** GitHub only, null otherwise. `unavailable` means the App was uninstalled or suspended on GitHub and PostHog can no longer mint tokens for it; `connected` otherwise. */+ readonly installation_status?: InstallationStatusEnum | null;}export interface PatchedIntervieweeContext {