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.

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

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

import { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { isUUIDLike } from 'lib/utils/guards'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

import { wizardRunsPartialUpdate, wizardRunsRetrieve } from '../generated/api'
import type { WizardRunApi, WizardRunArtifactApi, WizardRunGitDiffArtifactApi } from '../generated/api.schemas'
import { wizardRunEventProperties } from '../lib/wizardAnalytics'
import { loadWizardRunArtifactContent, loadWizardRunArtifacts } from '../lib/wizardApi'
import { wizardRunDiffCanRender, wizardRunIsActive } from '../lib/wizardRunDisplay'
import { wizardRunsLogic } from './wizardRunsLogic'

const RUN_DETAIL_POLL_INTERVAL_MS = 10_000

type WizardRunDiffContent = {
    artifactId: string
    content: string
}

export type WizardRunDetailSource =
    | 'fab_click'
    | 'fab_expand_icon_click'
    | 'wizard_datatable'
    | 'wizard_library'
    | 'wizard_sidebar'
export type WizardRunArtifactSource = 'button' | 'artifacts_section'
export type WizardRunIdLocation = 'bottom_button' | 'run_id_label'

function requestError(error: unknown, fallback: string): string {
    return error instanceof ApiError && error.detail ? error.detail : fallback
}

// Rethrows the original error only when the request is still current; a superseded
// rejection must not dispatch a failure action against newer data.
async function rejectUnlessCurrent(breakpoint: BreakPointFunction, error: unknown): Promise<never> {
    await breakpoint()
    throw error
}

export interface wizardRunDetailsLogicValues {
    currentProjectId: number | null
    artifactRunIdsLoaded: string[]
    cancelRunRequest: WizardRunApi | null
    cancelRunRequestLoading: boolean
    runArtifacts: WizardRunArtifactApi[]
    runArtifactsError: string | null
    runArtifactsLoading: boolean
    runDetails: WizardRunApi | null
    runDetailsError: string | null
    runDetailsLoading: boolean
    runDiff: WizardRunDiffContent | null
    runDiffError: string | null
    runDiffLoading: boolean
    selectedRun: WizardRunApi | null
    selectedRunArtifacts: WizardRunArtifactApi[]
    selectedRunArtifactsInitialLoading: boolean
    selectedRunDiffArtifactId: string | null
    selectedRunDiffContent: string | null
    selectedRunId: string | null
    selectedRunSummary: WizardRunApi | null
}

export interface wizardRunDetailsLogicActions {
    openLinkedRun: (runId: string) => { runId: string }
    cancelRun: (run: WizardRunApi) => { run: WizardRunApi }
    cancelRunRequest: ({ runId }: { runId: string }) => { runId: string }
    cancelRunRequestFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
    cancelRunRequestSuccess: (
        cancelRunRequest: WizardRunApi | null,
        payload?: { runId: string }
    ) => {
        cancelRunRequest: WizardRunApi | null
        payload?: { runId: string }
    }
    closeRunDiff: () => { value: true }
    artifactClicked: (
        artifact: WizardRunArtifactApi,
        source: WizardRunArtifactSource
    ) => {
        artifact: WizardRunArtifactApi
        source: WizardRunArtifactSource
    }
    copyRunId: (runId: string, location: WizardRunIdLocation) => { runId: string; location: WizardRunIdLocation }
    loadRunArtifacts: ({ runId }: { runId: string }) => { runId: string }
    loadRunArtifactsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
    loadRunArtifactsSuccess: (
        runArtifacts: WizardRunArtifactApi[],
        payload?: { runId: string }
    ) => {
        runArtifacts: WizardRunArtifactApi[]
        payload?: { runId: string }
    }
    loadRunDetails: ({ runId }: { runId: string }) => { runId: string }
    loadRunDetailsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
    loadRunDetailsSuccess: (
        runDetails: WizardRunApi | null,
        payload?: { runId: string }
    ) => {
        runDetails: WizardRunApi | null
        payload?: { runId: string }
    }
    loadRunDiff: ({ artifactId, runId }: { artifactId: string; runId: string }) => {
        artifactId: string
        runId: string
    }
    loadRunDiffFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
    loadRunDiffSuccess: (
        runDiff: WizardRunDiffContent | null,
        payload?: { artifactId: string; runId: string }
    ) => {
        runDiff: WizardRunDiffContent | null
        payload?: { artifactId: string; runId: string }
    }
    openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => { artifact: WizardRunGitDiffArtifactApi }
    refreshRuns: () => { value: true }
    refreshSelectedRun: () => { value: true }
    selectRun: (
        run: WizardRunApi | null,
        source?: WizardRunDetailSource
    ) => {
        run: WizardRunApi | null
        source?: WizardRunDetailSource
    }
}

export interface wizardRunDetailsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        selectedRun: (runDetails: WizardRunApi | null, selectedRunSummary: WizardRunApi | null) => WizardRunApi | null
        selectedRunArtifacts: (
            selectedRunId: string | null,
            runArtifacts: WizardRunArtifactApi[]
        ) => WizardRunArtifactApi[]
        selectedRunArtifactsInitialLoading: (
            selectedRunId: string | null,
            runArtifactsLoading: boolean,
            artifactRunIdsLoaded: string[]
        ) => boolean
        selectedRunDiffContent: (
            selectedRunDiffArtifactId: string | null,
            runDiff: WizardRunDiffContent | null
        ) => string | null
        selectedRunId: (selectedRunSummary: WizardRunApi | null) => string | null
    }
}

export type wizardRunDetailsLogicType = MakeLogicType<
    wizardRunDetailsLogicValues,
    wizardRunDetailsLogicActions,
    Record<string, never>,
    wizardRunDetailsLogicMeta
>

export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([
    path(['products', 'wizard', 'wizardRunDetailsLogic']),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
        actions: [wizardRunsLogic, ['refreshRuns']],
    })),
    actions({
        openLinkedRun: (runId: string) => ({ runId }),
        selectRun: (run: WizardRunApi | null, source?: WizardRunDetailSource) => ({ run, source }),
        openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => ({ artifact }),
        artifactClicked: (artifact: WizardRunArtifactApi, source: WizardRunArtifactSource) => ({ artifact, source }),
        closeRunDiff: true,
        refreshSelectedRun: true,
        cancelRun: (run: WizardRunApi) => ({ run }),
        copyRunId: (runId: string, location: WizardRunIdLocation) => ({ runId, location }),
    }),
    reducers({
        selectedRunSummary: [
            null as WizardRunApi | null,
            {
                selectRun: (_, { run }) => run,
                cancelRunRequestSuccess: (state, { cancelRunRequest }) =>
                    state?.id === cancelRunRequest?.id ? cancelRunRequest : state,
            },
        ],
        artifactRunIdsLoaded: [
            [] as string[],
            {
                loadRunArtifactsSuccess: (state, { payload }) => {
                    const runId = payload?.runId

                    return runId && !state.includes(runId) ? [...state, runId] : state
                },
            },
        ],
        runArtifactsError: [
            null as string | null,
            {
                loadRunArtifacts: () => null,
                loadRunArtifactsSuccess: () => null,
                loadRunArtifactsFailure: (_, { errorObject }) => requestError(errorObject, "Couldn't load artifacts."),
            },
        ],
        runDetailsError: [
            null as string | null,
            {
                loadRunDetails: () => null,
                loadRunDetailsSuccess: () => null,
                loadRunDetailsFailure: (_, { errorObject }) =>
                    requestError(errorObject, "Couldn't load the latest run state."),
            },
        ],
        selectedRunDiffArtifactId: [
            null as string | null,
            {
                openRunDiff: (_, { artifact }) => artifact.id,
                closeRunDiff: () => null,
                selectRun: () => null,
            },
        ],
        runDiffError: [
            null as string | null,
            {
                openRunDiff: () => null,
                closeRunDiff: () => null,
                loadRunDiffSuccess: () => null,
                loadRunDiffFailure: (_, { errorObject }) =>
                    requestError(errorObject, "Couldn't load this diff. Try again."),
            },
        ],
    }),
    loaders(({ values }) => ({
        runDetails: [
            null as WizardRunApi | null,
            {
                loadRunDetails: async ({ runId }: { runId: string }, breakpoint) => {
                    if (!values.currentProjectId) {
                        return null
                    }

                    try {
                        const run = await wizardRunsRetrieve(String(values.currentProjectId), runId)

                        await breakpoint()

                        return run
                    } catch (error) {
                        return await rejectUnlessCurrent(breakpoint, error)
                    }
                },
            },
        ],
        runArtifacts: [
            [] as WizardRunArtifactApi[],
            {
                loadRunArtifacts: async ({ runId }: { runId: string }, breakpoint) => {
                    if (!values.currentProjectId) {
                        return []
                    }

                    try {
                        const artifacts = await loadWizardRunArtifacts(String(values.currentProjectId), runId)

                        await breakpoint()

                        return [...values.runArtifacts.filter((artifact) => artifact.run_id !== runId), ...artifacts]
                    } catch (error) {
                        return await rejectUnlessCurrent(breakpoint, error)
                    }
                },
            },
        ],
        runDiff: [
            null as WizardRunDiffContent | null,
            {
                loadRunDiff: async ({ artifactId, runId }: { artifactId: string; runId: string }, breakpoint) => {
                    if (!values.currentProjectId) {
                        return null
                    }

                    try {
                        const content = await loadWizardRunArtifactContent(
                            String(values.currentProjectId),
                            runId,
                            artifactId
                        )

                        await breakpoint()

                        return { artifactId, content }
                    } catch (error) {
                        return await rejectUnlessCurrent(breakpoint, error)
                    }
                },
            },
        ],
        cancelRunRequest: [
            null as WizardRunApi | null,
            {
                cancelRunRequest: async ({ runId }: { runId: string }) => {
                    if (!values.currentProjectId) {
                        return null
                    }

                    const properties = {
                        event_source: 'wizard_ui',
                        project_id: String(values.currentProjectId),
                        wizard_run_id: runId,
                    }
                    posthog.capture('wizard run cancel requested', properties)
                    try {
                        const run = await wizardRunsPartialUpdate(String(values.currentProjectId), runId, {
                            status: 'cancelled',
                        })
                        posthog.capture('wizard run cancel succeeded', wizardRunEventProperties(run))
                        return run
                    } catch (error) {
                        posthog.capture('wizard run cancel failed', {
                            ...properties,
                            http_status: error instanceof ApiError ? error.status : null,
                        })
                        throw error
                    }
                },
            },
        ],
    })),
    selectors({
        selectedRunId: [
            (s) => [s.selectedRunSummary],
            (selectedRunSummary: WizardRunApi | null): string | null => selectedRunSummary?.id ?? null,
        ],
        selectedRun: [
            (s) => [s.runDetails, s.selectedRunSummary],
            (runDetails: WizardRunApi | null, selectedRunSummary: WizardRunApi | null): WizardRunApi | null => {
                if (!runDetails || runDetails.id !== selectedRunSummary?.id) {
                    return selectedRunSummary
                }

                // Details cached from an earlier drawer session can be older than a fresh table
                // summary or a cancellation response, so defer to whichever changed more recently.
                const detailsTime = runDetails.updated_at ? dayjs(runDetails.updated_at).valueOf() : 0
                const summaryTime = selectedRunSummary.updated_at ? dayjs(selectedRunSummary.updated_at).valueOf() : 0

                return summaryTime > detailsTime ? selectedRunSummary : runDetails
            },
        ],
        selectedRunArtifacts: [
            (s) => [s.selectedRunId, s.runArtifacts],
            (selectedRunId: string | null, runArtifacts: WizardRunArtifactApi[]): WizardRunArtifactApi[] =>
                selectedRunId ? runArtifacts.filter((artifact) => artifact.run_id === selectedRunId) : [],
        ],
        selectedRunArtifactsInitialLoading: [
            (s) => [s.selectedRunId, s.runArtifactsLoading, s.artifactRunIdsLoaded],
            (selectedRunId: string | null, runArtifactsLoading: boolean, artifactRunIdsLoaded: string[]): boolean =>
                !!selectedRunId && runArtifactsLoading && !artifactRunIdsLoaded.includes(selectedRunId),
        ],
        selectedRunDiffContent: [
            (s) => [s.selectedRunDiffArtifactId, s.runDiff],
            (selectedRunDiffArtifactId: string | null, runDiff: WizardRunDiffContent | null): string | null =>
                selectedRunDiffArtifactId && runDiff?.artifactId === selectedRunDiffArtifactId ? runDiff.content : null,
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        openLinkedRun: async ({ runId }, breakpoint) => {
            const projectId = values.currentProjectId
            if (!projectId || values.selectedRunId === runId) {
                return
            }
            const selectionVersion = cache.selectionVersion ?? 0
            const isCurrent = (): boolean =>
                values.currentProjectId === projectId &&
                cache.linkedRunId === runId &&
                (cache.selectionVersion ?? 0) === selectionVersion
            try {
                const run = await wizardRunsRetrieve(String(projectId), runId)
                await breakpoint()
                if (isCurrent()) {
                    actions.selectRun(run, 'wizard_sidebar')
                }
            } catch (error) {
                await breakpoint()
                if (isCurrent()) {
                    lemonToast.error(requestError(error, "Couldn't open the run. Refresh the page to try again."))
                }
            }
        },
        selectRun: ({ run, source }) => {
            cache.selectionVersion = (cache.selectionVersion ?? 0) + 1
            cache.disposables.dispose('wizardRunDetailPolling')

            if (!run) {
                if (cache.openRun) {
                    posthog.capture('wizard run detail dialog closed', wizardRunEventProperties(cache.openRun))
                    cache.openRun = undefined
                }
                return
            }

            cache.openRun = run
            posthog.capture('wizard run detail dialog opened', {
                ...wizardRunEventProperties(run),
                source,
            })
            if (source === 'wizard_sidebar') {
                cache.terminalArtifactFetchRunId = wizardRunIsActive(run) ? undefined : run.id
                actions.loadRunDetailsSuccess(run)
            } else {
                actions.loadRunDetails({ runId: run.id })
            }
            actions.loadRunArtifacts({ runId: run.id })

            if (wizardRunIsActive(run)) {
                cache.disposables.add(() => {
                    const timerId = window.setInterval(() => {
                        actions.loadRunDetails({ runId: run.id })
                        actions.loadRunArtifacts({ runId: run.id })
                    }, RUN_DETAIL_POLL_INTERVAL_MS)

                    return () => window.clearInterval(timerId)
                }, 'wizardRunDetailPolling')
            }
        },
        openRunDiff: ({ artifact }) => {
            if (!wizardRunDiffCanRender(artifact.size_bytes)) {
                return
            }

            actions.artifactClicked(artifact, 'artifacts_section')

            // Artifacts are immutable, so reuse the cached content instead of re-downloading it.
            if (values.runDiff?.artifactId !== artifact.id) {
                actions.loadRunDiff({ runId: artifact.run_id, artifactId: artifact.id })
            }
        },
        refreshSelectedRun: () => {
            if (values.selectedRunId) {
                posthog.capture('wizard run refreshed', {
                    ...(values.selectedRun ? wizardRunEventProperties(values.selectedRun) : {}),
                    wizard_run_id: values.selectedRunId,
                    location: 'detail_dialog',
                })
                actions.loadRunDetails({ runId: values.selectedRunId })
                actions.loadRunArtifacts({ runId: values.selectedRunId })
            }
        },
        loadRunDetailsSuccess: ({ runDetails }) => {
            if (!runDetails || runDetails.id !== values.selectedRunId) {
                return
            }

            if (wizardRunIsActive(runDetails)) {
                return
            }

            cache.disposables.dispose('wizardRunDetailPolling')

            // The artifacts request of the same poll cycle can read before the run finished,
            // so fetch artifacts once more now that the run is terminal.
            if (cache.terminalArtifactFetchRunId !== runDetails.id) {
                cache.terminalArtifactFetchRunId = runDetails.id
                actions.loadRunArtifacts({ runId: runDetails.id })
            }
        },
        cancelRun: ({ run }) => {
            LemonDialog.open({
                title: 'Cancel Wizard run?',
                description: 'The agent stops this run. You cannot resume it.',
                primaryButton: {
                    children: 'Cancel run',
                    status: 'danger',
                    onClick: () => actions.cancelRunRequest({ runId: run.id }),
                },
                secondaryButton: { children: 'Keep running' },
            })
        },
        cancelRunRequestSuccess: ({ cancelRunRequest }) => {
            lemonToast.success('Wizard run canceled.')

            actions.refreshRuns()
            if (cancelRunRequest?.id === values.selectedRunId) {
                actions.loadRunDetails({ runId: cancelRunRequest.id })
                actions.loadRunArtifacts({ runId: cancelRunRequest.id })
            }
        },
        cancelRunRequestFailure: ({ errorObject }) => {
            lemonToast.error(requestError(errorObject, "Couldn't cancel the Wizard run. Try again."))
        },
        artifactClicked: ({ artifact, source }) => {
            posthog.capture('artifact clicked', {
                ...(values.selectedRun?.id === artifact.run_id
                    ? wizardRunEventProperties(values.selectedRun)
                    : { event_source: 'wizard_ui', wizard_run_id: artifact.run_id }),
                type: artifact.artifact_type === 'git_diff' ? 'diff' : 'pull_request',
                url: artifact.artifact_type === 'pull_request' ? artifact.url : null,
                name: artifact.artifact_type === 'pull_request' ? `Pull request #${artifact.number}` : 'Git diff',
                source,
            })
        },
        copyRunId: ({ runId, location }) => {
            void copyToClipboard(runId, 'Wizard run ID').then((copied) => {
                if (copied) {
                    posthog.capture('run id copied', {
                        event_source: 'wizard_ui',
                        wizard_run_id: runId,
                        location,
                    })
                }
            })
        },
    })),
    urlToAction(({ actions, values, cache }) => ({
        [urls.wizardRuns()]: (_, searchParams) => {
            const previousRunId = cache.linkedRunId
            // The run id becomes part of the API path, so anything other than a UUID is ignored.
            const runId = typeof searchParams.run === 'string' && isUUIDLike(searchParams.run) ? searchParams.run : null
            cache.linkedRunId = runId
            if (runId) {
                actions.openLinkedRun(runId)
            } else if (previousRunId && values.selectedRunId === previousRunId) {
                actions.selectRun(null)
            }
        },
    })),
])