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.

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

import { ApiError } from 'lib/api-error'
import { downloadBlob } from 'lib/components/ExportButton/exporter'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { parseWebAnalyticsURL } from 'scenes/web-analytics/common'

import * as webAnalyticsApi from 'products/web_analytics/frontend/generated/api'
import type {
    ContentAutopilotExportResponseApi,
    ContentAutopilotOpportunityApi,
    ContentAutopilotProposalApi,
    ContentAutopilotProposalListApi,
    ContentAutopilotRunApi,
    ContentAutopilotSiteDiscoveryResponseApi,
    ContentAutopilotSiteProfileApi,
} from 'products/web_analytics/frontend/generated/api.schemas'
import { webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax } from 'products/web_analytics/frontend/generated/api.zod'

import { ContentAutopilotPageTarget, opportunitiesNeedRefresh, pageToUpdate, proposalPagePath } from './utils'

export type ContentAutopilotOnboardingStep = 'site' | 'sources'

export type ContentAutopilotProposalTab = 'preview' | 'draft' | 'changes' | 'brief' | 'sources'
export type ContentAutopilotWorkspaceTab = 'overview' | 'prompts' | 'opportunities' | 'drafts' | 'settings'
export type ContentAutopilotWorkspaceResource = 'profiles' | 'runs' | 'proposals'
export type ContentAutopilotProfileResource = 'runs' | 'proposals'
export type ContentAutopilotWorkspaceErrors = Partial<Record<ContentAutopilotWorkspaceResource, string>>
export type ContentAutopilotWorkspaceSettled = Record<ContentAutopilotWorkspaceResource, boolean>
export type ContentAutopilotProfileDataSettled = Record<ContentAutopilotProfileResource, boolean>
export type ContentAutopilotDraftRow = {
    id: string
    title: string
    question: string
    isNewPage: boolean
    path: string
    updatedAt: string
    proposal: ContentAutopilotProposalListApi | null
}

const DRAFT_ERROR_CODES = new Set(['checks_failed', 'draft_failed'])

const REVIEW_ORDER: Record<ContentAutopilotProposalListApi['lifecycle_status'], number> = {
    ready_for_review: 0,
    failed: 1,
    generating: 2,
    exported: 3,
    rejected: 4,
}

export interface ContentAutopilotProposalActionReasons {
    reject?: string
    regenerate?: string
    save?: string
    exportMarkdown?: string
}

export interface ContentAutopilotProfileDraft {
    name: string
    domain: string
    sourceUrls: string
    contentBoundaries: string
    brandRules: string
}

const EMPTY_PROFILE_DRAFT: ContentAutopilotProfileDraft = {
    name: '',
    domain: '',
    sourceUrls: '',
    contentBoundaries: '/',
    brandRules: '',
}

const WORKSPACE_POLL_INTERVAL_MS = 10_000
export const MAX_DRAFTS_PER_RUN = webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax
const WORKSPACE_PAGE_LIMIT = 100
const EMPTY_WORKSPACE_SETTLED: ContentAutopilotWorkspaceSettled = {
    profiles: false,
    runs: false,
    proposals: false,
}
const EMPTY_PROFILE_DATA_SETTLED: ContentAutopilotProfileDataSettled = {
    runs: false,
    proposals: false,
}

interface PaginatedResults<T> {
    count: number
    results: T[]
}

const UNDRAFTABLE_STATUSES = new Set<ContentAutopilotOpportunityApi['status']>(['queued', 'dismissed'])

const fetchAllPages = async <T>(
    loadPage: (offset: number, limit: number) => Promise<PaginatedResults<T>>
): Promise<T[]> => {
    const collected: T[] = []
    for (;;) {
        const page = await loadPage(collected.length, WORKSPACE_PAGE_LIMIT)
        collected.push(...page.results)
        if (page.results.length === 0 || collected.length >= page.count) {
            return collected
        }
    }
}

const fetchOpportunities = (teamId: string, profileId: string): Promise<ContentAutopilotOpportunityApi[]> =>
    fetchAllPages((offset, limit) =>
        webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesList(teamId, { limit, offset, profile_id: profileId })
    )

const draftableSelection = (selectedIds: string[], opportunities: ContentAutopilotOpportunityApi[]): string[] =>
    selectedIds.filter((id) =>
        opportunities.some((opportunity) => opportunity.id === id && !UNDRAFTABLE_STATUSES.has(opportunity.status))
    )

const withoutWorkspaceError = (
    errors: ContentAutopilotWorkspaceErrors,
    resource: ContentAutopilotWorkspaceResource
): ContentAutopilotWorkspaceErrors => {
    const nextErrors = { ...errors }
    delete nextErrors[resource]
    return nextErrors
}

const splitLines = (value: string): string[] =>
    value
        .split('\n')
        .map((line) => line.trim())
        .filter(Boolean)

const draftFromProfile = (profile: ContentAutopilotSiteProfileApi): ContentAutopilotProfileDraft => ({
    name: profile.name ?? '',
    domain: profile.domain,
    sourceUrls: profile.source_urls.join('\n'),
    contentBoundaries: profile.content_boundaries.join('\n'),
    brandRules: profile.brand_rules.join('\n'),
})

const getErrorMessage = (error: unknown): string => {
    if (error instanceof Error) {
        return error.message
    }
    if (typeof error === 'object' && error !== null && 'detail' in error && typeof error.detail === 'string') {
        return error.detail
    }
    return 'Something went wrong. Try again.'
}

const toastClientError = (error: unknown): void => {
    if (!(error instanceof ApiError) || error.status === undefined) {
        lemonToast.error(getErrorMessage(error))
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotLogicValues {
    currentTeamIdStrict: number | string // teamLogic
    activeRun: ContentAutopilotRunApi | null
    deletedProfile: string | null
    deletedProfileLoading: boolean
    discoveredSite: ContentAutopilotSiteDiscoveryResponseApi | null
    discoveredSiteLoading: boolean
    dismissedOpportunity: ContentAutopilotOpportunityApi | null
    dismissedOpportunityCount: number
    dismissedOpportunityLoading: boolean
    dismissingOpportunityId: string | null
    draftDisabledReason: string | undefined
    draftRows: ContentAutopilotDraftRow[]
    draftingOpportunityIds: string[]
    exportedProposal: ContentAutopilotExportResponseApi | null
    exportedProposalLoading: boolean
    latestRunErrors: string[]
    onboardingOpen: boolean
    onboardingStep: ContentAutopilotOnboardingStep
    opportunities: ContentAutopilotOpportunityApi[] | null
    opportunitiesError: string | null
    opportunitiesLoading: boolean
    opportunityByPromptId: Record<string, ContentAutopilotOpportunityApi>
    opportunityProposals: Record<string, ContentAutopilotProposalListApi>
    opportunitySearch: string
    pagesToUpdate: Record<string, ContentAutopilotPageTarget | null>
    profile: ContentAutopilotSiteProfileApi | null
    profileDataLoaded: boolean
    profileDataSettled: ContentAutopilotProfileDataSettled
    profileDraft: ContentAutopilotProfileDraft
    proposalActionReasons: ContentAutopilotProposalActionReasons
    proposalDetail: ContentAutopilotProposalApi | null
    proposalDetailLoading: boolean
    proposalHasUnsavedChanges: boolean
    proposalMutation: ContentAutopilotProposalApi | null
    proposalMutationLoading: boolean
    proposalTab: ContentAutopilotProposalTab
    proposals: ContentAutopilotProposalListApi[]
    proposalsLoading: boolean
    proposedMarkdown: string
    readyDraftCount: number
    rowDraftDisabledReason: string | undefined
    runMutation: ContentAutopilotRunApi | null
    runMutationLoading: boolean
    runs: ContentAutopilotRunApi[]
    runsLoading: boolean
    savedProfile: ContentAutopilotSiteProfileApi | null
    savedProfileLoading: boolean
    selectedOpportunityIds: string[]
    selectedProfileId: string | null
    selectedProposal: ContentAutopilotProposalApi | null
    selectedProposalId: string | null
    showDismissedOpportunities: boolean
    siteProfiles: ContentAutopilotSiteProfileApi[]
    siteProfilesLoading: boolean
    siteProposals: ContentAutopilotProposalListApi[]
    siteRuns: ContentAutopilotRunApi[]
    visibleOpportunities: ContentAutopilotOpportunityApi[]
    workspaceError: string | null
    workspaceErrors: ContentAutopilotWorkspaceErrors
    workspaceInitialized: boolean
    workspaceSettled: ContentAutopilotWorkspaceSettled
    workspaceTab: ContentAutopilotWorkspaceTab
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotLogicActions {
    beginOnboarding: () => {
        value: true
    }
    cancelOnboarding: () => {
        value: true
    }
    cancelRun: (runId: string) => string
    cancelRunFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    cancelRunSuccess: (
        runMutation: ContentAutopilotRunApi,
        payload?: string
    ) => {
        runMutation: ContentAutopilotRunApi
        payload?: string
    }
    clearOpportunitySelection: () => {
        value: true
    }
    deleteProfile: (profileId: string) => string
    deleteProfileFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteProfileSuccess: (
        deletedProfile: string,
        payload?: string
    ) => {
        deletedProfile: string
        payload?: string
    }
    discoverSite: () => any
    discoverSiteFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    discoverSiteSuccess: (
        discoveredSite: ContentAutopilotSiteDiscoveryResponseApi,
        payload?: any
    ) => {
        discoveredSite: ContentAutopilotSiteDiscoveryResponseApi
        payload?: any
    }
    dismissOpportunity: (opportunityId: string) => string
    dismissOpportunityFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    dismissOpportunitySuccess: (
        dismissedOpportunity: ContentAutopilotOpportunityApi,
        payload?: string
    ) => {
        dismissedOpportunity: ContentAutopilotOpportunityApi
        payload?: string
    }
    draftOpportunities: (opportunityIds?: string[]) => string[]
    draftOpportunitiesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    draftOpportunitiesSuccess: (
        runMutation: ContentAutopilotRunApi,
        payload?: string[]
    ) => {
        runMutation: ContentAutopilotRunApi
        payload?: string[]
    }
    exportProposal: (proposalId: string) => string
    exportProposalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    exportProposalSuccess: (
        exportedProposal: ContentAutopilotExportResponseApi,
        payload?: string
    ) => {
        exportedProposal: ContentAutopilotExportResponseApi
        payload?: string
    }
    loadOpportunities: () => {
        value: true
    }
    loadOpportunitiesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOpportunitiesSuccess: (
        opportunities: ContentAutopilotOpportunityApi[],
        payload?: {
            value: true
        }
    ) => {
        opportunities: ContentAutopilotOpportunityApi[]
        payload?: {
            value: true
        }
    }
    loadProposal: (proposalId: string) => string
    loadProposalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProposalSuccess: (
        proposalDetail: ContentAutopilotProposalApi,
        payload?: string
    ) => {
        proposalDetail: ContentAutopilotProposalApi
        payload?: string
    }
    loadProposals: () => {
        value: true
    }
    loadProposalsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProposalsSuccess: (
        proposals: ContentAutopilotProposalListApi[],
        payload?: {
            value: true
        }
    ) => {
        proposals: ContentAutopilotProposalListApi[]
        payload?: {
            value: true
        }
    }
    loadRuns: () => {
        value: true
    }
    loadRunsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRunsSuccess: (
        runs: ContentAutopilotRunApi[],
        payload?: {
            value: true
        }
    ) => {
        runs: ContentAutopilotRunApi[]
        payload?: {
            value: true
        }
    }
    loadSiteProfiles: () => {
        value: true
    }
    loadSiteProfilesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSiteProfilesSuccess: (
        siteProfiles: ContentAutopilotSiteProfileApi[],
        payload?: {
            value: true
        }
    ) => {
        siteProfiles: ContentAutopilotSiteProfileApi[]
        payload?: {
            value: true
        }
    }
    loadWorkspace: () => {
        value: true
    }
    refreshOpportunities: () => {
        value: true
    }
    refreshOpportunitiesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    refreshOpportunitiesSuccess: (
        opportunities: ContentAutopilotOpportunityApi[] | null,
        payload?: {
            value: true
        }
    ) => {
        opportunities: ContentAutopilotOpportunityApi[] | null
        payload?: {
            value: true
        }
    }
    regenerateProposal: (proposalId: string) => string
    regenerateProposalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    regenerateProposalSuccess: (
        proposalMutation: ContentAutopilotProposalApi,
        payload?: string
    ) => {
        proposalMutation: ContentAutopilotProposalApi
        payload?: string
    }
    rejectProposal: (proposalId: string) => string
    rejectProposalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    rejectProposalSuccess: (
        proposalMutation: ContentAutopilotProposalApi,
        payload?: string
    ) => {
        proposalMutation: ContentAutopilotProposalApi
        payload?: string
    }
    resetProfileDraft: (profileDraft: ContentAutopilotProfileDraft) => {
        profileDraft: ContentAutopilotProfileDraft
    }
    saveProfile: () => any
    saveProfileFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveProfileSuccess: (
        savedProfile: ContentAutopilotSiteProfileApi,
        payload?: any
    ) => {
        savedProfile: ContentAutopilotSiteProfileApi
        payload?: any
    }
    saveProposal: (proposalId: string) => string
    saveProposalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveProposalSuccess: (
        proposalMutation: ContentAutopilotProposalApi,
        payload?: string
    ) => {
        proposalMutation: ContentAutopilotProposalApi
        payload?: string
    }
    selectProfile: (profileId: string) => {
        profileId: string
    }
    selectProposal: (proposalId: string | null) => {
        proposalId: string | null
    }
    setOnboardingStep: (onboardingStep: ContentAutopilotOnboardingStep) => {
        onboardingStep: ContentAutopilotOnboardingStep
    }
    setOpportunitySearch: (opportunitySearch: string) => {
        opportunitySearch: string
    }
    setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => {
        profileDraft: Partial<ContentAutopilotProfileDraft>
    }
    setProposalTab: (proposalTab: ContentAutopilotProposalTab) => {
        proposalTab: ContentAutopilotProposalTab
    }
    setProposedMarkdown: (proposedMarkdown: string) => {
        proposedMarkdown: string
    }
    setShowDismissedOpportunities: (showDismissedOpportunities: boolean) => {
        showDismissedOpportunities: boolean
    }
    setWorkspaceTab: (workspaceTab: ContentAutopilotWorkspaceTab) => {
        workspaceTab: ContentAutopilotWorkspaceTab
    }
    startRun: () => any
    startRunFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    startRunSuccess: (
        runMutation: ContentAutopilotRunApi,
        payload?: any
    ) => {
        runMutation: ContentAutopilotRunApi
        payload?: any
    }
    toggleOpportunitySelection: (opportunityId: string) => {
        opportunityId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        profile: (
            siteProfiles: ContentAutopilotSiteProfileApi[],
            selectedProfileId: string | null
        ) => ContentAutopilotSiteProfileApi | null
        siteRuns: (runs: ContentAutopilotRunApi[]) => ContentAutopilotRunApi[]
        siteProposals: (proposals: ContentAutopilotProposalListApi[]) => ContentAutopilotProposalListApi[]
        activeRun: (siteRuns: ContentAutopilotRunApi[]) => ContentAutopilotRunApi | null
        selectedProposal: (
            proposalDetail: ContentAutopilotProposalApi | null,
            selectedProposalId: string | null
        ) => ContentAutopilotProposalApi | null
        proposalHasUnsavedChanges: (
            selectedProposal: ContentAutopilotProposalApi | null,
            proposedMarkdown: string
        ) => boolean
        opportunityProposals: (
            opportunities: ContentAutopilotOpportunityApi[] | null,
            siteProposals: ContentAutopilotProposalListApi[]
        ) => Record<string, ContentAutopilotProposalListApi>
        pagesToUpdate: (
            opportunities: ContentAutopilotOpportunityApi[] | null,
            opportunityProposals: Record<string, ContentAutopilotProposalListApi>
        ) => Record<string, ContentAutopilotPageTarget | null>
        readyDraftCount: (siteProposals: ContentAutopilotProposalListApi[]) => number
        draftRows: (
            siteProposals: ContentAutopilotProposalListApi[],
            opportunities: ContentAutopilotOpportunityApi[] | null,
            siteRuns: ContentAutopilotRunApi[]
        ) => ContentAutopilotDraftRow[]
        latestRunErrors: (siteRuns: ContentAutopilotRunApi[], activeRun: ContentAutopilotRunApi | null) => string[]
        workspaceInitialized: (workspaceSettled: ContentAutopilotWorkspaceSettled) => boolean
        profileDataLoaded: (profileDataSettled: ContentAutopilotProfileDataSettled) => boolean
        proposalActionReasons: (
            selectedProposal: ContentAutopilotProposalApi | null,
            proposalHasUnsavedChanges: boolean,
            proposalDetailLoading: boolean,
            proposalMutationLoading: boolean,
            exportedProposalLoading: boolean
        ) => ContentAutopilotProposalActionReasons
        opportunityByPromptId: (
            opportunities: ContentAutopilotOpportunityApi[] | null,
            profile: ContentAutopilotSiteProfileApi | null
        ) => Record<string, ContentAutopilotOpportunityApi>
        visibleOpportunities: (
            opportunities: ContentAutopilotOpportunityApi[] | null,
            showDismissedOpportunities: boolean,
            opportunitySearch: string
        ) => ContentAutopilotOpportunityApi[]
        dismissedOpportunityCount: (opportunities: ContentAutopilotOpportunityApi[] | null) => number
        rowDraftDisabledReason: (
            activeRun: ContentAutopilotRunApi | null,
            profileDataLoaded: boolean,
            runMutationLoading: boolean
        ) => string | undefined
        draftDisabledReason: (
            selectedOpportunityIds: string[],
            rowDraftDisabledReason: string | undefined
        ) => string | undefined
        workspaceError: (workspaceErrors: Partial<Record<ContentAutopilotWorkspaceResource, string>>) => string | null
    }
}

export type contentAutopilotLogicType = MakeLogicType<
    contentAutopilotLogicValues,
    contentAutopilotLogicActions,
    Record<string, any>,
    contentAutopilotLogicMeta
>

export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
    path(['products', 'webAnalytics', 'contentAutopilot', 'contentAutopilotLogic']),
    connect(() => ({ values: [teamLogic, ['currentTeamIdStrict']] })),
    actions({
        loadWorkspace: true,
        loadSiteProfiles: true,
        loadRuns: true,
        loadProposals: true,
        beginOnboarding: true,
        cancelOnboarding: true,
        selectProfile: (profileId: string) => ({ profileId }),
        setOnboardingStep: (onboardingStep: ContentAutopilotOnboardingStep) => ({ onboardingStep }),
        resetProfileDraft: (profileDraft: ContentAutopilotProfileDraft) => ({ profileDraft }),
        setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => ({ profileDraft }),
        selectProposal: (proposalId: string | null) => ({ proposalId }),
        setProposedMarkdown: (proposedMarkdown: string) => ({ proposedMarkdown }),
        setProposalTab: (proposalTab: ContentAutopilotProposalTab) => ({ proposalTab }),
        loadOpportunities: true,
        refreshOpportunities: true,
        toggleOpportunitySelection: (opportunityId: string) => ({ opportunityId }),
        clearOpportunitySelection: true,
        setShowDismissedOpportunities: (showDismissedOpportunities: boolean) => ({ showDismissedOpportunities }),
        setOpportunitySearch: (opportunitySearch: string) => ({ opportunitySearch }),
        setWorkspaceTab: (workspaceTab: ContentAutopilotWorkspaceTab) => ({ workspaceTab }),
    }),
    reducers({
        profileDraft: [
            EMPTY_PROFILE_DRAFT,
            {
                resetProfileDraft: (_, { profileDraft }) => profileDraft,
                setProfileDraft: (state, { profileDraft }) => ({ ...state, ...profileDraft }),
            },
        ],
        selectedProfileId: [
            null as string | null,
            {
                selectProfile: (_, { profileId }) => profileId,
                saveProfileSuccess: (_, { savedProfile }) => savedProfile.id,
                deleteProfileSuccess: () => null,
            },
        ],
        onboardingOpen: [
            false,
            {
                beginOnboarding: () => true,
                cancelOnboarding: () => false,
                saveProfileSuccess: () => false,
            },
        ],
        onboardingStep: [
            'site' as ContentAutopilotOnboardingStep,
            {
                beginOnboarding: () => 'site',
                setOnboardingStep: (_, { onboardingStep }) => onboardingStep,
                discoverSiteSuccess: () => 'sources',
            },
        ],
        selectedProposalId: [
            null as string | null,
            {
                selectProposal: (_, { proposalId }) => proposalId,
            },
        ],
        proposedMarkdown: [
            '',
            {
                setProposedMarkdown: (_, { proposedMarkdown }) => proposedMarkdown,
            },
        ],
        proposalTab: [
            'preview' as ContentAutopilotProposalTab,
            {
                selectProposal: () => 'preview',
                setProposalTab: (_, { proposalTab }) => proposalTab,
            },
        ],
        workspaceTab: [
            'overview' as ContentAutopilotWorkspaceTab,
            {
                setWorkspaceTab: (_, { workspaceTab }) => workspaceTab,
                deleteProfileSuccess: () => 'overview',
            },
        ],
        draftingOpportunityIds: [
            [] as string[],
            {
                draftOpportunities: (_, opportunityIds) => opportunityIds ?? [],
                draftOpportunitiesSuccess: () => [],
                draftOpportunitiesFailure: () => [],
            },
        ],
        opportunitySearch: [
            '',
            {
                setOpportunitySearch: (_, { opportunitySearch }) => opportunitySearch,
                selectProfile: () => '',
            },
        ],
        selectedOpportunityIds: [
            [] as string[],
            {
                toggleOpportunitySelection: (state, { opportunityId }) =>
                    state.includes(opportunityId)
                        ? state.filter((id) => id !== opportunityId)
                        : [...state, opportunityId],
                selectProfile: () => [],
                clearOpportunitySelection: () => [],
                loadOpportunitiesSuccess: (state, { opportunities }) => draftableSelection(state, opportunities),
                refreshOpportunitiesSuccess: (state, { opportunities }) =>
                    opportunities ? draftableSelection(state, opportunities) : state,
                dismissOpportunitySuccess: (state, { dismissedOpportunity }) =>
                    state.filter((id) => id !== dismissedOpportunity.id),
            },
        ],
        dismissingOpportunityId: [
            null as string | null,
            {
                dismissOpportunity: (_, opportunityId) => opportunityId,
                dismissOpportunitySuccess: () => null,
                dismissOpportunityFailure: () => null,
            },
        ],
        showDismissedOpportunities: [
            false,
            {
                setShowDismissedOpportunities: (_, { showDismissedOpportunities }) => showDismissedOpportunities,
            },
        ],
        opportunitiesError: [
            null as string | null,
            {
                loadOpportunities: () => null,
                refreshOpportunities: () => null,
                loadOpportunitiesFailure: (_, { errorObject }) => getErrorMessage(errorObject),
                refreshOpportunitiesFailure: (_, { errorObject }) => getErrorMessage(errorObject),
            },
        ],
        workspaceSettled: [
            EMPTY_WORKSPACE_SETTLED,
            {
                loadWorkspace: () => EMPTY_WORKSPACE_SETTLED,
                loadSiteProfilesSuccess: (state) => ({ ...state, profiles: true }),
                loadSiteProfilesFailure: (state) => ({ ...state, profiles: true }),
                loadRunsSuccess: (state) => ({ ...state, runs: true }),
                loadRunsFailure: (state) => ({ ...state, runs: true }),
                loadProposalsSuccess: (state) => ({ ...state, proposals: true }),
                loadProposalsFailure: (state) => ({ ...state, proposals: true }),
            },
        ],
        profileDataSettled: [
            EMPTY_PROFILE_DATA_SETTLED,
            {
                selectProfile: () => EMPTY_PROFILE_DATA_SETTLED,
                loadRunsSuccess: (state) => ({ ...state, runs: true }),
                loadRunsFailure: (state) => ({ ...state, runs: true }),
                loadProposalsSuccess: (state) => ({ ...state, proposals: true }),
                loadProposalsFailure: (state) => ({ ...state, proposals: true }),
            },
        ],
        workspaceErrors: [
            {} as ContentAutopilotWorkspaceErrors,
            {
                loadWorkspace: () => ({}),
                loadSiteProfilesSuccess: (state) => withoutWorkspaceError(state, 'profiles'),
                loadRunsSuccess: (state) => withoutWorkspaceError(state, 'runs'),
                loadProposalsSuccess: (state) => withoutWorkspaceError(state, 'proposals'),
                loadSiteProfilesFailure: (state, { errorObject }) => ({
                    ...state,
                    profiles: getErrorMessage(errorObject),
                }),
                loadRunsFailure: (state, { errorObject }) => ({
                    ...state,
                    runs: getErrorMessage(errorObject),
                }),
                loadProposalsFailure: (state, { errorObject }) => ({
                    ...state,
                    proposals: getErrorMessage(errorObject),
                }),
            },
        ],
    }),
    loaders(({ values }) => ({
        siteProfiles: [
            [] as ContentAutopilotSiteProfileApi[],
            {
                loadSiteProfiles: async (_, breakpoint) => {
                    const profiles = await fetchAllPages((offset, limit) =>
                        webAnalyticsApi.webAnalyticsContentAutopilotProfilesList(String(values.currentTeamIdStrict), {
                            limit,
                            offset,
                        })
                    )
                    breakpoint()
                    return profiles
                },
            },
        ],
        runs: [
            [] as ContentAutopilotRunApi[],
            {
                loadRuns: async (_, breakpoint) => {
                    const profile = values.profile
                    if (!profile) {
                        return []
                    }
                    const runs = await fetchAllPages((offset, limit) =>
                        webAnalyticsApi.webAnalyticsContentAutopilotRunsList(String(values.currentTeamIdStrict), {
                            limit,
                            offset,
                            profile_id: profile.id,
                        })
                    )
                    breakpoint()
                    return runs
                },
            },
        ],
        proposals: [
            [] as ContentAutopilotProposalListApi[],
            {
                loadProposals: async (_, breakpoint) => {
                    const profile = values.profile
                    if (!profile) {
                        return []
                    }
                    const proposals = await fetchAllPages((offset, limit) =>
                        webAnalyticsApi.webAnalyticsContentAutopilotProposalsList(String(values.currentTeamIdStrict), {
                            limit,
                            offset,
                            profile_id: profile.id,
                        })
                    )
                    breakpoint()
                    return proposals
                },
            },
        ],
        opportunities: [
            null as ContentAutopilotOpportunityApi[] | null,
            {
                loadOpportunities: async (_, breakpoint) => {
                    const profile = values.profile
                    if (!profile) {
                        return []
                    }
                    const opportunities = await fetchOpportunities(String(values.currentTeamIdStrict), profile.id)
                    breakpoint()
                    return opportunities
                },
                refreshOpportunities: async (_, breakpoint) => {
                    const profile = values.profile
                    if (!profile) {
                        return []
                    }
                    const teamId = String(values.currentTeamIdStrict)
                    await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesRefresh(teamId, {
                        profile_id: profile.id,
                    })
                    breakpoint()
                    const opportunities = await fetchOpportunities(teamId, profile.id)
                    breakpoint()
                    return values.profile?.id === profile.id ? opportunities : values.opportunities
                },
            },
        ],
        dismissedOpportunity: [
            null as ContentAutopilotOpportunityApi | null,
            {
                dismissOpportunity: async (opportunityId: string) =>
                    await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesDismiss(
                        String(values.currentTeamIdStrict),
                        opportunityId
                    ),
            },
        ],
        proposalDetail: [
            null as ContentAutopilotProposalApi | null,
            {
                loadProposal: async (proposalId: string, breakpoint) => {
                    const proposal = await webAnalyticsApi.webAnalyticsContentAutopilotProposalsRetrieve(
                        String(values.currentTeamIdStrict),
                        proposalId
                    )
                    breakpoint()
                    return proposal
                },
            },
        ],
        discoveredSite: [
            null as ContentAutopilotSiteDiscoveryResponseApi | null,
            {
                discoverSite: async () =>
                    await webAnalyticsApi.webAnalyticsContentAutopilotProfilesDiscover(
                        String(values.currentTeamIdStrict),
                        {
                            domain: values.profileDraft.domain.trim(),
                        }
                    ),
            },
        ],
        savedProfile: [
            null as ContentAutopilotSiteProfileApi | null,
            {
                saveProfile: async () => {
                    const payload = {
                        name: values.profileDraft.name.trim(),
                        domain: values.profileDraft.domain.trim(),
                        source_urls: splitLines(values.profileDraft.sourceUrls),
                        content_boundaries: splitLines(values.profileDraft.contentBoundaries),
                        brand_rules: splitLines(values.profileDraft.brandRules),
                    }
                    const profile = values.onboardingOpen ? null : values.profile
                    if (profile) {
                        return await webAnalyticsApi.webAnalyticsContentAutopilotProfilesPartialUpdate(
                            String(values.currentTeamIdStrict),
                            profile.id,
                            payload
                        )
                    }
                    return await webAnalyticsApi.webAnalyticsContentAutopilotProfilesCreate(
                        String(values.currentTeamIdStrict),
                        payload
                    )
                },
            },
        ],
        deletedProfile: [
            null as string | null,
            {
                deleteProfile: async (profileId: string) => {
                    await webAnalyticsApi.webAnalyticsContentAutopilotProfilesDestroy(
                        String(values.currentTeamIdStrict),
                        profileId
                    )
                    return profileId
                },
            },
        ],
        runMutation: [
            null as ContentAutopilotRunApi | null,
            {
                startRun: async () => {
                    if (!values.profile) {
                        throw new Error('Select a site before starting a content run')
                    }
                    return await webAnalyticsApi.webAnalyticsContentAutopilotRunsStart(
                        String(values.currentTeamIdStrict),
                        {
                            profile_id: values.profile.id,
                        }
                    )
                },
                // Without ids, drafts the opportunities selected in the table.
                draftOpportunities: async (opportunityIds?: string[]) => {
                    if (!values.profile) {
                        throw new Error('Select a site before drafting content')
                    }
                    return await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesDraft(
                        String(values.currentTeamIdStrict),
                        {
                            profile_id: values.profile.id,
                            opportunity_ids: opportunityIds ?? values.selectedOpportunityIds,
                        }
                    )
                },
                cancelRun: async (runId: string) =>
                    await webAnalyticsApi.webAnalyticsContentAutopilotRunsCancel(
                        String(values.currentTeamIdStrict),
                        runId
                    ),
            },
        ],
        proposalMutation: [
            null as ContentAutopilotProposalApi | null,
            {
                rejectProposal: async (proposalId: string) =>
                    await webAnalyticsApi.webAnalyticsContentAutopilotProposalsReject(
                        String(values.currentTeamIdStrict),
                        proposalId
                    ),
                regenerateProposal: async (proposalId: string) =>
                    await webAnalyticsApi.webAnalyticsContentAutopilotProposalsRegenerate(
                        String(values.currentTeamIdStrict),
                        proposalId
                    ),
                saveProposal: async (proposalId: string) => {
                    const proposal = values.selectedProposal?.id === proposalId ? values.selectedProposal : null
                    if (!proposal) {
                        throw new Error('Proposal not found')
                    }
                    return await webAnalyticsApi.webAnalyticsContentAutopilotProposalsEdit(
                        String(values.currentTeamIdStrict),
                        proposalId,
                        {
                            proposed_markdown: values.proposedMarkdown,
                            content_package: proposal.content_package,
                        }
                    )
                },
            },
        ],
        exportedProposal: [
            null as ContentAutopilotExportResponseApi | null,
            {
                exportProposal: async (proposalId: string) => {
                    if (values.selectedProposalId === proposalId && values.proposalHasUnsavedChanges) {
                        throw new Error('Save or discard your changes before downloading this draft')
                    }
                    const exported = await webAnalyticsApi.webAnalyticsContentAutopilotProposalsExport(
                        String(values.currentTeamIdStrict),
                        proposalId
                    )
                    downloadBlob(new Blob([exported.markdown], { type: 'text/markdown' }), exported.filename)
                    return exported
                },
            },
        ],
    })),
    reducers({
        runs: [[] as ContentAutopilotRunApi[], { selectProfile: () => [] }],
        proposals: [[] as ContentAutopilotProposalListApi[], { selectProfile: () => [] }],
        opportunities: [
            null as ContentAutopilotOpportunityApi[] | null,
            {
                selectProfile: () => null,
                dismissOpportunitySuccess: (state, { dismissedOpportunity }) =>
                    state?.map((opportunity) =>
                        opportunity.id === dismissedOpportunity.id ? dismissedOpportunity : opportunity
                    ) ?? null,
            },
        ],
    }),
    selectors({
        profile: [
            (selectors) => [selectors.siteProfiles, selectors.selectedProfileId],
            (
                siteProfiles: ContentAutopilotSiteProfileApi[],
                selectedProfileId: string | null
            ): ContentAutopilotSiteProfileApi | null =>
                siteProfiles.find(({ id }) => id === selectedProfileId) ?? siteProfiles[0] ?? null,
        ],
        siteRuns: [(selectors) => [selectors.runs], (runs: ContentAutopilotRunApi[]): ContentAutopilotRunApi[] => runs],
        siteProposals: [
            (selectors) => [selectors.proposals],
            (proposals: ContentAutopilotProposalListApi[]): ContentAutopilotProposalListApi[] => proposals,
        ],
        activeRun: [
            (selectors) => [selectors.siteRuns],
            (runs: ContentAutopilotRunApi[]): ContentAutopilotRunApi | null =>
                runs.find(({ run_status }) => run_status === 'pending' || run_status === 'generating') ?? null,
        ],
        selectedProposal: [
            (selectors) => [selectors.proposalDetail, selectors.selectedProposalId],
            (
                proposalDetail: ContentAutopilotProposalApi | null,
                selectedProposalId: string | null
            ): ContentAutopilotProposalApi | null =>
                proposalDetail?.id === selectedProposalId ? proposalDetail : null,
        ],
        proposalHasUnsavedChanges: [
            (selectors) => [selectors.selectedProposal, selectors.proposedMarkdown],
            (selectedProposal: ContentAutopilotProposalApi | null, proposedMarkdown: string): boolean =>
                selectedProposal !== null && proposedMarkdown !== selectedProposal.proposed_markdown,
        ],
        opportunityProposals: [
            (selectors) => [selectors.opportunities, selectors.siteProposals],
            (
                opportunities: ContentAutopilotOpportunityApi[] | null,
                proposals: ContentAutopilotProposalListApi[]
            ): Record<string, ContentAutopilotProposalListApi> => {
                const proposalsById = new Map(proposals.map((proposal) => [proposal.id, proposal]))
                return Object.fromEntries(
                    (opportunities ?? []).flatMap((opportunity) => {
                        const proposal = opportunity.proposal_id
                            ? proposalsById.get(opportunity.proposal_id)
                            : undefined
                        return proposal ? [[opportunity.id, proposal]] : []
                    })
                )
            },
        ],
        pagesToUpdate: [
            (selectors) => [selectors.opportunities, selectors.opportunityProposals],
            (
                opportunities: ContentAutopilotOpportunityApi[] | null,
                opportunityProposals: Record<string, ContentAutopilotProposalListApi>
            ): Record<string, ContentAutopilotPageTarget | null> =>
                Object.fromEntries(
                    (opportunities ?? []).map((opportunity) => [
                        opportunity.id,
                        pageToUpdate(opportunity, opportunityProposals[opportunity.id]),
                    ])
                ),
        ],
        readyDraftCount: [
            (selectors) => [selectors.siteProposals],
            (proposals: ContentAutopilotProposalListApi[]): number =>
                proposals.filter(({ lifecycle_status }) => lifecycle_status === 'ready_for_review').length,
        ],
        draftRows: [
            (selectors) => [selectors.siteProposals, selectors.opportunities, selectors.siteRuns],
            (
                proposals: ContentAutopilotProposalListApi[],
                opportunities: ContentAutopilotOpportunityApi[] | null,
                runs: ContentAutopilotRunApi[]
            ): ContentAutopilotDraftRow[] => [
                ...[...proposals]
                    .sort((a, b) => REVIEW_ORDER[a.lifecycle_status] - REVIEW_ORDER[b.lifecycle_status])
                    .map(
                        (proposal): ContentAutopilotDraftRow => ({
                            id: proposal.id,
                            title: proposal.title,
                            question: proposal.target_query,
                            isNewPage: proposal.proposal_type === 'new_content',
                            path: proposalPagePath(proposal),
                            updatedAt: proposal.updated_at,
                            proposal,
                        })
                    ),
                ...(opportunities ?? [])
                    .filter(
                        ({ status, proposal_id, run_id }) =>
                            status === 'queued' &&
                            !runs.some(
                                ({ id, run_status }) =>
                                    id === run_id && run_status !== 'pending' && run_status !== 'generating'
                            ) &&
                            !proposals.some(
                                ({ id, run_id: proposalRunId }) => id === proposal_id && proposalRunId === run_id
                            )
                    )
                    .map(
                        (opportunity): ContentAutopilotDraftRow => ({
                            id: opportunity.id,
                            title: opportunity.title,
                            question: '',
                            isNewPage: opportunity.recommended_type === 'new_content',
                            path: opportunity.target_url
                                ? (parseWebAnalyticsURL(opportunity.target_url).pathname ?? '')
                                : '',
                            updatedAt: opportunity.updated_at,
                            proposal: null,
                        })
                    ),
            ],
        ],
        latestRunErrors: [
            (selectors) => [selectors.siteRuns, selectors.activeRun],
            (runs: ContentAutopilotRunApi[], activeRun: ContentAutopilotRunApi | null): string[] =>
                activeRun || !runs[0]
                    ? []
                    : runs[0].errors
                          .filter(({ error_code }) => !DRAFT_ERROR_CODES.has(error_code))
                          .map(({ message }) => message),
        ],
        workspaceInitialized: [
            (selectors) => [selectors.workspaceSettled],
            (workspaceSettled: ContentAutopilotWorkspaceSettled): boolean =>
                Object.values(workspaceSettled).every(Boolean),
        ],
        profileDataLoaded: [
            (selectors) => [selectors.profileDataSettled],
            (profileDataSettled: ContentAutopilotProfileDataSettled): boolean =>
                Object.values(profileDataSettled).every(Boolean),
        ],
        proposalActionReasons: [
            (selectors) => [
                selectors.selectedProposal,
                selectors.proposalHasUnsavedChanges,
                selectors.proposalDetailLoading,
                selectors.proposalMutationLoading,
                selectors.exportedProposalLoading,
            ],
            (
                selectedProposal: ContentAutopilotProposalApi | null,
                proposalHasUnsavedChanges: boolean,
                proposalDetailLoading: boolean,
                proposalMutationLoading: boolean,
                exportedProposalLoading: boolean
            ): ContentAutopilotProposalActionReasons => {
                if (!selectedProposal) {
                    return {}
                }
                const readyForReview = selectedProposal.lifecycle_status === 'ready_for_review'
                const exportInFlight = exportedProposalLoading ? 'Wait for the download to finish' : undefined
                const unsavedChanges = proposalHasUnsavedChanges ? 'Save or discard your changes first' : undefined
                return {
                    reject:
                        (!readyForReview ? 'Only a draft ready for review can be rejected' : undefined) ??
                        exportInFlight ??
                        unsavedChanges,
                    regenerate:
                        (!readyForReview && selectedProposal.lifecycle_status !== 'failed'
                            ? 'Only drafts ready for review or failed can be regenerated'
                            : undefined) ??
                        exportInFlight ??
                        unsavedChanges,
                    save:
                        (!readyForReview ? 'Only a draft ready for review can be edited' : undefined) ??
                        (proposalDetailLoading ? 'Wait for the proposal to load' : undefined) ??
                        exportInFlight ??
                        (!proposalHasUnsavedChanges ? 'No unsaved changes' : undefined),
                    exportMarkdown:
                        (!selectedProposal.validation_report.passed
                            ? 'Fix the checks marked Must fix first'
                            : undefined) ??
                        (!readyForReview ? 'Only a draft ready for review can be downloaded' : undefined) ??
                        (proposalHasUnsavedChanges ? 'Save or discard your changes before downloading' : undefined) ??
                        (proposalMutationLoading ? 'Wait for your changes to save' : undefined),
                }
            },
        ],
        opportunityByPromptId: [
            (selectors) => [selectors.opportunities, selectors.profile],
            (
                opportunities: ContentAutopilotOpportunityApi[] | null,
                profile: ContentAutopilotSiteProfileApi | null
            ): Record<string, ContentAutopilotOpportunityApi> =>
                Object.fromEntries(
                    (opportunities ?? []).flatMap((opportunity) =>
                        // Opportunities of a deleted or unselected site must not offer drafts.
                        opportunity.aeo_prompt_id && opportunity.profile_id === profile?.id
                            ? [[opportunity.aeo_prompt_id, opportunity]]
                            : []
                    )
                ),
        ],
        visibleOpportunities: [
            (selectors) => [selectors.opportunities, selectors.showDismissedOpportunities, selectors.opportunitySearch],
            (
                opportunities: ContentAutopilotOpportunityApi[] | null,
                showDismissedOpportunities: boolean,
                opportunitySearch: string
            ): ContentAutopilotOpportunityApi[] => {
                const search = opportunitySearch.trim().toLowerCase()
                return (opportunities ?? []).filter(
                    ({ status, title }) =>
                        (showDismissedOpportunities || status !== 'dismissed') &&
                        (!search || title.toLowerCase().includes(search))
                )
            },
        ],
        dismissedOpportunityCount: [
            (selectors) => [selectors.opportunities],
            (opportunities: ContentAutopilotOpportunityApi[] | null): number =>
                (opportunities ?? []).filter(({ status }) => status === 'dismissed').length,
        ],
        rowDraftDisabledReason: [
            (selectors) => [selectors.activeRun, selectors.profileDataLoaded, selectors.runMutationLoading],
            (
                activeRun: ContentAutopilotRunApi | null,
                profileDataLoaded: boolean,
                runMutationLoading: boolean
            ): string | undefined => {
                if (!profileDataLoaded) {
                    return 'Wait for this site to finish loading'
                }
                if (activeRun || runMutationLoading) {
                    return 'Wait for the current run to finish'
                }
                return undefined
            },
        ],
        draftDisabledReason: [
            (selectors) => [selectors.selectedOpportunityIds, selectors.rowDraftDisabledReason],
            (selectedOpportunityIds: string[], rowDraftDisabledReason: string | undefined): string | undefined => {
                if (rowDraftDisabledReason) {
                    return rowDraftDisabledReason
                }
                if (selectedOpportunityIds.length === 0) {
                    return 'Select at least one opportunity'
                }
                if (selectedOpportunityIds.length > MAX_DRAFTS_PER_RUN) {
                    return `Select up to ${MAX_DRAFTS_PER_RUN} opportunities`
                }
                return undefined
            },
        ],
        workspaceError: [
            (selectors) => [selectors.workspaceErrors],
            (workspaceErrors: ContentAutopilotWorkspaceErrors): string | null =>
                Object.values(workspaceErrors).join(' ') || null,
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        loadWorkspace: () => {
            actions.loadSiteProfiles()
        },
        beginOnboarding: () => {
            actions.resetProfileDraft(EMPTY_PROFILE_DRAFT)
        },
        cancelOnboarding: () => {
            if (values.profile) {
                actions.resetProfileDraft(draftFromProfile(values.profile))
            }
        },
        selectProfile: ({ profileId }) => {
            const profile = values.siteProfiles.find(({ id }) => id === profileId)
            if (profile) {
                actions.resetProfileDraft(draftFromProfile(profile))
            }
            actions.selectProposal(null)
            actions.loadRuns()
            actions.loadProposals()
            cache.refreshOpportunitiesAfterLoad = true
            actions.loadOpportunities()
        },
        loadOpportunitiesSuccess: ({ opportunities }) => {
            if (cache.refreshOpportunitiesAfterLoad) {
                const profileChanged = cache.profileChanged
                cache.refreshOpportunitiesAfterLoad = false
                cache.profileChanged = false
                if (profileChanged || opportunitiesNeedRefresh(opportunities, Date.now())) {
                    actions.refreshOpportunities()
                }
            }
        },
        loadSiteProfilesSuccess: () => {
            if (values.profile) {
                actions.selectProfile(values.profile.id)
            } else {
                actions.beginOnboarding()
                actions.loadRunsSuccess([])
                actions.loadProposalsSuccess([])
            }
        },
        loadSiteProfilesFailure: () => {
            actions.loadRunsSuccess([])
            actions.loadProposalsSuccess([])
        },
        discoverSiteSuccess: ({ discoveredSite }) => {
            actions.setProfileDraft({
                name: discoveredSite.name,
                domain: discoveredSite.domain,
                sourceUrls: discoveredSite.source_urls.join('\n'),
                contentBoundaries: discoveredSite.content_boundaries.join('\n'),
            })
        },
        discoverSiteFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        selectProposal: ({ proposalId }) => {
            actions.setProposedMarkdown('')
            if (proposalId) {
                actions.loadProposal(proposalId)
            }
        },
        loadProposalSuccess: ({ proposalDetail }) => {
            if (proposalDetail.id === values.selectedProposalId) {
                actions.setProposedMarkdown(proposalDetail.proposed_markdown)
            }
        },
        loadProposalFailure: ({ errorObject }) => {
            toastClientError(errorObject)
            actions.selectProposal(null)
        },
        saveProfileSuccess: ({ savedProfile }) => {
            lemonToast.success('Site profile saved')
            actions.resetProfileDraft(draftFromProfile(savedProfile))
            cache.profileChanged = true
            actions.loadSiteProfiles()
        },
        saveProfileFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        deleteProfileSuccess: () => {
            lemonToast.success('Site deleted')
            actions.selectProposal(null)
            actions.loadSiteProfiles()
        },
        deleteProfileFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        dismissOpportunityFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        draftOpportunitiesSuccess: ({ runMutation, payload }) => {
            if (runMutation.profile_id !== values.profile?.id) {
                return
            }
            if (!payload) {
                actions.clearOpportunitySelection()
            }
            if (!payload || values.workspaceTab === 'opportunities') {
                actions.setWorkspaceTab('drafts')
            } else {
                // Drafting from a prompt keeps the user where they are.
                lemonToast.success('Drafting started.', {
                    button: { label: 'View drafts', action: () => actions.setWorkspaceTab('drafts') },
                })
            }
            actions.loadRuns()
            actions.loadOpportunities()
        },
        draftOpportunitiesFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        startRunSuccess: () => {
            lemonToast.success('Content run started')
            actions.loadRuns()
        },
        cancelRunSuccess: () => {
            lemonToast.success('Content run canceled')
            actions.loadRuns()
            actions.loadOpportunities()
        },
        cancelRunFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        startRunFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        rejectProposalSuccess: () => {
            lemonToast.success('Proposal rejected')
            actions.selectProposal(null)
            actions.loadProposals()
        },
        rejectProposalFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        regenerateProposalSuccess: () => {
            lemonToast.success('Proposal queued for regeneration')
            actions.selectProposal(null)
            actions.loadProposals()
        },
        regenerateProposalFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        saveProposalSuccess: () => {
            lemonToast.success('Changes saved and queued for validation')
            actions.selectProposal(null)
            actions.loadProposals()
        },
        saveProposalFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
        exportProposalSuccess: () => {
            lemonToast.success('Draft downloaded')
            actions.loadProposals()
        },
        exportProposalFailure: ({ errorObject }) => {
            toastClientError(errorObject)
        },
    })),
    afterMount(({ actions, cache, values }) => {
        actions.loadWorkspace()
        cache.disposables.add(() => {
            const pollTimer = window.setInterval(() => {
                const isProcessing =
                    values.activeRun !== null ||
                    values.siteProposals.some(({ lifecycle_status }) => lifecycle_status === 'generating')
                if (!isProcessing) {
                    return
                }
                if (values.runsLoading || values.proposalsLoading) {
                    return
                }
                actions.loadRuns()
                actions.loadProposals()
                if (!values.opportunitiesLoading) {
                    actions.loadOpportunities()
                }
            }, WORKSPACE_POLL_INTERVAL_MS)
            return () => clearInterval(pollTimer)
        }, 'workspacePoll')
    }),
])