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.

feat(integrations): mark a github connection that needs reconnecting (#113292)

Vojta Bartoš73dc429b1d7e
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index e156e7ddf3ba..f41a057b45ae 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -6269,6 +6269,13 @@ export interface UserGitHubIntegrationItemApi {
* * `connected` - connected
* * `unavailable` - unavailable */
installation_status: InstallationStatusEnumApi
+ /** True when GitHub rejected the stored credentials and PostHog dropped them. The installation is still on GitHub, but PostHog cannot act as the user until they authorize it again. */
+ needs_reauthorization: boolean
+ /**
+ * When the stored credentials stopped working, or null while they still work.
+ * @nullable
+ */
+ needs_reauthorization_at: string | null
/** When this integration row was created. */
created_at: string
}
diff --git a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
index 16ffee888d0a..2105754c9ceb 100644
--- a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
+++ b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
-import { IconGithub, IconPlus, IconTrash } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton } from '@posthog/lemon-ui'
+import { IconGithub, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
@@ -27,7 +27,8 @@ function reportPersonalIntegrationConnectClicked(kind: string): void {
}
function GitHubInstallationRow({ integration }: { integration: PersonalGitHubIntegration }): JSX.Element {
- const { disconnectGitHub } = useActions(personalIntegrationsLogic)
+ const { disconnectGitHub, connectGitHub } = useActions(personalIntegrationsLogic)
+ const { githubConnecting } = useValues(personalIntegrationsLogic)
const installationId = integration.installation_id
const accountType = integration.account?.type
@@ -39,6 +40,7 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
logic ?? userGithubIntegrationLogic({ installationId: '' })
)
const installationUnavailable = integration.installation_status === 'unavailable'
+ const needsReauthorization = !!integration.needs_reauthorization
const handleDisconnect = (): void => {
LemonDialog.open({
@@ -75,13 +77,18 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
</div>
</div>
<div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
<span className="font-semibold">{accountName || 'GitHub'}</span>
{accountType === 'Organization' ? (
<span className="text-xs text-muted bg-surface-secondary px-1.5 py-0.5 rounded">Org</span>
) : (
<span className="text-xs text-muted bg-surface-secondary px-1.5 py-0.5 rounded">Personal</span>
)}
+ {needsReauthorization ? (
+ <LemonTag type="warning" size="small">
+ Needs reconnecting
+ </LemonTag>
+ ) : null}
</div>
<div className="mt-0.5 text-xs text-secondary">
{integration.created_at ? (
@@ -110,6 +117,32 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
still need it.
</LemonBanner>
) : null}
+ {needsReauthorization ? (
+ <LemonBanner
+ type="warning"
+ className="mt-2"
+ alignItems="start"
+ action={{
+ children: 'Reconnect',
+ icon: <IconRefresh />,
+ onClick: () => {
+ reportPersonalIntegrationConnectClicked('github')
+ connectGitHub()
+ },
+ loading: githubConnecting,
+ disabledReason: githubConnecting ? 'Starting GitHub authorization…' : undefined,
+ }}
+ >
+ GitHub stopped accepting this connection
+ {integration.needs_reauthorization_at ? (
+ <>
+ {' '}
+ <TZLabel time={integration.needs_reauthorization_at} className="align-baseline" />
+ </>
+ ) : null}
+ . Reconnect to let PostHog read your repos and open pull requests as you again.
+ </LemonBanner>
+ ) : null}
</div>
<div className="flex shrink-0 items-center">
<LemonButton
@@ -186,7 +219,8 @@ function SlackLinkRow({ integration }: { integration: PersonalSlackIntegration }
}
export function PersonalGitHubIntegrations(): JSX.Element {
- const { integrations, integrationsLoading, githubConnecting } = useValues(personalIntegrationsLogic)
+ const { integrations, healthyIntegrations, integrationsLoading, githubConnecting } =
+ useValues(personalIntegrationsLogic)
const { connectGitHub, startPolling, stopPolling } = useActions(personalIntegrationsLogic)
// Refresh the personal rows while this section stays mounted, so an App removed on GitHub shows
@@ -239,7 +273,7 @@ export function PersonalGitHubIntegrations(): JSX.Element {
loading={githubConnecting}
disabledReason={githubConnecting ? 'Starting GitHub installation…' : undefined}
>
- {integrations.length === 0 ? 'Connect GitHub' : 'Add account/organization'}
+ {healthyIntegrations.length === 0 ? 'Connect GitHub' : 'Add account/organization'}
</LemonButton>
<span className="text-xs text-secondary text-balance">
Heads up: if GitHub's <strong>Save</strong> button is disabled at the end of the flow, flip
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts
index 290ca913e42d..b5c8ce527e32 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts
@@ -42,4 +42,33 @@ describe('personalIntegrationsLogic', () => {
logic.actions.stopPolling()
expect(logic.cache.disposables.registry.has('poll')).toBe(false)
})
+
+ it('keeps a connection that needs reconnecting in the list but out of the healthy count', async () => {
+ useMocks({
+ get: {
+ '/api/users/@me/integrations/': () => [
+ 200,
+ {
+ results: [
+ { kind: 'github', installation_id: '1', needs_reauthorization: false },
+ {
+ kind: 'github',
+ installation_id: '2',
+ needs_reauthorization: true,
+ needs_reauthorization_at: '2024-01-01T12:00:00Z',
+ },
+ ],
+ },
+ ],
+ },
+ })
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadIntegrationsSuccess'])
+ .toMatchValues({
+ integrations: expect.arrayContaining([expect.objectContaining({ installation_id: '2' })]),
+ healthyIntegrations: [expect.objectContaining({ installation_id: '1' })],
+ })
+ })
})
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index 3fa8394f0721..32299da6f882 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -32,6 +32,8 @@ export interface PersonalGitHubIntegration {
installation_shared?: UserGitHubIntegrationItemApi['installation_shared']
/** `unavailable` once the App was removed or suspended on GitHub. */
installation_status?: UserGitHubIntegrationItemApi['installation_status']
+ needs_reauthorization?: UserGitHubIntegrationItemApi['needs_reauthorization']
+ needs_reauthorization_at?: UserGitHubIntegrationItemApi['needs_reauthorization_at']
created_at: string | null
}
@@ -100,6 +102,7 @@ function writeConnectFromStorage(value: string | null): void {
export interface personalIntegrationsLogicValues {
currentTeam: TeamPublicType | TeamType | null // teamLogic
githubConnecting: boolean
+ healthyIntegrations: PersonalGitHubIntegration[]
integrations: PersonalGitHubIntegration[]
integrationsLoading: boolean
linkableSlackWorkspaces: LinkableSlackWorkspace[]
@@ -207,9 +210,18 @@ export interface personalIntegrationsLogicActions {
}
}
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface personalIntegrationsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ healthyIntegrations: (integrations: PersonalGitHubIntegration[]) => PersonalGitHubIntegration[]
+ }
+}
+
export type personalIntegrationsLogicType = MakeLogicType<
personalIntegrationsLogicValues,
- personalIntegrationsLogicActions
+ personalIntegrationsLogicActions,
+ Record<string, any>,
+ personalIntegrationsLogicMeta
>
export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
@@ -327,7 +339,15 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
],
})),
- selectors({}),
+ selectors({
+ // A flagged row holds no usable credentials, so the connect surface reads this instead of the
+ // full list. Otherwise a user whose only install was flagged is offered "add another".
+ healthyIntegrations: [
+ (s) => [s.integrations],
+ (integrations: PersonalGitHubIntegration[]): PersonalGitHubIntegration[] =>
+ integrations.filter((integration) => !integration.needs_reauthorization),
+ ],
+ }),
listeners(({ actions, values, cache }) => ({
// Keep the personal GitHub rows current while the section is open, so an App removed on
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index 752c7895ac5e..8c29b7adbdf2 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -161,6 +161,23 @@ class TestUserIntegrationEndpoints(APIBaseTest):
self.assertEqual(response.json()["results"][0]["installation_status"], "unavailable")
+ def test_list_keeps_a_credential_that_needs_reconnecting_and_marks_it(self):
+ integration = _create_user_integration(self.user)
+ integration.config = {
+ **integration.config,
+ "needs_reauthorization_reason": "refresh rejected by GitHub",
+ "needs_reauthorization_at": 1704110400,
+ }
+ integration.save()
+
+ response = self.client.get("/api/users/@me/integrations/")
+
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertTrue(results[0]["needs_reauthorization"])
+ self.assertEqual(results[0]["needs_reauthorization_at"], "2024-01-01T12:00:00Z")
+ self.assertNotIn("needs_reauthorization_reason", results[0])
+
@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(
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 6d8cc6d6fa37..484434f7c17e 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -129,6 +129,16 @@ class UserGitHubIntegrationItemSerializer(serializers.Serializer):
"mint tokens for it; `connected` otherwise."
),
)
+ needs_reauthorization = serializers.BooleanField(
+ help_text=(
+ "True when GitHub rejected the stored credentials and PostHog dropped them. The installation is "
+ "still on GitHub, but PostHog cannot act as the user until they authorize it again."
+ ),
+ )
+ needs_reauthorization_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the stored credentials stopped working, or null while they still work.",
+ )
created_at = serializers.DateTimeField(help_text="When this integration row was created.")
@@ -1026,6 +1036,8 @@ def _serialize_github_integration(
"uses_shared_installation": integration.integration_id in team_integration_installation_ids,
"installation_shared": installation_shared,
"installation_status": "unavailable" if github.installation_unavailable() else "connected",
+ "needs_reauthorization": github.needs_reauthorization,
+ "needs_reauthorization_at": github.needs_reauthorization_at,
"created_at": integration.created_at,
}
diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.py
index 9baecfdaa5e9..3b2b96cbf747 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -1,5 +1,5 @@
import time
-from datetime import datetime
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from uuid import UUID, uuid4
@@ -306,6 +306,13 @@ class UserGitHubIntegration(GitHubIntegrationBase):
"""Whether the stored user tokens were stripped and the person has to reconnect."""
return bool((self.integration.config or {}).get(NEEDS_REAUTHORIZATION_AT_CONFIG_KEY))
+ @property
+ def needs_reauthorization_at(self) -> datetime | None:
+ flagged_at = (self.integration.config or {}).get(NEEDS_REAUTHORIZATION_AT_CONFIG_KEY)
+ if not isinstance(flagged_at, int | float):
+ return None
+ return datetime.fromtimestamp(flagged_at, tz=UTC)
+
def refresh_user_access_token(self) -> None:
"""Exchange the refresh token for a fresh user-to-server access token.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f6256c738d27..04a808cb61f7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -77499,6 +77499,13 @@ export namespace Schemas {
* * `connected` - connected
* * `unavailable` - unavailable */
installation_status: InstallationStatusEnum;
+ /** True when GitHub rejected the stored credentials and PostHog dropped them. The installation is still on GitHub, but PostHog cannot act as the user until they authorize it again. */
+ needs_reauthorization: boolean;
+ /**
+ * When the stored credentials stopped working, or null while they still work.
+ * @nullable
+ */
+ needs_reauthorization_at: string | null;
/** When this integration row was created. */
created_at: string;
}