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(signals): share live repository access checks in inbox (#123896)

Georgiy Tarasovd82421952455
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 93704324ae42..1394e9ccc3b8 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -227,6 +227,10 @@ A saved repository is reused before checking GitHub availability. A data-only fa
The report remains readable and supports discussion, assignment, resolution, and eligible monitoring. Pull request creation requires usable repository access. The access check probes GitHub directly, preserving temporary failures for retry instead of treating a stale repository list as a permission decision. Any installation that confirms access enables the action without waiting for other installations. Connecting or repairing GitHub does not enable automatic implementation; the user must opt in separately. Previous blocked reports are not automatically rerun.
+Report access checks share pending and recent results by project, installation, and repository for up to 30 seconds. Explicit retries invalidate the project cache. A pending request is canceled when its last report reader leaves or after 30 seconds, allowing stalled checks to be retried; temporary failures are not cached. The backend still checks live access before creating an implementation task.
+
+Client-side access controls apply only after the server confirms pilot eligibility. Unknown eligibility, including a pending or failed onboarding request, leaves the existing implementation action available; the backend remains responsible for checking repository access.
+
Disable the flag to remove pilot activation and restore legacy behavior on subsequent research passes. Running passes finish with their recorded decision. Reports and saved source/scout settings remain intact; fleet dispatch still applies its ordinary enrollment and exclusion gates.
Without a repository, legacy ownership lookup is skipped. Existing human assignments remain intact.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7d8a5c6b763c..0c4d87209310 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -223,6 +223,7 @@ export const FEATURE_FLAGS = {
SCOUTS_MODEL_CONFIG: 'scouts-model-config', // owner: #team-self-driving, gates the per-scout model pin in the inbox scout settings (also checked server-side)
SCOUTS_TOOL_ACCESS: 'scouts-tool-access', // owner: #team-self-driving, gates the per-scout MCP tool list in the inbox scout settings (also checked server-side)
SELF_DRIVING_FREE_TRIAL: 'self-driving-free-trial', // owner: #team-self-driving, the org is on a Self-driving free trial: reports only, no pull requests (also checked server-side)
+ SELF_DRIVING_GITHUB_OPTIONAL: 'self-driving-github-optional',
SELF_DRIVING_QUOTA_ENFORCEMENT: 'self-driving-quota-enforcement', // owner: #team-self-driving, gates self-driving PR-limit enforcement (also checked server-side)
SELF_DRIVING_UBP: 'self-driving-ubp', // owner: #team-self-driving
SESSION_REPLAY_BACKEND_LOGS: 'session-replay-backend-logs', // owner: #team-replay
diff --git a/products/signals/backend/test/test_github_optional.py b/products/signals/backend/test/test_github_optional.py
index 7833825d66bf..bb6eae2b8581 100644
--- a/products/signals/backend/test/test_github_optional.py
+++ b/products/signals/backend/test/test_github_optional.py
@@ -4,11 +4,17 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from parameterized import parameterized
+from requests import Timeout
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models import Team
-from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration
-from products.signals.backend.github_optional import GITHUB_OPTIONAL_FLAG, ResearchAccessPolicy
+from products.signals.backend.github_optional import (
+ GITHUB_OPTIONAL_FLAG,
+ RepositoryAccessTemporarilyUnavailable,
+ ResearchAccessPolicy,
+)
from products.signals.backend.models import SignalTeamConfig
from products.signals.backend.scout_harness.team_limits import _parse_enrollment, _resolve_enrolled
from products.signals.backend.temporal.agentic.scout_coordinator import _participating_teams
@@ -65,3 +71,31 @@ class TestResearchAccessPolicy(BaseTest):
assert (self.team.id in {team.id for team, _ in _participating_teams(enrollment)}) is expected
with patch("posthoganalytics.default_client", None):
assert ResearchAccessPolicy.enrolled_team_ids() == set()
+
+ @parameterized.expand(
+ [
+ (Timeout(), False, True),
+ (GitHubRateLimitError("Rate limited", retry_after=30), False, True),
+ (GitHubIntegrationError("Unavailable", status_code=503), False, True),
+ (GitHubIntegrationError("Forbidden", status_code=403), False, False),
+ (Timeout(), True, False),
+ ]
+ )
+ def test_repository_access_preserves_transient_failures_after_trying_other_installations(
+ self, error: Exception, other_available: bool, retryable: bool
+ ) -> None:
+ Integration.objects.create(team=self.team, kind="github", integration_id="first")
+ second = Integration.objects.create(team=self.team, kind="github", integration_id="second")
+ with patch.object(
+ GitHubIntegration, "installation_can_access_repository", side_effect=[error, other_available]
+ ):
+ if retryable:
+ with self.assertRaises(RepositoryAccessTemporarilyUnavailable) as raised:
+ ResearchAccessPolicy.repository_integration_id(self.team.id, "example/product")
+ assert raised.exception.status_code == 503
+ if isinstance(error, GitHubRateLimitError):
+ assert raised.exception.wait == 30
+ else:
+ assert ResearchAccessPolicy.repository_integration_id(self.team.id, "example/product") == (
+ second.id if other_available else None
+ )
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 38319d3adc86..2dd06f7dbe9c 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -176,6 +176,7 @@ export type InboxReportActionType =
| 'resume_discussion'
| 'restore'
| 'create_pr'
+ | 'github_access_recovery'
| 'copy_implementation_prompt'
| 'refund'
| 'open_pr'
diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts
index c45f6ac88234..1d31bb7947a5 100644
--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts
+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts
@@ -46,6 +46,7 @@ import {
} from 'products/tasks/frontend/generated/api.schemas'
import { InboxReportActionType, captureInboxReportActionCompleted } from './inboxAnalytics'
+import { reportGithubAccessLogic } from './logics/reportGithubAccessLogic'
import {
SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,
SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,
@@ -968,13 +969,19 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([
}
},
createPrFromReport: async ({ report, feedback }) => {
- if (values.createPrDisabledReason) {
- lemonToast.error(values.createPrDisabledReason)
+ const disabledReason =
+ values.createPrDisabledReason ??
+ (
+ reportGithubAccessLogic.findMounted({ report, surface: 'triage_mode' }) ??
+ reportGithubAccessLogic.findMounted({ report })
+ )?.values.disabledReason
+ if (disabledReason) {
+ lemonToast.error(disabledReason)
captureInboxReportActionCompleted({
report,
actionType: 'create_pr',
outcome: 'blocked',
- blockedReason: values.createPrDisabledReason,
+ blockedReason: disabledReason,
})
actions.createPrFailure()
return
diff --git a/products/signals/frontend/inbox/logics/GithubAccessProbes.test.ts b/products/signals/frontend/inbox/logics/GithubAccessProbes.test.ts
new file mode 100644
index 000000000000..25249857538f
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/GithubAccessProbes.test.ts
@@ -0,0 +1,79 @@
+import { integrationsGithubRepositoryAccessRetrieve } from 'products/integrations/frontend/generated/api'
+
+import { GithubAccessProbes } from './GithubAccessProbes'
+
+jest.mock('products/integrations/frontend/generated/api', () => ({
+ integrationsGithubRepositoryAccessRetrieve: jest.fn(),
+}))
+
+describe('GithubAccessProbes', () => {
+ const request = jest.mocked(integrationsGithubRepositoryAccessRetrieve)
+
+ beforeEach(() => request.mockReset())
+ afterEach(() => {
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
+
+ it('shares recent checks while keeping projects, installations, and repositories separate', async () => {
+ request.mockResolvedValue({ available: true })
+ const now = jest.spyOn(Date, 'now').mockReturnValue(100_000)
+ const probes = new GithubAccessProbes()
+ const first = probes.acquire('1', 1, 'example/app')
+ const second = probes.acquire('1', 1, 'example/app')
+ expect(await Promise.all([first.promise, second.promise])).toEqual([true, true])
+ first.release()
+ second.release()
+ expect(await probes.acquire('1', 1, 'example/app').promise).toBe(true)
+ expect(request).toHaveBeenCalledTimes(1)
+ for (const [project, integration, repository] of [
+ ['2', 1, 'example/app'],
+ ['1', 2, 'example/app'],
+ ['1', 1, 'example/other'],
+ ] as const) {
+ await probes.acquire(project, integration, repository).promise
+ }
+ expect(request).toHaveBeenCalledTimes(4)
+ now.mockReturnValue(130_001)
+ await probes.acquire('1', 1, 'example/app').promise
+ expect(request).toHaveBeenCalledTimes(5)
+ probes.invalidate('1')
+ await probes.acquire('1', 1, 'example/app').promise
+ expect(request).toHaveBeenCalledTimes(6)
+ })
+
+ it.each(['last reader leaves', 'deadline expires'])('cancels a pending request when its %s', async (cause) => {
+ jest.useFakeTimers()
+ request.mockImplementation(
+ (_project, _integration, _params, options) =>
+ new Promise((_resolve, reject) => {
+ options?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')))
+ })
+ )
+ const probes = new GithubAccessProbes()
+ const first = probes.acquire('1', 1, 'example/app')
+ const second = probes.acquire('1', 1, 'example/app')
+ const signal = request.mock.calls[0][3]!.signal!
+ first.release()
+ expect(signal.aborted).toBe(false)
+ if (cause === 'deadline expires') {
+ jest.advanceTimersByTime(30_000)
+ } else {
+ second.release()
+ }
+ expect(signal.aborted).toBe(true)
+ await expect(second.promise).rejects.toMatchObject({ name: 'AbortError' })
+ second.release()
+ request.mockResolvedValue({ available: true })
+ expect(await probes.acquire('1', 1, 'example/app').promise).toBe(true)
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(jest.getTimerCount()).toBe(0)
+ })
+
+ it('rechecks failed probes instead of caching a temporary error', async () => {
+ request.mockRejectedValueOnce(new Error('Unavailable')).mockResolvedValue({ available: false })
+ const probes = new GithubAccessProbes()
+ await expect(probes.acquire('1', 1).promise).rejects.toThrow('Unavailable')
+ expect(await probes.acquire('1', 1).promise).toBe(false)
+ })
+})
diff --git a/products/signals/frontend/inbox/logics/GithubAccessProbes.ts b/products/signals/frontend/inbox/logics/GithubAccessProbes.ts
new file mode 100644
index 000000000000..a089379c83be
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/GithubAccessProbes.ts
@@ -0,0 +1,96 @@
+import { getContext } from 'kea'
+
+import { integrationsGithubRepositoryAccessRetrieve } from 'products/integrations/frontend/generated/api'
+
+interface Probe {
+ promise: Promise<boolean>
+ controller: AbortController
+ readers: number
+ expiresAt: number
+}
+
+export interface GithubAccessProbe {
+ promise: Promise<boolean>
+ release: () => void
+}
+
+export class GithubAccessProbes {
+ private static contexts = new WeakMap<object, GithubAccessProbes>()
+ private probes = new Map<string, Probe>()
+
+ static forContext(): GithubAccessProbes {
+ const context = getContext()
+ let probes = this.contexts.get(context)
+ if (!probes) {
+ probes = new GithubAccessProbes()
+ this.contexts.set(context, probes)
+ }
+ return probes
+ }
+
+ invalidate(projectId: string): void {
+ for (const key of this.probes.keys()) {
+ if (key.startsWith(`${projectId}/`)) {
+ this.probes.delete(key)
+ }
+ }
+ }
+
+ acquire(projectId: string, integrationId: number, repository?: string): GithubAccessProbe {
+ for (const [key, probe] of this.probes) {
+ if (probe.expiresAt <= Date.now()) {
+ this.probes.delete(key)
+ }
+ }
+ const key = `${projectId}/${integrationId}/${repository ?? ''}`
+ let probe = this.probes.get(key)
+ if (!probe) {
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), 30_000)
+ probe = {
+ controller,
+ readers: 0,
+ expiresAt: Infinity,
+ promise: integrationsGithubRepositoryAccessRetrieve(
+ projectId,
+ integrationId,
+ repository ? { repository } : undefined,
+ { signal: controller.signal }
+ )
+ .then(({ available }) => available)
+ .finally(() => clearTimeout(timeout)),
+ }
+ const pending = probe
+ void pending.promise.then(
+ () => {
+ pending.expiresAt = Date.now() + 30_000
+ },
+ () => {
+ if (this.probes.get(key) === pending) {
+ this.probes.delete(key)
+ }
+ }
+ )
+ this.probes.set(key, probe)
+ }
+ const acquired = probe
+ acquired.readers++
+ let released = false
+ return {
+ promise: acquired.promise,
+ release: () => {
+ if (released) {
+ return
+ }
+ released = true
+ acquired.readers--
+ if (acquired.readers === 0 && acquired.expiresAt === Infinity) {
+ acquired.controller.abort()
+ if (this.probes.get(key) === acquired) {
+ this.probes.delete(key)
+ }
+ }
+ },
+ }
+ }
+}
diff --git a/products/signals/frontend/inbox/logics/reportGithubAccessLogic.test.ts b/products/signals/frontend/inbox/logics/reportGithubAccessLogic.test.ts
new file mode 100644
index 000000000000..9cbcf62f95a7
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/reportGithubAccessLogic.test.ts
@@ -0,0 +1,192 @@
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { makeReport } from '../__mocks__/inboxMocks'
+import { reportGithubAccessLogic } from './reportGithubAccessLogic'
+
+describe('reportGithubAccessLogic', () => {
+ let logic: ReturnType<typeof reportGithubAccessLogic.build>
+ let integrationStatus: number
+ let repositoryStatus: number
+ let repositories: string[]
+ let githubOptional: boolean
+ let setupStatus: number
+
+ beforeEach(() => {
+ localStorage.clear()
+ integrationStatus = 200
+ repositoryStatus = 200
+ repositories = ['example/app']
+ githubOptional = true
+ setupStatus = 200
+ useMocks({
+ get: {
+ '/api/projects/:project/signals/scout/configs/': [],
+ '/api/projects/:project/signals/onboarding/': () => [
+ setupStatus,
+ {
+ draft: null,
+ completed_at: null,
+ github_optional_available: githubOptional,
+ },
+ ],
+ '/api/projects/:project/integrations/': () => [
+ integrationStatus,
+ { results: [{ id: 1, kind: 'github', installation_status: 'connected' }], next: null },
+ ],
+ '/api/projects/:project/integrations/1/github_repository_access/': () => [
+ repositoryStatus,
+ { available: repositories.includes('example/app') },
+ ],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ })
+
+ afterEach(() => logic?.unmount())
+
+ it.each([
+ ['accessible', ['example/app'], 200, 200, null, true, 200],
+ ['empty installation', [], 200, 200, 'repair', true, 200],
+ ['different repository', ['example/other'], 200, 200, 'repair', true, 200],
+ ['repository request failed', [], 200, 503, 'retry', true, 200],
+ ['integration request failed', [], 503, 200, 'retry', true, 200],
+ ['pilot eligibility request failed', [], 200, 200, null, true, 503],
+ ['non-pilot eligibility request failed', [], 200, 200, null, false, 503],
+ ['pilot disabled', [], 200, 200, null, false, 200],
+ ] as const)(
+ 'handles %s without confusing failed checks with missing access',
+ async (_, repos, integrationCode, repositoryCode, expected, pilot, setupCode) => {
+ const capture = jest.spyOn(posthog, 'capture')
+ repositories = [...repos]
+ integrationStatus = integrationCode
+ repositoryStatus = repositoryCode
+ githubOptional = pilot
+ setupStatus = setupCode
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SELF_DRIVING_GITHUB_OPTIONAL], {
+ [FEATURE_FLAGS.SELF_DRIVING_GITHUB_OPTIONAL]: !pilot,
+ })
+ logic = reportGithubAccessLogic({ report: makeReport({ id: 'github-access', repo_slug: 'example/app' }) })
+ logic.mount()
+ await waitFor(() => expect(logic.values.loading).toBe(false))
+ expect(logic.values.repairNeeded).toBe(expected === 'repair')
+ expect(logic.values.failed).toBe(expected === 'retry')
+ if (expected === null) {
+ expect(logic.values.disabledReason).toBeNull()
+ }
+ if (expected === 'retry') {
+ integrationStatus = 200
+ repositoryStatus = 200
+ repositories = ['example/app']
+ setupStatus = 200
+ logic.actions.retryAccess()
+ await waitFor(() => expect(logic.values.disabledReason).toBeNull())
+ expect(capture).toHaveBeenCalledWith(
+ 'Inbox report action',
+ expect.objectContaining({ report_id: 'github-access', surface: 'detail_pane', stage: 'retry' }),
+ undefined
+ )
+ expect(capture).toHaveBeenCalledWith(
+ 'Inbox report action',
+ expect.objectContaining({ outcome: 'available' }),
+ undefined
+ )
+ }
+ }
+ )
+
+ it.each([true, false])(
+ 'does not gate implementation before eligibility is known (team loaded: %s)',
+ async (teamLoaded) => {
+ let finish!: () => void
+ const pending = new Promise<void>((resolve) => (finish = resolve))
+ useMocks({
+ get: {
+ '/api/projects/:project/signals/onboarding/': async () => {
+ await pending
+ return { draft: null, completed_at: null, github_optional_available: false }
+ },
+ },
+ })
+ if (!teamLoaded) {
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ }
+ logic = reportGithubAccessLogic({ report: makeReport() })
+ logic.mount()
+ try {
+ await waitFor(() => expect(logic.values.integrationsLoading).toBe(false))
+ expect(logic.values.savedStateLoading).toBe(teamLoaded)
+ expect(logic.values.failed).toBe(false)
+ expect(logic.values.repairNeeded).toBe(false)
+ expect(logic.values.disabledReason).toBeNull()
+ } finally {
+ finish()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ }
+ )
+
+ it('enables implementation before an unrelated installation finishes checking', async () => {
+ let finishSlowCheck!: () => void
+ const slowCheck = new Promise<void>((resolve) => (finishSlowCheck = resolve))
+ useMocks({
+ get: {
+ '/api/projects/:project/integrations/': {
+ results: [1, 2].map((id) => ({ id, kind: 'github', installation_status: 'connected' })),
+ next: null,
+ },
+ '/api/projects/:project/integrations/1/github_repository_access/': async () => {
+ await slowCheck
+ return [503, {}]
+ },
+ '/api/projects/:project/integrations/2/github_repository_access/': { available: true },
+ },
+ })
+ logic = reportGithubAccessLogic({ report: makeReport({ id: 'github-access', repo_slug: 'example/app' }) })
+ logic.mount()
+ try {
+ await waitFor(() => expect(logic.values.access).toBe('available'))
+ expect(logic.values.disabledReason).toBeNull()
+ expect(logic.values.loading).toBe(false)
+ } finally {
+ finishSlowCheck()
+ }
+ })
+
+ it.each([200, 503])('ignores a superseded probe result (status %i)', async (status) => {
+ let finish!: () => void
+ let started!: () => void
+ const pending = new Promise<void>((resolve) => (finish = resolve))
+ const requested = new Promise<void>((resolve) => (started = resolve))
+ useMocks({
+ get: {
+ '/api/projects/:project/integrations/1/github_repository_access/': async () => {
+ started()
+ await pending
+ return [status, { available: true }]
+ },
+ },
+ })
+ logic = reportGithubAccessLogic({ report: makeReport({ id: 'changing-access', repo_slug: 'example/app' }) })
+ logic.mount()
+ await requested
+ integrationsLogic.actions.loadIntegrationsSuccess([])
+ await waitFor(() => expect(logic.values.access).toBe('unavailable'))
+ finish()
+ await expectLogic(logic).toFinishListeners()
+ await waitFor(() => expect(logic.values.accessLoading).toBe(false))
+ expect(logic.values.access).toBe('unavailable')
+ expect(logic.values.failed).toBe(false)
+ })
+})
diff --git a/products/signals/frontend/inbox/logics/reportGithubAccessLogic.ts b/products/signals/frontend/inbox/logics/reportGithubAccessLogic.ts
new file mode 100644
index 000000000000..0627a5333c8b
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/reportGithubAccessLogic.ts
@@ -0,0 +1,301 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+
+import type { IntegrationType } from '~/types'
+
+import type { InboxOnboardingStateApi } from '../../generated/api.schemas'
+import { captureInboxReportAction } from '../inboxAnalytics'
+import { SignalReport } from '../types'
+import { GithubAccessProbes } from './GithubAccessProbes'
+import { inboxSetupLogic } from './inboxSetupLogic'
+
+export interface ReportGithubAccessLogicProps {
+ report: SignalReport | null
+ surface?: 'detail_pane' | 'triage_mode'
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportGithubAccessLogicValues {
+ isGithubOptionalSetup: boolean // inboxSetupLogic
+ savedState: InboxOnboardingStateApi | null // inboxSetupLogic
+ savedStateLoading: boolean // inboxSetupLogic
+ currentProjectId: number | string // integrationsLogic
+ githubIntegrations: IntegrationType[] // integrationsLogic
+ integrations: IntegrationType[] | null // integrationsLogic
+ integrationsLoading: boolean // integrationsLogic
+ access: 'available' | 'unavailable' | null
+ accessFailed: boolean
+ accessLoading: boolean
+ connectionOpen: boolean
+ disabledReason: string | null
+ failed: boolean
+ loading: boolean
+ pilot: boolean
+ repairNeeded: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportGithubAccessLogicActions {
+ loadSetup: () => any // inboxSetupLogic
+ loadSetupFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // inboxSetupLogic
+ loadSetupSuccess: (
+ savedState: InboxOnboardingStateApi,
+ payload?: any
+ ) => {
+ payload?: any
+ savedState: InboxOnboardingStateApi
+ } // inboxSetupLogic
+ loadIntegrations: (_?: any) => any // integrationsLogic
+ loadIntegrationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // integrationsLogic
+ loadIntegrationsSuccess: (
+ integrations: IntegrationType[],
+ payload?: any
+ ) => {
+ integrations: IntegrationType[]
+ payload?: any
+ } // integrationsLogic
+ checkAccess: (_: void) => void
+ checkAccessFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ checkAccessSuccess: (
+ access: 'available' | 'unavailable' | null,
+ payload?: void
+ ) => {
+ access: 'available' | 'unavailable' | null
+ payload?: void
+ }
+ retryAccess: () => {
+ value: true
+ }
+ setConnectionOpen: (open: boolean) => {
+ open: boolean
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportGithubAccessLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ pilot: (isGithubOptionalSetup: boolean) => boolean
+ loading: (integrationsLoading: boolean, accessLoading: boolean, savedStateLoading: boolean) => boolean
+ failed: (
+ pilot: boolean,
+ accessFailed: boolean,
+ integrations: IntegrationType[] | null,
+ loading: boolean
+ ) => boolean
+ repairNeeded: (
+ pilot: boolean,
+ access: 'available' | 'unavailable' | null,
+ loading: boolean,
+ failed: boolean
+ ) => boolean
+ disabledReason: (
+ pilot: boolean,
+ access: 'available' | 'unavailable' | null,
+ loading: boolean,
+ failed: boolean
+ ) => string | null
+ }
+}
+
+export type reportGithubAccessLogicType = MakeLogicType<
+ reportGithubAccessLogicValues,
+ reportGithubAccessLogicActions,
+ ReportGithubAccessLogicProps,
+ reportGithubAccessLogicMeta
+>
+
+export const reportGithubAccessLogic = kea<reportGithubAccessLogicType>([
+ props({} as ReportGithubAccessLogicProps),
+ key(({ report, surface }) => `${report?.id ?? 'none'}:${report?.repo_slug ?? ''}:${surface ?? 'detail_pane'}`),
+ path((key) => ['products', 'signals', 'inbox', 'logics', 'reportGithubAccessLogic', key]),
+ connect({
+ values: [
+ integrationsLogic,
+ ['integrations', 'integrationsLoading', 'githubIntegrations', 'currentProjectId'],
+ inboxSetupLogic,
+ ['isGithubOptionalSetup', 'savedState', 'savedStateLoading'],
+ ],
+ actions: [
+ integrationsLogic,
+ ['loadIntegrations', 'loadIntegrationsSuccess', 'loadIntegrationsFailure'],
+ inboxSetupLogic,
+ ['loadSetup', 'loadSetupSuccess', 'loadSetupFailure'],
+ ],
+ }),
+ actions({ retryAccess: true, setConnectionOpen: (open: boolean) => ({ open }) }),
+ reducers({
+ connectionOpen: [false, { setConnectionOpen: (_, { open }) => open }],
+ accessFailed: [
+ false,
+ {
+ checkAccessSuccess: () => false,
+ checkAccessFailure: () => true,
+ loadIntegrationsFailure: () => true,
+ },
+ ],
+ }),
+ loaders(({ values, props, cache }) => ({
+ access: [
+ null as 'available' | 'unavailable' | null,
+ {
+ checkAccess: async (_: void, breakpoint): Promise<'available' | 'unavailable' | null> => {
+ if (
+ !values.pilot ||
+ !props.report ||
+ values.integrations === null ||
+ values.currentProjectId === null
+ ) {
+ return null
+ }
+ const repository = props.report.repo_slug?.toLowerCase()
+ const unavailable = Symbol('unavailable')
+ const probes = values.githubIntegrations
+ .filter((integration) => integration.installation_status !== 'unavailable')
+ .map((integration) =>
+ GithubAccessProbes.forContext().acquire(
+ String(values.currentProjectId),
+ integration.id,
+ repository
+ )
+ )
+ const release = (): void => probes.forEach((probe) => probe.release())
+ const disposables = cache.disposables
+ const disposableKey = `github-access-${(cache.probeSequence = (cache.probeSequence ?? 0) + 1)}`
+ disposables.add(() => release, disposableKey, { pauseOnPageHidden: false })
+ try {
+ await Promise.any(
+ probes.map(async (probe): Promise<void> => {
+ if (!(await probe.promise)) {
+ throw unavailable
+ }
+ })
+ )
+ await breakpoint()
+ return 'available'
+ } catch (error) {
+ await breakpoint()
+ if (disposables.isDisposed) {
+ return null
+ }
+ if (!(error instanceof AggregateError)) {
+ throw error
+ }
+ const failure = error.errors.find((reason) => reason !== unavailable)
+ if (failure) {
+ throw failure
+ }
+ return 'unavailable'
+ } finally {
+ disposables.dispose(disposableKey)
+ }
+ },
+ },
+ ],
+ })),
+ selectors({
+ pilot: [(s) => [s.isGithubOptionalSetup], (available: boolean): boolean => available],
+ loading: [
+ (s) => [s.integrationsLoading, s.accessLoading, s.savedStateLoading],
+ (integrationsLoading: boolean, accessLoading: boolean, setupLoading: boolean): boolean =>
+ integrationsLoading || accessLoading || setupLoading,
+ ],
+ failed: [
+ (s) => [s.pilot, s.accessFailed, s.integrations, s.loading],
+ (pilot: boolean, failed: boolean, integrations: IntegrationType[] | null, loading: boolean): boolean =>
+ pilot && (failed || (integrations === null && !loading)),
+ ],
+ repairNeeded: [
+ (s) => [s.pilot, s.access, s.loading, s.failed],
+ (pilot: boolean, access: 'available' | 'unavailable' | null, loading: boolean, failed: boolean): boolean =>
+ pilot && access === 'unavailable' && !loading && !failed,
+ ],
+ disabledReason: [
+ (s) => [s.pilot, s.access, s.loading, s.failed],
+ (
+ pilot: boolean,
+ access: 'available' | 'unavailable' | null,
+ loading: boolean,
+ failed: boolean
+ ): string | null =>
+ !pilot
+ ? null
+ : failed
+ ? "Couldn't check GitHub access. Try again."
+ : loading || access === null
+ ? 'Checking GitHub access'
+ : access === 'unavailable'
+ ? 'Connect or repair GitHub access to create a pull request'
+ : null,
+ ],
+ }),
+ listeners(({ actions, values, props }) => {
+ const track = (stage: string, outcome?: string): void => {
+ if (!props.report) {
+ return
+ }
+ captureInboxReportAction({
+ report: props.report,
+ actionType: 'github_access_recovery',
+ surface: props.surface ?? 'detail_pane',
+ extra: { stage, outcome },
+ })
+ }
+ return {
+ loadIntegrationsSuccess: () => actions.checkAccess(),
+ loadSetupSuccess: () => actions.checkAccess(),
+ loadSetupFailure: () => track('check', 'failed'),
+ loadIntegrationsFailure: () => {
+ if (values.pilot) {
+ track('check', 'failed')
+ }
+ },
+ checkAccessFailure: () => track('check', 'failed'),
+ checkAccessSuccess: ({ access }) => {
+ if (access) {
+ track('check', access)
+ }
+ if (access === 'available') {
+ actions.setConnectionOpen(false)
+ }
+ },
+ setConnectionOpen: ({ open }) => {
+ if (open) {
+ track('connect')
+ }
+ },
+ retryAccess: () => {
+ if (values.loading) {
+ return
+ }
+ track('retry')
+ GithubAccessProbes.forContext().invalidate(String(values.currentProjectId))
+ if (values.savedState === null) {
+ actions.loadSetup()
+ }
+ actions.loadIntegrations()
+ },
+ }
+ }),
+ afterMount(({ actions }) => actions.checkAccess()),
+])
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index cedc0b6a26b1..b23f3b6cff5a 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -96,6 +96,7 @@ export const ACTIONABLE_ACTIONABILITY_VALUES: SignalReportActionability[] = [
export interface SignalReport extends Pick<SignalReportApi, 'monitoring_started_at'> {
startup_failure?: SignalReportApi['startup_failure']
+ research_context?: SignalReportApi['research_context']
repo_slug?: SignalReportApi['repo_slug']
pull_requests?: readonly SignalReportPullRequestApi[]
assignee?: SignalReportAssigneeApi | null