Skip to content

: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.

fix(integrations): clarify github connect and disconnect states (#106665)

Georgiy Tarasov9d1960ef200a
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 6d4eb156870a..43df69ed5d70 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -115,13 +115,14 @@ from posthog.permissions import (
)
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
from posthog.tasks.email import send_integration_access_request
-from posthog.utils import is_relative_url
+from posthog.utils import absolute_uri, is_relative_url
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
from products.batch_exports.backend.facade.api import list_batch_exports_using_integration
from products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integration
from products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODES
-from products.tasks.backend.facade.api import count_in_progress_runs_for_github_integration
+from products.tasks.backend.facade.api import get_in_progress_runs_for_github_integration
+from products.tasks.backend.facade.contracts import InProgressGithubRunsDTO
from products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration
logger = structlog.get_logger(__name__)
@@ -261,6 +262,26 @@ def _concat_names_or_ids(items: Iterable[_HasNameOrId]) -> str:
return ", ".join(sorted(it.name or str(it.id) for it in items))
+def _github_disconnect_blocked_message(live_runs: InProgressGithubRunsDTO, team_id: int) -> str:
+ # Link one task so that the user can find what blocks the disconnect, and count the rest.
+ if live_runs.oldest_task_id is None:
+ runs = f"{live_runs.count} in-progress background agent run{'s' if live_runs.count != 1 else ''}"
+ else:
+ task_url = absolute_uri(f"/project/{team_id}/ai?task={live_runs.oldest_task_id}")
+ if live_runs.oldest_task_title:
+ runs = f'the in-progress background agent task "{live_runs.oldest_task_title}" ({task_url})'
+ else:
+ runs = f"an in-progress background agent task ({task_url})"
+ others = live_runs.count - 1
+ if others:
+ runs += f" and {others} other run{'s' if others != 1 else ''}"
+ pronoun = "it" if live_runs.count == 1 else "them"
+ return (
+ f"This GitHub integration is being used by {runs}. "
+ f"Wait for {pronoun} to finish or cancel {pronoun} before disconnecting it."
+ )
+
+
class NativeEmailIntegrationSerializer(serializers.Serializer):
email = serializers.EmailField()
name = serializers.CharField()
@@ -1405,15 +1426,11 @@ class IntegrationViewSet(
)
if instance.kind == "github":
- live_run_count = count_in_progress_runs_for_github_integration(
- team_id=instance.team_id, integration_id=instance.id
+ live_runs = get_in_progress_runs_for_github_integration(
+ team_id=instance.team_id, integration_id=instance.id, user_id=self.request.user.id
)
- if live_run_count:
- raise ValidationError(
- f"This GitHub integration is being used by {live_run_count} in-progress background agent "
- f"run{'s' if live_run_count != 1 else ''}. Wait for them to finish or cancel them before "
- "disconnecting it."
- )
+ if live_runs.count:
+ raise ValidationError(_github_disconnect_blocked_message(live_runs, team_id=instance.team_id))
if instance.kind == "stripe":
try:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index e7ea16f9cb4f..3845d8fa6ac8 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -5,6 +5,7 @@ import hashlib
from datetime import timedelta
from typing import Any, cast
from urllib.parse import quote, urlencode
+from uuid import uuid4
import pytest
import time_machine
@@ -82,6 +83,7 @@ from products.batch_exports.backend.facade import testing as batch_exports_testi
from products.batch_exports.backend.facade.contracts import DestinationType
from products.cdp.backend.models import HogFunction
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.tasks.backend.facade.contracts import InProgressGithubRunsDTO
from products.workflows.backend.models import HogFlow
@@ -6560,23 +6562,30 @@ class TestGitHubIntegrationUninstall:
assert not Integration.objects.filter(id=integration.id).exists()
@patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation_status")
- @patch("posthog.api.integration.count_in_progress_runs_for_github_integration")
+ @patch("posthog.api.integration.get_in_progress_runs_for_github_integration")
def test_destroy_github_blocked_while_background_agent_runs_in_progress(
self, mock_count, _mock_uninstall, client: HttpClient
):
integration = self._create_github_integration("12345")
_mock_uninstall.return_value = "uninstalled"
- mock_count.return_value = 2
+ task_id = uuid4()
+ mock_count.return_value = InProgressGithubRunsDTO(
+ count=3, oldest_task_id=task_id, oldest_task_title="Fix the login redirect"
+ )
client.force_login(self.user)
response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "2 in-progress background agent runs" in response.json()["detail"]
+ assert response.json()["detail"] == (
+ 'This GitHub integration is being used by the in-progress background agent task "Fix the login redirect" '
+ f"({settings.SITE_URL}/project/{self.team.pk}/ai?task={task_id}) and 2 other runs. "
+ "Wait for them to finish or cancel them before disconnecting it."
+ )
assert Integration.objects.filter(id=integration.id).exists()
- mock_count.assert_called_once_with(team_id=self.team.pk, integration_id=integration.id)
+ mock_count.assert_called_once_with(team_id=self.team.pk, integration_id=integration.id, user_id=self.user.id)
- mock_count.return_value = 0
+ mock_count.return_value = InProgressGithubRunsDTO(count=0)
response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
assert response.status_code == status.HTTP_204_NO_CONTENT
diff --git a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
index bcfaf6a7eabc..f77c22744a95 100644
--- a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
+++ b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
@@ -1,5 +1,6 @@
import { useActions, useMountedLogic, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
+import { useEffect } from 'react'
import { IconBolt, IconCheckCircle, IconChevronRight, IconCompass, IconGithub } from '@posthog/icons'
import { LemonModal, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
@@ -37,6 +38,8 @@ interface SetupWidgetCardProps {
tone: WidgetTone
size: WidgetSize
loading?: boolean
+ /** Blocks clicks, e.g. while a request that `onClick` would repeat is in flight. */
+ disabled?: boolean
/** One-line context, shown on `lg` cards only. */
description?: string
onClick?: () => void
@@ -90,10 +93,10 @@ const CARD_PADDING_CLASS: Record<WidgetSize, string> = {
}
function SetupWidgetCard(props: SetupWidgetCardProps): JSX.Element {
- const { icon, title, status, tone, size, loading, description, onClick, to, children } = props
+ const { icon, title, status, tone, size, loading, disabled, description, onClick, to, children } = props
const cardClassName = cn(
- 'group flex rounded border border-primary bg-surface-primary text-left no-underline cursor-pointer transition-colors hover:border-secondary',
+ 'group flex rounded border border-primary bg-surface-primary text-left no-underline cursor-pointer transition-colors hover:border-secondary disabled:cursor-default disabled:hover:border-primary',
size === 'sm' ? 'items-center justify-between gap-2' : 'flex-col',
CARD_PADDING_CLASS[size]
)
@@ -158,7 +161,7 @@ function SetupWidgetCard(props: SetupWidgetCardProps): JSX.Element {
)
}
return (
- <button type="button" onClick={onClick} className={cardClassName}>
+ <button type="button" onClick={onClick} disabled={disabled} className={cardClassName}>
{content}
</button>
)
@@ -201,18 +204,41 @@ function ScoutTroopWidget(): JSX.Element {
}
function CodeAccessWidget(): JSX.Element {
- const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)
+ const { getIntegrationsByKind, integrations, integrationsLoading } = useValues(integrationsLogic)
+ const { loadIntegrations, startPolling, stopPolling } = useActions(integrationsLogic)
const { openSetupModal } = useActions(agentSetupModalLogic)
const hasGithub = getIntegrationsByKind(['github']).length > 0
+ // The loader keeps its last list on failure, so a null list after loading means the first fetch failed.
+ const loadFailed = integrations === null && !integrationsLoading
+ // Background polls keep the last known status on screen; only a load with no list yet shows the skeleton.
+ const firstLoadInFlight = integrations === null && integrationsLoading
+
+ // The GitHub App install finishes on github.com and returns to a settings page, often in another tab.
+ // Refetch on an interval and on window focus until GitHub shows up, so the card does not stay stale.
+ useEffect(() => {
+ if (hasGithub) {
+ return
+ }
+ startPolling()
+ return () => stopPolling()
+ }, [hasGithub]) // eslint-disable-line react-hooks/exhaustive-deps
+
return (
<SetupWidgetCard
icon={<IconGithub />}
title="Code access"
size="md"
- tone={hasGithub ? 'done' : 'todo'}
- loading={integrationsLoading && !hasGithub}
- status={hasGithub ? 'GitHub connected' : 'Foundational. Connect to start.'}
- onClick={() => openSetupModal('github')}
+ tone={hasGithub ? 'done' : loadFailed ? 'neutral' : 'todo'}
+ loading={firstLoadInFlight}
+ disabled={firstLoadInFlight}
+ status={
+ hasGithub
+ ? 'GitHub connected'
+ : loadFailed
+ ? "Couldn't check GitHub. Click to retry."
+ : 'Foundational. Connect to start.'
+ }
+ onClick={() => (loadFailed ? loadIntegrations() : openSetupModal('github'))}
/>
)
}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7c446f63eb3a..4889cfcb7c30 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1135,18 +1135,30 @@ def task_exempt_from_code_access(task_id: str | UUID, team_id: int) -> bool:
).exists()
-def count_in_progress_runs_for_github_integration(team_id: int, integration_id: int) -> int:
+def get_in_progress_runs_for_github_integration(
+ team_id: int, integration_id: int, user_id: int | None
+) -> contracts.InProgressGithubRunsDTO:
"""In-progress runs whose task uses this team GitHub integration.
Used by core's integration API to block disconnecting a GitHub integration while
live runs still depend on it for credential refresh — deleting the row SET_NULLs
``Task.github_integration`` and permanently orphans every live sandbox's token.
+ The count covers every run, but the named task is the oldest one ``user_id`` can read.
"""
- return TaskRun.objects.filter(
+ runs = TaskRun.objects.filter(
team_id=team_id,
status=TaskRun.Status.IN_PROGRESS,
task__github_integration_id=integration_id,
- ).count()
+ )
+ count = runs.count()
+ if not count:
+ return contracts.InProgressGithubRunsDTO(count=0)
+ oldest = runs.filter(task_run_visibility_q(user_id)).order_by("created_at").values("task_id", "task__title").first()
+ if oldest is None:
+ return contracts.InProgressGithubRunsDTO(count=count)
+ return contracts.InProgressGithubRunsDTO(
+ count=count, oldest_task_id=oldest["task_id"], oldest_task_title=oldest["task__title"] or None
+ )
def is_task_controllable_by_user(task_id: str | UUID, user_id: int | None) -> bool:
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 28d948813a6b..95b80c26eddc 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -131,6 +131,15 @@ class TaskRunDTO:
pr_url: str | None = None
+@dataclass(frozen=True)
+class InProgressGithubRunsDTO:
+ """In-progress runs that block disconnecting a team GitHub integration."""
+
+ count: int
+ oldest_task_id: UUID | None = None
+ oldest_task_title: str | None = None
+
+
@dataclass(frozen=True)
class WizardPrReadyEmailContextDTO:
"""Everything ``send_wizard_pr_ready_email`` needs to read off a task run's PR-ready state."""
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 11fcdf7c3e16..22eca881fe7c 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -542,18 +542,38 @@ class TestFacadeReadsAndMappers(TestCase):
assert latest_terminal is not None
self.assertEqual(latest_terminal.id, terminal.id)
- def test_count_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):
+ def test_get_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):
integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
other_integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
-
- live_task = self._make_task(github_integration=integration)
- TaskRun.objects.create(task=live_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
- TaskRun.objects.create(task=live_task, team=self.team, status=TaskRun.Status.COMPLETED)
+ colleague = User.objects.create(email="[email protected]", distinct_id="colleague-distinct")
+ outsider = User.objects.create(email="[email protected]", distinct_id="outsider-distinct")
+
+ colleague_task = self._make_task(github_integration=integration, title="Colleague's task", created_by=colleague)
+ TaskRun.objects.create(task=colleague_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ TaskRun.objects.create(task=colleague_task, team=self.team, status=TaskRun.Status.COMPLETED)
+ own_task = self._make_task(github_integration=integration, title="Own task")
+ TaskRun.objects.create(task=own_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
other_task = self._make_task(github_integration=other_integration)
TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
- self.assertEqual(facade.count_in_progress_runs_for_github_integration(self.team.id, integration.id), 1)
- self.assertEqual(facade.count_in_progress_runs_for_github_integration(self.team.id + 999, integration.id), 0)
+ self.assertEqual(
+ facade.get_in_progress_runs_for_github_integration(self.team.id, integration.id, colleague.id),
+ contracts.InProgressGithubRunsDTO(
+ count=2, oldest_task_id=colleague_task.id, oldest_task_title="Colleague's task"
+ ),
+ )
+ self.assertEqual(
+ facade.get_in_progress_runs_for_github_integration(self.team.id, integration.id, self.user.id),
+ contracts.InProgressGithubRunsDTO(count=2, oldest_task_id=own_task.id, oldest_task_title="Own task"),
+ )
+ self.assertEqual(
+ facade.get_in_progress_runs_for_github_integration(self.team.id, integration.id, outsider.id),
+ contracts.InProgressGithubRunsDTO(count=2),
+ )
+ self.assertEqual(
+ facade.get_in_progress_runs_for_github_integration(self.team.id + 999, integration.id, self.user.id),
+ contracts.InProgressGithubRunsDTO(count=0),
+ )
def test_get_latest_pr_url_and_run_by_task(self):
task = self._make_task()