: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): edit the debug prompt and show the debug summary (#114583)
Christian Rafferty787c1fa42f14
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayButton.tsx b/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayButton.tsxindex 37338ba13e93..f580f87afca8 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayButton.tsx+++ b/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayButton.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useMemo } from 'react'+import { useEffect, useMemo, useState } from 'react'import { IconChevronDown, IconSparkles } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'@@ -7,82 +7,110 @@ import { LemonButton } from '@posthog/lemon-ui'import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { isTerminalRunStatus, useAttachedContext } from 'products/posthog_ai/frontend/api/logics'-import { debugReplayChatLogic } from './debugReplayChatLogic'+import { DebugChatSummary, debugReplayChatLogic } from './debugReplayChatLogic'import { buildDebugReplayContextItems } from './debugReplayPrompt'+import { DebugReplayPromptModal } from './DebugReplayPromptModal'++function debugChatTooltip(debugChatSummary: DebugChatSummary | undefined): JSX.Element | string {+ if (debugChatSummary?.summary) {+ return (+ <div className="space-y-1">+ <div className="max-h-80 overflow-y-auto whitespace-pre-line">{debugChatSummary.summary}</div>+ <div className="text-xs text-tertiary">Click to open the chat.</div>+ </div>+ )+ }+ if (debugChatSummary && !isTerminalRunStatus(debugChatSummary.runStatus)) {+ return 'PostHog AI is still debugging this recording. Click to open the chat.'+ }+ return 'Opens the PostHog AI chat that debugged this recording.'+}export function DebugReplayButton(): JSX.Element {const { sessionRecordingId, debugRecordingPreparing } = useValues(sessionRecordingPlayerLogic)- const { debugRecordingWithAI } = useActions(sessionRecordingPlayerLogic)- const { taskIdBySessionRecordingId, openingSessionRecordingId } = useValues(debugReplayChatLogic)- const { openDebugChat } = useActions(debugReplayChatLogic)+ const { taskIdBySessionRecordingId, openingSessionRecordingId, debugChatSummaryBySessionRecordingId } =+ useValues(debugReplayChatLogic)+ const { openDebugChat, loadDebugChatSummary } = useActions(debugReplayChatLogic)+ const [promptModalOpen, setPromptModalOpen] = useState(false)const contextItems = useMemo(() => buildDebugReplayContextItems(sessionRecordingId), [sessionRecordingId])useAttachedContext(contextItems)const hasDebugChat = !!taskIdBySessionRecordingId[sessionRecordingId]const openingDebugChat = openingSessionRecordingId === sessionRecordingId+ const debugChatSummary = debugChatSummaryBySessionRecordingId[sessionRecordingId]const preparingTooltip = 'Loading the recording data for PostHog AI'+ useEffect(() => {+ if (hasDebugChat && !debugChatSummary) {+ loadDebugChatSummary(sessionRecordingId)+ }+ }, [hasDebugChat, debugChatSummary, sessionRecordingId, loadDebugChatSummary])++ const promptModal = promptModalOpen ? <DebugReplayPromptModal onClose={() => setPromptModalOpen(false)} /> : null+if (hasDebugChat) {return (+ <>+ <LemonButton+ size="small"+ type="secondary"+ className="shrink-0"+ icon={<IconSparkles />}+ onClick={() => openDebugChat(sessionRecordingId)}+ loading={openingDebugChat || debugRecordingPreparing}+ tooltip={debugRecordingPreparing ? preparingTooltip : debugChatTooltip(debugChatSummary)}+ data-attr="replay-debug-chat-open"+ sideAction={{+ icon: <IconChevronDown />,+ dropdown: {+ placement: 'bottom-end',+ overlay: (+ <LemonMenuOverlay+ items={[+ {+ label: 'Debug again in a new chat',+ onClick: () => setPromptModalOpen(true),+ 'data-attr': 'replay-debug-with-ai-again',+ },+ ]}+ />+ ),+ },+ divider: false,+ disabledReason: debugRecordingPreparing ? preparingTooltip : null,+ 'aria-label': 'More debug options',+ 'data-attr': 'replay-debug-chat-more',+ }}+ >+ Open debug chat+ </LemonButton>+ {promptModal}+ </>+ )+ }++ return (+ <><LemonButtonsize="small"type="secondary"className="shrink-0"icon={<IconSparkles />}- onClick={() => openDebugChat(sessionRecordingId)}- loading={openingDebugChat || debugRecordingPreparing}+ onClick={() => setPromptModalOpen(true)}+ loading={debugRecordingPreparing}tooltip={debugRecordingPreparing? preparingTooltip- : 'Opens the PostHog AI chat that debugged this recording.'+ : 'Asks PostHog AI what went wrong in this recording. You can edit the prompt first.'}- data-attr="replay-debug-chat-open"- sideAction={{- icon: <IconChevronDown />,- dropdown: {- placement: 'bottom-end',- overlay: (- <LemonMenuOverlay- items={[- {- label: 'Debug again in a new chat',- onClick: debugRecordingWithAI,- 'data-attr': 'replay-debug-with-ai-again',- },- ]}- />- ),- },- divider: false,- disabledReason: debugRecordingPreparing ? preparingTooltip : null,- 'aria-label': 'More debug options',- 'data-attr': 'replay-debug-chat-more',- }}+ data-attr="replay-debug-with-ai">- Open debug chat+ Debug this replay</LemonButton>- )- }-- return (- <LemonButton- size="small"- type="secondary"- className="shrink-0"- icon={<IconSparkles />}- onClick={debugRecordingWithAI}- loading={debugRecordingPreparing}- tooltip={- debugRecordingPreparing- ? preparingTooltip- : 'Sends the recording JSON to PostHog AI and asks what went wrong.'- }- data-attr="replay-debug-with-ai"- >- Debug this replay- </LemonButton>+ {promptModal}+ </>)}diff --git a/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayPromptModal.tsx b/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayPromptModal.tsxnew file mode 100644index 000000000000..a099c1b8efaf--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/player-meta/DebugReplayPromptModal.tsx@@ -0,0 +1,64 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonModal, LemonTextArea } from '@posthog/lemon-ui'++import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'++import { buildDebugReplayPrompt } from './debugReplayPrompt'++export function DebugReplayPromptModal({ onClose }: { onClose: () => void }): JSX.Element {+ const { sessionRecordingId, currentPlayerTimeSeconds, debugRecordingPreparing } =+ useValues(sessionRecordingPlayerLogic)+ const { debugRecordingWithAI } = useActions(sessionRecordingPlayerLogic)++ // The default prompt names the current player time, so it is built once when the dialog opens.+ const [defaultPrompt] = useState(() => buildDebugReplayPrompt(sessionRecordingId, currentPlayerTimeSeconds))+ const [prompt, setPrompt] = useState(defaultPrompt)++ const trimmedPrompt = prompt.trim()++ const submit = (): void => {+ if (!trimmedPrompt) {+ return+ }+ debugRecordingWithAI(trimmedPrompt, trimmedPrompt !== defaultPrompt)+ onClose()+ }++ return (+ <LemonModal+ isOpen+ onClose={onClose}+ title="Debug this replay with PostHog AI"+ description="Edit the prompt if you want to. PostHog AI gets the recording data along with it."+ width={640}+ footer={+ <>+ <LemonButton type="secondary" onClick={onClose} data-attr="replay-debug-prompt-cancel">+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={submit}+ loading={debugRecordingPreparing}+ disabledReason={trimmedPrompt ? undefined : 'Write a prompt first'}+ data-attr="replay-debug-prompt-submit"+ >+ Send to PostHog AI+ </LemonButton>+ </>+ }+ >+ <LemonTextArea+ value={prompt}+ onChange={setPrompt}+ onPressCmdEnter={submit}+ minRows={8}+ maxRows={16}+ autoFocus+ data-attr="replay-debug-prompt-input"+ />+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.tsindex 352ed64b4f63..9331627f4c4b 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts@@ -1,10 +1,13 @@+import { expectLogic } from 'kea-test-utils'+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import { debugReplayChatLogic } from './debugReplayChatLogic'+import { DebugChatSummary, debugReplayChatLogic } from './debugReplayChatLogic'describe('debugReplayChatLogic', () => {let logic: ReturnType<typeof debugReplayChatLogic.build>@@ -41,4 +44,24 @@ describe('debugReplayChatLogic', () => {}expect(logic.values.taskIdBySessionRecordingId).toEqual(expected)})++ test.each<[string, [number, Record<string, unknown>], DebugChatSummary | undefined, Record<string, string>]>([+ [+ 'stores the summary of the latest run',+ [200, { id: 'task-1', latest_run: { id: 'run-1', status: 'completed', task_summary: ' Found it. ' } }],+ { summary: 'Found it.', runStatus: 'completed' },+ { 'session-1': 'task-1' },+ ],+ ['forgets a chat whose task was deleted', [404, { detail: 'Not found.' }], undefined, {}],+ ])('loading the summary %s', async (_, response, expectedSummary, expectedTasks) => {+ useMocks({ get: { '/api/projects/:team_id/tasks/:id/': () => response } })+ logic.actions.rememberDebugChat('session-1', 'task-1')++ await expectLogic(logic, () => {+ logic.actions.loadDebugChatSummary('session-1')+ }).toFinishAllListeners()++ expect(logic.values.debugChatSummaryBySessionRecordingId['session-1']).toEqual(expectedSummary)+ expect(logic.values.taskIdBySessionRecordingId).toEqual(expectedTasks)+ })})diff --git a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.tsindex baac3ad66dd5..5797c2ea0742 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts@@ -14,6 +14,7 @@ import { SidePanelTab } from '~/types'import { ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'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@@ -25,10 +26,24 @@ export interface PendingDebugChat {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 // maxGlobalLogiccurrentProjectId: number | null // projectLogic+ debugChatSummaryBySessionRecordingId: Record<string, DebugChatSummary>openingSessionRecordingId: string | nullpendingDebugChat: PendingDebugChat | nulltaskIdBySessionRecordingId: Record<string, string>@@ -58,6 +73,9 @@ export interface debugReplayChatLogicActions {forgetDebugChat: (sessionRecordingId: string) => {sessionRecordingId: string}+ loadDebugChatSummary: (sessionRecordingId: string) => {+ sessionRecordingId: string+ }openDebugChat: (sessionRecordingId: string) => {sessionRecordingId: string}@@ -71,6 +89,13 @@ export interface debugReplayChatLogicActions {sessionRecordingId: stringtaskId: string}+ setDebugChatSummary: (+ sessionRecordingId: string,+ summary: DebugChatSummary+ ) => {+ sessionRecordingId: string+ summary: DebugChatSummary+ }}export type debugReplayChatLogicType = MakeLogicType<debugReplayChatLogicValues, debugReplayChatLogicActions>@@ -99,6 +124,11 @@ export const debugReplayChatLogic = kea<debugReplayChatLogicType>([forgetDebugChat: (sessionRecordingId: string) => ({ sessionRecordingId }),openDebugChat: (sessionRecordingId: string) => ({ sessionRecordingId }),openDebugChatFinished: true,+ loadDebugChatSummary: (sessionRecordingId: string) => ({ sessionRecordingId }),+ setDebugChatSummary: (sessionRecordingId: string, summary: DebugChatSummary) => ({+ sessionRecordingId,+ summary,+ }),}),reducers({taskIdBySessionRecordingId: [@@ -143,6 +173,19 @@ export const debugReplayChatLogic = kea<debugReplayChatLogicType>([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 }) => {@@ -152,6 +195,21 @@ export const debugReplayChatLogic = kea<debugReplayChatLogicType>([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) {@@ -160,6 +218,7 @@ export const debugReplayChatLogic = kea<debugReplayChatLogicType>([}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)diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 5d66059ee93a..b842b2847fc5 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -53,7 +53,6 @@ import { debugReplayChatLogic } from 'scenes/session-recordings/player/player-meimport { buildDebugReplayData } from 'scenes/session-recordings/player/player-meta/debugReplayData'import {buildDebugReplayDataContextItem,- buildDebugReplayPrompt,debugReplayFileName,} from 'scenes/session-recordings/player/player-meta/debugReplayPrompt'import {@@ -969,8 +968,12 @@ export interface sessionRecordingPlayerLogicActions {reportNextRecordingTriggered: (automatic: boolean) => {automatic: boolean} // sessionRecordingEventUsageLogic- reportRecordingDebuggedWithAI: (playerTimeSeconds: number) => {+ reportRecordingDebuggedWithAI: (+ playerTimeSeconds: number,+ promptEdited: boolean+ ) => {playerTimeSeconds: number+ promptEdited: boolean} // sessionRecordingEventUsageLogicreportRecordingExportedToFile: (format: 'json' | 'mp4') => {format: 'json' | 'mp4'@@ -1047,8 +1050,12 @@ export interface sessionRecordingPlayerLogicActions {config: Record<string, any>integrationId: number}- debugRecordingWithAI: () => {- value: true+ debugRecordingWithAI: (+ prompt: string,+ promptEdited: boolean+ ) => {+ prompt: string+ promptEdited: boolean}deleteRecording: () => {value: true@@ -1605,7 +1612,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(flushDoctorDiagnostics: (diagnostics: DoctorDiagnostics) => ({ diagnostics }),syncSnapshotsWithPlayer: true,exportRecordingToFile: true,- debugRecordingWithAI: true,+ debugRecordingWithAI: (prompt: string, promptEdited: boolean) => ({ prompt, promptEdited }),setDebugRecordingPreparing: (preparing: boolean) => ({ preparing }),deleteRecording: true,openExplorer: true,@@ -3663,7 +3670,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(cache.pausedMediaElements = []},- debugRecordingWithAI: async () => {+ debugRecordingWithAI: async ({ prompt, promptEdited }) => {if (!values.sessionRecordingId || values.debugRecordingPreparing) {return}@@ -3709,11 +3716,8 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(}// The side panel renders behind a fullscreen player.actions.setIsFullScreen(false)- actions.openSidePanel(- SidePanelTab.Max,- autoRunMaxPrompt(buildDebugReplayPrompt(values.sessionRecordingId, values.currentPlayerTimeSeconds))- )- actions.reportRecordingDebuggedWithAI(values.currentPlayerTimeSeconds)+ actions.openSidePanel(SidePanelTab.Max, autoRunMaxPrompt(prompt))+ actions.reportRecordingDebuggedWithAI(values.currentPlayerTimeSeconds, promptEdited)},exportRecordingToFile: async () => {diff --git a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.tsindex adc95d82fe6b..5b6268a790cd 100644--- a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts+++ b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts@@ -51,8 +51,12 @@ export interface sessionRecordingEventUsageLogicActions {reportRecordingDebugChatReopened: () => {value: true}- reportRecordingDebuggedWithAI: (playerTimeSeconds: number) => {+ reportRecordingDebuggedWithAI: (+ playerTimeSeconds: number,+ promptEdited: boolean+ ) => {playerTimeSeconds: number+ promptEdited: boolean}reportRecordingExportedToFile: (format: 'json' | 'mp4') => {format: 'json' | 'mp4'@@ -184,7 +188,10 @@ export const sessionRecordingEventUsageLogic = kea<sessionRecordingEventUsageLogautomatic,}),reportRecordingExportedToFile: (format: 'json' | 'mp4') => ({ format }),- reportRecordingDebuggedWithAI: (playerTimeSeconds: number) => ({ playerTimeSeconds }),+ reportRecordingDebuggedWithAI: (playerTimeSeconds: number, promptEdited: boolean) => ({+ playerTimeSeconds,+ promptEdited,+ }),reportRecordingDebugChatReopened: true,reportRecordingLoadedFromFile: (data: { success: boolean; error?: string }) => data,reportRecordingListVisibilityToggled: (type: string, visible: boolean) => ({ type, visible }),@@ -272,8 +279,11 @@ export const sessionRecordingEventUsageLogic = kea<sessionRecordingEventUsageLogreportRecordingExportedToFile: ({ format }) => {posthog.capture('recording exported to file', { format })},- reportRecordingDebuggedWithAI: ({ playerTimeSeconds }) => {- posthog.capture('recording debugged with ai', { player_time_seconds: playerTimeSeconds })+ reportRecordingDebuggedWithAI: ({ playerTimeSeconds, promptEdited }) => {+ posthog.capture('recording debugged with ai', {+ player_time_seconds: playerTimeSeconds,+ prompt_edited: promptEdited,+ })},reportRecordingDebugChatReopened: () => {posthog.capture('recording debug chat reopened')