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.

32.6 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

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'
import { urls } from 'scenes/urls'

import { AccessControlLevel } from '~/types'

import {
    stamphogRepoConfigsAddRepositoryCreate,
    stamphogRepoConfigsAvailableRepositoriesRetrieve,
    stamphogRepoConfigsInstallInfoRetrieve,
    stamphogRepoConfigsList,
    stamphogRepoConfigsOwnersFileRetrieve,
    stamphogRepoConfigsPartialUpdate,
    stamphogRepoConfigsSyncInstallationCreate,
} from '../../generated/api'
import {
    OwnersFileStatusEnumApi,
    type PatchedStamphogRepoConfigWriteApi,
    type StamphogAvailableRepositoriesApi,
    type StamphogDiscoveredInstallationApi,
    type StamphogInstallInfoApi,
    type StamphogRepoConfigApi,
    type StamphogSyncInstallationRequestApi,
    type 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 every added repository loads in one request. The list endpoint sets no max limit.
const REPO_CONFIGS_PAGE_SIZE = 1000

const AVAILABLE_REPOSITORIES_LIMIT = 50
const AVAILABLE_SEARCH_DEBOUNCE_MS = 300

// 'checking' while the request is in flight. A repository nobody expanded yet has no entry at all.
export type OwnersFileCheck = OwnersFileStatusEnumApi | 'checking'

function sortByRepository(repos: StamphogRepoConfigApi[]): StamphogRepoConfigApi[] {
    return [...repos].sort((a, b) => a.repository.localeCompare(b.repository))
}

// 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: boolean
    appNotInstalled: boolean
    availableRepositories: StamphogAvailableRepositoriesApi | null
    availableRepositoriesFailed: boolean
    availableRepositoriesLoading: boolean
    availableRepositoryOptions: LemonInputSelectOption[]
    availableSearch: string
    connectDisabledReason: string | null
    discoveredInstallations: readonly StamphogDiscoveredInstallationApi[]
    expandedRepoIds: string[]
    filteredRepoConfigs: StamphogRepoConfigApi[]
    hasInstallation: boolean | null
    installInfo: StamphogInstallInfoApi | null
    installInfoLoading: boolean
    installUrl: string
    openingInstallPage: boolean
    ownersFileChecks: Record<string, OwnersFileCheck>
    refreshingFromGitHub: boolean
    repoConfigs: StamphogRepoConfigApi[]
    repoConfigsFailed: boolean
    repoConfigsLoading: boolean
    repoSearch: string
    repositoryToAdd: string | null
    savingTriggerLabelRepoIds: string[]
    skippedRepos: readonly string[]
    stamphogAccessLevel: AccessControlLevel | undefined
    syncResult: StamphogSyncInstallationResponseApi | null
    syncResultLoading: boolean
    triggerLabelFieldResets: Record<string, number>
    updatingRepoIds: string[]
}

// 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
    }
    checkOwnersFile: (id: string) => {
        id: string
    }
    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: () => any
    loadInstallInfoFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInstallInfoSuccess: (
        installInfo: StamphogInstallInfoApi,
        payload?: any
    ) => {
        installInfo: StamphogInstallInfoApi
        payload?: any
    }
    loadRepoConfigs: () => {
        value: true
    }
    loadRepoConfigsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRepoConfigsSuccess: (
        repoConfigs: StamphogRepoConfigApi[],
        payload?: {
            value: true
        }
    ) => {
        repoConfigs: StamphogRepoConfigApi[]
        payload?: {
            value: true
        }
    }
    openInstallPage: () => {
        value: true
    }
    openInstallPageFailed: () => {
        value: true
    }
    ownersFileChecked: (
        id: string,
        status: OwnersFileStatusEnumApi
    ) => {
        id: string
        status: OwnersFileStatusEnumApi
    }
    refreshFromGitHub: () => {
        value: true
    }
    refreshFromGitHubFailed: () => {
        value: true
    }
    repoConfigUpdated: (config: StamphogRepoConfigApi) => {
        config: StamphogRepoConfigApi
    }
    repoUpdateDone: (id: string) => {
        id: string
    }
    resetTriggerLabelField: (id: string) => {
        id: string
    }
    setAvailableSearch: (search: string) => {
        search: string
    }
    setRepoExpanded: (
        id: string,
        expanded: boolean
    ) => {
        expanded: boolean
        id: string
    }
    setRepoSearch: (search: string) => {
        search: string
    }
    setRepositoryToAdd: (repository: string | null) => {
        repository: string | null
    }
    syncInstallation: ({
        installationId,
        code,
        state,
    }: {
        code: string
        // Optional: absent when the callback carries only a code, where the backend discovers the
        // caller's installations from the code instead of trusting a supplied id.
        installationId?: string
        state: string
    }) => {
        installationId?: string
        code: string
        state: string
    }
    syncInstallationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    syncInstallationSuccess: (
        syncResult: StamphogSyncInstallationResponseApi,
        payload?: {
            installationId?: string
            code: string
            state: string
        }
    ) => {
        syncResult: StamphogSyncInstallationResponseApi
        payload?: {
            installationId?: string
            code: string
            state: string
        }
    }
    triggerLabelEditStarted: (id: string) => {
        id: string
    }
    triggerLabelSaveDone: (id: string) => {
        id: string
    }
    updateRepoConfig: (
        id: string,
        patch: PatchedStamphogRepoConfigWriteApi
    ) => {
        id: string
        patch: PatchedStamphogRepoConfigWriteApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        installUrl: (installInfo: StamphogInstallInfoApi | null) => string
        appNotInstalled: (syncResult: StamphogSyncInstallationResponseApi | null) => boolean
        discoveredInstallations: (
            syncResult: StamphogSyncInstallationResponseApi | null
        ) => readonly StamphogDiscoveredInstallationApi[]
        skippedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly string[]
        hasInstallation: (availableRepositories: StamphogAvailableRepositoriesApi | null) => boolean | null
        availableRepositoryOptions: (
            availableRepositories: StamphogAvailableRepositoriesApi | null,
            availableRepositoriesFailed: boolean
        ) => LemonInputSelectOption[]
        stamphogAccessLevel: (repoConfigs: StamphogRepoConfigApi[]) => AccessControlLevel | undefined
        connectDisabledReason: (
            installInfo: StamphogInstallInfoApi | null,
            installInfoLoading: boolean,
            stamphogAccessLevel: AccessControlLevel | undefined
        ) => string | null
        filteredRepoConfigs: (repoConfigs: StamphogRepoConfigApi[], repoSearch: string) => StamphogRepoConfigApi[]
    }
}

export type stamphogSceneLogicType = MakeLogicType<
    stamphogSceneLogicValues,
    stamphogSceneLogicActions,
    Record<string, any>,
    stamphogSceneLogicMeta
>

export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
    path(['products', 'stamphog', 'frontend', 'scenes', 'StamphogScene', 'stamphogSceneLogic']),

    connect(() => ({
        values: [teamLogic, ['currentProjectId']],
    })),

    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 }),
        triggerLabelEditStarted: (id: string) => ({ id }),
        resetTriggerLabelField: (id: string) => ({ id }),
        triggerLabelSaveDone: (id: string) => ({ id }),
        repoUpdateDone: (id: string) => ({ id }),
        repoConfigUpdated: (config: StamphogRepoConfigApi) => ({ config }),
        setRepoSearch: (search: string) => ({ search }),
        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,
        checkOwnersFile: (id: string) => ({ id }),
        ownersFileChecked: (id: string, status: OwnersFileStatusEnumApi) => ({ id, status }),
    }),

    loaders(({ values }) => ({
        repoConfigs: [
            [] as StamphogRepoConfigApi[],
            {
                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), {
                            limit: REPO_CONFIGS_PAGE_SIZE,
                            offset,
                        })
                        all.push(...response.results)
                        if (all.length >= response.count || response.results.length === 0) {
                            break
                        }
                    }
                    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])
                },
            },
        ],
        installInfo: [
            null as StamphogInstallInfoApi | null,
            {
                loadInstallInfo: async () => {
                    return stamphogRepoConfigsInstallInfoRetrieve(String(values.currentProjectId))
                },
            },
        ],
        // 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: [
            null as StamphogSyncInstallationResponseApi | null,
            {
                syncInstallation: async ({
                    installationId,
                    code,
                    state,
                }: {
                    // Optional: absent when the callback carries only a code, where the backend discovers the
                    // caller's installations from the code instead of trusting a supplied id.
                    installationId?: string
                    code: string
                    state: string
                }) => {
                    const body: StamphogSyncInstallationRequestApi = { code, state }
                    if (installationId) {
                        body.installation_id = installationId
                    }
                    return stamphogRepoConfigsSyncInstallationCreate(String(values.currentProjectId), body)
                },
            },
        ],
    })),

    reducers({
        // Repos with an in-flight PATCH — used to disable their switches so a
        // second toggle can't fire before the first resolves.
        updatingRepoIds: [
            [] as string[],
            {
                updateRepoConfig: (state, { id }) => (state.includes(id) ? state : [...state, id]),
                repoUpdateDone: (state, { id }) => state.filter((x) => x !== id),
            },
        ],
        // Repos with an in-flight label PATCH. A second label save before the first settles could land
        // out of order and leave the older label stored.
        savingTriggerLabelRepoIds: [
            [] as string[],
            {
                updateRepoConfig: (state, { id, patch }) =>
                    'trigger_label' in patch && !state.includes(id) ? [...state, id] : state,
                triggerLabelSaveDone: (state, { id }) => state.filter((x) => x !== id),
            },
        ],
        // The label editor keeps a draft it did not save on screen, so a bumped count remounts it from the stored label.
        triggerLabelFieldResets: [
            {} as Record<string, number>,
            {
                resetTriggerLabelField: (state, { id }) => ({ ...state, [id]: (state[id] ?? 0) + 1 }),
            },
        ],
        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]),
        },
        // 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,
            {
                openInstallPage: () => true,
                openInstallPageFailed: () => false,
            },
        ],
        refreshingFromGitHub: [
            false,
            {
                refreshFromGitHub: () => true,
                refreshFromGitHubFailed: () => false,
            },
        ],
        // The check costs a GitHub call, so each repository asks once per page load, when it first expands.
        ownersFileChecks: [
            {} as Record<string, OwnersFileCheck>,
            {
                checkOwnersFile: (state, { id }) => ({ ...state, [id]: 'checking' }),
                ownersFileChecked: (state, { id, status }) => ({ ...state, [id]: status }),
            },
        ],
    }),

    selectors({
        installUrl: [
            (s) => [s.installInfo],
            (installInfo: StamphogInstallInfoApi | null): string => installInfo?.install_url ?? '',
        ],
        appNotInstalled: [
            (s) => [s.syncResult],
            (syncResult: StamphogSyncInstallationResponseApi | null): boolean => syncResult?.app_not_installed ?? false,
        ],
        // Non-empty only when discovery found several installations and bound nothing: the user must
        // pick which one this team connects (reachability is not intent).
        discoveredInstallations: [
            (s) => [s.syncResult],
            (syncResult: StamphogSyncInstallationResponseApi | null): readonly StamphogDiscoveredInstallationApi[] =>
                syncResult?.installations ?? [],
        ],
        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: [
            (s) => [s.repoConfigs],
            (repoConfigs: StamphogRepoConfigApi[]): AccessControlLevel | undefined =>
                repoConfigs.length > 0 ? toAccessControlLevel(repoConfigs[0].user_access_level) : undefined,
        ],
        // 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
            },
        ],
        filteredRepoConfigs: [
            (s) => [s.repoConfigs, s.repoSearch],
            (repoConfigs: StamphogRepoConfigApi[], repoSearch: string): StamphogRepoConfigApi[] => {
                const needle = repoSearch.trim().toLowerCase()
                return needle
                    ? repoConfigs.filter((repo) => repo.repository.toLowerCase().includes(needle))
                    : repoConfigs
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        updateRepoConfig: async ({ id, patch }) => {
            try {
                actions.repoConfigUpdated(
                    await stamphogRepoConfigsPartialUpdate(String(values.currentProjectId), id, patch)
                )
                // The event names are frozen: insights on settings usage break if one is renamed. The label
                // text is left out because it is free text a team typed.
                posthog.capture('stamphog repo settings updated', {
                    repo_config_id: id,
                    fields: Object.keys(patch),
                    review_mode: patch.review_mode,
                    enabled: patch.enabled,
                    digest_enabled: patch.digest_enabled,
                    routing_mode: patch.routing_mode,
                })
            } catch {
                lemonToast.error('Failed to update repository')
                if ('trigger_label' in patch) {
                    actions.resetTriggerLabelField(id)
                }
            } finally {
                actions.repoUpdateDone(id)
                if ('trigger_label' in patch) {
                    actions.triggerLabelSaveDone(id)
                }
            }
        },
        setRepoExpanded: ({ id, expanded }) => {
            const check = values.ownersFileChecks[id]
            // A failed check asks again on the next expand. Any other answer holds for the page load.
            if (expanded && (check === undefined || check === OwnersFileStatusEnumApi.Unavailable)) {
                actions.checkOwnersFile(id)
            }
        },
        checkOwnersFile: async ({ id }) => {
            try {
                const response = await stamphogRepoConfigsOwnersFileRetrieve(String(values.currentProjectId), id)
                actions.ownersFileChecked(id, response.owners_file)
            } catch {
                actions.ownersFileChecked(id, OwnersFileStatusEnumApi.Unavailable)
            }
        },
        triggerLabelEditStarted: ({ id }) => {
            posthog.capture('stamphog trigger label edit started', { repo_config_id: 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: ({ config }) => {
            actions.loadRepoConfigs()
            actions.loadAvailableRepositories({ search: '' })
            // An added repository opens by itself, without the expand that asks for the check.
            actions.checkOwnersFile(config.id)
        },
        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.
            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 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.
                // The banner and connect button surface the install link.
                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')
        },
    })),

    urlToAction(({ actions }) => ({
        [urls.stamphogCallback()]: (_, searchParams) => {
            // Two redirects land here, both carrying the state token we minted in install_info:
            //   - authorize/fresh-install: a user OAuth code (+ installation_id on a fresh install). The
            //     backend proves ownership from the code and discovers or verifies the installation.
            //   - setup_action=update (app already installed): installation_id + state but NO code. The id
            //     is user-editable and not trusted, so restart via authorize to obtain a real code.
            // GitHub sends the user back with ?error=access_denied when they hit Cancel on the
            // authorize screen — a normal action on the primary connect flow, not a failure. Land
            // them back on the plain page instead of a silent dead-end on the callback URL.
            // Read and clear the stashed pick before any early return, so a stale id cannot bind the wrong
            // installation on a later code-only callback.
            const stashedInstallationId = sessionStorage.getItem(PENDING_INSTALLATION_STORAGE_KEY)
            sessionStorage.removeItem(PENDING_INSTALLATION_STORAGE_KEY)
            if (searchParams.error) {
                router.actions.replace(urls.stamphog())
                if (searchParams.error === 'access_denied') {
                    lemonToast.info('GitHub authorization was cancelled.')
                } else {
                    lemonToast.error('GitHub authorization failed. Try again.')
                }
                return
            }
            // A member without admin rights on the GitHub organization only files an install request, so
            // GitHub returns without an installation or a code. Nothing can connect until an owner approves.
            if (searchParams.setup_action === 'request') {
                router.actions.replace(urls.stamphog())
                lemonToast.info(
                    'GitHub sent your install request to the organization owners. Connect again once they approve it.'
                )
                return
            }
            // A stashed pick fills in for the missing installation_id on the authorize redirect; an explicit
            // URL param wins.
            const installationId = searchParams.installation_id || stashedInstallationId || undefined
            const code = searchParams.code
            const state = searchParams.state
            if (code && state) {
                actions.syncInstallation({
                    installationId: installationId ? String(installationId) : undefined,
                    code: String(code),
                    state: String(state),
                })
            } else if (installationId && state) {
                actions.connectInstallation(String(installationId))
            } else {
                // Backing out of GitHub's install page returns only the state, so there is nothing to connect.
                router.actions.replace(urls.stamphog())
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadRepoConfigs()
        actions.loadInstallInfo()
        actions.loadAvailableRepositories({ search: '' })
    }),
])