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.

29.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'

import { captureInboxSettingsChanged } from '../inboxAnalytics'
import type { SignalReportPriority, SignalTeamConfig } from '../types'

export interface BaseBranchOverride {
    repo: string
    branch: string
}

function isRepositoryKey(repo: string): boolean {
    const parts = repo.trim().split('/')
    return parts.length === 2 && parts.every((part) => !!part)
}

// Floor between return-to-tab refreshes; without it, alt-tab flapping turns into request bursts.
// Mirrors inboxOnboardingLogic's VISIBILITY_REFETCH_THROTTLE_MS in this same folder.
const VISIBILITY_REFETCH_THROTTLE_MS = 5 * 1000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalTeamConfigLogicValues {
    addBaseBranchOverrideDisabledReason: string | null
    addImplementationRepositoryDisabledReason: string | null
    anomalyScoringAvailable: boolean
    anomalyScoringEnabled: boolean
    autostartEnabled: boolean
    baseBranchOverrides: BaseBranchOverride[]
    baseBranchPickerOpen: boolean
    dailyReportLimitReached: boolean
    defaultAutostartPriority: SignalReportPriority
    defaultOpenPullRequestReady: boolean
    draftBaseBranchBranch: string
    draftBaseBranchIntegrationId: number | null
    draftBaseBranchRepo: string
    draftImplementationRepository: string
    draftImplementationRepositoryIntegrationId: number | null
    draftIssueTrackerIntegrationId: number | null
    draftMaxReportsPerDay: number | null
    draftPullRequestLabel: string
    githubIssueWritebackEnabled: boolean
    implementationRepositories: string[]
    implementationRepositoryPickerOpen: boolean
    issueTrackerConfig: Record<string, string>
    issueTrackerIntegrationId: number | null
    issueTrackerTargetPickerOpen: boolean
    maxReportsPerDay: number | null
    patchesInFlight: number
    pullRequestLabel: string
    pullRequestLabelEnabled: boolean
    reportsGeneratedToday: number
    saveMaxReportsPerDayDisabledReason: string | null
    savePullRequestLabelDisabledReason: string | null
    selectedIssueTrackerIntegrationId: number | null
    teamConfig: SignalTeamConfig | null
    teamConfigLoading: boolean
    teamConfigUpdating: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalTeamConfigLogicActions {
    addBaseBranchOverride: () => {
        value: true
    }
    addImplementationRepository: () => {
        value: true
    }
    clearDraftBaseBranch: () => {
        value: true
    }
    loadTeamConfig: () => any
    loadTeamConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTeamConfigSuccess: (
        teamConfig: SignalTeamConfig,
        payload?: any
    ) => {
        teamConfig: SignalTeamConfig
        payload?: any
    }
    patchTeamConfig: (
        patch: Partial<SignalTeamConfig>,
        clearDraftOnSuccess?: boolean
    ) => {
        clearDraftOnSuccess: boolean
        patch: Partial<SignalTeamConfig>
    }
    patchTeamConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    patchTeamConfigSuccess: (
        teamConfig: SignalTeamConfig,
        payload?: {
            clearDraftOnSuccess: boolean
            patch: Partial<SignalTeamConfig>
        }
    ) => {
        teamConfig: SignalTeamConfig
        payload?: {
            clearDraftOnSuccess: boolean
            patch: Partial<SignalTeamConfig>
        }
    }
    removeBaseBranchOverride: (repo: string) => {
        repo: string
    }
    removeImplementationRepository: (repo: string) => {
        repo: string
    }
    saveDraftMaxReportsPerDay: () => {
        value: true
    }
    saveDraftPullRequestLabel: () => {
        value: true
    }
    setBaseBranchPickerOpen: (open: boolean) => {
        open: boolean
    }
    setDraftBaseBranchBranch: (branch: string) => {
        branch: string
    }
    setDraftBaseBranchIntegrationId: (integrationId: number | null) => {
        integrationId: number | null
    }
    setDraftBaseBranchRepo: (repo: string) => {
        repo: string
    }
    setDraftImplementationRepository: (repo: string) => {
        repo: string
    }
    setDraftImplementationRepositoryIntegrationId: (integrationId: number | null) => {
        integrationId: number | null
    }
    setDraftIssueTrackerIntegrationId: (integrationId: number | null) => {
        integrationId: number | null
    }
    setDraftMaxReportsPerDay: (value: number | null) => {
        value: number | null
    }
    setDraftPullRequestLabel: (value: string) => {
        value: string
    }
    setImplementationRepositoryPickerOpen: (open: boolean) => {
        open: boolean
    }
    setIssueTrackerTargetPickerOpen: (open: boolean) => {
        open: boolean
    }
    updateBaseBranchOverride: (
        repo: string,
        branch: string
    ) => {
        branch: string
        repo: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalTeamConfigLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        autostartEnabled: (teamConfig: SignalTeamConfig | null) => boolean
        defaultAutostartPriority: (teamConfig: SignalTeamConfig | null) => SignalReportPriority
        baseBranchOverrides: (teamConfig: SignalTeamConfig | null) => BaseBranchOverride[]
        implementationRepositories: (teamConfig: SignalTeamConfig | null) => string[]
        maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | null
        defaultOpenPullRequestReady: (teamConfig: SignalTeamConfig | null) => boolean
        githubIssueWritebackEnabled: (teamConfig: SignalTeamConfig | null) => boolean
        pullRequestLabelEnabled: (teamConfig: SignalTeamConfig | null) => boolean
        pullRequestLabel: (teamConfig: SignalTeamConfig | null) => string
        anomalyScoringEnabled: (teamConfig: SignalTeamConfig | null) => boolean
        anomalyScoringAvailable: (teamConfig: SignalTeamConfig | null) => boolean
        issueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | null
        issueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>
        selectedIssueTrackerIntegrationId: (
            draftIssueTrackerIntegrationId: number | null,
            issueTrackerIntegrationId: number | null
        ) => number | null
        reportsGeneratedToday: (teamConfig: SignalTeamConfig | null) => number
        dailyReportLimitReached: (teamConfig: SignalTeamConfig | null) => boolean
        teamConfigUpdating: (patchesInFlight: number) => boolean
        saveMaxReportsPerDayDisabledReason: (
            draftMaxReportsPerDay: number | null,
            maxReportsPerDay: number | null
        ) => string | null
        savePullRequestLabelDisabledReason: (draftPullRequestLabel: string, pullRequestLabel: string) => string | null
        addBaseBranchOverrideDisabledReason: (
            draftBaseBranchRepo: string,
            draftBaseBranchBranch: string
        ) => string | null
        addImplementationRepositoryDisabledReason: (
            draftImplementationRepository: string,
            implementationRepositories: string[]
        ) => string | null
    }
}

export type signalTeamConfigLogicType = MakeLogicType<
    signalTeamConfigLogicValues,
    signalTeamConfigLogicActions,
    Record<string, any>,
    signalTeamConfigLogicMeta
>

/**
 * Team-level Self-driving config (singleton per team). Wraps the
 * `signals/team_config` endpoint via `api.signalTeamConfig`. Surfaces the
 * team-wide default PR auto-start threshold (which seeds every user's effective
 * threshold until they set a personal override in `userAutonomyLogic`) and the
 * team-wide default Slack notification channel, where every actionable report is
 * posted regardless of whether a suggested reviewer resolves. The auto-start
 * field is non-nullable (P0–P4), so unlike the per-user override there is no
 * "Never" option; the channel is nullable and `null` disables the team default.
 */
export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
    path(['scenes', 'inbox', 'logics', 'signalTeamConfigLogic']),
    actions({
        // Declared up front so the loader below adopts this signature instead of generating a
        // single-payload one: callers say `patchTeamConfig({ autostart_enabled: false })`.
        patchTeamConfig: (patch: Partial<SignalTeamConfig>, clearDraftOnSuccess: boolean = false) => ({
            patch,
            clearDraftOnSuccess,
        }),
        setDraftBaseBranchIntegrationId: (integrationId: number | null) => ({ integrationId }),
        setDraftBaseBranchRepo: (repo: string) => ({ repo }),
        setDraftBaseBranchBranch: (branch: string) => ({ branch }),
        clearDraftBaseBranch: true,
        addBaseBranchOverride: true,
        updateBaseBranchOverride: (repo: string, branch: string) => ({ repo, branch }),
        removeBaseBranchOverride: (repo: string) => ({ repo }),
        setDraftMaxReportsPerDay: (value: number | null) => ({ value }),
        saveDraftMaxReportsPerDay: true,
        setDraftPullRequestLabel: (value: string) => ({ value }),
        saveDraftPullRequestLabel: true,
        setDraftIssueTrackerIntegrationId: (integrationId: number | null) => ({ integrationId }),
        setBaseBranchPickerOpen: (open: boolean) => ({ open }),
        setImplementationRepositoryPickerOpen: (open: boolean) => ({ open }),
        setDraftImplementationRepositoryIntegrationId: (integrationId: number | null) => ({ integrationId }),
        setDraftImplementationRepository: (repo: string) => ({ repo }),
        addImplementationRepository: true,
        removeImplementationRepository: (repo: string) => ({ repo }),
        setIssueTrackerTargetPickerOpen: (open: boolean) => ({ open }),
    }),
    loaders(() => {
        // Every patch of `autostart_base_branches` sends the whole map, so two in flight at once let the
        // server settle on whichever lands last rather than whichever was asked for last.
        let updateQueue: Promise<unknown> = Promise.resolve()

        return {
            teamConfig: [
                null as SignalTeamConfig | null,
                {
                    loadTeamConfig: async () => {
                        return await api.signalTeamConfig.get()
                    },
                    // Partial update of the singleton, e.g. `{ default_slack_notification_channel: null }`
                    // to clear the team channel. One action serves every patchable field.
                    patchTeamConfig: async ({
                        patch,
                    }: {
                        patch: Partial<SignalTeamConfig>
                        clearDraftOnSuccess: boolean
                    }) => {
                        const update = updateQueue.then(() => api.signalTeamConfig.update(patch))
                        updateQueue = update.then(
                            () => undefined,
                            () => undefined
                        )
                        return await update
                    },
                },
            ],
        }
    }),
    reducers({
        // Optimistically reflect the patched values so the controls don't flicker
        // back to the stale ones while the request is in flight.
        teamConfig: {
            patchTeamConfig: (state, { patch }) => (state ? { ...state, ...patch } : state),
        },
        draftBaseBranchIntegrationId: [
            null as number | null,
            {
                setDraftBaseBranchIntegrationId: (_, { integrationId }) => integrationId,
            },
        ],
        draftBaseBranchRepo: [
            '',
            {
                setDraftBaseBranchRepo: (_, { repo }) => repo,
                setDraftBaseBranchIntegrationId: () => '',
                clearDraftBaseBranch: () => '',
            },
        ],
        draftBaseBranchBranch: [
            '',
            {
                setDraftBaseBranchBranch: (_, { branch }) => branch,
                setDraftBaseBranchRepo: () => '',
                setDraftBaseBranchIntegrationId: () => '',
                clearDraftBaseBranch: () => '',
            },
        ],
        // The pickers below fetch their option lists on mount, and Linear and Jira do so from the
        // provider. They mount only after a person asks to add or change a value, so a view of
        // the section costs no integration request. Closing also drops the base branch draft.
        baseBranchPickerOpen: [
            false,
            {
                setBaseBranchPickerOpen: (_, { open }) => open,
                clearDraftBaseBranch: () => false,
            },
        ],
        // Same mount-on-request rule as the base branch picker. A successful add closes it, a failed
        // one keeps it open so the person can read the error and pick again.
        implementationRepositoryPickerOpen: [
            false,
            {
                setImplementationRepositoryPickerOpen: (_, { open }) => open,
                patchTeamConfigSuccess: (state, { payload }) =>
                    payload?.patch && 'implementation_repositories' in payload.patch ? false : state,
            },
        ],
        draftImplementationRepositoryIntegrationId: [
            null as number | null,
            {
                setDraftImplementationRepositoryIntegrationId: (_, { integrationId }) => integrationId,
            },
        ],
        draftImplementationRepository: [
            '',
            {
                setDraftImplementationRepository: (_, { repo }) => repo,
                setDraftImplementationRepositoryIntegrationId: () => '',
                setImplementationRepositoryPickerOpen: () => '',
                patchTeamConfigSuccess: (state, { payload }) =>
                    payload?.patch && 'implementation_repositories' in payload.patch ? '' : state,
            },
        ],
        issueTrackerTargetPickerOpen: [
            false,
            {
                setIssueTrackerTargetPickerOpen: (_, { open }) => open,
                setDraftIssueTrackerIntegrationId: () => false,
                patchTeamConfigSuccess: (state, { payload }) =>
                    payload?.patch && 'issue_tracking_config' in payload.patch ? false : state,
            },
        ],
        // A save is in flight while this is above zero. Tracked explicitly rather than read off
        // teamConfigLoading, because that flag also flips for the initial load and the background
        // tab-return refresh (both plain GETs), neither of which should disable the save controls.
        patchesInFlight: [
            0,
            {
                patchTeamConfig: (state: number) => state + 1,
                patchTeamConfigSuccess: (state: number) => Math.max(0, state - 1),
                patchTeamConfigFailure: (state: number) => Math.max(0, state - 1),
            },
        ],
        // Which tracker the person just picked, before they have chosen a target inside it. The
        // backend rejects an integration with no target, so the pair is only sent once both exist.
        // Null means no pending pick: turning tracking off saves straight away, so the draft never
        // has to hold that state.
        draftIssueTrackerIntegrationId: [
            null as number | null,
            {
                setDraftIssueTrackerIntegrationId: (_, { integrationId }) => integrationId,
                patchTeamConfigSuccess: (state, { payload }) =>
                    payload?.patch && 'issue_tracking_integration' in payload.patch ? null : state,
            },
        ],
        // The daily-limit input's draft. Seeded from the server once on first load (see the
        // loadTeamConfigSuccess listener) and re-anchored only when its own save settles, so saving
        // an unrelated setting on this shared singleton logic never wipes an unsaved edit.
        draftMaxReportsPerDay: [
            null as number | null,
            {
                // A cleared number LemonInput emits NaN, which is never a valid draft — treat it as
                // null ("no limit") so the field can be reset to unlimited.
                setDraftMaxReportsPerDay: (_, { value }) => (value != null && Number.isNaN(value) ? null : value),
                patchTeamConfigSuccess: (state, { teamConfig, payload }) =>
                    payload?.patch && 'max_reports_per_day' in payload.patch
                        ? (teamConfig?.max_reports_per_day ?? null)
                        : state,
            },
        ],
        // The label input's draft, anchored the same way as the daily limit above: seeded once on
        // first load, and re-read from the server only when its own save settles.
        draftPullRequestLabel: [
            '',
            {
                setDraftPullRequestLabel: (_, { value }) => value,
                patchTeamConfigSuccess: (state: string, { teamConfig, payload }) =>
                    payload?.patch && 'pull_request_label' in payload.patch
                        ? (teamConfig?.pull_request_label ?? '')
                        : state,
            },
        ],
    }),
    selectors({
        // Master switch for autonomous inbox PRs: only an explicit false disables
        // auto-start, so a team that never touched the setting stays on.
        autostartEnabled: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.autostart_enabled !== false,
        ],
        defaultAutostartPriority: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): SignalReportPriority =>
                teamConfig?.default_autostart_priority ?? 'P4',
        ],
        baseBranchOverrides: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): BaseBranchOverride[] =>
                Object.entries(teamConfig?.autostart_base_branches ?? {})
                    .map(([repo, branch]) => ({ repo, branch }))
                    .sort((a, b) => a.repo.localeCompare(b.repo)),
        ],
        implementationRepositories: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): string[] => teamConfig?.implementation_repositories ?? [],
        ],
        maxReportsPerDay: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): number | null => teamConfig?.max_reports_per_day ?? null,
        ],
        defaultOpenPullRequestReady: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.default_open_pull_request_ready ?? false,
        ],
        githubIssueWritebackEnabled: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.github_issue_writeback_enabled ?? false,
        ],
        pullRequestLabelEnabled: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.pull_request_label_enabled ?? false,
        ],
        pullRequestLabel: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): string => teamConfig?.pull_request_label ?? '',
        ],
        anomalyScoringEnabled: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.anomaly_scoring_enabled ?? true,
        ],
        anomalyScoringAvailable: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.anomaly_scoring_available ?? false,
        ],
        issueTrackerIntegrationId: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,
        ],
        issueTrackerConfig: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): Record<string, string> => teamConfig?.issue_tracking_config ?? {},
        ],
        selectedIssueTrackerIntegrationId: [
            (s) => [s.draftIssueTrackerIntegrationId, s.issueTrackerIntegrationId],
            (draftIssueTrackerIntegrationId: number | null, issueTrackerIntegrationId: number | null): number | null =>
                draftIssueTrackerIntegrationId ?? issueTrackerIntegrationId,
        ],
        reportsGeneratedToday: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): number => teamConfig?.reports_generated_today ?? 0,
        ],
        dailyReportLimitReached: [
            (s) => [s.teamConfig],
            (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.daily_report_limit_reached === true,
        ],
        // True only while a save (patch) is in flight. Deliberately not derived from teamConfigLoading:
        // the shared loader also raises that flag for the initial load and the background tab-return
        // refresh, and neither should disable the save controls or show a "Saving changes" state.
        teamConfigUpdating: [(s) => [s.patchesInFlight], (patchesInFlight: number): boolean => patchesInFlight > 0],
        // Doubles as the save button's tooltip, same single-statement pattern as
        // addBaseBranchOverrideDisabledReason below.
        saveMaxReportsPerDayDisabledReason: [
            (s) => [s.draftMaxReportsPerDay, s.maxReportsPerDay],
            (draftMaxReportsPerDay: number | null, maxReportsPerDay: number | null): string | null => {
                if (
                    draftMaxReportsPerDay !== null &&
                    (!Number.isInteger(draftMaxReportsPerDay) || draftMaxReportsPerDay < 1)
                ) {
                    return 'Enter a whole number of at least 1'
                }
                return draftMaxReportsPerDay === maxReportsPerDay ? 'No changes to save' : null
            },
        ],
        // Doubles as the save button's tooltip, in the same shape as the daily limit above. A blank
        // name is a valid save: it means "use the default label".
        savePullRequestLabelDisabledReason: [
            (s) => [s.draftPullRequestLabel, s.pullRequestLabel],
            (draftPullRequestLabel: string, pullRequestLabel: string): string | null =>
                draftPullRequestLabel.trim() === pullRequestLabel.trim() ? 'No changes to save' : null,
        ],
        // Doubles as the add button's tooltip, so what blocks the add is stated once rather than
        // derived separately for the guard and for the copy.
        addBaseBranchOverrideDisabledReason: [
            (s) => [s.draftBaseBranchRepo, s.draftBaseBranchBranch],
            (draftBaseBranchRepo: string, draftBaseBranchBranch: string): string | null => {
                if (!isRepositoryKey(draftBaseBranchRepo)) {
                    return 'Choose a repository first'
                }
                return draftBaseBranchBranch.trim() ? null : 'Choose a branch first'
            },
        ],
        addImplementationRepositoryDisabledReason: [
            (s) => [s.draftImplementationRepository, s.implementationRepositories],
            (draftImplementationRepository: string, implementationRepositories: string[]): string | null => {
                if (!isRepositoryKey(draftImplementationRepository)) {
                    return 'Choose a repository first'
                }
                return implementationRepositories.includes(draftImplementationRepository.trim().toLowerCase())
                    ? 'This repository is already in the list'
                    : null
            },
        ],
    }),
    listeners(({ actions, values, cache }) => {
        // The patch is applied optimistically before these listeners run, so the setting names are
        // taken off the request rather than read back off state. A FIFO is enough to pair a
        // success/failure with its patch: the loader serializes the requests, so they settle in send order.
        const captureSettled = (success: boolean): void => {
            const patch: Partial<SignalTeamConfig> | undefined = cache.pendingSettingPatches?.shift()
            for (const [setting, newValue] of Object.entries(patch ?? {})) {
                captureInboxSettingsChanged({ setting, newValue, success, scope: 'team' })
            }
        }

        return {
            patchTeamConfig: ({ patch }) => {
                ;(cache.pendingSettingPatches ??= []).push(patch)
            },
            addBaseBranchOverride: () => {
                if (values.addBaseBranchOverrideDisabledReason) {
                    return
                }
                actions.patchTeamConfig(
                    {
                        autostart_base_branches: {
                            ...values.teamConfig?.autostart_base_branches,
                            [values.draftBaseBranchRepo.trim().toLowerCase()]: values.draftBaseBranchBranch.trim(),
                        },
                    },
                    true
                )
            },
            updateBaseBranchOverride: ({ repo, branch }) => {
                const trimmed = branch.trim()
                if (!trimmed || values.teamConfig?.autostart_base_branches?.[repo] === trimmed) {
                    return
                }
                actions.patchTeamConfig({
                    autostart_base_branches: { ...values.teamConfig?.autostart_base_branches, [repo]: trimmed },
                })
            },
            removeBaseBranchOverride: ({ repo }) => {
                const next = { ...values.teamConfig?.autostart_base_branches }
                delete next[repo]
                actions.patchTeamConfig({ autostart_base_branches: next })
            },
            addImplementationRepository: () => {
                if (values.addImplementationRepositoryDisabledReason) {
                    return
                }
                actions.patchTeamConfig({
                    implementation_repositories: [
                        ...values.implementationRepositories,
                        values.draftImplementationRepository.trim().toLowerCase(),
                    ],
                })
            },
            removeImplementationRepository: ({ repo }) => {
                actions.patchTeamConfig({
                    implementation_repositories: values.implementationRepositories.filter((entry) => entry !== repo),
                })
            },
            saveDraftMaxReportsPerDay: () => {
                // Guard the Enter path against double-submission: the Save button disables itself while
                // a save runs, but LemonInput's onPressEnter does not, so also bail while any request
                // for this singleton is in flight. A save must not race a concurrent GET or PATCH — they
                // share one loader key with no ordering, so a late response could clobber the saved value.
                if (values.saveMaxReportsPerDayDisabledReason || values.teamConfigLoading) {
                    return
                }
                actions.patchTeamConfig({ max_reports_per_day: values.draftMaxReportsPerDay })
            },
            saveDraftPullRequestLabel: () => {
                // Same double-submission guard as the daily limit above: Enter bypasses the button's
                // own disabled state, and a save must not race a concurrent GET or PATCH.
                if (values.savePullRequestLabelDisabledReason || values.teamConfigLoading) {
                    return
                }
                actions.patchTeamConfig({ pull_request_label: values.draftPullRequestLabel.trim() || null })
            },
            loadTeamConfigSuccess: ({ teamConfig }) => {
                // Seed the drafts from the server only on the first load, so a later reload (e.g. the
                // one triggered when an unrelated setting's save fails) can't wipe an unsaved edit.
                if (!cache.draftsSeeded) {
                    cache.draftsSeeded = true
                    actions.setDraftMaxReportsPerDay(teamConfig?.max_reports_per_day ?? null)
                    actions.setDraftPullRequestLabel(teamConfig?.pull_request_label ?? '')
                }
            },
            patchTeamConfigSuccess: ({ payload }) => {
                captureSettled(true)
                if (payload?.clearDraftOnSuccess) {
                    actions.clearDraftBaseBranch()
                }
            },
            patchTeamConfigFailure: ({ error, errorObject }) => {
                captureSettled(false)
                actions.setDraftIssueTrackerIntegrationId(null)
                lemonToast.error(errorObject?.detail ?? error ?? 'Failed to update team self-driving settings')
                // The optimistic value is now a lie, and the server holds the truth about what stuck.
                actions.loadTeamConfig()
            },
        }
    }),
    afterMount(({ actions, values, cache }) => {
        actions.loadTeamConfig()
        // Refresh on return to the tab: reports keep generating in the background, so the
        // daily-limit count and reached-banner would otherwise stay stale until a reload or save.
        cache.disposables.add(
            () => {
                const handler = (): void => {
                    if (document.visibilityState !== 'visible' || values.teamConfigLoading) {
                        return
                    }
                    const now = Date.now()
                    if (now - (cache.lastVisibilityRefetch ?? 0) < VISIBILITY_REFETCH_THROTTLE_MS) {
                        return
                    }
                    cache.lastVisibilityRefetch = now
                    actions.loadTeamConfig()
                }
                document.addEventListener('visibilitychange', handler)
                return () => document.removeEventListener('visibilitychange', handler)
            },
            'refreshOnTabReturn',
            { pauseOnPageHidden: false }
        )
    }),
])