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.

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

import { ApiError } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import {
    aeoPromptsBulkImport,
    aeoPromptsSuggest,
    aeoPromptsSuggestionRetrieve,
} from 'products/web_analytics/frontend/generated/api'
import type {
    AEOPromptImportResultApi,
    AEOPromptSuggestionApi,
    AEOPromptSuggestionJobApi,
    ContentAutopilotSiteProfileApi,
} from 'products/web_analytics/frontend/generated/api.schemas'

import { contentAutopilotLogic } from './contentAutopilotLogic'
import { contentAutopilotPromptsLogic } from './contentAutopilotPromptsLogic'

export const SUGGESTION_POLL_INTERVAL_MS = 3000
export const SUGGESTION_COUNTS = [10, 20, 30, 50]
const MAX_POLL_FAILURES = 5

export interface PromptSuggestionJobRef {
    id: string
    teamId: number | string
    // Optional because a reference stored before these fields existed lacks them.
    domain?: string
    startedAt?: number
}

// The server marks a lost job failed after 8 minutes; this is the fallback if that answer never arrives.
const CLIENT_JOB_DEADLINE_MS = 10 * 60 * 1000

export interface PromptSuggestionForm {
    domain: string
    brand: string
    description: string
    competitors: string[]
    topics: string[]
    count: number
}

const EMPTY_FORM: PromptSuggestionForm = {
    domain: '',
    brand: '',
    description: '',
    competitors: [],
    topics: [],
    count: 20,
}

export const siteDomain = (input: string): string => {
    const value = input.trim()
    if (!value) {
        return ''
    }
    try {
        return new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(value) ? value : `https://${value}`).hostname.replace(/\.$/, '')
    } catch {
        return value
    }
}

const startErrorMessage = (error: unknown): string =>
    error instanceof ApiError && error.status && error.status < 500 && error.detail
        ? error.detail
        : "Couldn't start the suggestions. Try again."

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotPromptSuggestionsLogicValues {
    profile: ContentAutopilotSiteProfileApi | null // contentAutopilotLogic
    currentTeamIdStrict: number | string // teamLogic
    adding: boolean
    editingInputs: boolean
    form: PromptSuggestionForm
    job: AEOPromptSuggestionJobApi | null
    jobRef: PromptSuggestionJobRef | null
    selectedPrompts: string[]
    selectedSuggestions: AEOPromptSuggestionApi[]
    startError: string | null
    starting: boolean
    suggestOpen: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotPromptSuggestionsLogicActions {
    addPromptsSuccess: (result: AEOPromptImportResultApi) => {
        result: AEOPromptImportResultApi
    } // contentAutopilotPromptsLogic
    addSelected: () => {
        value: true
    }
    addSelectedFailure: () => {
        value: true
    }
    addSelectedSuccess: () => {
        value: true
    }
    backToSuggestions: () => {
        value: true
    }
    closeSuggest: () => {
        value: true
    }
    editRequest: () => {
        value: true
    }
    loadJob: () => {
        value: true
    }
    openSuggest: () => {
        value: true
    }
    resumeJob: () => {
        value: true
    }
    setForm: (form: Partial<PromptSuggestionForm>) => {
        form: Partial<PromptSuggestionForm>
    }
    setJob: (job: AEOPromptSuggestionJobApi) => {
        job: AEOPromptSuggestionJobApi
    }
    setJobRef: (jobRef: PromptSuggestionJobRef | null) => {
        jobRef: PromptSuggestionJobRef | null
    }
    setSelectedPrompts: (prompts: string[]) => {
        prompts: string[]
    }
    startSuggestions: () => {
        value: true
    }
    startSuggestionsFailure: (error: string) => {
        error: string
    }
    toggleSuggestion: (prompt: string) => {
        prompt: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface contentAutopilotPromptSuggestionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        selectedSuggestions: (
            job: AEOPromptSuggestionJobApi | null,
            selectedPrompts: string[]
        ) => AEOPromptSuggestionApi[]
    }
}

export type contentAutopilotPromptSuggestionsLogicType = MakeLogicType<
    contentAutopilotPromptSuggestionsLogicValues,
    contentAutopilotPromptSuggestionsLogicActions,
    Record<string, any>,
    contentAutopilotPromptSuggestionsLogicMeta
>

export const contentAutopilotPromptSuggestionsLogic = kea<contentAutopilotPromptSuggestionsLogicType>([
    path(['products', 'webAnalytics', 'contentAutopilot', 'contentAutopilotPromptSuggestionsLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamIdStrict'], contentAutopilotLogic, ['profile']],
        actions: [contentAutopilotPromptsLogic, ['addPromptsSuccess']],
    })),
    actions({
        openSuggest: true,
        closeSuggest: true,
        setForm: (form: Partial<PromptSuggestionForm>) => ({ form }),
        startSuggestions: true,
        startSuggestionsFailure: (error: string) => ({ error }),
        setJobRef: (jobRef: PromptSuggestionJobRef | null) => ({ jobRef }),
        setJob: (job: AEOPromptSuggestionJobApi) => ({ job }),
        loadJob: true,
        editRequest: true,
        backToSuggestions: true,
        resumeJob: true,
        toggleSuggestion: (prompt: string) => ({ prompt }),
        setSelectedPrompts: (prompts: string[]) => ({ prompts }),
        addSelected: true,
        addSelectedSuccess: true,
        addSelectedFailure: true,
    }),
    reducers({
        suggestOpen: [
            false,
            {
                openSuggest: () => true,
                closeSuggest: () => false,
                addSelectedSuccess: () => false,
            },
        ],
        form: [
            EMPTY_FORM,
            {
                setForm: (state, { form }) => ({ ...state, ...form }),
            },
        ],
        // Only a reference to the job is kept, so a job started before leaving the page can be read again.
        jobRef: [
            null as PromptSuggestionJobRef | null,
            { persist: true },
            {
                setJobRef: (_, { jobRef }) => jobRef,
                addSelectedSuccess: () => null,
            },
        ],
        job: [
            null as AEOPromptSuggestionJobApi | null,
            {
                setJob: (_, { job }) => job,
                addSelectedSuccess: () => null,
            },
        ],
        // Editing the inputs keeps the current suggestions until a new request replaces them.
        editingInputs: [
            false,
            {
                editRequest: () => true,
                backToSuggestions: () => false,
                setJobRef: () => false,
                addSelectedSuccess: () => false,
            },
        ],
        starting: [
            false,
            {
                startSuggestions: () => true,
                setJob: () => false,
                startSuggestionsFailure: () => false,
            },
        ],
        startError: [
            null as string | null,
            {
                startSuggestions: () => null,
                startSuggestionsFailure: (_, { error }) => error,
                backToSuggestions: () => null,
            },
        ],
        selectedPrompts: [
            [] as string[],
            {
                setSelectedPrompts: (_, { prompts }) => prompts,
                toggleSuggestion: (state, { prompt }) =>
                    state.includes(prompt) ? state.filter((p) => p !== prompt) : [...state, prompt],
                startSuggestions: () => [],
                addSelectedSuccess: () => [],
            },
        ],
        adding: [
            false,
            {
                addSelected: () => true,
                addSelectedSuccess: () => false,
                addSelectedFailure: () => false,
            },
        ],
    }),
    selectors({
        selectedSuggestions: [
            (s) => [s.job, s.selectedPrompts],
            (job: AEOPromptSuggestionJobApi | null, selectedPrompts: string[]): AEOPromptSuggestionApi[] =>
                (job?.suggestions ?? []).filter(({ prompt }) => selectedPrompts.includes(prompt)),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        openSuggest: () => {
            // pinned: analytics event name, renaming it breaks dashboards
            posthog.capture('web analytics content autopilot prompt suggestions opened')
            if (!values.form.domain && values.profile) {
                actions.setForm({ domain: siteDomain(values.profile.domain), brand: values.profile.name ?? '' })
            }
        },
        startSuggestions: async () => {
            const { form } = values
            const domain = siteDomain(form.domain)
            try {
                const job = await aeoPromptsSuggest(String(values.currentTeamIdStrict), {
                    domain,
                    brand: form.brand.trim(),
                    description: form.description.trim(),
                    competitors: form.competitors,
                    topics: form.topics,
                    count: form.count,
                })
                // pinned: analytics event name, renaming it breaks dashboards
                posthog.capture('web analytics content autopilot prompt suggestions started', { count: form.count })
                cache.pollFailures = 0
                actions.setJobRef({ id: job.id, teamId: values.currentTeamIdStrict, domain, startedAt: Date.now() })
                actions.setJob(job)
            } catch (error) {
                actions.startSuggestionsFailure(startErrorMessage(error))
            }
        },
        setJob: ({ job }) => {
            if (job.status === 'pending') {
                cache.pollingJobId = job.id
                actions.resumeJob()
                return
            }
            cache.disposables.dispose('suggestionPoll')
            if (job.status === 'completed' && values.selectedPrompts.length === 0) {
                actions.setSelectedPrompts(job.suggestions.map(({ prompt }) => prompt))
            }
            // Only a job this page watched finish counts, so restoring a finished job reports nothing.
            if (cache.pollingJobId !== job.id) {
                return
            }
            cache.pollingJobId = null
            if (job.status === 'completed') {
                // pinned: analytics event name, renaming it breaks dashboards
                posthog.capture('web analytics content autopilot prompt suggestions completed', {
                    suggestions: job.suggestions.length,
                })
            }
            // With the dialog closed, the result would otherwise go unnoticed.
            if (!values.suggestOpen) {
                if (job.status === 'completed') {
                    lemonToast.success(
                        job.suggestions.length
                            ? `${job.suggestions.length} prompt suggestions are ready.`
                            : 'Prompt suggestions finished with no new prompts.',
                        { button: { label: 'Review', action: () => actions.openSuggest() } }
                    )
                } else {
                    lemonToast.error(job.error || "Couldn't suggest prompts. Try again.")
                }
            }
        },
        resumeJob: () => {
            cache.disposables.add(() => {
                const id = setInterval(() => actions.loadJob(), SUGGESTION_POLL_INTERVAL_MS)
                return () => clearInterval(id)
            }, 'suggestionPoll')
        },
        loadJob: async () => {
            const jobRef = values.jobRef
            const jobId = jobRef?.id
            // Polls never overlap, so a slow response cannot be overtaken and miscounted as a failure.
            if (!jobId || cache.pollInFlight) {
                return
            }
            if (jobRef?.startedAt && Date.now() - jobRef.startedAt > CLIENT_JOB_DEADLINE_MS) {
                actions.setJob({
                    id: jobId,
                    status: 'failed',
                    suggestions: [],
                    error: 'Prompt suggestions stopped before they finished. Try again.',
                })
                return
            }
            cache.pollInFlight = true
            try {
                const job = await aeoPromptsSuggestionRetrieve(String(values.currentTeamIdStrict), jobId)
                cache.pollFailures = 0
                // A job the user replaced with a new request must not overwrite it.
                if (
                    !cache.disposables.isDisposed &&
                    job.id === values.jobRef?.id &&
                    job.status !== values.job?.status
                ) {
                    actions.setJob(job)
                }
            } catch (error) {
                if (cache.disposables.isDisposed || values.jobRef?.id !== jobId) {
                    return
                }
                const expired = error instanceof ApiError && error.status === 404
                cache.pollFailures = (cache.pollFailures ?? 0) + 1
                if (expired || cache.pollFailures >= MAX_POLL_FAILURES) {
                    cache.pollFailures = 0
                    actions.setJob({
                        id: jobId,
                        status: 'failed',
                        suggestions: [],
                        error: expired
                            ? 'These suggestions expired. Start again to get new ones.'
                            : "Couldn't load the suggestions.",
                    })
                }
            } finally {
                cache.pollInFlight = false
            }
        },
        addSelected: async () => {
            const selected = values.selectedSuggestions
            const suggested = values.job?.suggestions.length ?? 0
            const teamId = String(values.currentTeamIdStrict)
            let result: AEOPromptImportResultApi
            try {
                result = await aeoPromptsBulkImport(teamId, {
                    prompts: selected.map(({ prompt, topic }) => ({ prompt, topic, origin: 'suggestion' })),
                })
            } catch (error) {
                if (!cache.disposables.isDisposed) {
                    actions.addSelectedFailure()
                    // A 400 explains why the import was refused, so show it rather than asking for a retry.
                    const detail = error instanceof ApiError && error.status === 400 ? error.detail : null
                    lemonToast.error(detail || "Couldn't add the prompts. Try again.")
                }
                return
            }
            // pinned: analytics event name, renaming it breaks dashboards
            posthog.capture('web analytics content autopilot prompt suggestions added', {
                added: selected.length,
                suggested,
            })
            if (!cache.disposables.isDisposed) {
                actions.addSelectedSuccess()
                // Reuses the import toast, and reloads the list, topics and overview.
                actions.addPromptsSuccess(result)
            }
        },
    })),
    afterMount(({ actions, values }) => {
        const { jobRef } = values
        if (!jobRef) {
            return
        }
        // A stored job from another project cannot be read here.
        if (String(jobRef.teamId) !== String(values.currentTeamIdStrict)) {
            actions.setJobRef(null)
            return
        }
        // Polling, not a single read, so a failed first read is retried like any other poll.
        actions.loadJob()
        actions.resumeJob()
    }),
])