:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(stamphog): list added repositories with an add bar (#105353)
Julian Beza1ff7dc2276a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d5a453d08ffd..56fb41a65925 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11416,10 +11416,30 @@ snapshots:hash: v1.k794b7964.2ff771815c26e56d32f41eae88bb1c453a6fe50e273cb5095c1c3f9477dc590f.5A7_p3_Mbh5nL3T1e5olwqpfNMu6t4_-TKQ0j1ja1AYscenes-app-stamphog-digests--digests-list-empty--light:hash: v1.k794b7964.46c349724a92b59d4693ac9e9164bcff7c89c8d04ef967fee23ff5052457c63e.HqC03R4DRb_7TP-ljXEykmHv_DOCNYRAhZeNr5fSAoE+ scenes-app-stamphog-repositories--add-repository-picker-open--dark:+ hash: v1.k794b7964.7c70df7eb2aba8e63827f52ca587fba6245bdef4030d41d0ee4b356c111267e1.7PTfVCbXSGaxOy0S60kvBXR3ukQWRQ4uhqE387ODGwE+ scenes-app-stamphog-repositories--add-repository-picker-open--light:+ hash: v1.k794b7964.8d55815d8b741d0af2a63e9b7ee4c4105453c58ed407a72b7b0338ad6d41c95b.XC_XCin3PpNFO8rLkoDSPEuF14x3VbaIq2lJCG-TwKI+ scenes-app-stamphog-repositories--connected-after-sync--dark:+ hash: v1.k794b7964.eccb7a6a19ac75eb6f3ae74d108d7964bc7205030b254c844d1fe0adf121917d.uEEHiQpJWlzEpmOg3Vt2XOrdjb1wRVsISQfAjX9DM_Q+ scenes-app-stamphog-repositories--connected-after-sync--light:+ hash: v1.k794b7964.cfa31afd9dd7e1aaec6538da8851dc08ac7062a3a15f2565accf9596827d7777.VUvFzSZFUiRfsYmpHRAMqtgMC55xQ1f1NNA9Rgrk9EA+ scenes-app-stamphog-repositories--first-repository--dark:+ hash: v1.k794b7964.1975eded573d56013d5cdde0b008189e7339a4392eddfdcd9c8acf6ba49975c4.7b0dzklN_3prLtvf3A0nC7CkMjA26k2SyK4HmdDantA+ scenes-app-stamphog-repositories--first-repository--light:+ hash: v1.k794b7964.697a57ed8f474f15c42129d955b53b9de5f387577e4581dd3574879c079be10f.35765sT3uU8Cy6EUM1xBAhv9b_5EWT-xGvoyOqBdK_4+ scenes-app-stamphog-repositories--not-connected--dark:+ hash: v1.k794b7964.d66764ddcf73498bb22127281c32c30edc6cfa5206c5985ffe418afdfb460af6.tsu9ky_1CHhLrgpkUZRGDzp5nqI9KUrBTH1Zd0obpr8+ scenes-app-stamphog-repositories--not-connected--light:+ hash: v1.k794b7964.9c4dc3ba392a7ea7cb00133fc2e74398aa66703a3949ecf5d9524898d540f5b2.LFrpHsUlnxgGDD3VJp8h8DoVfwMUB7IbFa7FIjRh9VYscenes-app-stamphog-repositories--repositories-list--dark:- hash: v1.k794b7964.d3fef1c6e6cfe2236106ae143dca48f4532d29c1c5bfcd3d6c5995b2b7c917fc.TwE2zKzmtrveSPIxEAtz5ZpkWvOwZQ0qSKDWYbbSPRM+ hash: v1.k794b7964.05246c47bc288778b938b2f9379458e1cbc18214cdfcfca46bd647d7f910d93f.zYwEB_zyw7fXCT-6E--jWdhNWkqNWJ-TdEB90mgEERoscenes-app-stamphog-repositories--repositories-list--light:- hash: v1.k794b7964.69b3f8946be364d5f94d9ac4c0c05413edf014ea55069c181f924d30bbab458a.urlrVpziCX4AJeDE8XUxOBBD79YMKSsUOQnTd4CnD2o+ hash: v1.k794b7964.da354a1edb7c115d0c7f695ef58237970f3057d26e1aedb0db0dd3fda4511780.htoHBFn118PVvGOY4sN_3CzVB5jwVcvMTod2ttIKi1Q+ scenes-app-stamphog-repositories--repository-expanded--dark:+ hash: v1.k794b7964.f9e813ba71635974004268f9b7ccf89fa23cf4bc192653f0ac49ae9bdb22a55c.UYt1dmvJpiE0V3pvXdB37EkNNxGwr5h7Kkp0Q7GktLY+ scenes-app-stamphog-repositories--repository-expanded--light:+ hash: v1.k794b7964.07ea2b4e15d17ef6c449dfb3c93089c0bbb836033e6deb240cc66540cfebc2b8.Ex8TXB5UPcDZjQgwE4DljCUwwNwFnjY7eI2sSwByglEscenes-app-stamphog-runs--runs-list--dark:hash: v1.k794b7964.0f6fb2d21628b8c0f8781d21610ca6fd605216cb07cfeae30f9fc6189ca72d2b.GzyJek2YNFSPSBQoznkgE_FcldLmSLCiVa0gCaHUIxIscenes-app-stamphog-runs--runs-list--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c58f3b1de275..a20dc1d4ae35 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4790,6 +4790,12 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@testing-library/dom':+ specifier: '*'+ version: 10.4.0+ '@testing-library/user-event':+ specifier: '*'+ version: 14.6.1(@testing-library/[email protected])'@types/react':specifier: 18.3.27version: 18.3.27diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex c661a6644cc7..9ff45e709dfc 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -49,9 +49,9 @@ Every other rule still applies: drafts, closed PRs, bot-authored PRs, PRs from o1. Install the Stamphog GitHub App on your GitHub organization.2. Open Stamphog in the PostHog app and connect GitHub. The callback records the repositories you can reach with your own GitHub account. It adds none of them yet.-3. Add each repository you want reviewed (`POST repo_configs/add_repository`). Adding a repository turns its reviews on. The list of repositories you can add comes from `GET repo_configs/available_repositories`.-4. Pick a **review mode**: "All PRs" reviews every pull request, "Label-triggered" reviews only PRs carrying the trigger label. Set the trigger label name next to the mode.-5. Turn on **Digest enabled** if you want the daily Slack digest of merged PRs. The project needs a connected Slack integration first, or the digest run stops silently before posting.+3. Add each repository you want reviewed from the **Add a repository** search (`POST repo_configs/add_repository`). Adding a repository turns its reviews on. The search lists the repositories you can add, from `GET repo_configs/available_repositories`.+4. Expand the repository's row and pick a **review mode**: "All PRs" reviews every pull request, "Label-triggered" reviews only PRs carrying the trigger label. Set the trigger label name next to the mode.+5. Turn on **Include in the digest** if you want the daily Slack digest of merged PRs. The project needs a connected Slack integration first, or the digest run stops silently before posting.The repositories you can add are the ones a project member reached with their own GitHub account, not every repository the installation can reach.Each member who connects adds the repositories they can reach, and connecting again refreshes the list.diff --git a/products/stamphog/frontend/scenes/StamphogScene/AddRepositoryBar.tsx b/products/stamphog/frontend/scenes/StamphogScene/AddRepositoryBar.tsxnew file mode 100644index 000000000000..61c3de4808e2--- /dev/null+++ b/products/stamphog/frontend/scenes/StamphogScene/AddRepositoryBar.tsx@@ -0,0 +1,173 @@+import { useActions, useValues } from 'kea'++import { IconGithub, IconPlus, IconRefresh } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInputSelect, LemonSkeleton } from '@posthog/lemon-ui'++import { editorDisabledReason } from './repoAccess'+import { stamphogSceneLogic } from './stamphogSceneLogic'++function addPlaceholder(addableCount: number | null): string {+ if (addableCount === null) {+ return 'Search repositories to add'+ }+ if (addableCount === 0) {+ return 'No repositories left to add'+ }+ return addableCount === 1 ? 'Search 1 repository to add' : `Search ${addableCount} repositories to add`+}++function ConnectGitHubPrompt(): JSX.Element {+ const { openingInstallPage, connectDisabledReason } = useValues(stamphogSceneLogic)+ const { openInstallPage } = useActions(stamphogSceneLogic)+ return (+ <div className="flex flex-wrap items-center justify-between gap-4 border rounded bg-surface-primary p-4">+ <div className="flex flex-col gap-1 min-w-0 max-w-160">+ <h4 className="m-0">Connect GitHub to add repositories</h4>+ <p className="m-0 text-secondary">+ Install the Stamphog GitHub App on your organization. Then pick the repositories you want reviewed.+ </p>+ </div>+ <LemonButton+ type="primary"+ icon={<IconGithub />}+ onClick={openInstallPage}+ loading={openingInstallPage}+ disabledReason={connectDisabledReason}+ data-attr="stamphog-connect-repository"+ >+ Connect GitHub+ </LemonButton>+ </div>+ )+}++function MissingRepositoryHelp(): JSX.Element {+ const { openingInstallPage, refreshingFromGitHub, connectDisabledReason } = useValues(stamphogSceneLogic)+ const { openInstallPage, refreshFromGitHub } = useActions(stamphogSceneLogic)+ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className="text-secondary text-xs">+ Missing a repository? An admin of your GitHub organization can give Stamphog access to it.+ </span>+ <div className="flex flex-wrap items-center gap-1">+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconGithub />}+ onClick={openInstallPage}+ loading={openingInstallPage}+ disabledReason={connectDisabledReason}+ data-attr="stamphog-grant-repository-access"+ >+ Grant access on GitHub+ </LemonButton>+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconRefresh />}+ onClick={refreshFromGitHub}+ loading={refreshingFromGitHub}+ disabledReason={connectDisabledReason}+ tooltip="Checks GitHub again for the repositories you can reach"+ data-attr="stamphog-refresh-repositories"+ >+ Refresh the list+ </LemonButton>+ </div>+ </div>+ )+}++export function AddRepositoryBar(): JSX.Element {+ const {+ hasInstallation,+ availableRepositories,+ availableRepositoriesLoading,+ availableRepositoriesFailed,+ availableRepositoryOptions,+ addableCount,+ repositoryToAdd,+ addingRepository,+ stamphogAccessLevel,+ availableSearch,+ } = useValues(stamphogSceneLogic)+ const { setAvailableSearch, setRepositoryToAdd, addRepository, loadAvailableRepositories } =+ useActions(stamphogSceneLogic)++ if (availableRepositoriesFailed && hasInstallation === null) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => loadAvailableRepositories({ search: '' }) }}+ data-attr="stamphog-available-repositories-error"+ >+ Could not load the repositories you can add. This is usually temporary.+ </LemonBanner>+ )+ }+ if (hasInstallation === null) {+ return <LemonSkeleton className="h-24" />+ }+ if (!hasInstallation) {+ return <ConnectGitHubPrompt />+ }++ const shownCount = availableRepositories?.repositories.length ?? 0+ const matchCount = availableRepositories?.total_count ?? 0+ const accessReason = editorDisabledReason(stamphogAccessLevel)++ return (+ <div className="flex flex-col gap-2 border rounded bg-surface-primary p-3">+ <h4 className="m-0">Add a repository</h4>+ {availableRepositoriesFailed && (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: () => loadAvailableRepositories({ search: availableSearch }),+ }}+ data-attr="stamphog-available-repositories-search-error"+ >+ Could not load the repositories you can add. Try again.+ </LemonBanner>+ )}+ <div className="flex flex-wrap items-center gap-2">+ <LemonInputSelect+ mode="single"+ className="flex-1 min-w-60"+ placeholder={addPlaceholder(addableCount)}+ options={availableRepositoryOptions}+ value={repositoryToAdd ? [repositoryToAdd] : []}+ onChange={(values) => setRepositoryToAdd(values[0] ?? null)}+ onInputChange={setAvailableSearch}+ // The server already filtered by the search, so the picker shows its answer as is.+ disableFiltering+ loading={availableRepositoriesLoading}+ title={+ matchCount > shownCount+ ? `Showing ${shownCount} of ${matchCount}. Type to narrow the list.`+ : undefined+ }+ emptyStateComponent={+ <p className="text-secondary italic p-1 m-0">+ {addableCount === 0 ? 'No repositories left to add.' : 'No repository matches this search.'}+ </p>+ }+ disabledReason={accessReason ?? (addingRepository ? 'Adding the repository' : undefined)}+ data-attr="stamphog-add-repository-picker"+ />+ <LemonButton+ type="primary"+ icon={<IconPlus />}+ onClick={addRepository}+ loading={addingRepository}+ disabledReason={accessReason ?? (repositoryToAdd ? undefined : 'Pick a repository first')}+ data-attr="stamphog-add-repository"+ >+ Add repository+ </LemonButton>+ </div>+ <MissingRepositoryHelp />+ </div>+ )+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsxnew file mode 100644index 000000000000..345f4fabaf02--- /dev/null+++ b/products/stamphog/frontend/scenes/StamphogScene/ExpandedRepoSettings.tsx@@ -0,0 +1,135 @@+import { useActions, useValues } from 'kea'++import { LemonInput, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'++import { toAccessControlLevel } from 'lib/utils/accessControlUtils'++import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'+import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'+import { editorDisabledReason, managerDisabledReason } from './repoAccess'+import { stamphogSceneLogic } from './stamphogSceneLogic'++function Section({+ title,+ description,+ children,+}: {+ title: string+ description: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <section className="flex flex-col gap-2 min-w-0">+ <h5 className="text-muted mb-0">{title}</h5>+ {children}+ <p className="text-secondary text-xs m-0">{description}</p>+ </section>+ )+}++function TriggerSettings({+ repo,+ updatingReason,+}: {+ repo: StamphogRepoConfigApi+ updatingReason?: string+}): JSX.Element {+ const { updateRepoConfig } = useActions(stamphogSceneLogic)+ const disabledReason = managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ?? updatingReason++ const saveTriggerLabel = (value: string): void => {+ const trimmed = value.trim()+ // Save only real changes — blur after no edit (or after enter already saved) must not re-PATCH,+ // and a blank label is rejected by the API anyway.+ if (trimmed && trimmed !== repo.trigger_label) {+ updateRepoConfig(repo.id, { trigger_label: trimmed })+ }+ }++ return (+ <div className="flex flex-wrap items-center gap-2">+ <LemonSelect+ size="small"+ value={repo.review_mode ?? ReviewModeEnumApi.All}+ disabledReason={disabledReason}+ onChange={(mode) => updateRepoConfig(repo.id, { review_mode: mode })}+ options={[+ { value: ReviewModeEnumApi.All, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.All] },+ { value: ReviewModeEnumApi.Label, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.Label] },+ ]}+ data-attr="stamphog-repo-review-mode"+ />+ {repo.review_mode === ReviewModeEnumApi.Label && (+ <LemonInput+ // Uncontrolled on purpose: the label saves on blur/enter, not per keystroke.+ // Keying by the saved value resets the draft after a reload.+ key={`${repo.id}-${repo.trigger_label}`}+ size="small"+ className="w-40"+ defaultValue={repo.trigger_label}+ placeholder="Trigger label"+ disabledReason={disabledReason}+ onBlur={(e) => saveTriggerLabel(e.currentTarget.value)}+ onPressEnter={(e) => saveTriggerLabel(e.currentTarget.value)}+ data-attr="stamphog-repo-trigger-label"+ />+ )}+ </div>+ )+}++export function ExpandedRepoSettings({ repo }: { repo: StamphogRepoConfigApi }): JSX.Element {+ const { updatingRepoIds } = useValues(stamphogSceneLogic)+ const { updateRepoConfig } = useActions(stamphogSceneLogic)+ const level = toAccessControlLevel(repo.user_access_level)+ const updatingReason = updatingRepoIds.includes(repo.id) ? 'Updating' : undefined++ return (+ <div className="@container pl-2 pr-4 py-4">+ <div className="grid grid-cols-1 @2xl:grid-cols-3 gap-x-8 gap-y-6">+ <Section+ title="Triggers"+ description={+ repo.review_mode === ReviewModeEnumApi.Label+ ? 'Stamphog reviews a pull request once someone adds this label.'+ : 'Stamphog reviews every pull request that is ready for review.'+ }+ >+ <TriggerSettings repo={repo} updatingReason={updatingReason} />+ </Section>+ <Section+ title="Daily digest"+ description="Posts the merged pull requests that Stamphog approved to Slack once a day."+ >+ <LemonSwitch+ label="Include in the digest"+ checked={!!repo.digest_enabled}+ // The API refuses a digest without reviews, because the digest lists only approved merges.+ disabledReason={+ editorDisabledReason(level) ??+ (repo.enabled ? updatingReason : 'Turn reviews on to include this repository in the digest')+ }+ onChange={(checked) => updateRepoConfig(repo.id, { digest_enabled: checked })}+ data-attr="stamphog-repo-digest-toggle"+ />+ </Section>+ <Section+ title="Reviews"+ description="Pausing also takes the repository out of the digest. The trigger settings stay."+ >+ <LemonSwitch+ label="Review pull requests"+ checked={repo.enabled}+ // Pausing undoes a review decision, so it takes a higher level than turning reviews on.+ disabledReason={+ (repo.enabled ? managerDisabledReason(level) : editorDisabledReason(level)) ??+ updatingReason+ }+ onChange={(checked) => updateRepoConfig(repo.id, { enabled: checked })}+ data-attr="stamphog-repo-reviews-toggle"+ />+ </Section>+ </div>+ </div>+ )+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsxindex fb3a6a2c08a2..0942e838282d 100644--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.stories.tsx@@ -1,45 +1,29 @@import type { Meta, StoryObj } from '@storybook/react'+import { within } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'import { App } from 'scenes/App'import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'+import { AccessControlLevel, AccessControlResourceType } from '~/types'-import type { StamphogRepoConfigApi } from '../../generated/api.schemas'+import type { StamphogAvailableRepositoriesApi, StamphogRepoConfigApi } from '../../generated/api.schemas'-const REPO_NAMES = [- 'posthog',- 'posthog-js',- 'posthog-python',- 'posthog-node',- 'posthog-ios',- 'posthog-android',- 'posthog-flutter',- 'posthog-go',- 'posthog-ruby',- 'posthog-php',- 'posthog.com',- 'charts',- 'hogql-parser',- 'plugin-server',- 'rrweb',- 'wizard',- 'hogland',- 'pr-approval-agent',-]--const repoConfig = (name: string, index: number, on: { enabled: boolean; digest: boolean }): StamphogRepoConfigApi =>+const repoConfig = (index: number, overrides: Partial<StamphogRepoConfigApi>): StamphogRepoConfigApi =>({id: `00000000-0000-0000-0000-${String(index).padStart(12, '0')}`,- repository: `PostHog/${name}`,+ repository: 'PostHog/posthog',provider: 'github',- enabled: on.enabled,- digest_enabled: on.digest,+ enabled: true,+ digest_enabled: false,installation_id: '1',review_mode: 'all',trigger_label: 'stamphog',+ user_access_level: 'manager',created_at: '2026-07-01T00:00:00Z',updated_at: '2026-07-01T00:00:00Z',+ ...overrides,}) as StamphogRepoConfigApiconst page = (results: StamphogRepoConfigApi[]): Record<string, unknown> => ({@@ -49,17 +33,29 @@ const page = (results: StamphogRepoConfigApi[]): Record<string, unknown> => ({results,})-const repoConfigs = page(- REPO_NAMES.map((name, index) =>- repoConfig(name, index, { enabled: name === 'posthog' || name === 'wizard', digest: name === 'posthog-js' })- )-)+// One row per status the table can show: reviewing, reviewing on a label, and paused with or without the digest.+const repoConfigs = page([+ repoConfig(1, { repository: 'PostHog/posthog', digest_enabled: true }),+ repoConfig(2, {+ repository: 'PostHog/posthog-js',+ review_mode: 'label',+ trigger_label: 'needs-review',+ created_at: '2026-08-02T00:00:00Z',+ }),+ repoConfig(3, {+ repository: 'PostHog/posthog.com',+ enabled: false,+ digest_enabled: true,+ created_at: '2026-08-10T00:00:00Z',+ }),+ repoConfig(4, { repository: 'PostHog/hogland', enabled: false, created_at: '2026-08-12T00:00:00Z' }),+])-const allOrgRepoConfigs = page(- Array.from({ length: 730 }, (_, index) =>- repoConfig(`service-${String(index).padStart(3, '0')}`, index, { enabled: index % 97 === 0, digest: false })- )-)+const availableRepositories: StamphogAvailableRepositoriesApi = {+ repositories: ['PostHog/charts', 'PostHog/plugin-server', 'PostHog/posthog-python', 'PostHog/wizard'],+ total_count: 4,+ has_installation: true,+}const meta: Meta = {component: App,@@ -69,12 +65,25 @@ const meta: Meta = {viewMode: 'story',mockDate: '2026-08-17 23:30:00',pageUrl: urls.stamphog(),- testOptions: { waitForSelector: '[data-attr="stamphog-repo-status-filter-all"]' },+ testOptions: { waitForSelector: '[data-attr="stamphog-repo-table"]' },+ },+ // With no repository loaded the page reads the access level from the app context, so a fresh team needs it there.+ beforeEach: () => {+ const context = window.POSTHOG_APP_CONTEXT!+ const previous = context.resource_access_control+ context.resource_access_control = {+ ...previous,+ [AccessControlResourceType.Stamphog]: AccessControlLevel.Editor,+ }+ return () => {+ context.resource_access_control = previous+ }},decorators: [mswDecorator({get: {'/api/projects/:team_id/stamphog/repo_configs/': repoConfigs,+ '/api/projects/:team_id/stamphog/repo_configs/available_repositories/': availableRepositories,'/api/projects/:team_id/stamphog/repo_configs/install_info/': {app_slug: 'stamphog',install_url: 'https://github.com/apps/stamphog/installations/new',@@ -88,13 +97,68 @@ export default metaexport const RepositoriesList: StoryObj = {}-// Too tall for a useful snapshot. It exists to check that search and the status filter stay fast at org scale.-export const AllOrgRepositories: StoryObj = {- tags: ['test-skip'],+// Expands the label-triggered row, the only one that shows the trigger label input.+export const RepositoryExpanded: StoryObj = {+ play: async ({ canvasElement }) => {+ const labelRow = (await within(canvasElement).findByText('posthog-js', {}, { timeout: 15000 })).closest('tr')+ await userEvent.click(within(labelRow!).getByTitle('Show more'))+ await within(canvasElement).findByText('Daily digest')+ },+}++export const AddRepositoryPickerOpen: StoryObj = {+ play: async ({ canvasElement }) => {+ const picker = await within(canvasElement).findByPlaceholderText(+ 'Search 4 repositories to add',+ {},+ { timeout: 15000 }+ )+ await userEvent.click(picker)+ await within(document.body).findByText('PostHog/charts')+ },+}++// Connected to GitHub, nothing added yet: the add bar is the whole page.+export const FirstRepository: StoryObj = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/stamphog/repo_configs/': page([]),+ },+ }),+ ],+}++export const NotConnected: StoryObj = {decorators: [mswDecorator({get: {- '/api/projects/:team_id/stamphog/repo_configs/': allOrgRepoConfigs,+ '/api/projects/:team_id/stamphog/repo_configs/': page([]),+ '/api/projects/:team_id/stamphog/repo_configs/available_repositories/': {+ repositories: [],+ total_count: 0,+ has_installation: false,+ },+ },+ }),+ ],+}++// GitHub sent the member back with a code: the sync records their repositories and turns no reviews on.+export const ConnectedAfterSync: StoryObj = {+ parameters: {+ pageUrl: `${urls.stamphogCallback()}?code=example-code&state=example-state`,+ },+ decorators: [+ mswDecorator({+ post: {+ '/api/projects/:team_id/stamphog/repo_configs/sync_installation/': {+ synced: [],+ skipped: ['PostHog/charts'],+ available_count: 4,+ app_not_installed: false,+ installations: [],+ },},}),],diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsxindex 7fbad2acc3ed..4329699229e5 100644--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx@@ -1,74 +1,47 @@import { useActions, useValues } from 'kea'import { IconGithub } from '@posthog/icons'-import {- LemonBanner,- LemonButton,- LemonInput,- LemonSegmentedButton,- LemonSelect,- LemonSwitch,- LemonTable,- Link,-} from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonInput, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { getAccessControlDisabledReason, toAccessControlLevel } from 'lib/utils/accessControlUtils'import { SceneExport } from 'scenes/sceneTypes'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import { StamphogTabs } from '../../components/StamphogTabs'-import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'-import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'-import { type RepoStatusFilter, stamphogSceneLogic } from './stamphogSceneLogic'+import { type StamphogRepoConfigApi } from '../../generated/api.schemas'+import { AddRepositoryBar } from './AddRepositoryBar'+import { ExpandedRepoSettings } from './ExpandedRepoSettings'+import { repoStatusDisplay, triggerSummary } from './repoDisplay'+import { stamphogSceneLogic } from './stamphogSceneLogic'-// Whether a repository is reviewed at all is a manager decision. The digest only changes who hears-// about the work, and connecting a repository starts no review on its own, so both stay at editor.-//-// The level comes from the API rather than the app context, because the app context answers for the-// environment in the URL while these rows belong to its parent project. Undefined when no repository-// has loaded yet, which sends the check back to the app context.-const managerDisabledReason = (level: AccessControlLevel | undefined): string | null =>- getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Manager, level)-const editorDisabledReason = (level: AccessControlLevel | undefined): string | null =>- getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Editor, level)+// A search box only helps once the list no longer fits on one screen.+const REPO_SEARCH_MIN_ROWS = 10export const scene: SceneExport = {component: StamphogScene,logic: stamphogSceneLogic,}-function ConnectRepositoryButton(): JSX.Element {- const { installInfo, installUrl, installInfoLoading, stamphogAccessLevel } = useValues(stamphogSceneLogic)- // The callback finishes through the authorize URL, so an install link alone cannot connect anything.- const canConnect = !!installUrl && !!installInfo?.authorize_url+function RepositoryName({ repository }: { repository: string }): JSX.Element {+ const [owner, name] = repository.split('/', 2)+ if (!name) {+ return <span className="font-medium">{repository}</span>+ }+ // A break opportunity after the slash lets a narrow table wrap at the owner instead of mid-word.return (- <LemonButton- type="primary"- icon={<IconGithub />}- to={canConnect ? installUrl : undefined}- disableClientSideRouting- data-attr="stamphog-connect-repository"- disabledReason={- editorDisabledReason(stamphogAccessLevel) ??- (installInfoLoading- ? 'Loading install details'- : canConnect- ? undefined- : 'GitHub App not configured yet')- }- >- Connect a repository- </LemonButton>+ <span className="font-medium">+ <span>{`${owner}/`}</span>+ <wbr />+ <span>{name}</span>+ </span>)}function SyncedBanner(): JSX.Element | null {- const { syncedRepos, skippedRepos, appNotInstalled, installUrl, discoveredInstallations } =+ const { syncResult, skippedRepos, appNotInstalled, installUrl, discoveredInstallations } =useValues(stamphogSceneLogic)const { connectInstallation } = useActions(stamphogSceneLogic)@@ -117,129 +90,81 @@ function SyncedBanner(): JSX.Element | null {)}- if (syncedRepos.length === 0 && skippedRepos.length === 0) {+ if (!syncResult) {return null}- // A sync can connect nothing (every repo already owned by another team) — that still needs- // an explanation, not a silent no-op.+ // A sync only makes repositories available to add and turns no reviews on, so the banner says so.+ const availableCount = syncResult.available_countreturn (- <LemonBanner type={syncedRepos.length > 0 ? 'success' : 'warning'}>- {syncedRepos.length > 0 ? (- <>- <p className="font-medium">Connected {syncedRepos.length} repositories</p>- <p>Stamphog isn't reviewing them yet. Turn on the ones you want reviewed in the table below.</p>- </>- ) : (- <p className="font-medium">No repositories connected</p>- )}+ <LemonBanner type={skippedRepos.length > 0 ? 'warning' : 'success'}>+ <p className="font-medium">GitHub is connected</p>+ <p>+ {availableCount === 0+ ? 'There are no new repositories to add.'+ : availableCount === 1+ ? 'You can now add 1 repository. Reviews start once you add it.'+ : `You can now add ${availableCount} repositories. Reviews start for each one you add.`}+ </p>{skippedRepos.length > 0 && (- <p className={syncedRepos.length > 0 ? 'text-warning mt-2' : 'mt-2'}>- Skipped {skippedRepos.join(', ')} because another team already owns them under this installation.+ <p className="mt-2">+ {`Skipped ${skippedRepos.join(', ')} because another project already uses ${skippedRepos.length === 1 ? 'it' : 'them'} with this GitHub installation.`}</p>)}</LemonBanner>)}-function ReviewModeCell({ repo, updating }: { repo: StamphogRepoConfigApi; updating: boolean }): JSX.Element {- const { updateRepoConfig } = useActions(stamphogSceneLogic)- const disabledReason =- managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ?? (updating ? 'Updating' : undefined)-- const saveTriggerLabel = (value: string): void => {- const trimmed = value.trim()- // Save only real changes — blur after no edit (or after enter already saved) must not re-PATCH,- // and a blank label is rejected by the API anyway.- if (trimmed && trimmed !== repo.trigger_label) {- updateRepoConfig(repo.id, { trigger_label: trimmed })- }- }-- return (- <div className="flex items-center gap-2">- <LemonSelect- size="small"- value={repo.review_mode ?? ReviewModeEnumApi.All}- disabledReason={disabledReason}- onChange={(mode) => updateRepoConfig(repo.id, { review_mode: mode })}- options={[- { value: ReviewModeEnumApi.All, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.All] },- { value: ReviewModeEnumApi.Label, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.Label] },- ]}- />- {repo.review_mode === ReviewModeEnumApi.Label && (- <LemonInput- // Uncontrolled on purpose: the label saves on blur/enter, not per keystroke.- // Keying by the saved value resets the draft after a reload.- key={`${repo.id}-${repo.trigger_label}`}- size="small"- className="w-40"- defaultValue={repo.trigger_label}- placeholder="Trigger label"- disabledReason={disabledReason}- onBlur={(e) => saveTriggerLabel(e.currentTarget.value)}- onPressEnter={(e) => saveTriggerLabel(e.currentTarget.value)}- />- )}- </div>- )-}-function RepoConfigsTable(): JSX.Element {const {- visibleRepoConfigs,filteredRepoConfigs,repoConfigs,repoConfigsLoading,- updatingRepoIds,+ repoConfigsFailed,repoSearch,- repoStatusFilter,- repoStatusCounts,+ expandedRepoIds,+ hasInstallation,} = useValues(stamphogSceneLogic)- const { updateRepoConfig, setRepoSearch, setRepoStatusFilter, showAllRepos } = useActions(stamphogSceneLogic)+ const { setRepoSearch, setRepoExpanded, loadRepoConfigs } = useActions(stamphogSceneLogic)++ if (repoConfigsFailed && repoConfigs.length === 0) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => loadRepoConfigs() }}+ data-attr="stamphog-repo-configs-error"+ >+ Could not load your repositories. This is usually temporary.+ </LemonBanner>+ )+ }const columns: LemonTableColumns<StamphogRepoConfigApi> = [{title: 'Repository',dataIndex: 'repository',- render: (repository) => <span className="font-medium">{repository as string}</span>,+ render: (repository) => <RepositoryName repository={repository as string} />,},{- title: 'Enabled',- key: 'enabled',- render: (_, repo) => (- <LemonSwitch- checked={!!repo.enabled}- disabledReason={- managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ??- (updatingRepoIds.includes(repo.id) ? 'Updating' : undefined)- }- onChange={(checked) => updateRepoConfig(repo.id, { enabled: checked })}- />- ),+ title: 'Status',+ key: 'status',+ render: (_, repo) => {+ const { type, label } = repoStatusDisplay(repo)+ return <LemonTag type={type}>{label}</LemonTag>+ },},{- title: 'Review mode',- key: 'review_mode',- render: (_, repo) => <ReviewModeCell repo={repo} updating={updatingRepoIds.includes(repo.id)} />,+ title: 'Trigger',+ key: 'trigger',+ render: (_, repo) => triggerSummary(repo),},{- title: 'Digest enabled',+ title: 'Digest',key: 'digest_enabled',- render: (_, repo) => (- <LemonSwitch- checked={!!repo.digest_enabled}- disabledReason={- editorDisabledReason(toAccessControlLevel(repo.user_access_level)) ??- (updatingRepoIds.includes(repo.id) ? 'Updating' : undefined)- }- onChange={(checked) => updateRepoConfig(repo.id, { digest_enabled: checked })}- />- ),+ render: (_, repo) => (repo.digest_enabled ? 'On' : <span className="text-secondary">Off</span>),},{- title: 'Created',+ title: 'Added',dataIndex: 'created_at',render: (created_at) => <TZLabel time={created_at as string} />,},@@ -247,66 +172,36 @@ function RepoConfigsTable(): JSX.Element {return (<div className="flex flex-col gap-2">- {repoConfigs.length > 10 && (- <div className="flex items-center gap-2 flex-wrap">- <LemonInput- type="search"- placeholder="Search repositories"- value={repoSearch}- onChange={setRepoSearch}- className="max-w-100"- data-attr="stamphog-repo-search"- />- <LemonSegmentedButton<RepoStatusFilter>- size="small"- value={repoStatusFilter}- onChange={setRepoStatusFilter}- options={[- {- value: 'all',- label: `All (${repoStatusCounts.all})`,- 'data-attr': 'stamphog-repo-status-filter-all',- },- {- value: 'on',- label: `On (${repoStatusCounts.on})`,- tooltip: 'Reviews or the digest are turned on',- 'data-attr': 'stamphog-repo-status-filter-on',- },- {- value: 'off',- label: `Off (${repoStatusCounts.off})`,- tooltip: 'Connected, with reviews and the digest turned off',- 'data-attr': 'stamphog-repo-status-filter-off',- },- ]}- />- </div>+ {repoConfigs.length > REPO_SEARCH_MIN_ROWS && (+ <LemonInput+ type="search"+ placeholder="Search added repositories"+ value={repoSearch}+ onChange={setRepoSearch}+ className="max-w-100"+ data-attr="stamphog-repo-search"+ />)}<LemonTablecolumns={columns}- dataSource={visibleRepoConfigs}+ dataSource={filteredRepoConfigs}loading={repoConfigsLoading}rowKey="id"+ expandable={{+ expandedRowRender: (repo) => <ExpandedRepoSettings repo={repo} />,+ isRowExpanded: (repo) => expandedRepoIds.includes(repo.id),+ onRowExpand: (repo) => setRepoExpanded(repo.id, true),+ onRowCollapse: (repo) => setRepoExpanded(repo.id, false),+ }}emptyState={- repoConfigs.length === 0- ? 'No repositories yet. Install the Stamphog GitHub App to get started.'- : 'No repositories match. Clear the search or pick All to see every repository.'+ repoConfigs.length > 0+ ? 'No added repository matches this search.'+ : hasInstallation === false+ ? 'No repositories yet. Connect GitHub to add the first one.'+ : 'No repositories yet. Add one above to start reviews.'}+ data-attr="stamphog-repo-table"/>- {filteredRepoConfigs.length > visibleRepoConfigs.length && (- <div className="flex items-center gap-2 flex-wrap text-secondary">- <span>{`Showing ${visibleRepoConfigs.length} of ${filteredRepoConfigs.length}. Search to find a repository, or show the full list.`}</span>- <LemonButton- size="small"- type="secondary"- onClick={showAllRepos}- data-attr="stamphog-repo-show-all"- >- {`Show all ${filteredRepoConfigs.length}`}- </LemonButton>- </div>- )}</div>)}@@ -318,10 +213,10 @@ export function StamphogScene(): JSX.Element {name="Stamphog"description="Automated pull request reviews and merged-PR digests, per repository."resourceType={{ type: 'stamphog' }}- actions={<ConnectRepositoryButton />}/><StamphogTabs activeKey="repositories" /><SyncedBanner />+ <AddRepositoryBar /><RepoConfigsTable /></SceneContent>)diff --git a/products/stamphog/frontend/scenes/StamphogScene/repoAccess.ts b/products/stamphog/frontend/scenes/StamphogScene/repoAccess.tsnew file mode 100644index 000000000000..db23c9a8877d--- /dev/null+++ b/products/stamphog/frontend/scenes/StamphogScene/repoAccess.ts@@ -0,0 +1,18 @@+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++// Turning reviews on, the digest, and connecting GitHub need editor. Turning reviews off and changing+// when they run need manager, because those undo or narrow a review decision.+//+// The level comes from the API rather than the app context, because the app context answers for the+// environment in the URL while these rows belong to its parent project. Undefined when no repository+// has loaded yet, which sends the check back to the app context, so a team with no rows can still+// add its first repository.+export function managerDisabledReason(level: AccessControlLevel | undefined): string | null {+ return getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Manager, level)+}++export function editorDisabledReason(level: AccessControlLevel | undefined): string | null {+ return getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Editor, level)+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/repoDisplay.ts b/products/stamphog/frontend/scenes/StamphogScene/repoDisplay.tsnew file mode 100644index 000000000000..f408a7d81add--- /dev/null+++ b/products/stamphog/frontend/scenes/StamphogScene/repoDisplay.ts@@ -0,0 +1,18 @@+import { LemonTagType } from 'lib/lemon-ui/LemonTag'++import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'+import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'++export function repoStatusDisplay(repo: StamphogRepoConfigApi): { type: LemonTagType; label: string } {+ if (repo.enabled) {+ return { type: 'success', label: 'Reviewing' }+ }+ return { type: 'muted', label: 'Paused' }+}++export function triggerSummary(repo: StamphogRepoConfigApi): string {+ if (repo.review_mode === ReviewModeEnumApi.Label) {+ return `Label: ${repo.trigger_label ?? ''}`+ }+ return REVIEW_MODE_LABELS[ReviewModeEnumApi.All]+}diff --git a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.tsindex fc135be35e99..0dc5f43bd564 100644--- a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts+++ b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reduimport { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'+import { LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { toAccessControlLevel } from 'lib/utils/accessControlUtils'import { teamLogic } from 'scenes/teamLogic'@@ -10,6 +11,8 @@ import { urls } from 'scenes/urls'import { AccessControlLevel } from '~/types'import {+ stamphogRepoConfigsAddRepositoryCreate,+ stamphogRepoConfigsAvailableRepositoriesRetrieve,stamphogRepoConfigsInstallInfoRetrieve,stamphogRepoConfigsList,stamphogRepoConfigsPartialUpdate,@@ -17,61 +20,116 @@ import {} from '../../generated/api'import type {PatchedStamphogRepoConfigWriteApi,+ StamphogAvailableRepositoriesApi,StamphogDiscoveredInstallationApi,StamphogInstallInfoApi,StamphogRepoConfigApi,StamphogSyncInstallationRequestApi,StamphogSyncInstallationResponseApi,} from '../../generated/api.schemas'+import { editorDisabledReason } from './repoAccess'// Carries the user's installation pick across the authorize redirect: the OAuth code is single-use// and consumed server-side before installations are known, so the choice can't ride the request// that discovered them — it rides the browser instead, and the explicit-id path verifies it.const PENDING_INSTALLATION_STORAGE_KEY = 'stamphog-pending-installation-id'-// Large enough that an organization-wide install loads in one request. The list endpoint sets no max limit.+// Large enough that every added repository loads in one request. The list endpoint sets no max limit.const REPO_CONFIGS_PAGE_SIZE = 1000-// Every table row mounts two switches and a select, so mounting an org's worth of rows stalls the page-// for a noticeable moment on each search or filter change. Search is how people find a repo among-// hundreds, so the table renders the first matches and offers the full list on request.-const VISIBLE_REPO_LIMIT = 100+const AVAILABLE_REPOSITORIES_LIMIT = 50+const AVAILABLE_SEARCH_DEBOUNCE_MS = 300-export type RepoStatusFilter = 'all' | 'on' | 'off'+function sortByRepository(repos: StamphogRepoConfigApi[]): StamphogRepoConfigApi[] {+ return [...repos].sort((a, b) => a.repository.localeCompare(b.repository))+}-function isRepoOn(repo: StamphogRepoConfigApi): boolean {- return !!repo.enabled || !!repo.digest_enabled+// The install_info state token expires, and the page can stay open for longer than that. So every+// redirect fetches a fresh URL instead of reading the one the page loaded on mount.+async function redirectToGitHub(projectId: string, target: 'authorize_url' | 'install_url'): Promise<boolean> {+ try {+ const info = await stamphogRepoConfigsInstallInfoRetrieve(projectId)+ const url = info[target]+ if (url) {+ window.location.href = url+ return true+ }+ lemonToast.error('The Stamphog GitHub App is not configured, so it cannot connect.')+ } catch {+ lemonToast.error('Could not load GitHub connection details. Try again.')+ }+ return false}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface stamphogSceneLogicValues {currentProjectId: number | string // teamLogic+ addableCount: number | null+ addedRepoIds: string[]+ addingRepository: booleanappNotInstalled: boolean+ availableRepositories: StamphogAvailableRepositoriesApi | null+ availableRepositoriesFailed: boolean+ availableRepositoriesLoading: boolean+ availableRepositoryOptions: LemonInputSelectOption[]+ availableSearch: string+ connectDisabledReason: string | nulldiscoveredInstallations: readonly StamphogDiscoveredInstallationApi[]+ expandedRepoIds: string[]filteredRepoConfigs: StamphogRepoConfigApi[]+ hasInstallation: boolean | nullinstallInfo: StamphogInstallInfoApi | nullinstallInfoLoading: booleaninstallUrl: string+ openingInstallPage: boolean+ refreshingFromGitHub: booleanrepoConfigs: StamphogRepoConfigApi[]+ repoConfigsFailed: booleanrepoConfigsLoading: booleanrepoSearch: string- repoStatusCounts: Record<RepoStatusFilter, number>- repoStatusFilter: RepoStatusFilter- showingAllRepos: boolean+ repositoryToAdd: string | nullskippedRepos: readonly string[]stamphogAccessLevel: AccessControlLevel | undefinedsyncResult: StamphogSyncInstallationResponseApi | nullsyncResultLoading: boolean- syncedRepos: readonly StamphogRepoConfigApi[]updatingRepoIds: string[]- visibleRepoConfigs: StamphogRepoConfigApi[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface stamphogSceneLogicActions {+ addRepository: () => {+ value: true+ }+ addRepositoryFailure: () => {+ value: true+ }+ addRepositorySuccess: (config: StamphogRepoConfigApi) => {+ config: StamphogRepoConfigApi+ }connectInstallation: (installationId: string) => {installationId: string}+ loadAvailableRepositories: ({ search }: { search: string }) => {+ search: string+ }+ loadAvailableRepositoriesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAvailableRepositoriesSuccess: (+ availableRepositories: StamphogAvailableRepositoriesApi,+ payload?: {+ search: string+ }+ ) => {+ availableRepositories: StamphogAvailableRepositoriesApi+ payload?: {+ search: string+ }+ }loadInstallInfo: () => anyloadInstallInfoFailure: (error: string,@@ -87,7 +145,9 @@ export interface stamphogSceneLogicActions {installInfo: StamphogInstallInfoApipayload?: any}- loadRepoConfigs: () => any+ loadRepoConfigs: () => {+ value: true+ }loadRepoConfigsFailure: (error: string,errorObject?: any@@ -97,10 +157,26 @@ export interface stamphogSceneLogicActions {}loadRepoConfigsSuccess: (repoConfigs: StamphogRepoConfigApi[],- payload?: any+ payload?: {+ value: true+ }) => {repoConfigs: StamphogRepoConfigApi[]- payload?: any+ payload?: {+ value: true+ }+ }+ openInstallPage: () => {+ value: true+ }+ openInstallPageFailed: () => {+ value: true+ }+ refreshFromGitHub: () => {+ value: true+ }+ refreshFromGitHubFailed: () => {+ value: true}repoConfigUpdated: (config: StamphogRepoConfigApi) => {config: StamphogRepoConfigApi@@ -108,14 +184,21 @@ export interface stamphogSceneLogicActions {repoUpdateDone: (id: string) => {id: string}- setRepoSearch: (search: string) => {+ setAvailableSearch: (search: string) => {search: string}- setRepoStatusFilter: (filter: RepoStatusFilter) => {- filter: RepoStatusFilter+ setRepoExpanded: (+ id: string,+ expanded: boolean+ ) => {+ expanded: boolean+ id: string+ }+ setRepoSearch: (search: string) => {+ search: string}- showAllRepos: () => {- value: true+ setRepositoryToAdd: (repository: string | null) => {+ repository: string | null}syncInstallation: ({installationId,@@ -171,19 +254,19 @@ export interface stamphogSceneLogicMeta {discoveredInstallations: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly StamphogDiscoveredInstallationApi[]- syncedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly StamphogRepoConfigApi[]skippedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly string[]+ hasInstallation: (availableRepositories: StamphogAvailableRepositoriesApi | null) => boolean | null+ availableRepositoryOptions: (+ availableRepositories: StamphogAvailableRepositoriesApi | null,+ availableRepositoriesFailed: boolean+ ) => LemonInputSelectOption[]stamphogAccessLevel: (repoConfigs: StamphogRepoConfigApi[]) => AccessControlLevel | undefined- repoStatusCounts: (repoConfigs: StamphogRepoConfigApi[]) => Record<RepoStatusFilter, number>- filteredRepoConfigs: (- repoConfigs: StamphogRepoConfigApi[],- repoSearch: string,- repoStatusFilter: RepoStatusFilter- ) => StamphogRepoConfigApi[]- visibleRepoConfigs: (- filteredRepoConfigs: StamphogRepoConfigApi[],- showingAllRepos: boolean- ) => StamphogRepoConfigApi[]+ connectDisabledReason: (+ installInfo: StamphogInstallInfoApi | null,+ installInfoLoading: boolean,+ stamphogAccessLevel: AccessControlLevel | undefined+ ) => string | null+ filteredRepoConfigs: (repoConfigs: StamphogRepoConfigApi[], repoSearch: string) => StamphogRepoConfigApi[]}}@@ -202,23 +285,33 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([})),actions({+ // Declared here because the loader takes a breakpoint: typegen would otherwise infer a required+ // payload from its first parameter, and every `loadRepoConfigs()` call would stop compiling.+ loadRepoConfigs: true,updateRepoConfig: (id: string, patch: PatchedStamphogRepoConfigWriteApi) => ({ id, patch }),repoUpdateDone: (id: string) => ({ id }),repoConfigUpdated: (config: StamphogRepoConfigApi) => ({ config }),setRepoSearch: (search: string) => ({ search }),- setRepoStatusFilter: (filter: RepoStatusFilter) => ({ filter }),- showAllRepos: true,+ setRepoExpanded: (id: string, expanded: boolean) => ({ id, expanded }),connectInstallation: (installationId: string) => ({ installationId }),+ openInstallPage: true,+ openInstallPageFailed: true,+ refreshFromGitHub: true,+ refreshFromGitHubFailed: true,+ setAvailableSearch: (search: string) => ({ search }),+ setRepositoryToAdd: (repository: string | null) => ({ repository }),+ addRepository: true,+ addRepositorySuccess: (config: StamphogRepoConfigApi) => ({ config }),+ addRepositoryFailure: true,}),loaders(({ values }) => ({repoConfigs: [[] as StamphogRepoConfigApi[],{- loadRepoConfigs: async () => {- // A GitHub installation can surface hundreds of repos, so fetch every page. The table- // searches and filters this list client-side, so a truncated first page would hide- // repos that nobody could then find or toggle.+ loadRepoConfigs: async (_, breakpoint) => {+ // Fetch every page, because the table searches this list client-side and a truncated+ // first page would hide repositories that nobody could then find.const all: StamphogRepoConfigApi[] = []for (let offset = 0; ; offset += REPO_CONFIGS_PAGE_SIZE) {const response = await stamphogRepoConfigsList(String(values.currentProjectId), {@@ -230,9 +323,13 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([break}}- // Repos that are on go first so they don't sink among hundreds of idle ones. The sort- // runs on load only, so a toggled row stays where it is until the next load.- return all.sort((a, b) => Number(isRepoOn(b)) - Number(isRepoOn(a)))+ breakpoint()+ // A read replica can trail the add, so keep a row this page added until the list has it.+ const fetchedIds = new Set(all.map((repo) => repo.id))+ const addedHere = values.repoConfigs.filter(+ (repo) => values.addedRepoIds.includes(repo.id) && !fetchedIds.has(repo.id)+ )+ return sortByRepository([...all, ...addedHere])},},],@@ -244,6 +341,21 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([},},],+ // Null until the first answer, so the page can tell "not connected" apart from "not known yet".+ availableRepositories: [+ null as StamphogAvailableRepositoriesApi | null,+ {+ loadAvailableRepositories: async ({ search }: { search: string }, breakpoint) => {+ const response = await stamphogRepoConfigsAvailableRepositoriesRetrieve(+ String(values.currentProjectId),+ { search: search.trim(), limit: AVAILABLE_REPOSITORIES_LIMIT }+ )+ // Drop a slow response once a newer search has started.+ breakpoint()+ return response+ },+ },+ ],// Sync is a loader so the button can wire its in-flight state off// syncResultLoading and guard double-submission during the callback.syncResult: [@@ -282,17 +394,82 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([],repoConfigs: {repoConfigUpdated: (state, { config }) => state.map((repo) => (repo.id === config.id ? config : repo)),+ // Adding a paused repository turns its existing row back on, so replace before inserting.+ addRepositorySuccess: (state, { config }) =>+ sortByRepository([...state.filter((repo) => repo.id !== config.id), config]),},- repoSearch: ['', { setRepoSearch: (_, { search }) => search }],- repoStatusFilter: ['all' as RepoStatusFilter, { setRepoStatusFilter: (_, { filter }) => filter }],- // A new search or filter goes back to the capped list, so clearing a search later doesn't mount- // every row again.- showingAllRepos: [+ // An added repository opens by itself, so a search that hides it has to go.+ repoSearch: ['', { setRepoSearch: (_, { search }) => search, addRepositorySuccess: () => '' }],+ // A failed first load leaves the list empty, which must not read as "no repositories yet".+ repoConfigsFailed: [+ false,+ {+ loadRepoConfigs: () => false,+ loadRepoConfigsSuccess: () => false,+ loadRepoConfigsFailure: () => true,+ },+ ],+ availableRepositoriesFailed: [+ false,+ {+ loadAvailableRepositories: () => false,+ loadAvailableRepositoriesSuccess: () => false,+ loadAvailableRepositoriesFailure: () => true,+ },+ ],+ addedRepoIds: [+ [] as string[],+ {+ addRepositorySuccess: (state, { config }) => [...state.filter((x) => x !== config.id), config.id],+ },+ ],+ availableSearch: ['', { setAvailableSearch: (_, { search }) => search }],+ expandedRepoIds: [+ [] as string[],+ {+ setRepoExpanded: (state, { id, expanded }) =>+ expanded ? [...state.filter((x) => x !== id), id] : state.filter((x) => x !== id),+ addRepositorySuccess: (state, { config }) => [...state.filter((x) => x !== config.id), config.id],+ },+ ],+ // Only an unfiltered answer counts every addable repository, so a search result leaves it alone.+ addableCount: [+ null as number | null,+ {+ loadAvailableRepositoriesSuccess: (state, { availableRepositories, payload }) =>+ payload?.search.trim() ? state : availableRepositories.total_count,+ },+ ],+ repositoryToAdd: [+ null as string | null,+ {+ setRepositoryToAdd: (_, { repository }) => repository,+ // A new search replaces the options, so a pick from the old results must not stay armed.+ setAvailableSearch: (state, { search }) => (search.trim() ? null : state),+ addRepositorySuccess: () => null,+ },+ ],+ addingRepository: [+ false,+ {+ addRepository: () => true,+ addRepositorySuccess: () => false,+ addRepositoryFailure: () => false,+ },+ ],+ // The browser leaves for GitHub on success, so only a failure needs to reset these.+ openingInstallPage: [false,{- showAllRepos: () => true,- setRepoSearch: () => false,- setRepoStatusFilter: () => false,+ openInstallPage: () => true,+ openInstallPageFailed: () => false,+ },+ ],+ refreshingFromGitHub: [+ false,+ {+ refreshFromGitHub: () => true,+ refreshFromGitHubFailed: () => false,},],}),@@ -313,15 +490,29 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([(syncResult: StamphogSyncInstallationResponseApi | null): readonly StamphogDiscoveredInstallationApi[] =>syncResult?.installations ?? [],],- syncedRepos: [- (s) => [s.syncResult],- (syncResult: StamphogSyncInstallationResponseApi | null): readonly StamphogRepoConfigApi[] =>- syncResult?.synced ?? [],- ],skippedRepos: [(s) => [s.syncResult],(syncResult: StamphogSyncInstallationResponseApi | null): readonly string[] => syncResult?.skipped ?? [],],+ hasInstallation: [+ (s) => [s.availableRepositories],+ (availableRepositories: StamphogAvailableRepositoriesApi | null): boolean | null =>+ availableRepositories?.has_installation ?? null,+ ],+ // A failed search keeps the loader's previous answer, which belongs to another search.+ availableRepositoryOptions: [+ (s) => [s.availableRepositories, s.availableRepositoriesFailed],+ (+ availableRepositories: StamphogAvailableRepositoriesApi | null,+ availableRepositoriesFailed: boolean+ ): LemonInputSelectOption[] =>+ availableRepositoriesFailed+ ? []+ : (availableRepositories?.repositories ?? []).map((repository) => ({+ key: repository,+ label: repository,+ })),+ ],// Every row reports the same team-wide level, so the first one answers for the whole scene.// Undefined until a repository loads, which sends the access checks back to the app context.stamphogAccessLevel: [@@ -329,34 +520,37 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([(repoConfigs: StamphogRepoConfigApi[]): AccessControlLevel | undefined =>repoConfigs.length > 0 ? toAccessControlLevel(repoConfigs[0].user_access_level) : undefined,],- repoStatusCounts: [- (s) => [s.repoConfigs],- (repoConfigs: StamphogRepoConfigApi[]): Record<RepoStatusFilter, number> => {- const on = repoConfigs.filter(isRepoOn).length- return { all: repoConfigs.length, on, off: repoConfigs.length - on }+ // Connecting, granting access, and refreshing all record the member's repositories for the team.+ // The flow finishes through the authorize URL, so an install link alone cannot connect anything.+ connectDisabledReason: [+ (s) => [s.installInfo, s.installInfoLoading, s.stamphogAccessLevel],+ (+ installInfo: StamphogInstallInfoApi | null,+ installInfoLoading: boolean,+ stamphogAccessLevel: AccessControlLevel | undefined+ ): string | null => {+ const accessReason = editorDisabledReason(stamphogAccessLevel)+ if (accessReason) {+ return accessReason+ }+ if (installInfoLoading) {+ return 'Loading install details'+ }+ if (!installInfo?.install_url || !installInfo.authorize_url) {+ return 'The Stamphog GitHub App is not configured yet'+ }+ return null},],- // A GitHub App install can surface hundreds of repos, so the table filters client-side by name and status.filteredRepoConfigs: [- (s) => [s.repoConfigs, s.repoSearch, s.repoStatusFilter],- (- repoConfigs: StamphogRepoConfigApi[],- repoSearch: string,- repoStatusFilter: RepoStatusFilter- ): StamphogRepoConfigApi[] => {+ (s) => [s.repoConfigs, s.repoSearch],+ (repoConfigs: StamphogRepoConfigApi[], repoSearch: string): StamphogRepoConfigApi[] => {const needle = repoSearch.trim().toLowerCase()- return repoConfigs.filter(- (repo) =>- (repoStatusFilter === 'all' || isRepoOn(repo) === (repoStatusFilter === 'on')) &&- (!needle || repo.repository.toLowerCase().includes(needle))- )+ return needle+ ? repoConfigs.filter((repo) => repo.repository.toLowerCase().includes(needle))+ : repoConfigs},],- visibleRepoConfigs: [- (s) => [s.filteredRepoConfigs, s.showingAllRepos],- (filteredRepoConfigs: StamphogRepoConfigApi[], showingAllRepos: boolean): StamphogRepoConfigApi[] =>- showingAllRepos ? filteredRepoConfigs : filteredRepoConfigs.slice(0, VISIBLE_REPO_LIMIT),- ],}),listeners(({ actions, values }) => ({@@ -371,26 +565,58 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([actions.repoUpdateDone(id)}},+ setAvailableSearch: async ({ search }, breakpoint) => {+ await breakpoint(AVAILABLE_SEARCH_DEBOUNCE_MS)+ actions.loadAvailableRepositories({ search })+ },+ addRepository: async () => {+ const repository = values.repositoryToAdd+ if (!repository) {+ actions.addRepositoryFailure()+ return+ }+ try {+ const config = await stamphogRepoConfigsAddRepositoryCreate(String(values.currentProjectId), {+ repository,+ })+ actions.addRepositorySuccess(config)+ lemonToast.success(`Stamphog now reviews ${config.repository}`)+ } catch (error: any) {+ lemonToast.error(error?.detail || 'Could not add the repository. Try again.')+ actions.addRepositoryFailure()+ }+ },+ addRepositorySuccess: () => {+ actions.loadRepoConfigs()+ actions.loadAvailableRepositories({ search: '' })+ },connectInstallation: async ({ installationId }) => {sessionStorage.setItem(PENDING_INSTALLATION_STORAGE_KEY, installationId)// The setup_action=update redirect carries no code (nothing to sync), so bounce the browser// through the authorize URL for one silent hop. GitHub redirects straight back with a code, and- // the stashed installation id goes with it. Fetch install info directly rather than racing the- // loader, which may not have resolved yet when the callback fires.- try {- const info = await stamphogRepoConfigsInstallInfoRetrieve(String(values.currentProjectId))- if (info.authorize_url) {- window.location.href = info.authorize_url- } else {- lemonToast.error('GitHub App is not configured, so it cannot be connected')- }- } catch {- lemonToast.error('Could not load GitHub connection details. Try again.')+ // the stashed installation id goes with it.+ if (!(await redirectToGitHub(String(values.currentProjectId), 'authorize_url'))) {+ sessionStorage.removeItem(PENDING_INSTALLATION_STORAGE_KEY)+ }+ },+ openInstallPage: async () => {+ if (!(await redirectToGitHub(String(values.currentProjectId), 'install_url'))) {+ actions.openInstallPageFailed()+ }+ },+ refreshFromGitHub: async () => {+ // A refresh picks no installation. A pick left over from a failed connect would otherwise ride+ // this callback and bind that installation instead.+ sessionStorage.removeItem(PENDING_INSTALLATION_STORAGE_KEY)+ // An App that is already authorized sends the browser straight back with a code, and the sync+ // re-lists the repositories this member can reach with their own GitHub token.+ if (!(await redirectToGitHub(String(values.currentProjectId), 'authorize_url'))) {+ actions.refreshFromGitHubFailed()}},syncInstallationSuccess: ({ syncResult }) => {// Drop the callback params from the URL so a refresh doesn't re-sync,- // then refresh the list to show the newly bound repos.+ // then reload both lists, because a sync can change what is available to add.router.actions.replace(urls.stamphog())if (syncResult?.app_not_installed) {// Discovery found no installation the user can reach — they still need to install the App.@@ -398,6 +624,7 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([lemonToast.info("Stamphog isn't installed on GitHub yet. Use the install link to add it.")}actions.loadRepoConfigs()+ actions.loadAvailableRepositories({ search: '' })},syncInstallationFailure: () => {lemonToast.error('Could not connect the GitHub App installation')@@ -459,5 +686,6 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([afterMount(({ actions }) => {actions.loadRepoConfigs()actions.loadInstallInfo()+ actions.loadAvailableRepositories({ search: '' })}),])diff --git a/products/stamphog/package.json b/products/stamphog/package.jsonindex 4384705292a8..1267b7ecf24f 100644--- a/products/stamphog/package.json+++ b/products/stamphog/package.json@@ -18,6 +18,8 @@"@posthog/icons": "catalog:","@posthog/react": "*","@storybook/react": "catalog:",+ "@testing-library/dom": "*",+ "@testing-library/user-event": "*","@types/react": "*","react": "*"}