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.

10.3 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'

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

import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { projectLogic } from 'scenes/projectLogic'
import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'
import { urls } from 'scenes/urls'

import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'

import { tasksRetrieve } from 'products/tasks/frontend/generated/api'
import { TaskDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'

// Local storage holds one entry per debugged recording, so the oldest entries are dropped past this count.
const MAX_REMEMBERED_DEBUG_CHATS = 200

/** A debug prompt that was sent to the side panel and whose task does not exist yet. */
export interface PendingDebugChat {
    sessionRecordingId: string
    /** The panel's client key for the optimistic run. It is null until the panel opens that run. */
    streamKey: string | null
}

/** What the remembered chat found, read from the task's latest run. */
export interface DebugChatSummary {
    summary: string | null
    runStatus: string | null
}

function summaryFromTask(task: TaskDetailDTOApi): DebugChatSummary {
    return {
        summary: task.latest_run?.task_summary?.trim() || null,
        runStatus: task.latest_run?.status ?? null,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface debugReplayChatLogicValues {
    effectivePhaiView: PhaiViewMode // maxGlobalLogic
    currentProjectId: number | null // projectLogic
    debugChatSummaryBySessionRecordingId: Record<string, DebugChatSummary>
    openingSessionRecordingId: string | null
    pendingDebugChat: PendingDebugChat | null
    taskIdBySessionRecordingId: Record<string, string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface debugReplayChatLogicActions {
    clearActiveCreation: () => {
        value: true
    } // runnerPanelLogic
    setActiveCreation: (creation: ActiveCreation) => {
        creation: ActiveCreation
    } // runnerPanelLogic
    reportRecordingDebugChatReopened: () => {
        value: true
    } // sessionRecordingEventUsageLogic
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
    debugChatRequested: (sessionRecordingId: string) => {
        sessionRecordingId: string
    }
    forgetDebugChat: (sessionRecordingId: string) => {
        sessionRecordingId: string
    }
    loadDebugChatSummary: (sessionRecordingId: string) => {
        sessionRecordingId: string
    }
    openDebugChat: (sessionRecordingId: string) => {
        sessionRecordingId: string
    }
    openDebugChatFinished: () => {
        value: true
    }
    rememberDebugChat: (
        sessionRecordingId: string,
        taskId: string
    ) => {
        sessionRecordingId: string
        taskId: string
    }
    setDebugChatSummary: (
        sessionRecordingId: string,
        summary: DebugChatSummary
    ) => {
        sessionRecordingId: string
        summary: DebugChatSummary
    }
}

export type debugReplayChatLogicType = MakeLogicType<debugReplayChatLogicValues, debugReplayChatLogicActions>

/**
 * Remembers which PostHog AI chat debugged each recording, so that the player can reopen that chat.
 *
 * A task has no reference to a recording on the server. The link exists only in this browser's local storage.
 */
export const debugReplayChatLogic = kea<debugReplayChatLogicType>([
    path(['scenes', 'session-recordings', 'player', 'player-meta', 'debugReplayChatLogic']),
    connect(() => ({
        values: [maxGlobalLogic, ['effectivePhaiView'], projectLogic, ['currentProjectId']],
        actions: [
            runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['setActiveCreation', 'clearActiveCreation'],
            sidePanelStateLogic,
            ['openSidePanel'],
            sessionRecordingEventUsageLogic,
            ['reportRecordingDebugChatReopened'],
        ],
    })),
    actions({
        debugChatRequested: (sessionRecordingId: string) => ({ sessionRecordingId }),
        rememberDebugChat: (sessionRecordingId: string, taskId: string) => ({ sessionRecordingId, taskId }),
        forgetDebugChat: (sessionRecordingId: string) => ({ sessionRecordingId }),
        openDebugChat: (sessionRecordingId: string) => ({ sessionRecordingId }),
        openDebugChatFinished: true,
        loadDebugChatSummary: (sessionRecordingId: string) => ({ sessionRecordingId }),
        setDebugChatSummary: (sessionRecordingId: string, summary: DebugChatSummary) => ({
            sessionRecordingId,
            summary,
        }),
    }),
    reducers({
        taskIdBySessionRecordingId: [
            {} as Record<string, string>,
            { persist: true },
            {
                rememberDebugChat: (state, { sessionRecordingId, taskId }) => {
                    // Reinserting moves the recording to the end, so the entries stay ordered oldest first.
                    const { [sessionRecordingId]: _, ...rest } = state
                    const entries = [...Object.entries(rest), [sessionRecordingId, taskId]]
                    return Object.fromEntries(entries.slice(-MAX_REMEMBERED_DEBUG_CHATS))
                },
                forgetDebugChat: (state, { sessionRecordingId }) => {
                    const { [sessionRecordingId]: _, ...rest } = state
                    return rest
                },
            },
        ],
        pendingDebugChat: [
            null as PendingDebugChat | null,
            {
                debugChatRequested: (_, { sessionRecordingId }) => ({ sessionRecordingId, streamKey: null }),
                setActiveCreation: (state, { creation }) => {
                    if (!state) {
                        return state
                    }
                    if (state.streamKey === null) {
                        // The run for the prompt opens without a task. A creation that already has a task is
                        // a chat the user opened from history, so the prompt was not sent.
                        return creation.taskId ? null : { ...state, streamKey: creation.streamKey }
                    }
                    return creation.streamKey === state.streamKey ? state : null
                },
                clearActiveCreation: (state) => (state?.streamKey ? null : state),
                rememberDebugChat: () => null,
            },
        ],
        openingSessionRecordingId: [
            null as string | null,
            {
                openDebugChat: (_, { sessionRecordingId }) => sessionRecordingId,
                openDebugChatFinished: () => null,
            },
        ],
        debugChatSummaryBySessionRecordingId: [
            {} as Record<string, DebugChatSummary>,
            {
                setDebugChatSummary: (state, { sessionRecordingId, summary }) => ({
                    ...state,
                    [sessionRecordingId]: summary,
                }),
                forgetDebugChat: (state, { sessionRecordingId }) => {
                    const { [sessionRecordingId]: _, ...rest } = state
                    return rest
                },
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        setActiveCreation: ({ creation }) => {
            const pending = values.pendingDebugChat
            // The panel sets the task on the optimistic run after the server creates it.
            if (pending?.streamKey === creation.streamKey && creation.taskId) {
                actions.rememberDebugChat(pending.sessionRecordingId, creation.taskId)
            }
        },
        loadDebugChatSummary: async ({ sessionRecordingId }) => {
            const taskId = values.taskIdBySessionRecordingId[sessionRecordingId]
            if (!taskId || values.currentProjectId === null) {
                return
            }
            try {
                const task = await tasksRetrieve(String(values.currentProjectId), taskId)
                actions.setDebugChatSummary(sessionRecordingId, summaryFromTask(task))
            } catch (error) {
                // The button falls back to its plain tooltip on any other error, so only a deleted task needs handling.
                if ((error as { status?: number } | null)?.status === 404) {
                    actions.forgetDebugChat(sessionRecordingId)
                }
            }
        },
        openDebugChat: async ({ sessionRecordingId }) => {
            const taskId = values.taskIdBySessionRecordingId[sessionRecordingId]
            if (!taskId || values.currentProjectId === null) {
                actions.openDebugChatFinished()
                return
            }
            try {
                const task = await tasksRetrieve(String(values.currentProjectId), taskId)
                actions.setDebugChatSummary(sessionRecordingId, summaryFromTask(task))
                actions.reportRecordingDebugChatReopened()
                if (values.effectivePhaiView === 'new' && task.latest_run) {
                    actions.openSidePanel(SidePanelTab.Max)
                    actions.setActiveCreation({
                        streamKey: task.latest_run.id,
                        taskId: task.id,
                        runId: task.latest_run.id,
                    })
                } else {
                    // The legacy chat panel cannot show a task, and a task without a run has no thread to show.
                    router.actions.push(urls.taskDetail(task.id))
                }
            } catch (error) {
                if ((error as { status?: number } | null)?.status === 404) {
                    actions.forgetDebugChat(sessionRecordingId)
                    lemonToast.error('That chat no longer exists. Debug this replay again to start a new one.')
                } else {
                    lemonToast.error("Couldn't open the chat. Try again in a moment.")
                }
            } finally {
                actions.openDebugChatFinished()
            }
        },
    })),
])