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): show GitHub install status, org-owner handoff, and clearer disconnect (#85115)

Charles Viene900291ddeab
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5030a45b8727..c1b1a80b76d9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1220,6 +1220,22 @@ snapshots:
hash: v1.k794b7964.569cfd0e730a83543813b1eafb440926aa4609bb0152eb181dc59fee1ea5dfd3.45sa4VsBQ3Ff-WeTTpiTNY4rF2ENc8DS-adghxL68Bw
components-insighttooltip--math-tags-single-series--light:
hash: v1.k794b7964.7b71a93bc37c46ac51efcb9f53cd989daade7490f30ebde795b0b918e59d25e2.Y0ThCO5-ePDvaf3o5da7LvN_1quQ_FXQEnTSm5TCvog
+ components-integrations-githubreposummary--all-repositories--dark:
+ hash: v1.k794b7964.ad87b61d12c16bbe594c68eede01d3e9e279a7dfd08bcce06c734ea7ade4c9cb.iOP_47ViGava56NrIa0Sn2daPDaCDikXL9e_fXtcKgo
+ components-integrations-githubreposummary--all-repositories--light:
+ hash: v1.k794b7964.62d9d94a1b15230f0c2da0a6eff877d23ca721aa6851a6d2d8077b55a74e21c9.Hn3W0UinV-cPbJSD97g4DDUVoyPynUSN__jE-fR4nFE
+ components-integrations-githubreposummary--loading--dark:
+ hash: v1.k794b7964.2b94609c6a74c47f864438d01a543810036991028441943711e1d5537a837385.atudCSLpKIDPWse2yfggjtDV8MjRfdXFrFD9uipPRJc
+ components-integrations-githubreposummary--loading--light:
+ hash: v1.k794b7964.1d3414ca998863ffe6f63b0c1caed72702120a153bac7ee253bfae4a28b97151.1YV1C3g0Q6w-67cv8iXOlsMu-yi-923IgVhZu8TZW-Y
+ components-integrations-githubreposummary--no-repositories--dark:
+ hash: v1.k794b7964.ff6b0a153f5ed63d7ce62b21e349cd4a78b4e62b28bf8caec8691de379f51095.ar96UT8mflIKPO_aXUZfALG67i-IR8cvh_jlvvLeRiA
+ components-integrations-githubreposummary--no-repositories--light:
+ hash: v1.k794b7964.5184c4a6bde998761f8e1b1d6501af6032a5fb6724948bac273f26288c971d11.QUT-Erlz-8nalQbpxW8vLreruZVHQMPpXFM5dZkOmVg
+ components-integrations-githubreposummary--selected-repositories--dark:
+ hash: v1.k794b7964.6b312940bdf01caa208689ed498382b18d61245b170daf8151888ed606935dee.gaMtmp_75UOjdqpNSSgX-v0kWafPY7R8b5T5rqkO0_w
+ components-integrations-githubreposummary--selected-repositories--light:
+ hash: v1.k794b7964.7501429052c7c80c4c64f9bd050070979087fdf1226ccc54131aa51e6a86b756.dkuccKoaLQyC26bPGeTl8p4XUXRTk-CcffvqF858JDM
components-integrations-slack--slack-full-page-connect--dark:
hash: v1.k794b7964.0ec1f0782714a86fc84cc4b430b9d6b1edc9edd945e635c12b0aae0dbdad0854.DRZ-P0uQlhkiCa6sJb4YdjgeW1dJFG1hCCofSDE0ngc
components-integrations-slack--slack-full-page-connect--light:
@@ -7661,9 +7677,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-details--light:
hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.nm2ebJO-70lgkubc-wOB4EFtPnO-885kq4I93mt0TNs
scenes-app-settings-environment--settings-environment-error-tracking--dark:
- hash: v1.k794b7964.d9d299561ca437a5157edf37c4758a22d0d3db4844b78c5b23d2ad57fefeed46.1WzOoH8UOJjf6a6xfjBQfArtLbWmlU9q2VgRKExoisc
+ hash: v1.k794b7964.e6cf54c9386285877955daddf35940e48e435cf6d1e5040662c4e239ebd97fb8.vT3knk-UEsF5TKxAOnmLdi_4uIfbHYfBRW8Zz51BryA
scenes-app-settings-environment--settings-environment-error-tracking--light:
- hash: v1.k794b7964.98d311695dbaf5a8fe7e533170c3194f4a16a3221b62bd50a7a0d52de7ffb87a.nL8nCyaLMIlm4UNM11v_EYEgfHJwOgT1yk_ar2DduhM
+ hash: v1.k794b7964.5ac167271f00184ce6159d0072ce163542658b08419f6e70b5cf6a6ca201a718.X6dKpM6uGw_g_FAwdQ5PukTVcKWGAa77bMOzgw-kiXY
scenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:
hash: v1.k794b7964.610a8d8b91871b32a6b83b087df8523999636f905ebacd4d4bad4f6c2c10cdd2.N1EL1qb6-quDv9B8-LwQ5S-zyRZlCwgJJiR-ahq4p-8
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
@@ -7677,9 +7693,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-heatmaps--light:
hash: v1.k794b7964.05c858527b6a3deecc54799e4d4fad6c2b88ff83a26dc0baadff3448bf6635b4.u3Xak3I8OzaYGlO_KlLOvHMh7sWvmjOVDrKURMJBQLs
scenes-app-settings-environment--settings-environment-integrations--dark:
- hash: v1.k794b7964.c702b588bdda7c56430d8adf4a896345977abcf0a562e0e1bddf88238496770b.B_JN44u0kV7No27lpvJOOTBN7urhc6zcJ6r3kTOLFJk
+ hash: v1.k794b7964.eab246ccd1136c9853b8c784aee1ed549e3410869c14caf0ecdc44d4aadb7afa.OKw8YuAkErqsXqkceBujJ31q0OfGd13jMbDXDY6R5Rs
scenes-app-settings-environment--settings-environment-integrations--light:
- hash: v1.k794b7964.f249ac0b4d1984c3d0259394fef46e89186d039a4089c7d2acb19922e1d939d5.T0FKR0TfOB2Flt5kqA4HboFgQlUHjdI92AdocREcaoQ
+ hash: v1.k794b7964.676337e86614067960e5921914c746aa754fca36c8661e45f4413e9bab9f45eb.ARcWzCLx7_AvaL7WC9dutNLoampsgNI0YsTQ2d5vfEk
scenes-app-settings-environment--settings-environment-marketing-analytics--dark:
hash: v1.k794b7964.0c2038ca1ba04301309d89f6abed6353c1cd1cc948342a960ecfcce3a9619a48.K04BuaEcGkJJ30IFKapU7MOOl-6jjagnB0ZddGTrkaU
scenes-app-settings-environment--settings-environment-marketing-analytics--light:
@@ -7697,9 +7713,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-product-analytics--light:
hash: v1.k794b7964.70bf7959ecd4f39a1ac0d069beec0f6cdaf24d9afaee70e70b4cf75619f56de5.xQCvIAWzmRCUGafz6moNuItTspGJA6dwjKLb3mE16Uk
scenes-app-settings-environment--settings-environment-replay--dark:
- hash: v1.k794b7964.b4e3d6b8b8acafd3697cd1631eecb1901e436f21a60a6c7f2c632ca59fc549e8.oFRYxxDLs57K0Ps3pt0kDAqTaMYEVbf8DRqzO8qTcMo
+ hash: v1.k794b7964.f1cf2caf2a601eab997faf97731316405a676688daf7f18714f79c2a6ef4a8b0.KcPUVYm-x48YPs0PiftUkt7Q4vlIVbF6xsosB15zYOw
scenes-app-settings-environment--settings-environment-replay--light:
- hash: v1.k794b7964.e9746c76b206bd926fcdd913dd2941b430eb63bc39043b66bb15a8a06c414734.7NbFsK-o2SFeMtXCTTYKhY8jCdcI7J1UZm_HFPqJLVU
+ hash: v1.k794b7964.e0e88948b99c8a38e602dfe6ff8c26f68c346742b703d9b85e8a7ee319501e42.BPVUCBswE78Ps2DAYwsH5YW-rayV4hi7jswSw5UKwAM
scenes-app-settings-environment--settings-environment-revenue-analytics--dark:
hash: v1.k794b7964.1b59813d53eb3cf7f0505a250ff6dcac0c25785011679e74420d389dabe25582.Gn5HB_rvDNmwFNIlRts1ZZ17hRhFJ88yILUevtuwy0g
scenes-app-settings-environment--settings-environment-revenue-analytics--light:
@@ -7765,17 +7781,17 @@ snapshots:
scenes-app-settings-project--settings-project-details--light:
hash: v1.k794b7964.92d131dadd962625b5dfdd78a2cb9c42017b230b1c39f9ae1b293e8f6e9fe788.ufkrkTmgF764iFDi-uaHriqBvleJci3OVpjBAwJxiUw
scenes-app-settings-project--settings-project-integrations--dark:
- hash: v1.k794b7964.c702b588bdda7c56430d8adf4a896345977abcf0a562e0e1bddf88238496770b.1kRxkbRjHvzKooz7gjEbDDb3eVs_NFoQLI7EJGWU7d8
+ hash: v1.k794b7964.eab246ccd1136c9853b8c784aee1ed549e3410869c14caf0ecdc44d4aadb7afa.WtnZtBw3LuOsLLSWPJuRdXKbPKfnwKTZ9ntBKIXDJ5M
scenes-app-settings-project--settings-project-integrations--light:
- hash: v1.k794b7964.f249ac0b4d1984c3d0259394fef46e89186d039a4089c7d2acb19922e1d939d5.jJ02CU9zcmLg0Itz38r89UxL3MY_8Rnd-KddWUMrkP8
+ hash: v1.k794b7964.676337e86614067960e5921914c746aa754fca36c8661e45f4413e9bab9f45eb.AVzu-ilxexc1vSvtOeilduBEcoxNiQxxY8-H9A83EJk
scenes-app-settings-project--settings-project-product-analytics--dark:
hash: v1.k794b7964.925784616ac6ad5cb556351ede1916440226c9089930265fc96df7e14863046c.6iXpmU_M40nsD_JokXYH4Ey-T5YaQsEB1jGl35jRBgo
scenes-app-settings-project--settings-project-product-analytics--light:
hash: v1.k794b7964.527360edf55b268b83ba976288336721af6da9af6088605669a4395b5a9b7a20.qnXEVYP868iG2Q0bj-z9_tORjlspkGdyJEMj5GDuG-8
scenes-app-settings-project--settings-project-replay--dark:
- hash: v1.k794b7964.b4e3d6b8b8acafd3697cd1631eecb1901e436f21a60a6c7f2c632ca59fc549e8.rEnpv0vmgJOyLIMLm2EZMObrVa6KY-AGVTz4zeHRDJI
+ hash: v1.k794b7964.42643eba5e571cd19b8da6a56ab4dcf0c38b78a143e66bbe8b281bfab9701687.nqBxikOTaNS7A47m4-kBKi9aJSEd9SlbWrbcQKszW5I
scenes-app-settings-project--settings-project-replay--light:
- hash: v1.k794b7964.e9746c76b206bd926fcdd913dd2941b430eb63bc39043b66bb15a8a06c414734.huxrVyJtXMP0xQB1S9-PGTIcg-PCx_aPg5p2EAR9JLs
+ hash: v1.k794b7964.e0e88948b99c8a38e602dfe6ff8c26f68c346742b703d9b85e8a7ee319501e42.T9RgA2E-vBxzIliieWNns9bWN5kfnmtyalIcc8DpQy8
scenes-app-settings-project--settings-project-surveys--dark:
hash: v1.k794b7964.116b8618e7355d13ff8ddc83c5095b98edd1bca44d8326d7a05c2922e967b0d8.mYqdrV9UEmN1USMnHw5MMm3DWaOk8_s_BNmFP-aRMFU
scenes-app-settings-project--settings-project-surveys--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 85d92c474ecf..998d93c7eef6 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -50,6 +50,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'generateSummary', // Summary view renders its own retry state
'loadSelfDrivingEvaluationReports', // The self-driving eval table renders its own retry state
'loadToolDataEvents',
+ 'loadInstallRequests', // Polled in the background on Settings → Integrations; the banner just stays hidden
'loadPrChecks', // Polled in the Inbox report detail; the CI checks section renders its own error state
'loadPrComments', // The Inbox report detail's PR comments section renders its own error state
'loadMonitoringSnapshot', // The managed warehouse Monitoring tab renders its own retry state
diff --git a/frontend/src/lib/integrations/GitHubInstallRequestsBanner.tsx b/frontend/src/lib/integrations/GitHubInstallRequestsBanner.tsx
new file mode 100644
index 000000000000..b380023b9200
--- /dev/null
+++ b/frontend/src/lib/integrations/GitHubInstallRequestsBanner.tsx
@@ -0,0 +1,121 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { githubInstallRequestsLogic } from 'lib/integrations/githubInstallRequestsLogic'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import type { GitHubInstallRequestItemApi } from '~/generated/core/api.schemas'
+
+export function buildOrgOwnerMessage(installUrl: string): string {
+ return `Can you approve the PostHog GitHub app for our organization? Open ${installUrl}, pick the organization, and approve the pending request.`
+}
+
+/**
+ * Surfaces the "waiting for a GitHub org owner" state and its resolution. Rendering this
+ * subscribes the surface to install-request polling for as long as it stays mounted.
+ */
+export function GitHubInstallRequestsBanner({
+ onFinishConnecting,
+ finishConnectingUrl,
+}: {
+ /** Runs the surface's own connect flow once an owner has approved the install. */
+ onFinishConnecting?: () => void
+ /** Alternative to `onFinishConnecting` for surfaces whose connect is a plain link. */
+ finishConnectingUrl?: string
+}): JSX.Element | null {
+ const { pendingInstallRequests, approvedInstallRequests, installUrl, dismissingRequestIds } =
+ useValues(githubInstallRequestsLogic)
+ const { startPolling, stopPolling, dismissInstallRequest } = useActions(githubInstallRequestsLogic)
+
+ useOnMountEffect(() => {
+ startPolling()
+ return () => stopPolling()
+ })
+
+ if (pendingInstallRequests.length === 0 && approvedInstallRequests.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ {approvedInstallRequests.map((request: GitHubInstallRequestItemApi) => (
+ <LemonBanner key={request.id} type="success" hideIcon>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-sm font-normal">
+ An organization owner approved the PostHog app for{' '}
+ <strong>{request.account_login || request.github_login || 'your organization'}</strong>.
+ Finish connecting to start using it.
+ </span>
+ <div className="flex gap-2 shrink-0">
+ <LemonButton
+ type="primary"
+ size="small"
+ to={finishConnectingUrl}
+ disableClientSideRouting={!!finishConnectingUrl}
+ onClick={onFinishConnecting}
+ >
+ Finish connecting
+ </LemonButton>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ loading={dismissingRequestIds.includes(request.id)}
+ onClick={() => dismissInstallRequest(request.id)}
+ >
+ Dismiss
+ </LemonButton>
+ </div>
+ </div>
+ </LemonBanner>
+ ))}
+ {pendingInstallRequests.map((request: GitHubInstallRequestItemApi) => (
+ <LemonBanner key={request.id} type="info" hideIcon>
+ <div className="flex flex-col gap-2">
+ <span className="text-sm font-normal">
+ GitHub sent your request
+ {request.github_login ? (
+ <>
+ {' '}
+ (as <strong>{request.github_login}</strong>)
+ </>
+ ) : null}{' '}
+ to your organization owners. Once an owner approves the PostHog app, we'll finish connecting
+ here.
+ </span>
+ {installUrl ? (
+ <code className="text-xs whitespace-normal break-words">
+ {buildOrgOwnerMessage(installUrl)}
+ </code>
+ ) : null}
+ <div className="flex flex-wrap gap-2">
+ {installUrl ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() =>
+ void copyToClipboard(
+ buildOrgOwnerMessage(installUrl),
+ 'message for your org owner'
+ )
+ }
+ >
+ Copy message for your org owner
+ </LemonButton>
+ ) : null}
+ <LemonButton
+ type="tertiary"
+ size="small"
+ loading={dismissingRequestIds.includes(request.id)}
+ onClick={() => dismissInstallRequest(request.id)}
+ >
+ Dismiss
+ </LemonButton>
+ </div>
+ </div>
+ </LemonBanner>
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/integrations/GitHubRepoSummary.stories.tsx b/frontend/src/lib/integrations/GitHubRepoSummary.stories.tsx
new file mode 100644
index 000000000000..83babb167f79
--- /dev/null
+++ b/frontend/src/lib/integrations/GitHubRepoSummary.stories.tsx
@@ -0,0 +1,42 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { GitHubRepoSummary } from './GitHubRepoSummary'
+
+const meta: Meta<typeof GitHubRepoSummary> = {
+ title: 'Components/Integrations/GitHubRepoSummary',
+ component: GitHubRepoSummary,
+ args: {
+ installationId: '12345',
+ accountType: 'Organization',
+ accountName: 'PostHog',
+ loading: false,
+ repoNames: [],
+ },
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof GitHubRepoSummary>
+
+export const Loading: Story = {
+ args: { loading: true },
+ // The spinner never stops in this story, so the runner must not wait it out.
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+
+export const NoRepositories: Story = {}
+
+export const SelectedRepositories: Story = {
+ args: {
+ repositorySelection: 'selected',
+ repoNames: ['posthog', 'posthog-js', 'posthog.com', 'posthog-python', 'code'],
+ },
+}
+
+export const AllRepositories: Story = {
+ args: {
+ repositorySelection: 'all',
+ repoNames: ['posthog', 'posthog-js', 'posthog.com'],
+ total: 712,
+ },
+}
diff --git a/frontend/src/lib/integrations/GitHubRepoSummary.tsx b/frontend/src/lib/integrations/GitHubRepoSummary.tsx
index dc523f6965b8..890a1724b5fd 100644
--- a/frontend/src/lib/integrations/GitHubRepoSummary.tsx
+++ b/frontend/src/lib/integrations/GitHubRepoSummary.tsx
@@ -15,6 +15,8 @@ export function GitHubRepoSummary({
installationId,
accountType,
accountName,
+ repositorySelection,
+ total,
onBeforeManage,
}: {
repoNames: string[]
@@ -22,6 +24,10 @@ export function GitHubRepoSummary({
installationId?: string | null
accountType?: string
accountName?: string
+ /** GitHub's own scope for the installation: "all" repositories or "selected" ones. */
+ repositorySelection?: string | null
+ /** Total repositories the installation can see, when known without listing them all. */
+ total?: number | null
/** Called before opening the GitHub installation settings page. Use this to seed
* server-side state (via the `github_prepare_callback` endpoints) so the eventual
* Setup URL callback can be dispatched to the right team/personal handler. */
@@ -45,6 +51,19 @@ export function GitHubRepoSummary({
/>
) : null
+ if (repositorySelection === 'all') {
+ return (
+ <div className="flex items-center gap-2 min-h-5">
+ <div className="text-xs text-muted">
+ <IconBranch className="inline mr-1 text-sm" />
+ All repositories in {accountName || 'this account'}
+ {total != null ? ` (${total})` : ''}
+ </div>
+ {manageButton}
+ </div>
+ )
+ }
+
if (loading && repoNames.length === 0) {
return (
<div className="flex items-center gap-1 text-xs text-muted min-h-5">
@@ -55,11 +74,16 @@ export function GitHubRepoSummary({
}
if (repoNames.length > 0) {
+ const noun = repoNames.length === 1 ? 'repository' : 'repositories'
+ const countLabel =
+ repositorySelection === 'selected'
+ ? `${repoNames.length} selected ${noun}`
+ : `${repoNames.length} ${noun} accessible`
return (
<div className="flex items-center gap-2 min-h-5">
<div className="text-xs text-muted">
<IconBranch className="inline mr-1 text-sm" />
- {repoNames.length} repositor{repoNames.length === 1 ? 'y' : 'ies'} accessible:{' '}
+ {countLabel}:{' '}
{repoNames.length <= 3
? repoNames.join(', ')
: `${repoNames.slice(0, 3).join(', ')} and ${repoNames.length - 3} more`}
diff --git a/frontend/src/lib/integrations/IntegrationView.tsx b/frontend/src/lib/integrations/IntegrationView.tsx
index 0b249ed7286a..01eea5b7c099 100644
--- a/frontend/src/lib/integrations/IntegrationView.tsx
+++ b/frontend/src/lib/integrations/IntegrationView.tsx
@@ -40,18 +40,24 @@ export function IntegrationView({
})
const errors = (integration.errors && integration.errors?.split(',')) || []
- const { githubRepositoriesLoading, getGitHubRepositories } = useValues(integrationsLogic)
+ const { githubRepositoriesLoading, getGitHubRepositories, getGitHubRepositoriesTotal } =
+ useValues(integrationsLogic)
const { loadGitHubRepositories } = useActions(integrationsLogic)
const isGitHub = integration.kind === 'github'
const repositories = isGitHub ? getGitHubRepositories(integration.id) : []
+ const repositoriesTotal = isGitHub ? getGitHubRepositoriesTotal(integration.id) : null
const refreshedAtTimestamp = integration.config?.refreshed_at || null
+ const installationUnavailable = isGitHub && integration.installation_status === 'unavailable'
+ // Reload when the installation's repository scope changes, not just its id: polling and the
+ // focus refetch can flip repository_selection in place (e.g. after editing access on GitHub),
+ // and the cached list/total would otherwise stay stale until a full page reload.
useEffect(() => {
if (isGitHub) {
loadGitHubRepositories(integration.id)
}
- }, [isGitHub, integration.id, loadGitHubRepositories])
+ }, [isGitHub, integration.id, integration.config?.repository_selection, loadGitHubRepositories])
suffix = suffix || (
<div className="flex flex-row gap-2">
@@ -85,7 +91,9 @@ export function IntegrationView({
<div>
<div className="flex gap-2">
<span>
- {refreshedAtTimestamp ? (
+ {installationUnavailable ? (
+ <>No longer connected</>
+ ) : refreshedAtTimestamp ? (
<Tooltip
title={
<div className="flex gap-1 items-baseline">
@@ -118,6 +126,8 @@ export function IntegrationView({
installationId={integration.config?.installation_id}
accountType={integration.config?.account?.type}
accountName={integration.config?.account?.name}
+ repositorySelection={integration.config?.repository_selection}
+ total={repositoriesTotal}
onBeforeManage={
currentTeam?.id
? async () => {
@@ -142,7 +152,47 @@ export function IntegrationView({
{suffix}
</div>
- {errors.length > 0 ? (
+ {installationUnavailable ? (
+ <div className="p-2">
+ <LemonBanner type="error">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>
+ The PostHog app was removed from GitHub. Remove this connection or reinstall the app.
+ </span>
+ <div className="flex gap-2 shrink-0">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ onClick={() => deleteIntegration(integration.id)}
+ disabledReason={restrictedReason}
+ >
+ Remove
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ size="small"
+ disableClientSideRouting
+ to={api.integrations.authorizeUrl({
+ kind: integration.kind,
+ next: window.location.pathname,
+ })}
+ onClick={() =>
+ reportIntegrationConnectClicked(
+ integration.kind,
+ integration.kind,
+ 'unavailable_banner_reconnect'
+ )
+ }
+ disabledReason={restrictedReason}
+ >
+ Reconnect
+ </LemonButton>
+ </div>
+ </div>
+ </LemonBanner>
+ </div>
+ ) : errors.length > 0 ? (
<div className="p-2">
<LemonBanner
type="error"
diff --git a/frontend/src/lib/integrations/IntegrationsList.tsx b/frontend/src/lib/integrations/IntegrationsList.tsx
index 18642bddb62e..8e2ec973d3ee 100644
--- a/frontend/src/lib/integrations/IntegrationsList.tsx
+++ b/frontend/src/lib/integrations/IntegrationsList.tsx
@@ -1,7 +1,8 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { LemonSkeleton } from '@posthog/lemon-ui'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
@@ -11,12 +12,21 @@ export function IntegrationsList({
titleText = 'All connected integrations are listed here. These integrations may be used for various purposes, such as data warehouse or pipeline destinations. To connect a new integration, visit the relevant product area.',
onlyKinds,
omitKinds,
+ emptyState,
}: {
onlyKinds?: IntegrationKind[]
omitKinds?: IntegrationKind[]
titleText?: string
+ /** Rendered once the list has loaded and nothing matches. */
+ emptyState?: JSX.Element
}): JSX.Element {
const { integrations, integrationsLoading } = useValues(integrationsLogic)
+ const { startPolling, stopPolling } = useActions(integrationsLogic)
+
+ useOnMountEffect(() => {
+ startPolling()
+ return () => stopPolling()
+ })
const filteredIntegrations = integrations?.filter((integration) => {
if (onlyKinds && !onlyKinds.includes(integration.kind)) {
return false
@@ -32,11 +42,15 @@ export function IntegrationsList({
{titleText ? <p>{titleText}</p> : null}
<div className="deprecated-space-y-2">
- {filteredIntegrations?.length
- ? filteredIntegrations.map((integration) => (
- <IntegrationView key={integration.id} integration={integration} />
- ))
- : integrationsLoading && <LemonSkeleton className="h-10" />}
+ {filteredIntegrations?.length ? (
+ filteredIntegrations.map((integration) => (
+ <IntegrationView key={integration.id} integration={integration} />
+ ))
+ ) : integrationsLoading || integrations === null ? (
+ <LemonSkeleton className="h-10" />
+ ) : (
+ emptyState
+ )}
</div>
</div>
)
diff --git a/frontend/src/lib/integrations/githubDisconnectCopy.test.ts b/frontend/src/lib/integrations/githubDisconnectCopy.test.ts
new file mode 100644
index 000000000000..5e51c6e9d093
--- /dev/null
+++ b/frontend/src/lib/integrations/githubDisconnectCopy.test.ts
@@ -0,0 +1,32 @@
+import { buildGithubDisconnectDescription } from './githubDisconnectCopy'
+
+describe('buildGithubDisconnectDescription', () => {
+ it.each([
+ [
+ 'project scope, last reference',
+ false,
+ 'project' as const,
+ 'This uninstalls the PostHog app from PostHog on GitHub and disconnects it from every PostHog project and personal account that uses it.',
+ ],
+ [
+ 'project scope, shared',
+ true,
+ 'project' as const,
+ 'This project stops using GitHub. The PostHog app stays installed on GitHub because other projects or accounts still use it.',
+ ],
+ [
+ 'account scope, shared',
+ true,
+ 'account' as const,
+ 'Your account stops using GitHub. The PostHog app stays installed on GitHub because other projects or accounts still use it.',
+ ],
+ [
+ 'account scope, last reference',
+ false,
+ 'account' as const,
+ 'This uninstalls the PostHog app from PostHog on GitHub and disconnects it from every PostHog project and personal account that uses it.',
+ ],
+ ])('%s', (_name, installationShared, scope, expected) => {
+ expect(buildGithubDisconnectDescription('PostHog', installationShared, scope)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/integrations/githubDisconnectCopy.ts b/frontend/src/lib/integrations/githubDisconnectCopy.ts
new file mode 100644
index 000000000000..c2901463aa55
--- /dev/null
+++ b/frontend/src/lib/integrations/githubDisconnectCopy.ts
@@ -0,0 +1,18 @@
+export type GitHubDisconnectScope = 'project' | 'account'
+
+/**
+ * Backend rule: disconnecting the last reference to a GitHub App installation also uninstalls the
+ * App on GitHub and removes every other PostHog link to it, so the dialog has to say which case
+ * the user is in rather than the generic "this cannot be undone".
+ */
+export function buildGithubDisconnectDescription(
+ accountName: string,
+ installationShared: boolean,
+ scope: GitHubDisconnectScope = 'project'
+): string {
+ if (installationShared) {
+ const subject = scope === 'account' ? 'Your account stops using GitHub.' : 'This project stops using GitHub.'
+ return `${subject} The PostHog app stays installed on GitHub because other projects or accounts still use it.`
+ }
+ return `This uninstalls the PostHog app from ${accountName} on GitHub and disconnects it from every PostHog project and personal account that uses it.`
+}
diff --git a/frontend/src/lib/integrations/githubInstallRequestsLogic.test.ts b/frontend/src/lib/integrations/githubInstallRequestsLogic.test.ts
new file mode 100644
index 000000000000..4ba0330cc96b
--- /dev/null
+++ b/frontend/src/lib/integrations/githubInstallRequestsLogic.test.ts
@@ -0,0 +1,189 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { githubInstallRequestsLogic } from './githubInstallRequestsLogic'
+
+const pendingRequest = {
+ id: '018f0000-0000-7000-8000-000000000001',
+ github_login: 'octocat',
+ status: 'pending',
+ installation_id: null,
+ account_login: null,
+ account_type: null,
+ requested_at: '2026-08-18T00:00:00Z',
+ resolved_at: null,
+}
+
+const approvedRequest = {
+ ...pendingRequest,
+ id: '018f0000-0000-7000-8000-000000000002',
+ status: 'approved',
+ installation_id: '55555',
+ account_login: 'posthog-org',
+ account_type: 'Organization',
+ resolved_at: '2026-08-18T01:00:00Z',
+}
+
+describe('githubInstallRequestsLogic', () => {
+ let logic: ReturnType<typeof githubInstallRequestsLogic.build>
+ let results: Record<string, unknown>[]
+ let listCalls: number
+ let deletedIds: string[]
+
+ beforeEach(() => {
+ results = []
+ listCalls = 0
+ deletedIds = []
+ useMocks({
+ get: {
+ '/api/users/@me/integrations/github/install_requests/': () => {
+ listCalls += 1
+ return [200, { results, install_url: 'https://github.com/apps/posthog-dev/installations/new' }]
+ },
+ },
+ delete: {
+ '/api/users/@me/integrations/github/install_requests/:id/': ({ params }) => {
+ deletedIds.push(String(params.id))
+ return deletedIds.length === 1 ? [204] : [404, { detail: 'No GitHub install request found.' }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = githubInstallRequestsLogic()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ logic.unmount()
+ })
+
+ it('splits requests by status and exposes the shareable install url', async () => {
+ results = [pendingRequest, approvedRequest]
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+
+ expect(logic.values.pendingInstallRequests.map((r) => r.id)).toEqual([pendingRequest.id])
+ expect(logic.values.approvedInstallRequests.map((r) => r.id)).toEqual([approvedRequest.id])
+ expect(logic.values.installUrl).toBe('https://github.com/apps/posthog-dev/installations/new')
+ })
+
+ it.each([
+ ['pending request with a subscriber', [pendingRequest], true, true],
+ ['pending request without a subscriber', [pendingRequest], false, false],
+ ['only approved requests with a subscriber', [approvedRequest], true, false],
+ ])('polls only when %s', async (_name, rows, subscribed, expectPolling) => {
+ results = rows
+ jest.useFakeTimers()
+ logic.mount()
+ if (subscribed) {
+ logic.actions.startPolling()
+ }
+
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+
+ expect(logic.cache.disposables.registry.has('poll')).toBe(expectPolling)
+ })
+
+ it('stops polling once the last subscriber leaves and refetches on the interval while subscribed', async () => {
+ results = [pendingRequest]
+ jest.useFakeTimers()
+ logic.mount()
+ logic.actions.startPolling()
+ logic.actions.startPolling()
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+ const callsBeforeTick = listCalls
+
+ jest.advanceTimersByTime(15_000)
+ await expectLogic(logic).toDispatchActions(['loadInstallRequests', 'loadInstallRequestsSuccess'])
+ expect(listCalls).toBe(callsBeforeTick + 1)
+
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(false)
+ })
+
+ it('retries on the interval when the first load fails', async () => {
+ useMocks({
+ get: {
+ '/api/users/@me/integrations/github/install_requests/': () => {
+ listCalls += 1
+ return listCalls === 1
+ ? [500, { detail: 'Server error.' }]
+ : [200, { results: [pendingRequest], install_url: null }]
+ },
+ },
+ })
+ jest.useFakeTimers()
+ logic.mount()
+ logic.actions.startPolling()
+
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsFailure'])
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+
+ jest.advanceTimersByTime(15_000)
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+ expect(logic.values.pendingInstallRequests.map((r) => r.id)).toEqual([pendingRequest.id])
+ })
+
+ it('gives up polling once the endpoint keeps failing', async () => {
+ useMocks({
+ get: {
+ '/api/users/@me/integrations/github/install_requests/': () => {
+ listCalls += 1
+ return [500, { detail: 'Server error.' }]
+ },
+ },
+ })
+ jest.useFakeTimers()
+ logic.mount()
+ logic.actions.startPolling()
+
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsFailure'])
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+ jest.advanceTimersByTime(15_000)
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsFailure'])
+ }
+
+ expect(logic.cache.disposables.registry.has('poll')).toBe(false)
+ const callsAfterGivingUp = listCalls
+ jest.advanceTimersByTime(60_000)
+ expect(listCalls).toBe(callsAfterGivingUp)
+ })
+
+ it('reloads after dismissing, and treats an already-deleted request as dismissed', async () => {
+ results = [pendingRequest]
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+
+ results = []
+ await expectLogic(logic, () => {
+ logic.actions.dismissInstallRequest(pendingRequest.id)
+ }).toDispatchActions(['loadInstallRequests', 'loadInstallRequestsSuccess'])
+ expect(logic.values.pendingInstallRequests).toEqual([])
+
+ await expectLogic(logic, () => {
+ logic.actions.dismissInstallRequest(pendingRequest.id)
+ }).toDispatchActions(['loadInstallRequests', 'loadInstallRequestsSuccess'])
+ expect(deletedIds).toEqual([pendingRequest.id, pendingRequest.id])
+ })
+
+ it('marks a request as dismissing while its delete is in flight, then clears it', async () => {
+ results = [pendingRequest]
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstallRequestsSuccess'])
+
+ results = []
+ // The reducer applies synchronously on dispatch, before the DELETE resolves, so the button
+ // can disable itself for the duration.
+ logic.actions.dismissInstallRequest(pendingRequest.id)
+ expect(logic.values.dismissingRequestIds).toEqual([pendingRequest.id])
+
+ await expectLogic(logic).toDispatchActions(['dismissInstallRequestSuccess', 'loadInstallRequestsSuccess'])
+ expect(logic.values.dismissingRequestIds).toEqual([])
+ })
+})
diff --git a/frontend/src/lib/integrations/githubInstallRequestsLogic.ts b/frontend/src/lib/integrations/githubInstallRequestsLogic.ts
new file mode 100644
index 000000000000..cf1a4423207b
--- /dev/null
+++ b/frontend/src/lib/integrations/githubInstallRequestsLogic.ts
@@ -0,0 +1,203 @@
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiError } from 'lib/api'
+
+import {
+ usersIntegrationsGithubInstallRequestsDestroy,
+ usersIntegrationsGithubInstallRequestsRetrieve,
+} from '~/generated/core/api'
+import type { GitHubInstallRequestItemApi, GitHubInstallRequestListResponseApi } from '~/generated/core/api.schemas'
+
+const INSTALL_REQUESTS_POLL_INTERVAL_MS = 15_000
+// A background poll shouldn't keep hitting an endpoint that is down for the whole mount, so give up
+// after a few consecutive failures rather than retrying (and reporting) every 15 seconds.
+const MAX_CONSECUTIVE_POLL_FAILURES = 3
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface githubInstallRequestsLogicValues {
+ approvedInstallRequests: GitHubInstallRequestItemApi[]
+ consecutiveLoadFailures: number
+ dismissingRequestIds: string[]
+ hasPendingInstallRequests: boolean
+ installRequests: GitHubInstallRequestItemApi[]
+ installRequestsResponse: GitHubInstallRequestListResponseApi | null
+ installRequestsResponseLoading: boolean
+ installUrl: string | null
+ pendingInstallRequests: GitHubInstallRequestItemApi[]
+ pollingSubscribers: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface githubInstallRequestsLogicActions {
+ dismissInstallRequest: (id: string) => {
+ id: string
+ }
+ dismissInstallRequestFailure: (id: string) => {
+ id: string
+ }
+ dismissInstallRequestSuccess: (id: string) => {
+ id: string
+ }
+ loadInstallRequests: () => any
+ loadInstallRequestsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadInstallRequestsSuccess: (
+ installRequestsResponse: GitHubInstallRequestListResponseApi,
+ payload?: any
+ ) => {
+ installRequestsResponse: GitHubInstallRequestListResponseApi
+ payload?: any
+ }
+ startPolling: () => {
+ value: true
+ }
+ stopPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface githubInstallRequestsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ installRequests: (
+ installRequestsResponse: GitHubInstallRequestListResponseApi | null
+ ) => GitHubInstallRequestItemApi[]
+ installUrl: (installRequestsResponse: GitHubInstallRequestListResponseApi | null) => string | null
+ pendingInstallRequests: (installRequests: GitHubInstallRequestItemApi[]) => GitHubInstallRequestItemApi[]
+ approvedInstallRequests: (installRequests: GitHubInstallRequestItemApi[]) => GitHubInstallRequestItemApi[]
+ hasPendingInstallRequests: (pendingInstallRequests: GitHubInstallRequestItemApi[]) => boolean
+ }
+}
+
+export type githubInstallRequestsLogicType = MakeLogicType<
+ githubInstallRequestsLogicValues,
+ githubInstallRequestsLogicActions,
+ Record<string, any>,
+ githubInstallRequestsLogicMeta
+>
+
+/**
+ * Durable "waiting for a GitHub org owner" state. GitHub only tells us the outcome through the
+ * `installation.created` webhook, so while a request is pending and a consumer is mounted we poll
+ * the list; once every request is resolved or dismissed the poll stops.
+ */
+export const githubInstallRequestsLogic = kea<githubInstallRequestsLogicType>([
+ path(['lib', 'integrations', 'githubInstallRequestsLogic']),
+ actions({
+ startPolling: true,
+ stopPolling: true,
+ dismissInstallRequest: (id: string) => ({ id }),
+ dismissInstallRequestSuccess: (id: string) => ({ id }),
+ dismissInstallRequestFailure: (id: string) => ({ id }),
+ }),
+ loaders({
+ installRequestsResponse: [
+ null as GitHubInstallRequestListResponseApi | null,
+ {
+ loadInstallRequests: async () => await usersIntegrationsGithubInstallRequestsRetrieve('@me'),
+ },
+ ],
+ }),
+ reducers({
+ pollingSubscribers: [
+ 0,
+ {
+ startPolling: (state) => state + 1,
+ stopPolling: (state) => Math.max(0, state - 1),
+ },
+ ],
+ consecutiveLoadFailures: [
+ 0,
+ {
+ loadInstallRequestsSuccess: () => 0,
+ loadInstallRequestsFailure: (state) => state + 1,
+ },
+ ],
+ // Per-request in-flight state so each Dismiss button can disable itself while its DELETE
+ // runs, rather than allowing a repeat click to fire a redundant delete + reload.
+ dismissingRequestIds: [
+ [] as string[],
+ {
+ dismissInstallRequest: (state, { id }) => (state.includes(id) ? state : [...state, id]),
+ dismissInstallRequestSuccess: (state, { id }) => state.filter((x) => x !== id),
+ dismissInstallRequestFailure: (state, { id }) => state.filter((x) => x !== id),
+ },
+ ],
+ }),
+ selectors({
+ installRequests: [
+ (s) => [s.installRequestsResponse],
+ (response: GitHubInstallRequestListResponseApi | null): GitHubInstallRequestItemApi[] =>
+ response?.results ?? [],
+ ],
+ installUrl: [
+ (s) => [s.installRequestsResponse],
+ (response: GitHubInstallRequestListResponseApi | null): string | null => response?.install_url ?? null,
+ ],
+ pendingInstallRequests: [
+ (s) => [s.installRequests],
+ (installRequests: GitHubInstallRequestItemApi[]): GitHubInstallRequestItemApi[] =>
+ installRequests.filter((r) => r.status === 'pending'),
+ ],
+ approvedInstallRequests: [
+ (s) => [s.installRequests],
+ (installRequests: GitHubInstallRequestItemApi[]): GitHubInstallRequestItemApi[] =>
+ installRequests.filter((r) => r.status === 'approved'),
+ ],
+ hasPendingInstallRequests: [
+ (s) => [s.pendingInstallRequests],
+ (pendingInstallRequests: GitHubInstallRequestItemApi[]): boolean => pendingInstallRequests.length > 0,
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ const reconcilePolling = (): void => {
+ // A response that never loaded also keeps the timer armed, so a failed first load retries
+ // instead of hiding the banner for the rest of the mount.
+ const shouldPoll =
+ values.pollingSubscribers > 0 &&
+ values.consecutiveLoadFailures < MAX_CONSECUTIVE_POLL_FAILURES &&
+ (values.hasPendingInstallRequests || values.installRequestsResponse === null)
+ if (shouldPoll && !cache.disposables.registry.has('poll')) {
+ cache.disposables.add(() => {
+ const pollTimer = window.setInterval(
+ () => actions.loadInstallRequests(),
+ INSTALL_REQUESTS_POLL_INTERVAL_MS
+ )
+ return () => clearInterval(pollTimer)
+ }, 'poll')
+ } else if (!shouldPoll) {
+ cache.disposables.dispose('poll')
+ }
+ }
+ return {
+ // `afterMount` is the only initial load — the banner is the only consumer that mounts this
+ // logic, so a first subscriber always arrives at a logic that just ran it.
+ startPolling: reconcilePolling,
+ stopPolling: reconcilePolling,
+ loadInstallRequestsSuccess: reconcilePolling,
+ loadInstallRequestsFailure: reconcilePolling,
+ dismissInstallRequest: async ({ id }) => {
+ try {
+ await usersIntegrationsGithubInstallRequestsDestroy('@me', id)
+ } catch (e) {
+ // A 404 means the row is already gone, so the dismiss effectively succeeded.
+ if (!(e instanceof ApiError && e.status === 404)) {
+ actions.dismissInstallRequestFailure(id)
+ throw e
+ }
+ }
+ actions.dismissInstallRequestSuccess(id)
+ actions.loadInstallRequests()
+ },
+ }
+ }),
+ afterMount(({ actions }) => {
+ actions.loadInstallRequests()
+ }),
+])
diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.ts
index 7baf7c314ef3..ec9190df98a3 100644
--- a/frontend/src/lib/integrations/integrationsLogic.test.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts
@@ -3,134 +3,283 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import apiReal from 'lib/api'
+import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+
+import apiReal, { ApiError } from 'lib/api'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { IntegrationKind } from '~/types'
+import { IntegrationKind, IntegrationType } from '~/types'
import { integrationsLogic } from './integrationsLogic'
-describe('integrationsLogic — handleOauthCallback', () => {
+const githubIntegration = (overrides: Partial<IntegrationType> = {}): IntegrationType =>
+ ({
+ id: 42,
+ kind: 'github',
+ display_name: 'PostHog',
+ icon_url: '',
+ config: { installation_id: '12345', account: { name: 'PostHog', type: 'Organization' } },
+ created_at: '2026-08-18T00:00:00Z',
+ errors: '',
+ installation_shared: false,
+ installation_status: 'connected',
+ ...overrides,
+ }) as IntegrationType
+
+describe('integrationsLogic', () => {
let logic: ReturnType<typeof integrationsLogic.build>
let createSpy: jest.SpyInstance
+ let integrationsPayload: IntegrationType[]
+ let repoRequests: { integrationId: string; offset: string }[]
- useMocks({
- get: {
- '/api/environments/:team_id/integrations/': () => [200, { results: [] }],
- },
- })
-
- beforeEach(() => {
+ beforeEach(async () => {
+ integrationsPayload = []
+ repoRequests = []
+ // Handlers reset after every test, so register them per test.
+ useMocks({
+ get: {
+ '/api/environments/:team_id/integrations/': () => [200, { results: integrationsPayload }],
+ '/api/projects/:team_id/integrations/:id/github_repos/': ({ params, request }) => {
+ const offset = new URL(request.url).searchParams.get('offset') ?? '0'
+ repoRequests.push({ integrationId: String(params.id), offset })
+ const repositories = Array.from({ length: 100 }, (_, i) => ({
+ id: Number(offset) + i,
+ name: `repo${Number(offset) + i}`,
+ full_name: `posthog/repo${Number(offset) + i}`,
+ }))
+ return [200, { repositories, has_more: offset === '0', total: 200 }]
+ },
+ },
+ })
initKeaTests()
logic = integrationsLogic()
logic.mount()
+ // Drain the mount-time load so each test controls the next list response.
+ await expectLogic(logic).toDispatchActions(['loadIntegrationsSuccess'])
createSpy = jest.spyOn(apiReal.integrations, 'create')
})
afterEach(() => {
+ jest.useRealTimers()
jest.restoreAllMocks()
})
- it('redirects stripe marketplace callbacks to the confirmation page without POSTing', async () => {
- await expectLogic(logic, () => {
- logic.actions.handleOauthCallback('stripe' as IntegrationKind, {
- code: 'ac_123',
- stripe_user_id: 'acct_456',
- account_id: 'acc_789',
- user_id: 'usr_1',
- })
- }).toFinishAllListeners()
-
- expect(createSpy).not.toHaveBeenCalled()
- expect(router.values.location.pathname).toContain('/integrations/stripe/confirm-install')
- expect(router.values.searchParams).toEqual({
- code: 'ac_123',
- stripe_user_id: 'acct_456',
- account_id: 'acc_789',
- user_id: 'usr_1',
+ describe('GitHub repositories', () => {
+ it.each([
+ ['all', 1],
+ ['selected', 2],
+ ])('with repository_selection=%s it fetches %i page(s)', async (repositorySelection, expectedPages) => {
+ integrationsPayload = [
+ githubIntegration({
+ config: { installation_id: '12345', repository_selection: repositorySelection },
+ }),
+ ]
+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([
+ 'loadIntegrationsSuccess',
+ ])
+
+ await expectLogic(logic, () => logic.actions.loadGitHubRepositories(42)).toFinishAllListeners()
+
+ expect(repoRequests.filter((r) => r.integrationId === '42')).toHaveLength(expectedPages)
+ expect(logic.values.getGitHubRepositoriesTotal(42)).toBe(200)
+ expect(logic.values.githubRepositoriesLoading).toBe(false)
+ })
+
+ it('clears the cached total when a reload starts so a scope change cannot show a stale count', async () => {
+ integrationsPayload = [
+ githubIntegration({ config: { installation_id: '12345', repository_selection: 'selected' } }),
+ ]
+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([
+ 'loadIntegrationsSuccess',
+ ])
+ await expectLogic(logic, () => logic.actions.loadGitHubRepositories(42)).toFinishAllListeners()
+ expect(logic.values.getGitHubRepositoriesTotal(42)).toBe(200)
+
+ // A reload (e.g. after repository_selection flips via polling) drops the stale total
+ // immediately, before the refetch resolves.
+ logic.actions.loadGitHubRepositories(42)
+ expect(logic.values.getGitHubRepositoriesTotal(42)).toBeNull()
+
+ await expectLogic(logic).toFinishAllListeners()
})
})
- it('omits empty account_id and user_id when redirecting to the confirmation page', async () => {
- await expectLogic(logic, () => {
- logic.actions.handleOauthCallback('stripe' as IntegrationKind, {
- code: 'ac_123',
- stripe_user_id: 'acct_456',
+ describe('deleteIntegration', () => {
+ let dialogProps: any
+
+ beforeEach(() => {
+ dialogProps = null
+ jest.spyOn(LemonDialog, 'open').mockImplementation((props: any) => {
+ dialogProps = props
})
- }).toFinishAllListeners()
+ })
+
+ it.each([
+ [
+ 'last team reference',
+ false,
+ 'This uninstalls the PostHog app from PostHog on GitHub and disconnects it from every PostHog project and personal account that uses it.',
+ ],
+ [
+ 'shared with another project',
+ true,
+ 'This project stops using GitHub. The PostHog app stays installed on GitHub because other projects or accounts still use it.',
+ ],
+ ])('explains what disconnecting GitHub does when %s', async (_name, installationShared, description) => {
+ integrationsPayload = [githubIntegration({ installation_shared: installationShared })]
+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([
+ 'loadIntegrationsSuccess',
+ ])
+
+ logic.actions.deleteIntegration(42)
- expect(createSpy).not.toHaveBeenCalled()
- expect(router.values.location.pathname).toContain('/integrations/stripe/confirm-install')
- expect(router.values.searchParams).toEqual({
- code: 'ac_123',
- stripe_user_id: 'acct_456',
+ expect(dialogProps.title).toBe('Disconnect GitHub?')
+ expect(dialogProps.description).toBe(description)
+ })
+
+ it('treats a 404 on delete as already disconnected and reloads', async () => {
+ integrationsPayload = [githubIntegration()]
+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([
+ 'loadIntegrationsSuccess',
+ ])
+ jest.spyOn(apiReal.integrations, 'delete').mockRejectedValue(new ApiError('Not found', 404))
+ const infoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => 'toast')
+ const errorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast')
+
+ logic.actions.deleteIntegration(42)
+ await expectLogic(logic, async () => {
+ await dialogProps.primaryButton.onClick()
+ }).toDispatchActions(['loadIntegrations'])
+
+ expect(infoSpy).toHaveBeenCalledWith('Already disconnected.')
+ expect(errorSpy).not.toHaveBeenCalled()
})
})
- it('does not create the integration when the OAuth state token no longer matches the cookie', async () => {
- // A stale/expired flow: the cookie minted at authorize time is gone or changed, so the token
- // carried in the state can't match. The callback must recover by redirecting back rather than
- // POST a create, so an expired (or forged) state can never link an integration.
- document.cookie = 'ph_oauth_state=a-different-token'
- const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'
+ describe('polling', () => {
+ it('polls integrations only while at least one surface is subscribed', async () => {
+ jest.useFakeTimers()
- await expectLogic(logic, () => {
- logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
- }).toFinishAllListeners()
+ logic.actions.startPolling()
+ logic.actions.startPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
- expect(createSpy).not.toHaveBeenCalled()
- expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(30_000)
+ }).toDispatchActions(['loadIntegrations'])
- document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(false)
+ })
})
- describe('integration create team scoping', () => {
- let requestedTeamIds: string[]
+ describe('handleOauthCallback', () => {
+ it('redirects stripe marketplace callbacks to the confirmation page without POSTing', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.handleOauthCallback('stripe' as IntegrationKind, {
+ code: 'ac_123',
+ stripe_user_id: 'acct_456',
+ account_id: 'acc_789',
+ user_id: 'usr_1',
+ })
+ }).toFinishAllListeners()
- beforeEach(() => {
- requestedTeamIds = []
- document.cookie = 'ph_oauth_state=csrf-tok'
- useMocks({
- post: {
- '/api/environments/:team_id/integrations/': ({ params }) => {
- requestedTeamIds.push(String(params.team_id))
- return [201, { id: 7, kind: 'slack' }]
- },
- },
+ expect(createSpy).not.toHaveBeenCalled()
+ expect(router.values.location.pathname).toContain('/integrations/stripe/confirm-install')
+ expect(router.values.searchParams).toEqual({
+ code: 'ac_123',
+ stripe_user_id: 'acct_456',
+ account_id: 'acc_789',
+ user_id: 'usr_1',
})
})
- afterEach(() => {
- document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
+ it('omits empty account_id and user_id when redirecting to the confirmation page', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.handleOauthCallback('stripe' as IntegrationKind, {
+ code: 'ac_123',
+ stripe_user_id: 'acct_456',
+ })
+ }).toFinishAllListeners()
+
+ expect(createSpy).not.toHaveBeenCalled()
+ expect(router.values.location.pathname).toContain('/integrations/stripe/confirm-install')
+ expect(router.values.searchParams).toEqual({
+ code: 'ac_123',
+ stripe_user_id: 'acct_456',
+ })
})
- it('creates the integration against the team carried in the OAuth state', async () => {
- // The callback is a full-page round-trip on a non-project-scoped URL, so the SPA's
- // current team is the user's default team here (MOCK_TEAM_ID) — not team 228502,
- // which the state says initiated the flow.
- const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok&team_id=228502'
+ it('does not create the integration when the OAuth state token no longer matches the cookie', async () => {
+ // A stale/expired flow: the cookie minted at authorize time is gone or changed, so the token
+ // carried in the state can't match. The callback must recover by redirecting back rather than
+ // POST a create, so an expired (or forged) state can never link an integration.
+ document.cookie = 'ph_oauth_state=a-different-token'
+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'
await expectLogic(logic, () => {
logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
}).toFinishAllListeners()
- expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, 228502)
- expect(requestedTeamIds).toEqual(['228502'])
+ expect(createSpy).not.toHaveBeenCalled()
expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')
- expect(router.values.searchParams.integration_id).toBe(7)
+
+ document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})
- it('falls back to the current team when the OAuth state carries no team_id', async () => {
- // In-flight flows started before team_id was added to the state keep the old behavior.
- const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'
+ describe('integration create team scoping', () => {
+ let requestedTeamIds: string[]
- await expectLogic(logic, () => {
- logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
- }).toFinishAllListeners()
+ beforeEach(() => {
+ requestedTeamIds = []
+ document.cookie = 'ph_oauth_state=csrf-tok'
+ useMocks({
+ post: {
+ '/api/environments/:team_id/integrations/': ({ params }) => {
+ requestedTeamIds.push(String(params.team_id))
+ return [201, { id: 7, kind: 'slack' }]
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
+ })
+
+ it('creates the integration against the team carried in the OAuth state', async () => {
+ // The callback is a full-page round-trip on a non-project-scoped URL, so the SPA's
+ // current team is the user's default team here (MOCK_TEAM_ID) — not team 228502,
+ // which the state says initiated the flow.
+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok&team_id=228502'
+
+ await expectLogic(logic, () => {
+ logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
+ }).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, 228502)
+ expect(requestedTeamIds).toEqual(['228502'])
+ expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')
+ expect(router.values.searchParams.integration_id).toBe(7)
+ })
+
+ it('falls back to the current team when the OAuth state carries no team_id', async () => {
+ // In-flight flows started before team_id was added to the state keep the old behavior.
+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'
- expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, undefined)
- expect(requestedTeamIds).toEqual([String(MOCK_TEAM_ID)])
+ await expectLogic(logic, () => {
+ logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
+ }).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith(
+ { kind: 'slack', config: { state, code: 'oauth-code' } },
+ undefined
+ )
+ expect(requestedTeamIds).toEqual([String(MOCK_TEAM_ID)])
+ })
})
})
})
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index cef919656890..56f47b7e7139 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -6,6 +6,7 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, getCookie } from 'lib/api'
import { globalSetupLogic } from 'lib/components/ProductSetup'
+import { buildGithubDisconnectDescription } from 'lib/integrations/githubDisconnectCopy'
import { describeGithubSetupError, GITHUB_INSTALL_PENDING_MESSAGE } from 'lib/integrations/githubSetupErrors'
import { describeOAuthCallbackError } from 'lib/integrations/oauthCallbackErrors'
import { preflightLogic } from 'lib/logic/preflightLogic'
@@ -25,13 +26,16 @@ import type {
GitHubAvailableInstallationApi,
GitHubAvailableInstallationsResponseApi,
GitHubRepoApi,
+ InstallationStatusEnumApi,
IntegrationKindEnumApi,
} from 'products/integrations/frontend/generated/api.schemas'
import { ChannelType } from 'products/workflows/frontend/Channels/MessageChannels'
import type { AvailableSetupTaskIdsEnumApi } from '../../generated/core/api.schemas'
import type { PreflightStatus, UserBasicType } from '../../types'
-import { ICONS } from './utils'
+import { ICONS, getIntegrationNameFromKind } from './utils'
+
+const INTEGRATIONS_POLL_INTERVAL_MS = 30_000
function toastApiError(e: unknown): void {
const detail = e instanceof ApiError ? e.detail : null
@@ -49,6 +53,7 @@ export interface integrationsLogicValues {
domainGroupedEmailIntegrations: EmailIntegrationDomainGroupedType[]
getGitHubRepositories: (integrationId: number) => string[]
getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[]
+ getGitHubRepositoriesTotal: (integrationId: number) => number | null
getIntegrationsByKind: (
kinds: (
| 'apns'
@@ -102,11 +107,13 @@ export interface integrationsLogicValues {
githubPersonalConnected: boolean | null
githubRepositories: Record<number, GitHubRepoApi[]>
githubRepositoriesLoading: boolean
+ githubRepositoriesTotal: Record<number, number>
integrations: IntegrationType[] | null
integrationsLoading: boolean
linkedGithubInstallation: IntegrationType | null
linkedGithubInstallationLoading: boolean
newIntegrationModalKind: IntegrationKind | null
+ pollingSubscribers: number
requestedAccessKinds: IntegrationKind[]
selectedIntegration: IntegrationType | null
setupModalOpen: boolean
@@ -209,11 +216,13 @@ export interface integrationsLogicActions {
loadGitHubRepositoriesPageSuccess: (
integrationId: number,
repositories: GitHubRepoApi[],
- hasMore: boolean
+ hasMore: boolean,
+ total?: number | null
) => {
hasMore: boolean
integrationId: number
repositories: GitHubRepoApi[]
+ total: number | null
}
loadGithubAvailableInstallations: () => any
loadGithubAvailableInstallationsFailure: (
@@ -247,6 +256,8 @@ export interface integrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -301,6 +312,8 @@ export interface integrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -372,6 +385,8 @@ export interface integrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -430,6 +445,8 @@ export interface integrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -640,6 +657,12 @@ export interface integrationsLogicActions {
setAccessRequestReason: (reason: string) => {
reason: string
}
+ startPolling: () => {
+ value: true
+ }
+ stopPolling: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -708,6 +731,9 @@ export interface integrationsLogicMeta {
getGitHubRepositoriesFull: (
githubRepositories: Record<number, GitHubRepoApi[]>
) => (integrationId: number) => GitHubRepoApi[]
+ getGitHubRepositoriesTotal: (
+ githubRepositoriesTotal: Record<number, number>
+ ) => (integrationId: number) => number | null
domainGroupedEmailIntegrations: (integrations: IntegrationType[] | null) => EmailIntegrationDomainGroupedType[]
}
}
@@ -743,14 +769,18 @@ export const integrationsLogic = kea<integrationsLogicType>([
loadGitHubRepositoriesPageSuccess: (
integrationId: number,
repositories: GitHubRepoApi[],
- hasMore: boolean
+ hasMore: boolean,
+ total: number | null = null
) => ({
integrationId,
repositories,
hasMore,
+ total,
}),
loadGitHubRepositoriesPageFailure: (integrationId: number) => ({ integrationId }),
setAccessRequestReason: (reason: string) => ({ reason }),
+ startPolling: true,
+ stopPolling: true,
}),
reducers({
newIntegrationModalKind: [
@@ -804,6 +834,30 @@ export const integrationsLogic = kea<integrationsLogicType>([
loadGitHubRepositoriesPageFailure: () => false,
},
],
+ githubRepositoriesTotal: [
+ {} as Record<number, number>,
+ {
+ // Clear the cached total when a reload starts so a scope change can't briefly (or, on a
+ // slow/failed refetch, indefinitely) show the previous selection's count.
+ loadGitHubRepositories: (state, { integrationId }) => {
+ if (!(integrationId in state)) {
+ return state
+ }
+ const next = { ...state }
+ delete next[integrationId]
+ return next
+ },
+ loadGitHubRepositoriesPageSuccess: (state, { integrationId, total }) =>
+ total == null ? state : { ...state, [integrationId]: total },
+ },
+ ],
+ pollingSubscribers: [
+ 0,
+ {
+ startPolling: (state) => state + 1,
+ stopPolling: (state) => Math.max(0, state - 1),
+ },
+ ],
requestedAccessKinds: [
[] as IntegrationKind[],
{
@@ -921,7 +975,7 @@ export const integrationsLogic = kea<integrationsLogicType>([
},
],
})),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
loadGitHubRepositories: ({ integrationId }) => {
actions.loadGitHubRepositoriesPage(integrationId, 0)
},
@@ -938,11 +992,44 @@ export const integrationsLogic = kea<integrationsLogicType>([
offset,
})
await breakpoint()
- actions.loadGitHubRepositoriesPageSuccess(integrationId, response.repositories, response.has_more)
+ // An "all repositories" installation is summarized by its total, so one page is enough.
+ const integration = values.integrations?.find((x) => x.id === integrationId)
+ const summarizedByTotal = integration?.config?.repository_selection === 'all'
+ actions.loadGitHubRepositoriesPageSuccess(
+ integrationId,
+ response.repositories,
+ summarizedByTotal ? false : response.has_more,
+ response.total ?? null
+ )
} catch {
actions.loadGitHubRepositoriesPageFailure(integrationId)
}
},
+ startPolling: () => {
+ if (cache.disposables.registry.has('poll')) {
+ return
+ }
+ cache.disposables.add(() => {
+ const pollTimer = window.setInterval(() => actions.loadIntegrations(), INTEGRATIONS_POLL_INTERVAL_MS)
+ return () => clearInterval(pollTimer)
+ }, 'poll')
+ cache.disposables.add(
+ () => {
+ const onFocus = (): void => actions.loadIntegrations()
+ window.addEventListener('focus', onFocus)
+ return () => window.removeEventListener('focus', onFocus)
+ },
+ 'focusRefetch',
+ { pauseOnPageHidden: false }
+ )
+ },
+ stopPolling: () => {
+ if (values.pollingSubscribers > 0) {
+ return
+ }
+ cache.disposables.dispose('poll')
+ cache.disposables.dispose('focusRefetch')
+ },
handleOauthCallback: async ({ kind, searchParams }) => {
const { state, code, error, stripe_user_id, account_id, user_id } = searchParams
const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state)
@@ -1031,24 +1118,35 @@ export const integrationsLogic = kea<integrationsLogicType>([
return
}
+ const integrationName = getIntegrationNameFromKind(integration.kind)
LemonDialog.open({
- title: `Do you want to disconnect from this ${integration.kind} integration?`,
+ title: `Disconnect ${integrationName}?`,
description:
- 'This cannot be undone. PostHog resources configured to use this integration will remain but will stop working.',
+ integration.kind === 'github'
+ ? buildGithubDisconnectDescription(
+ integration.config?.account?.name || integrationName,
+ !!integration.installation_shared
+ )
+ : 'This cannot be undone. PostHog resources configured to use this integration will remain but will stop working.',
primaryButton: {
- children: 'Yes, disconnect',
+ children: 'Disconnect',
status: 'danger',
onClick: async () => {
try {
await api.integrations.delete(id)
actions.loadIntegrations()
} catch (e) {
- toastApiError(e)
+ if (e instanceof ApiError && e.status === 404) {
+ lemonToast.info('Already disconnected.')
+ actions.loadIntegrations()
+ } else {
+ toastApiError(e)
+ }
}
},
},
secondaryButton: {
- children: 'No thanks',
+ children: 'Cancel',
},
})
},
@@ -1122,6 +1220,12 @@ export const integrationsLogic = kea<integrationsLogicType>([
return (integrationId: number): GitHubRepoApi[] => githubRepositories[integrationId] || []
},
],
+ getGitHubRepositoriesTotal: [
+ (s) => [s.githubRepositoriesTotal],
+ (githubRepositoriesTotal: Record<number, number>) => {
+ return (integrationId: number): number | null => githubRepositoriesTotal[integrationId] ?? null
+ },
+ ],
domainGroupedEmailIntegrations: [
(s) => [s.integrations],
diff --git a/frontend/src/lib/integrations/userGithubIntegrationLogic.test.ts b/frontend/src/lib/integrations/userGithubIntegrationLogic.test.ts
new file mode 100644
index 000000000000..36445367c721
--- /dev/null
+++ b/frontend/src/lib/integrations/userGithubIntegrationLogic.test.ts
@@ -0,0 +1,61 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { userGithubIntegrationLogic } from './userGithubIntegrationLogic'
+
+const SCOPE_CASES: [string, string, string[]][] = [
+ ['a scope change refetches the repository list', 'all', ['12345:0', '12345:0']],
+ ['an unchanged scope keeps the cached list', 'selected', ['12345:0']],
+]
+
+describe('userGithubIntegrationLogic', () => {
+ let logic: ReturnType<typeof userGithubIntegrationLogic.build>
+ let repoRequests: string[]
+
+ beforeEach(async () => {
+ repoRequests = []
+ useMocks({
+ get: {
+ '/api/users/:uuid/integrations/github/:installationId/repos/': ({ params, request }) => {
+ const offset = new URL(request.url).searchParams.get('offset') ?? '0'
+ repoRequests.push(`${params.installationId}:${offset}`)
+ return [
+ 200,
+ {
+ repositories: [{ id: 1, name: 'posthog', full_name: 'PostHog/posthog' }],
+ has_more: false,
+ total: 712,
+ },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ logic = userGithubIntegrationLogic({ installationId: '12345', repositorySelection: 'selected' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ // The logic is keyed by installation id alone, so polling that flips repository_selection in place
+ // has to refetch — otherwise the row keeps describing the previous scope.
+ it.each(SCOPE_CASES)('%s', async (_, repositorySelection, expectedRequests) => {
+ userGithubIntegrationLogic({ installationId: '12345', repositorySelection })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(repoRequests).toEqual(expectedRequests)
+ expect(logic.values.repositoriesTotal).toBe(712)
+ })
+
+ it('clears the cached total when a reload starts so a scope change cannot show a stale count', async () => {
+ expect(logic.values.repositoriesTotal).toBe(712)
+
+ // A reload (e.g. after repository_selection flips via polling) drops the stale total
+ // immediately, before the refetch resolves.
+ logic.actions.loadRepositories()
+ expect(logic.values.repositoriesTotal).toBeNull()
+
+ await expectLogic(logic).toFinishAllListeners()
+ })
+})
diff --git a/frontend/src/lib/integrations/userGithubIntegrationLogic.ts b/frontend/src/lib/integrations/userGithubIntegrationLogic.ts
index 98e6a6601240..e6485f1260f5 100644
--- a/frontend/src/lib/integrations/userGithubIntegrationLogic.ts
+++ b/frontend/src/lib/integrations/userGithubIntegrationLogic.ts
@@ -1,6 +1,18 @@
-import { MakeLogicType, actions, events, isBreakpoint, kea, key, listeners, path, props, reducers } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ events,
+ isBreakpoint,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+} from 'kea'
-import api from 'lib/api'
+import { usersIntegrationsGithubReposRetrieve } from '~/generated/core/api'
import type { GitHubRepoApi } from 'products/integrations/frontend/generated/api.schemas'
@@ -8,6 +20,8 @@ const PAGE_SIZE = 500
export interface UserGitHubIntegrationLogicProps {
installationId: string
+ /** GitHub's scope for the installation. "all" is summarized by its total instead of being paged through. */
+ repositorySelection?: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -15,6 +29,7 @@ export interface userGithubIntegrationLogicValues {
currentOffset: number
repositories: GitHubRepoApi[]
repositoriesLoading: boolean
+ repositoriesTotal: number | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -30,10 +45,12 @@ export interface userGithubIntegrationLogicActions {
}
loadRepositoriesPageSuccess: (
repositories: GitHubRepoApi[],
- hasMore: boolean
+ hasMore: boolean,
+ total?: number | null
) => {
hasMore: boolean
repositories: GitHubRepoApi[]
+ total: number | null
}
}
@@ -57,9 +74,14 @@ export const userGithubIntegrationLogic = kea<userGithubIntegrationLogicType>([
actions({
loadRepositories: true,
loadRepositoriesPage: (offset: number) => ({ offset }),
- loadRepositoriesPageSuccess: (repositories: GitHubRepoApi[], hasMore: boolean) => ({
+ loadRepositoriesPageSuccess: (
+ repositories: GitHubRepoApi[],
+ hasMore: boolean,
+ total: number | null = null
+ ) => ({
repositories,
hasMore,
+ total,
}),
loadRepositoriesPageFailure: true,
}),
@@ -84,6 +106,15 @@ export const userGithubIntegrationLogic = kea<userGithubIntegrationLogicType>([
loadRepositoriesPageFailure: () => false,
},
],
+ repositoriesTotal: [
+ null as number | null,
+ {
+ // Clear the cached total when a reload starts so a scope change can't briefly (or, on a
+ // slow/failed refetch, indefinitely) show the previous selection's count.
+ loadRepositories: () => null,
+ loadRepositoriesPageSuccess: (state, { total }) => total ?? state,
+ },
+ ],
currentOffset: [
0,
{
@@ -104,11 +135,17 @@ export const userGithubIntegrationLogic = kea<userGithubIntegrationLogicType>([
},
loadRepositoriesPage: async ({ offset }, breakpoint) => {
try {
- const response = await api.get(
- `api/users/@me/integrations/github/${logicProps.installationId}/repos/?limit=${PAGE_SIZE}&offset=${offset}`
- )
+ const response = await usersIntegrationsGithubReposRetrieve('@me', logicProps.installationId, {
+ limit: PAGE_SIZE,
+ offset,
+ })
await breakpoint()
- actions.loadRepositoriesPageSuccess(response.repositories, response.has_more)
+ const summarizedByTotal = logicProps.repositorySelection === 'all'
+ actions.loadRepositoriesPageSuccess(
+ response.repositories,
+ summarizedByTotal ? false : response.has_more,
+ response.total ?? null
+ )
} catch (e: any) {
if (isBreakpoint(e)) {
throw e
@@ -118,6 +155,15 @@ export const userGithubIntegrationLogic = kea<userGithubIntegrationLogicType>([
},
})),
+ // The logic is keyed by installation id, so a scope change (all vs selected) reuses this instance:
+ // polling and the focus refetch can flip repository_selection in place, and the cached list and
+ // total would otherwise keep describing the previous scope until a full page reload.
+ propsChanged(({ actions, props }, previousProps) => {
+ if (props.installationId && props.repositorySelection !== previousProps.repositorySelection) {
+ actions.loadRepositories()
+ }
+ }),
+
events(({ actions, props }) => ({
afterMount: () => {
if (props.installationId) {
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index b29aa9b3b3a3..960a6ade1752 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -64,6 +64,8 @@ export type IntegrationConnectSurface =
| 'signals_agent_setup'
| 'task_composer'
| 'visual_review_settings'
+ | 'install_approved_banner'
+ | 'unavailable_banner_reconnect'
export const ICONS: Record<IntegrationKind, any> = {
slack: IconSlack,
diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx
index 2378b0f420e4..ad5afdf24b57 100644
--- a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx
+++ b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx
@@ -12,12 +12,18 @@ import { GithubIntegration } from './GithubIntegration'
describe('GithubIntegration', () => {
let captureSpy: jest.SpyInstance
+ let installRequests: Record<string, unknown>[]
beforeEach(() => {
+ installRequests = []
useMocks({
get: {
'/api/environments/:team_id/integrations': { results: [] },
'/api/projects/:team_id/integrations/github/available_installations/': { installations: [] },
+ '/api/users/@me/integrations/github/install_requests/': () => [
+ 200,
+ { results: installRequests, install_url: 'https://github.com/apps/posthog-dev/installations/new' },
+ ],
},
})
initKeaTests()
@@ -55,4 +61,31 @@ describe('GithubIntegration', () => {
expect(connectClicks()).toEqual([])
})
+
+ it.each([
+ ['pending', 'GitHub sent your request', 'Copy message for your org owner'],
+ ['approved', 'An organization owner approved the PostHog app for', 'Finish connecting'],
+ ])('shows the %s install request with its action', async (status, text, action) => {
+ installRequests = [
+ {
+ id: '018f0000-0000-7000-8000-000000000001',
+ github_login: 'octocat',
+ status,
+ installation_id: status === 'approved' ? '55555' : null,
+ account_login: status === 'approved' ? 'posthog-org' : null,
+ account_type: null,
+ requested_at: '2026-08-18T00:00:00Z',
+ resolved_at: null,
+ },
+ ]
+
+ render(
+ <Provider>
+ <GithubIntegration connectSurface="settings" />
+ </Provider>
+ )
+
+ expect(await screen.findByText(text, { exact: false })).toBeInTheDocument()
+ expect(screen.getByText(action)).toBeInTheDocument()
+ })
})
diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.tsx
index b9d2b09d9c7d..6f5dacaea1f9 100644
--- a/frontend/src/scenes/integrations/components/GithubIntegration.tsx
+++ b/frontend/src/scenes/integrations/components/GithubIntegration.tsx
@@ -5,6 +5,7 @@ import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
import api from 'lib/api'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { GitHubInstallRequestsBanner } from 'lib/integrations/GitHubInstallRequestsBanner'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import type { IntegrationConnectSurface } from 'lib/integrations/utils'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
@@ -31,14 +32,18 @@ export function GithubIntegration({
const { currentTeam } = useValues(teamLogic)
const { linkedGithubInstallationLoading, githubAvailableInstallations, githubPersonalConnected } =
useValues(integrationsLogic)
- const { linkExistingGithubInstallation, loadGithubAvailableInstallations } = useActions(integrationsLogic)
+ const { linkExistingGithubInstallation, loadGithubAvailableInstallations, startPolling, stopPolling } =
+ useActions(integrationsLogic)
const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)
const githubIntegrations = useIntegrations('github')
// integrationsLogic is a singleton mounted from dozens of unrelated surfaces, so this fetch
- // hangs off the GitHub setup UI instead of the shared integrations load.
+ // hangs off the GitHub setup UI instead of the shared integrations load. Polling is likewise
+ // scoped to the settings surface: an uninstall on GitHub should show up while someone is looking.
useOnMountEffect(() => {
loadGithubAvailableInstallations()
+ startPolling()
+ return () => stopPolling()
})
const settingsPath = next ?? urls.settings('environment-integrations')
@@ -65,6 +70,10 @@ export function GithubIntegration({
{/* w-full because Integration drops its children into a bare flex row, which would
otherwise size the banner to its longest word. */}
<div className="flex flex-col gap-y-4 w-full">
+ <GitHubInstallRequestsBanner
+ finishConnectingUrl={authorizationUrl}
+ onFinishConnecting={() => reportConnect('install_approved_banner')}
+ />
{/* An install GitHub already has is the exception, not a second way to connect, so it
reads as an aside with its own action rather than a button competing with the one
below. */}
diff --git a/frontend/src/scenes/integrations/components/SlackIntegration.tsx b/frontend/src/scenes/integrations/components/SlackIntegration.tsx
index 99013ce18afd..d5ae7ce4adda 100644
--- a/frontend/src/scenes/integrations/components/SlackIntegration.tsx
+++ b/frontend/src/scenes/integrations/components/SlackIntegration.tsx
@@ -1,4 +1,4 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { useMemo, useState } from 'react'
import { LemonButton, Link } from '@posthog/lemon-ui'
@@ -6,6 +6,7 @@ import { LemonButton, Link } from '@posthog/lemon-ui'
import api from 'lib/api'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { FEATURE_FLAGS } from 'lib/constants'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -54,7 +55,13 @@ const getSlackAppManifest = (): any => ({
export function SlackIntegration({ next, centered }: { next?: string; centered?: boolean } = {}): JSX.Element {
const { slackIntegrations, slackAvailable } = useValues(integrationsLogic)
+ const { startPolling, stopPolling } = useActions(integrationsLogic)
const [showSlackInstructions, setShowSlackInstructions] = useState(false)
+
+ useOnMountEffect(() => {
+ startPolling()
+ return () => stopPolling()
+ })
const { user } = useValues(userLogic)
const { featureFlags } = useValues(featureFlagLogic)
diff --git a/frontend/src/scenes/integrations/definitions/github.tsx b/frontend/src/scenes/integrations/definitions/github.tsx
index 1d3c693182a4..30fd4f3d836d 100644
--- a/frontend/src/scenes/integrations/definitions/github.tsx
+++ b/frontend/src/scenes/integrations/definitions/github.tsx
@@ -29,7 +29,7 @@ export const GitHub = defineIntegration(
'Link pull requests and issues to PostHog',
'Attribute code changes across your repositories',
],
- docsUrl: 'https://posthog.com/docs/error-tracking/integrations',
+ docsUrl: 'https://posthog.com/docs/libraries/github',
},
GithubIntegration
)
diff --git a/frontend/src/scenes/integrations/definitions/slack.tsx b/frontend/src/scenes/integrations/definitions/slack.tsx
index affeda3447e4..77dabb4a89ce 100644
--- a/frontend/src/scenes/integrations/definitions/slack.tsx
+++ b/frontend/src/scenes/integrations/definitions/slack.tsx
@@ -44,7 +44,7 @@ export const Slack = defineIntegration(
'Receive alerts and error-tracking notifications in your channels',
'Manage feature flags, experiments, and surveys from Slack',
],
- docsUrl: 'https://posthog.com/docs/webhooks/slack',
+ docsUrl: 'https://posthog.com/docs/libraries/slack',
PostConnect: SlackPostConnect,
useStatus: useSlackStatus,
},
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index fd71535c1447..8627c85a5ac9 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -1556,7 +1556,7 @@ export const SETTINGS_MAP: SettingSection[] = [
title: 'Slack integration',
description:
'Integrate with Slack to subscribe to insights or dashboards for regular reports to channels of your choice.',
- docsUrl: 'https://posthog.com/docs/webhooks/slack',
+ docsUrl: Slack.docsUrl,
component: <Slack.SettingsSection />,
keywords: ['slack', 'channel', 'notification', 'subscribe', 'report'],
},
@@ -1564,7 +1564,7 @@ export const SETTINGS_MAP: SettingSection[] = [
id: 'integration-github',
title: 'GitHub integration',
description: 'Connect GitHub to link issues and pull requests with PostHog insights.',
- docsUrl: 'https://posthog.com/docs/error-tracking/integrations',
+ docsUrl: GitHub.docsUrl,
component: <GitHub.SettingsSection connectSurface="settings" />,
keywords: ['github', 'git', 'repository', 'issue', 'pr'],
},
@@ -1572,15 +1572,41 @@ export const SETTINGS_MAP: SettingSection[] = [
id: 'integration-linear',
title: 'Linear integration',
description: 'Connect Linear to create and link issues directly from PostHog.',
- docsUrl: 'https://posthog.com/docs/error-tracking/integrations',
+ docsUrl: Linear.docsUrl,
component: <Linear.SettingsSection />,
keywords: ['linear', 'issue', 'project management', 'task'],
},
{
id: 'integration-other',
title: 'Other integrations',
- description: 'Browse and manage additional third-party integrations.',
- component: <IntegrationsList omitKinds={['slack', 'github', 'linear']} />,
+ description:
+ 'Integrations connected from other product areas, such as pipeline destinations, data warehouse sources, error tracking, and marketing analytics.',
+ component: (
+ <IntegrationsList
+ omitKinds={['slack', 'github', 'linear']}
+ titleText=""
+ emptyState={
+ <div className="px-4 py-6 text-center text-sm text-secondary rounded border bg-surface-primary">
+ <p className="mb-1">No other integrations connected</p>
+ <p className="text-xs text-muted text-balance mb-0">
+ These connect from the product area that uses them:{' '}
+ <Link to={urls.destinations()}>pipeline destinations</Link>,{' '}
+ <Link to={urls.sources()}>data warehouse sources</Link>,{' '}
+ <Link
+ to={urls.settings('environment-error-tracking', 'error-tracking-integrations')}
+ >
+ error tracking
+ </Link>{' '}
+ and{' '}
+ <Link to={urls.settings('environment-marketing-analytics', 'marketing-settings')}>
+ marketing analytics
+ </Link>
+ .
+ </p>
+ </div>
+ }
+ />
+ ),
keywords: ['integration', 'connect', 'third-party', 'app'],
},
{
diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
index 253c15211069..c73c0579bd08 100644
--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
@@ -8,6 +8,7 @@ import { ICONS } from 'lib/integrations/utils'
import { IntegrationKind, IntegrationType } from '~/types'
+import type { InstallationStatusEnumApi } from '../../../../../products/integrations/frontend/generated/api.schemas'
import type { UserBasicType } from '../../../types'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -85,6 +86,8 @@ export interface organizationIntegrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -139,6 +142,8 @@ export interface organizationIntegrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'aws-s3'
diff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
index a4837dafb6a3..1b9fda64b541 100644
--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
@@ -35,6 +35,12 @@ const meta: Meta<StoryProps> = {
},
'/api/billing/': { products: [] },
'/api/projects/:id/integrations': { results: [] },
+ // The GitHub section fetches both on mount; unmocked, their error toasts land in the snapshot.
+ '/api/projects/:id/integrations/github/available_installations/': {
+ installations: [],
+ personal_github_connected: false,
+ },
+ '/api/users/@me/integrations/github/install_requests/': { results: [], install_url: null },
'/api/projects/:id/core_memory': { results: [] },
'/api/projects/:id/hog_functions': { results: [] },
'/api/projects/:id/pipeline_destination_configs': { results: [] },
diff --git a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
index fbef621c85ee..04b553ef369e 100644
--- a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
@@ -34,6 +34,12 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
realm: 'cloud',
},
'/api/projects/:id/integrations': { results: [] },
+ // The GitHub section fetches both on mount; unmocked, their error toasts land in the snapshot.
+ '/api/projects/:id/integrations/github/available_installations/': {
+ installations: [],
+ personal_github_connected: false,
+ },
+ '/api/users/@me/integrations/github/install_requests/': { results: [], install_url: null },
},
patch: {
'/api/projects/:id': async ({ request }) => {
diff --git a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
index 238c1d3684d7..bfa207ed2475 100644
--- a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
+++ b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
@@ -4,6 +4,9 @@ import { IconGithub, IconPlus, IconTrash } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { buildGithubDisconnectDescription } from 'lib/integrations/githubDisconnectCopy'
+import { GitHubInstallRequestsBanner } from 'lib/integrations/GitHubInstallRequestsBanner'
import { GitHubRepoSummary } from 'lib/integrations/GitHubRepoSummary'
import { userGithubIntegrationLogic } from 'lib/integrations/userGithubIntegrationLogic'
import { IconSlack } from 'lib/lemon-ui/icons'
@@ -23,8 +26,12 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
const accountType = integration.account?.type
const accountName = integration.account?.name
- const logic = installationId ? userGithubIntegrationLogic({ installationId }) : null
- const { repositories, repositoriesLoading } = useValues(logic ?? userGithubIntegrationLogic({ installationId: '' }))
+ const repositorySelection = integration.repository_selection
+ const logic = installationId ? userGithubIntegrationLogic({ installationId, repositorySelection }) : null
+ const { repositories, repositoriesLoading, repositoriesTotal } = useValues(
+ logic ?? userGithubIntegrationLogic({ installationId: '' })
+ )
+ const installationUnavailable = integration.installation_status === 'unavailable'
const handleDisconnect = (): void => {
LemonDialog.open({
@@ -36,8 +43,11 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
open pull requests on GitHub.
</LemonBanner>
<p>
- PostHog will no longer be able to access repos from this installation or act on your behalf
- there.
+ {buildGithubDisconnectDescription(
+ accountName || 'this account',
+ !!integration.installation_shared,
+ 'account'
+ )}
</p>
</>
),
@@ -83,8 +93,16 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
installationId={installationId}
accountType={accountType}
accountName={accountName}
+ repositorySelection={repositorySelection}
+ total={repositoriesTotal}
/>
</div>
+ {installationUnavailable ? (
+ <LemonBanner type="error" className="mt-2">
+ The PostHog app was removed from GitHub. Disconnect this installation, then connect again if you
+ still need it.
+ </LemonBanner>
+ ) : null}
</div>
<div className="flex shrink-0 items-center">
<LemonButton
@@ -162,9 +180,16 @@ function SlackLinkRow({ integration }: { integration: PersonalSlackIntegration }
export function PersonalGitHubIntegrations(): JSX.Element {
const { integrations, integrationsLoading, githubConnecting } = useValues(personalIntegrationsLogic)
- const { connectGitHub } = useActions(personalIntegrationsLogic)
+ const { connectGitHub, startPolling, stopPolling } = useActions(personalIntegrationsLogic)
const { reportPersonalIntegrationConnectClicked } = useActions(eventUsageLogic)
+ // Refresh the personal rows while this section stays mounted, so an App removed on GitHub shows
+ // its unavailable notice without a manual reload.
+ useOnMountEffect(() => {
+ startPolling()
+ return () => stopPolling()
+ })
+
if (integrationsLoading && integrations.length === 0) {
return (
<div className="deprecated-space-y-2">
@@ -174,39 +199,48 @@ export function PersonalGitHubIntegrations(): JSX.Element {
}
return (
- <div className="divide-y rounded border bg-surface-primary">
- {integrations.length === 0 ? (
- <div className="px-4 py-6 text-center text-sm text-secondary">
- <IconGithub className="text-3xl mb-2 opacity-40" />
- <p className="mb-1">No GitHub installations connected yet</p>
- <p className="text-xs text-muted text-balance">
- Connect to let PostHog access your repos, attribute commits, open pull requests, and assign
- issues as you. You can add multiple installations for different accounts or organizations.
- </p>
+ <div className="flex flex-col gap-2">
+ <GitHubInstallRequestsBanner
+ onFinishConnecting={() => {
+ reportPersonalIntegrationConnectClicked('github')
+ connectGitHub()
+ }}
+ />
+ <div className="divide-y rounded border bg-surface-primary">
+ {integrations.length === 0 ? (
+ <div className="px-4 py-6 text-center text-sm text-secondary">
+ <IconGithub className="text-3xl mb-2 opacity-40" />
+ <p className="mb-1">No GitHub installations connected yet</p>
+ <p className="text-xs text-muted text-balance">
+ Connect to let PostHog access your repos, attribute commits, open pull requests, and assign
+ issues as you. You can add multiple installations for different accounts or organizations.
+ </p>
+ </div>
+ ) : (
+ integrations.map((integration: PersonalGitHubIntegration) => (
+ <GitHubInstallationRow key={integration.installation_id} integration={integration} />
+ ))
+ )}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={() => {
+ reportPersonalIntegrationConnectClicked('github')
+ connectGitHub()
+ }}
+ loading={githubConnecting}
+ disabledReason={githubConnecting ? 'Starting GitHub installation…' : undefined}
+ >
+ {integrations.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
+ between <strong>All repositories</strong> and <strong>Only select repositories</strong> to
+ proceed.
+ </span>
</div>
- ) : (
- integrations.map((integration: PersonalGitHubIntegration) => (
- <GitHubInstallationRow key={integration.installation_id} integration={integration} />
- ))
- )}
- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconPlus />}
- onClick={() => {
- reportPersonalIntegrationConnectClicked('github')
- connectGitHub()
- }}
- loading={githubConnecting}
- disabledReason={githubConnecting ? 'Starting GitHub installation…' : undefined}
- >
- {integrations.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 between{' '}
- <strong>All repositories</strong> and <strong>Only select repositories</strong> to proceed.
- </span>
</div>
</div>
)
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts
new file mode 100644
index 000000000000..290ca913e42d
--- /dev/null
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.test.ts
@@ -0,0 +1,45 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { personalIntegrationsLogic } from './personalIntegrationsLogic'
+
+describe('personalIntegrationsLogic', () => {
+ let logic: ReturnType<typeof personalIntegrationsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/users/@me/integrations/': () => [200, { results: [] }],
+ '/api/users/@me/integrations/slack/linkable_workspaces/': () => [200, { results: [] }],
+ },
+ })
+ initKeaTests()
+ logic = personalIntegrationsLogic()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ logic.unmount()
+ })
+
+ it('refreshes on an interval only while a section is subscribed, and stops with the last one', async () => {
+ jest.useFakeTimers()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadIntegrationsSuccess'])
+
+ logic.actions.startPolling()
+ logic.actions.startPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(30_000)
+ }).toDispatchActions(['loadIntegrations'])
+
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(true)
+ logic.actions.stopPolling()
+ expect(logic.cache.disposables.registry.has('poll')).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index 7cc764d0bd3a..aa471521c887 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -5,6 +5,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
+import { githubInstallRequestsLogic } from 'lib/integrations/githubInstallRequestsLogic'
import { describeGithubLinkError } from 'lib/integrations/githubSetupErrors'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -17,6 +18,7 @@ import {
usersIntegrationsSlackLinkableWorkspacesRetrieve,
usersIntegrationsSlackStartCreate,
} from '~/generated/core/api'
+import type { UserGitHubIntegrationItemApi } from '~/generated/core/api.schemas'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType, UserBasicType } from '../../../types'
@@ -29,6 +31,10 @@ export interface PersonalGitHubIntegration {
/** The connected user's own GitHub login (distinct from `account`, which is the installation org/user). */
github_login: string | null
uses_shared_installation: boolean
+ /** When false, disconnecting also uninstalls the App from GitHub. */
+ installation_shared?: UserGitHubIntegrationItemApi['installation_shared']
+ /** `unavailable` once the App was removed or suspended on GitHub. */
+ installation_status?: UserGitHubIntegrationItemApi['installation_status']
created_at: string | null
}
@@ -64,6 +70,8 @@ const SLACK_LINK_ERROR_MESSAGES: Record<string, string> = {
}
const SLACK_LINK_ERROR_FALLBACK = 'Could not connect Slack. Please try again.'
+const PERSONAL_INTEGRATIONS_POLL_INTERVAL_MS = 30_000
+
/** Key for stashing the ``connect_from`` URL param across the GitHub install roundtrip.
*
* The install flow leaves posthog.com for github.com and comes back, which drops the query
@@ -100,6 +108,7 @@ export interface personalIntegrationsLogicValues {
integrationsLoading: boolean
linkableSlackWorkspaces: LinkableSlackWorkspace[]
linkableSlackWorkspacesLoading: boolean
+ pollingSubscribers: number
slackConnect: boolean
slackConnectLoading: boolean
slackIntegrations: PersonalSlackIntegration[]
@@ -119,6 +128,11 @@ export interface personalIntegrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -173,6 +187,11 @@ export interface personalIntegrationsLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -297,6 +316,12 @@ export interface personalIntegrationsLogicActions {
slackIntegrations: PersonalSlackIntegration[]
payload?: any
}
+ startPolling: () => {
+ value: true
+ }
+ stopPolling: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -329,6 +354,8 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
connectGitHubFailure: true,
disconnectGitHub: (installationId: string) => ({ installationId }),
disconnectSlack: (slackUserId: string) => ({ slackUserId }),
+ startPolling: true,
+ stopPolling: true,
}),
reducers({
@@ -341,6 +368,13 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
connectGitHubFailure: () => false,
},
],
+ pollingSubscribers: [
+ 0,
+ {
+ startPolling: (state) => state + 1,
+ stopPolling: (state) => Math.max(0, state - 1),
+ },
+ ],
}),
loaders(() => ({
@@ -429,7 +463,38 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
+ // Keep the personal GitHub rows current while the section is open, so an App removed on
+ // GitHub surfaces its "unavailable" notice without a manual reload. Mirrors the project-side
+ // refresh in integrationsLogic; only runs while a mounted surface has subscribed.
+ startPolling: () => {
+ if (cache.disposables.registry.has('poll')) {
+ return
+ }
+ cache.disposables.add(() => {
+ const pollTimer = window.setInterval(
+ () => actions.loadIntegrations(),
+ PERSONAL_INTEGRATIONS_POLL_INTERVAL_MS
+ )
+ return () => clearInterval(pollTimer)
+ }, 'poll')
+ cache.disposables.add(
+ () => {
+ const onFocus = (): void => actions.loadIntegrations()
+ window.addEventListener('focus', onFocus)
+ return () => window.removeEventListener('focus', onFocus)
+ },
+ 'focusRefetch',
+ { pauseOnPageHidden: false }
+ )
+ },
+ stopPolling: () => {
+ if (values.pollingSubscribers > 0) {
+ return
+ }
+ cache.disposables.dispose('poll')
+ cache.disposables.dispose('focusRefetch')
+ },
projectIntegrationsLoaded: () => {
// When a project-level integration is added/removed, the backend may
// auto-create a user-level integration. Reload to pick it up.
@@ -496,7 +561,14 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
lemonToast.success('GitHub connected.')
} else if (params.has('github_link_error')) {
writeConnectFromStorage(null)
- lemonToast.error(describeGithubLinkError(params.get('github_link_error')))
+ const linkError = params.get('github_link_error')
+ if (linkError === 'github_install_pending') {
+ // Not a failure: GitHub is waiting on an org owner. The install-requests banner carries the state.
+ lemonToast.info(describeGithubLinkError(linkError))
+ githubInstallRequestsLogic.findMounted()?.actions.loadInstallRequests()
+ } else {
+ lemonToast.error(describeGithubLinkError(linkError))
+ }
}
if (params.has('slack_link_success')) {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 6e8a6d53b088..69877fcd0140 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -86,6 +86,7 @@ import type {
SyncFrequencyBoundsApi,
} from 'products/data_warehouse/frontend/generated/api.schemas'
import type { ExperimentFeatureFlagInputApi } from 'products/experiments/frontend/generated/api.schemas'
+import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'
import type { CommentSlackThreadRefApi } from 'products/platform_features/frontend/generated/api.schemas'
import type { InsightFilterOverrideContextApi } from 'products/product_analytics/frontend/generated/api.schemas'
import type { AIPromptConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'
@@ -5596,6 +5597,10 @@ export interface IntegrationType {
created_by?: UserBasicType | null
created_at: string
errors?: string
+ /** GitHub only. When false, disconnecting also uninstalls the App from GitHub. */
+ installation_shared?: IntegrationConfigApi['installation_shared']
+ /** GitHub only. `unavailable` once the App was removed or suspended on GitHub. */
+ installation_status?: IntegrationConfigApi['installation_status']
}
export interface EmailIntegrationDomainGroupedType {
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.ts
index 046d20ac6b21..a1a422ba9055 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts
@@ -75,6 +75,11 @@ export interface alertNotificationLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -129,6 +134,11 @@ export interface alertNotificationLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
index ace5b24bb9d4..d74b7ff3b354 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
@@ -70,6 +70,11 @@ export interface logsAlertNotificationLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -124,6 +129,11 @@ export interface logsAlertNotificationLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 0e5fad12f590..b144123f590e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -123,6 +123,11 @@ export interface taskTrackerSceneLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -177,6 +182,11 @@ export interface taskTrackerSceneLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
index 8ecbc5daf2f9..4abbd065214c 100644
--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts
@@ -59,6 +59,11 @@ export interface visualReviewSettingsSceneLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'
@@ -113,6 +118,11 @@ export interface visualReviewSettingsSceneLogicActions {
errors?: string | undefined
icon_url: any
id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
kind:
| 'apns'
| 'aws-s3'