: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(notebooks): keep AI questions with answers (#90153)
Marius Andra38a3e7d682ae
diff --git a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.mdindex 82e5fd554cbe..f4c2f38f69c0 100644--- a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md+++ b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md@@ -276,7 +276,7 @@ Generated charts and freeform widgets should use an isolated renderer based on t## Reserved tagsDo not reuse the tags of the default registry (`registry.tsx`): `Query`, `Image`, `Divider`, `Embed`, `Latex`, `Python`, `DuckSQL`, `HogQLSQL`, `RecordingPlaylist`, `FeatureFlag`, `Experiment`, `Survey`, `Person`, `Group`, `Cohort`, `Map`.-The internal AI tag `Prompt` is also reserved (registered by the notebooks scene).+The internal AI tag `Prompt` is also reserved (registered by the notebooks scene). Its `keepQuestion` boolean prop keeps the submitted question, with the submitting user's name, directly above the generated answer.`Image` and `Divider` are special: they serialize back to plain markdown (`` and `---`) rather than component-tag syntax.`Comment` is special too: its authorial-note flavor (`text` prop) serializes as a markdown `<!-- … -->` comment, while its discussion flavor (`ref` + `replies` props, a Google Docs-style thread anchored to an inline `<ref id="…">` highlight) serializes as a regular `<Comment … />` tag.The lowercase inline tags `<ref>` and `<mention>` are part of the inline grammar, not components — component tags must start with an uppercase letter.diff --git a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsxindex 3f80e0aaf3be..e82624109520 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx@@ -1,7 +1,7 @@import clsx from 'clsx'import { KeyboardEvent, MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'-import { IconSend, IconTrash } from '@posthog/icons'+import { IconBookmark, IconBookmarkSolid, IconSend, IconTrash } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { getNotebookStringProp, isPromptComponentNode } from './documentModel'@@ -37,6 +37,7 @@ export function EditablePromptComponent({const handledFocusRequestRef = useRef<number | undefined>(undefined)const [isCollapsed, setIsCollapsed] = useState(false)const question = getNotebookStringProp(node.props.question) ?? ''+ const keepQuestion = node.props.keepQuestion === trueconst isEmpty = question.length === 0const submitDisabledReason = question.trim()? isAIPromptSubmitDisabled@@ -117,6 +118,23 @@ export function EditablePromptComponent({deleteNodeAndFocusAdjacent()}+ const toggleKeepQuestion = (): void => {+ updateNode(node.id, (currentNode) => {+ if (!isPromptComponentNode(currentNode)) {+ return currentNode+ }++ const nextProps = { ...currentNode.props }+ if (keepQuestion) {+ delete nextProps.keepQuestion+ } else {+ nextProps.keepQuestion = true+ }++ return { ...currentNode, props: nextProps }+ })+ }+const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {event.stopPropagation()@@ -204,6 +222,17 @@ export function EditablePromptComponent({disabled={mode !== 'edit'}rows={1}/>+ <LemonButton+ size="xsmall"+ icon={keepQuestion ? <IconBookmarkSolid /> : <IconBookmark />}+ active={keepQuestion}+ tooltip="Keep question with answer"+ aria-label="Keep question with answer"+ aria-pressed={keepQuestion}+ onClick={toggleKeepQuestion}+ disabled={mode !== 'edit'}+ data-attr="markdown-notebook-ai-keep-question"+ /><LemonButtontype="primary"size="xsmall"diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex edf481809966..2127992ea950 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -3959,6 +3959,54 @@ Current AI paragraph`),expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nThinking...`)})+ it('keeps the named question above the AI response when enabled', () => {+ const onAskAI = jest.fn()+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n<Prompt question="What is PostHog?" />`,+ onAskAI,+ onChange,+ aiPromptAuthorName: 'Avery',+ createAIConversationId: () => TEST_AI_CONVERSATION_ID,+ })+ )+ const keepQuestionButton = container.querySelector(+ '[data-attr="markdown-notebook-ai-keep-question"]'+ ) as HTMLButtonElement++ expect(keepQuestionButton).toBeInstanceOf(HTMLButtonElement)+ expect(keepQuestionButton.getAttribute('aria-pressed')).toEqual('false')++ fireEvent.click(keepQuestionButton)++ expect(keepQuestionButton.getAttribute('aria-pressed')).toEqual('true')+ expect(keepQuestionButton.classList.contains('LemonButton--active')).toBe(true)+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n<Prompt question="What is PostHog?" keepQuestion />`+ )++ fireEvent.click(keepQuestionButton)++ expect(keepQuestionButton.getAttribute('aria-pressed')).toEqual('false')+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n<Prompt question="What is PostHog?" />`+ )++ fireEvent.click(keepQuestionButton)+ fireEvent.click(container.querySelector('[aria-label="Send prompt"]') as HTMLButtonElement)++ const markdownWithResponse = `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n**Avery:** What is PostHog?\n\nThinking...`+ expect(onChange).toHaveBeenLastCalledWith(markdownWithResponse)+ expect(onAskAI).toHaveBeenCalledWith(+ expect.objectContaining({+ conversationId: TEST_AI_CONVERSATION_ID,+ responseNodeIndex: 2,+ markdownWithResponse,+ })+ )+ })+it('submits a persisted Ask AI prompt from the prompt textarea', () => {const onAskAI = jest.fn()const onChange = jest.fn()diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex 08980ab9337f..678e7bcccae7 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -241,6 +241,7 @@ export type MarkdownNotebookProps = {value: stringonChange?: (value: string) => voidonAskAI?: (request: MarkdownNotebookAskAIRequest) => void+ aiPromptAuthorName?: stringisAskAIDisabled?: booleancreateAIConversationId?: () => stringmode?: NotebookMode@@ -356,6 +357,17 @@ function createDefaultAIConversationId(): string {return makeEmptyParagraph('ai-conversation').id}+function makeRetainedAIQuestionNode(authorName: string, question: string, idSeed: string): NotebookTextBlockNode {+ return {+ ...makeEmptyParagraph(idSeed),+ children: [+ { type: 'text', text: `${authorName.trim() || 'You'}:`, marks: [{ type: 'bold' }] },+ { type: 'text', text: ' ' },+ ...plainTextToInlineNodes(question),+ ],+ }+}+/** Below this container width, comment threads render inline instead of in the margin. */const COMMENT_GUTTER_MIN_CONTAINER_WIDTH_PX = 960@@ -569,6 +581,7 @@ function MarkdownNotebookEditor({value,onChange,onAskAI,+ aiPromptAuthorName = 'You',isAskAIDisabled: isAIPromptSubmitDisabled = false,createAIConversationId = createDefaultAIConversationId,mode = 'edit',@@ -5376,16 +5389,26 @@ function MarkdownNotebookEditor({}let responseNodeIndex = -1- const nodesWithResponse = nodes.map((currentNode, index): NotebookBlockNode => {+ const keepQuestion = currentPromptNode?.props.keepQuestion === true+ const nodesWithResponse = nodes.flatMap((currentNode, index): NotebookBlockNode[] => {if (currentNode.id !== nodeId || !isPromptComponentNode(currentNode)) {- return currentNode+ return [currentNode]}- responseNodeIndex = index- return {++ const responseNode: NotebookTextBlockNode = {id: currentNode.id,type: 'paragraph',children: plainTextToInlineNodes(NOTEBOOK_AI_WRITING_PLACEHOLDER),}+ if (!keepQuestion) {+ responseNodeIndex = index+ return [responseNode]+ }++ responseNodeIndex = index + 1+ const questionNode = makeRetainedAIQuestionNode(aiPromptAuthorName, query, `ai-question-${currentNode.id}`)+ questionNode.startsGroup = currentNode.startsGroup+ return [questionNode, responseNode]})if (responseNodeIndex === -1) {console.error('Prompt node not found for AI submission')diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.tsindex 24cf38570345..07102e6d8e07 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts@@ -152,15 +152,41 @@ describe('notebookAI', () => {})})- it('rebases the streamed AI response range after deleting an earlier generated block', () => {+ it.each([+ {+ change: 'deleting an earlier generated block',+ previousMarkdown: '# Notebook\n\nFirst paragraph\n\nSecond paragraph\n\nThird paragraph still writing',+ nextMarkdown: '# Notebook\n\nSecond paragraph\n\nThird paragraph still writing',+ responseNodeIndex: 3,+ responseNodeCount: 3,+ expectedRange: { responseNodeIndex: 2, responseNodeCount: 2 },+ },+ {+ change: 'editing the retained question before the response',+ previousMarkdown: '# Notebook\n\n**Avery:** What is PostHog?\n\nAnswer still writing',+ nextMarkdown: '# Notebook\n\n**Avery:** What does PostHog do?\n\nAnswer still writing',+ responseNodeIndex: 2,+ responseNodeCount: 1,+ expectedRange: { responseNodeIndex: 2, responseNodeCount: 1 },+ },+ {+ change: 'inserting a response-equivalent block before the active response',+ previousMarkdown: '# Notebook\n\n**Avery:** What is PostHog?\n\nAnswer still writing\n\nAfter the answer',+ nextMarkdown:+ '# Notebook\n\n**Avery:** What does PostHog do?\n\nAnswer still writing\n\nAnswer still writing\n\nAfter the answer',+ responseNodeIndex: 2,+ responseNodeCount: 1,+ expectedRange: { responseNodeIndex: 3, responseNodeCount: 1 },+ },+ ])('rebases the streamed AI response range after $change', (testCase) => {expect(rebaseNotebookAIResponseRange(- '# Notebook\n\nFirst paragraph\n\nSecond paragraph\n\nThird paragraph still writing',- '# Notebook\n\nSecond paragraph\n\nThird paragraph still writing',- 3,- 3+ testCase.previousMarkdown,+ testCase.nextMarkdown,+ testCase.responseNodeIndex,+ testCase.responseNodeCount)- ).toEqual({ responseNodeIndex: 2, responseNodeCount: 2 })+ ).toEqual(testCase.expectedRange)})it('replaces the active streamed block when the AI has only written one block so far', () => {diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.tsindex 9a90cce9a205..5e2fe4320eb4 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts@@ -54,11 +54,33 @@ export function rebaseNotebookAIResponseRange(previousDocument.nodes.length,previousRange.insertionIndex + previousRange.deleteCount)- const nextStartIndex = getRebasedNotebookAIResponseStartIndex(+ const nextStartBoundaryIndex = getRebasedNotebookAIResponseStartIndex(previousDocument.nodes,nextDocument.nodes,previousStartIndex)+ const nextEndBoundaryIndex = getRebasedNotebookAIResponseEndIndex(+ previousDocument.nodes,+ nextDocument.nodes,+ previousEndIndex,+ nextStartBoundaryIndex+ )+ const latestPossibleResponseStartIndex = Math.max(+ nextStartBoundaryIndex,+ nextEndBoundaryIndex - previousRange.deleteCount+ )+ const previousResponseStartNode = previousDocument.nodes[previousStartIndex]+ let nextResponseStartIndex: number | null = null+ if (previousResponseStartNode) {+ nextResponseStartIndex =+ getLastMatchingNodeFingerprintIndex(+ previousResponseStartNode,+ nextDocument.nodes,+ nextStartBoundaryIndex,+ latestPossibleResponseStartIndex+ ) ?? getMatchingNodeFingerprintIndex(previousResponseStartNode, nextDocument.nodes, nextStartBoundaryIndex)+ }+ const nextStartIndex = nextResponseStartIndex ?? nextStartBoundaryIndexconst nextEndIndex = getRebasedNotebookAIResponseEndIndex(previousDocument.nodes,nextDocument.nodes,@@ -278,6 +300,22 @@ function getMatchingNodeFingerprintIndex(return null}+function getLastMatchingNodeFingerprintIndex(+ node: NotebookBlockNode,+ candidateNodes: NotebookBlockNode[],+ startIndex: number,+ endIndex: number+): number | null {+ const nodeFingerprint = getNodeFingerprint(node)+ for (let index = Math.min(endIndex, candidateNodes.length - 1); index >= Math.max(0, startIndex); index--) {+ if (getNodeFingerprint(candidateNodes[index]) === nodeFingerprint) {+ return index+ }+ }++ return null+}+function getNextReplacementSearchIndexForPreservedNodes(currentNodes: NotebookBlockNode[],replacementNodes: NotebookBlockNode[]diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex 4d58ca2ae9ee..882a684b6366 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -29,6 +29,7 @@ import { getInlineText } from 'lib/components/MarkdownNotebook/utils'import { uploadFile } from 'lib/hooks/useUploadFiles'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'+import { userLogic } from 'scenes/userLogic'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'@@ -89,6 +90,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotmarkdownRemoteCarets,} = useValues(notebookLogic)const { featureFlags } = useValues(featureFlagLogic)+ const { user } = useValues(userLogic)const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])const hiddenInsertCommandKeys = useMemo(() => getHiddenInsertCommandKeysForFeatureFlags(featureFlags),@@ -686,6 +688,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot<NotebookComponentRunStatusContext.Provider value={resolveComponentRunStatus}><MarkdownNotebookvalue={markdownEditorValue}+ aiPromptAuthorName={user?.first_name || 'You'}remoteValue={remoteMarkdown}remoteVersion={notebook?.version}mode={isEditable ? 'edit' : 'view'}