: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
fix(notebooks): preserve inline ai edits and require consent (#101656)
Marius Andra6b96c75a5bde
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.mdindex a8da27bb5ef1..0b4c265d8721 100644--- a/docs/internal/generated-notebook-widgets.md+++ b/docs/internal/generated-notebook-widgets.md@@ -108,6 +108,10 @@ Loading a saved result does not execute a cell or mark dependent cells stale. IfNew notebooks place the typing caret in the title, including when opened through the command menu. Enter continues into the notebook body.The notebook's inline **Ask AI** uses LangGraph and receives widget authoring instructions when `notebook-generated-widgets` is enabled for the user.The bookmark toggle **Keep question with answer** is on by default, retaining the question and the submitting user's name above the answer. Turning it off saves `keepQuestion={false}` on that prompt.+**Ask AI** is disabled until the organization approves AI data processing, including submission from saved prompt blocks.+Inline notebook artifacts update the open notebook without saving a second copy, even when the tool requests a save.+Full-notebook replacements preserve the retained question when **Keep question with answer** is on.+Standalone AI notebook saves preserve Markdown separators and live MDX cells, including `<SQLV2 />` and `<Widget />`, while resolving visualization references.Its notebook context and `create_notebook` tool share the same instructions for inserting `<Widget title="Interactive visualization" prompt="Describe the visualization" />`.When the widget flag is enabled, inline AI insertion also converts plain, `md`, or `markdown` code fences containing only valid `<Widget>` tags into widget blocks. Fences containing other code, malformed tags, or an explicit language such as `text` remain code examples.The user clicks **Generate widget** in the inserted block's settings to start generation.diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex a0fc02e582e9..87117a49a82d 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -490,6 +490,10 @@ class AssistantContextManager(AssistantContextMixin):"- For broad edits such as cleaning up, rewriting, reorganizing, or replacing the entire ""notebook, use create_notebook with content containing the complete final notebook markdown."),+ (+ "- The editor applies that artifact to this notebook and preserves the user's prompt when "+ "requested. Do not save a second notebook or repeat the edit with another notebook tool."+ ),(f"- Full-notebook replacement content must omit `{response_marker}`, empty Prompt tags, and the ""user's inline prompt unless the user explicitly asks to keep them."diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.pyindex b6b847b3128b..32fea9be61eb 100644--- a/ee/hogai/tools/create_notebook/helpers.py+++ b/ee/hogai/tools/create_notebook/helpers.py@@ -2,6 +2,8 @@ from collections.abc import Sequencefrom enum import Enumfrom typing import Any+from posthog.schema import MarkdownBlock+from posthog.models import Team, Userfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -187,7 +189,18 @@ async def save_notebook_to_db(content: dict[str, Any] = tiptap_doctext_content: str | None = Noneif existing_notebook is None:- markdown = convert_notebook_content_to_markdown(tiptap_doc)+ # Markdown blocks can contain live MDX cells that the TipTap parser treats as plain text.+ markdown = "\n\n".join(+ [f"# {title}"]+ + [+ block.content+ if isinstance(block, MarkdownBlock)+ else convert_notebook_content_to_markdown(+ blocks_to_tiptap_doc([block], resolve_visualization=resolve_visualization)+ )+ for block in blocks+ ]+ )content = build_markdown_notebook_content(markdown)text_content = markdowndiff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.pyindex 3bd49f1406db..96dc78ceed31 100644--- a/ee/hogai/tools/create_notebook/test/test_helpers.py+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py@@ -6,7 +6,7 @@ from unittest.mock import patchfrom asgiref.sync import async_to_syncfrom parameterized import parameterized-from posthog.schema import TrendsQuery, VisualizationMessage+from posthog.schema import MarkdownBlock, TrendsQuery, VisualizationMessagefrom products.notebooks.backend.facade.collab import apply_utf16_text_changes, markdown_crcfrom products.notebooks.backend.models import Notebook@@ -196,6 +196,23 @@ class TestSaveNotebookToDb(BaseTest):self.assertIn("InsightVizNode", markdown)self.assertEqual(notebook.text_content, markdown)+ def test_save_notebook_keeps_mdx_cells_and_resolves_visualizations(self) -> None:+ parent = self._create_notebook_parent("mdxr")+ self._create_visualization_artifact({"kind": "TrendsQuery", "series": []}, "chrt")+ mdx = '---\n\n<SQLV2 code="SELECT 1" />\n\n<Widget prompt="Plot the results" />'+ async_to_sync(save_notebook_to_db)(+ team=self.team,+ user=self.user,+ artifact=parent,+ blocks=[MarkdownBlock(content=mdx), VisualizationRefBlock(artifact_id="chrt")],+ title="Chart notes",+ state_messages=[],+ )+ notebook = Notebook.objects.get(team=self.team, short_id=parent.short_id)+ markdown = _get_notebook_markdown(notebook)+ self.assertTrue(markdown.startswith(f"# Chart notes\n\n{mdx}\n\n"))+ self.assertEqual(len(_extract_query_props(markdown)), 1)+def test_save_notebook_keeps_tiptap_format_for_existing_notebook(self):parent = self._create_notebook_parent("ntfm")notebook = Notebook.objects.create(diff --git a/ee/hogai/tools/create_notebook/test/test_tool.py b/ee/hogai/tools/create_notebook/test/test_tool.pyindex 687c1ef69193..2a1281d69ca8 100644--- a/ee/hogai/tools/create_notebook/test/test_tool.py+++ b/ee/hogai/tools/create_notebook/test/test_tool.py@@ -5,6 +5,8 @@ from asgiref.sync import async_to_syncfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized+from posthog.schema import HumanMessage, MaxNotebookContext, MaxUIContext+from products.notebooks.backend.models import Notebookfrom products.posthog_ai.backend.models.assistant import Conversation@@ -164,6 +166,36 @@ class TestCreateNotebookTool(BaseTest):assert notebook.content is not Noneassert notebook.content["type"] == "doc"+ @parameterized.expand([(False,), (True,)])+ def test_inline_artifact_does_not_save_a_second_notebook(self, save_to_notebook: bool) -> None:+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, title="Chart notes")+ self.tool._state = AssistantState(+ messages=[+ HumanMessage(+ content="Add a chart section",+ ui_context=MaxUIContext(+ notebooks=[+ MaxNotebookContext(+ id=notebook.short_id,+ insertion_placeholder_block_id="inline-request",+ insertion_placeholder_marker="Thinking...",+ )+ ]+ ),+ )+ ]+ )+ _, artifact = async_to_sync(self.tool._arun_impl)(+ title="Chart notes",+ content='# Chart notes\n\n<SQLV2 code="SELECT 1" />',+ artifact_id=notebook.short_id,+ save_to_notebook=save_to_notebook,+ )+ assert artifact is not None+ assert Notebook.objects.filter(team=self.team).count() == 1+ assert notebook.short_id in artifact.messages[1].content+ assert "No separate notebook was saved" in artifact.messages[1].content+def test_save_to_notebook_uses_artifact_short_id(self):result, artifact = async_to_sync(self.tool._arun_impl)(title="Linked Notebook",diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.pyindex a3af4a120120..9cfa080020de 100644--- a/ee/hogai/tools/create_notebook/tool.py+++ b/ee/hogai/tools/create_notebook/tool.py@@ -105,6 +105,7 @@ Our signup funnel shows the following conversion rates:# Editing a Markdown notebook v2 from inline AI:- When the UI context includes a Markdown notebook with an inline response placeholder, use this tool with `content` when the user asks to clean up, rewrite, reorganize, or replace the whole notebook- In that case, `content` must be the complete final markdown for the notebook, not just the text that replaces the inline prompt+- The editor applies the artifact to the open notebook. Do not save a separate notebook or call another notebook editing tool for the same change- Do not include the inline placeholder text, empty `<Prompt question="" />` blocks, or the user's instruction prompt in the final markdown unless the user explicitly asks to keep them- Use a direct assistant markdown response instead of this tool only for local answers or small insertions that should replace the inline response placeholder{cell_guidance}@@ -185,6 +186,16 @@ class CreateNotebookTool(MaxTool):notebook_content = draft_content if is_draft else contentassert notebook_content is not None+ ui_context = self._context_manager.get_ui_context(self._state)+ inline_notebook = (+ next(+ (notebook for notebook in (ui_context.notebooks or []) if notebook.insertion_placeholder_block_id),+ None,+ )+ if ui_context+ else None+ )+artifact, status, blocks = await create_or_update_notebook_artifact(artifacts_manager=self._context_manager.artifacts,content=notebook_content,@@ -196,7 +207,9 @@ class CreateNotebookTool(MaxTool):is_already_saved = await notebook_exists_for_artifact(self._team, artifact.short_id)# Save to DB if explicitly requested or if updating an already-saved notebook- if save_to_notebook or is_already_saved:+ # The inline editor owns the save, including the user's retained prompt and unsaved edits.+ should_save = (save_to_notebook or is_already_saved) and inline_notebook is None+ if should_save:try:await save_notebook_to_db(team=self._team,@@ -222,7 +235,13 @@ class CreateNotebookTool(MaxTool):)# Build response message- if save_to_notebook or is_already_saved:+ if inline_notebook is not None:+ message = (+ f"The notebook artifact is for the open notebook {inline_notebook.id}. "+ "The editor applies it there when streamed. No separate notebook was saved. "+ "Do not save another copy or repeat this edit with another notebook tool."+ )+ elif should_save:if status == ArtifactStatus.UPDATED:message = f"The notebook artifact and saved notebook have been updated (short_id: {artifact.short_id})."else:diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dac9451fa6d5..cef5d9f91b0e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1380,6 +1380,10 @@ snapshots:hash: v1.k794b7964.b933911885203330331bde8bd799fd74fcd4e5964ba7fba4538dd075f07e32dc.QhPFXSfVCoIMya1xKmHLdyh3P9dJf-zNL4_zLUNqgqUcomponents-markdown-editor-rich--with-markdown--light:hash: v1.k794b7964.98bef7667e05e7a86864149a5db5c24b3d4733bcef7d413ab6faf3053c79fba8.evR63xGwLPTzXw6Hi35ROggl2AHmH_y5lT5p05kFGTg+ components-markdown-notebook--ask-ai-without-consent--dark:+ hash: v1.k794b7964.ebb253a1569c71c4c5a8e8b960f46c9c7c32b29ccab555b5c646cb50a88308ed.Cec9A53K1lhmiX7cygBRREm_UGPUFhNRq3CvIttZMJ4+ components-markdown-notebook--ask-ai-without-consent--light:+ hash: v1.k794b7964.e97394f9850e49896ddddf9624d3b43e20200250d74e94813707d83ab7badfa3.SAe1CR7VbZrrerWJx4oCvLsskyEJ9SwjKrMjxA0Fi3Ucomponents-markdown-notebook--component-catalog--dark:hash: v1.k794b7964.a7705b33b2bb9d98a08dad08712a89455876a99422d2d2c60e7d2186d2412796.wxqLNiekJQaoxnPyCAogVqcN8btyRGECwxbDHFxoS2ocomponents-markdown-notebook--component-catalog--light:diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsxindex afa75de11e31..097f5a2990bd 100644--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx@@ -52,7 +52,7 @@ export function FormattingToolbar({setBlockStyle,copySelection,askAIAboutSelection,- isAskAIDisabled,+ askAIDisabledReason,startInlineCommentAtSelection,lockPosition,returnFocusToEditor,@@ -71,7 +71,7 @@ export function FormattingToolbar({setBlockStyle: (style: TextBlockStyle) => voidcopySelection: () => voidaskAIAboutSelection?: () => void- isAskAIDisabled?: boolean+ askAIDisabledReason?: stringstartInlineCommentAtSelection?: () => voidlockPosition: () => void/** Moves focus back into the editor (Escape while the toolbar holds focus). */@@ -349,8 +349,7 @@ export function FormattingToolbar({icon={<IconSparkles />}tooltip="Ask AI"aria-label="Ask AI"- disabled={isAskAIDisabled}- disabledReason={isAskAIDisabled ? 'Ask AI is already active' : undefined}+ disabledReason={askAIDisabledReason}onClick={askAIAboutSelection}/>) : null}diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsxindex 3d18e167d785..d25734ed267f 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx@@ -387,6 +387,15 @@ export const SlashMenuAndInsertion: Story = {},}+export const AskAIWithoutConsent: Story = {+ args: {+ value: '',+ initialInsertMenu: { nodeIndex: 0, query: '' },+ onAskAI: fn(),+ askAIDisabledReason: 'Approve AI data processing in organization settings to use Ask AI.',+ },+}+export const MockedCollaboration: Story = {args: {value: textNotebook,diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex a4405f25f8d6..038443b050a7 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -3860,6 +3860,7 @@ ${queryMarkdown}`)markdown: `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n**You:** Add a summary here\n\nThinking...`,markdownWithResponse: `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n**You:** Add a summary here\n\nThinking...`,selectedMarkdown: undefined,+ retainedQuestionMarkdown: '**You:** Add a summary here',}))expect(aiRequest.query).not.toContain(TEST_NOTEBOOK_TITLE_MARKDOWN)@@ -3874,6 +3875,31 @@ ${queryMarkdown}`)expect(aiRequest.query).toContain('Full-notebook artifact content must not include the prompt')})+ it.each([false, true])('blocks Ask AI without consent, with persisted prompt %s', (persisted) => {+ const onAskAI = jest.fn()+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle(persisted ? '<Prompt question="Summarize the chart" />' : ' '),+ onAskAI,+ onChange,+ askAIDisabledReason: 'Approve AI data processing in organization settings to use Ask AI.',+ initialInsertMenu: persisted ? undefined : { nodeIndex: 1, query: '' },+ })+ )+ if (persisted) {+ fireEvent.keyDown(getAIPromptInput(container), { key: 'Enter' })+ } else {+ const option = container.querySelector('.MarkdownNotebook__insert-item') as HTMLButtonElement+ expect(option.textContent).toBe('Ask AI')+ expect(option.disabled).toBe(true)+ fireEvent.click(option)+ }+ expect(onAskAI).not.toHaveBeenCalled()+ expect(onChange).not.toHaveBeenCalled()+ expect(container.textContent).not.toContain('Thinking...')+ })+it('opens Ask AI prompts while an AI request is active but blocks submission', () => {const onAskAI = jest.fn()const onChange = jest.fn()@@ -4212,6 +4238,7 @@ Current AI paragraph`),expect.objectContaining({conversationId: TEST_AI_CONVERSATION_ID,query: expect.stringContaining('User request:\nWhat happened here?'),+ retainedQuestionMarkdown: undefined,}))expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nThinking...`)diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex 471600ca3bff..e92880a69879 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -243,6 +243,7 @@ export type MarkdownNotebookProps = {onAskAI?: (request: MarkdownNotebookAskAIRequest) => voidaiPromptAuthorName?: stringisAskAIDisabled?: boolean+ askAIDisabledReason?: stringcreateAIConversationId?: () => stringmode?: NotebookModeregistry?: NotebookComponentRegistry@@ -305,6 +306,7 @@ export type MarkdownNotebookAskAIRequest = {markdownWithResponse: stringselectedMarkdown?: stringselectedRefId?: string+ retainedQuestionMarkdown?: string}type CommitDocumentOptions = {@@ -600,7 +602,8 @@ function MarkdownNotebookEditor({onChange,onAskAI,aiPromptAuthorName = 'You',- isAskAIDisabled: isAIPromptSubmitDisabled = false,+ isAskAIDisabled = false,+ askAIDisabledReason,createAIConversationId = createDefaultAIConversationId,mode = 'edit',registry,@@ -629,6 +632,7 @@ function MarkdownNotebookEditor({onDebugOpenChange,'data-attr': dataAttr = 'markdown-notebook',}: MarkdownNotebookProps): JSX.Element {+ const isAIPromptSubmitDisabled = isAskAIDisabled || !!askAIDisabledReasonconst mergedRegistry = useMemo(() => mergeMarkdownNotebookRegistries(getMarkdownNotebookDefaultRegistry(), registry),[registry]@@ -2863,6 +2867,9 @@ function MarkdownNotebookEditor({nodeId: string,options?: { source?: 'slash' | 'selection'; selectedMarkdown?: string; selectedRefId?: string }): void => {+ if (askAIDisabledReason) {+ return+ }onInteractionStateChange?.(true)const currentDocument = documentRef.currentconst nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]@@ -2913,7 +2920,7 @@ function MarkdownNotebookEditor({selectedRefId: options?.selectedRefId,})},- [commitDocument, onInteractionStateChange]+ [askAIDisabledReason, commitDocument, onInteractionStateChange])const updateAIPromptQuery = (nodeId: string, query: string): void => {@@ -2955,7 +2962,7 @@ function MarkdownNotebookEditor({restoreSelectionRef.current = { nodeId, start: 0, end: 0 }},onAskAI ? openAIPrompt : undefined,- false,+ !!askAIDisabledReason,extraInsertCommands ? extraInsertCommands(insertMenuApi) : []),hiddenInsertCommandKeys@@ -2965,6 +2972,7 @@ function MarkdownNotebookEditor({replaceNodeWithInsertedComponent,replaceNode,onAskAI,+ askAIDisabledReason,openAIPrompt,extraInsertCommands,hiddenInsertCommandKeys,@@ -5533,6 +5541,7 @@ function MarkdownNotebookEditor({}let responseNodeIndex = -1+ let retainedQuestionMarkdown: string | undefinedconst keepQuestion = currentPromptNode?.props.keepQuestion !== falseconst nodesWithResponse = nodes.flatMap((currentNode, index): NotebookBlockNode[] => {if (currentNode.id !== nodeId || !isPromptComponentNode(currentNode)) {@@ -5552,6 +5561,7 @@ function MarkdownNotebookEditor({responseNodeIndex = index + 1const questionNode = makeRetainedAIQuestionNode(aiPromptAuthorName, query, `ai-question-${currentNode.id}`)questionNode.startsGroup = currentNode.startsGroup+ retainedQuestionMarkdown = serializeMarkdownNotebook({ ...currentDocument, nodes: [questionNode] })return [questionNode, responseNode]})if (responseNodeIndex === -1) {@@ -5583,6 +5593,7 @@ function MarkdownNotebookEditor({markdownWithResponse,selectedMarkdown,selectedRefId,+ retainedQuestionMarkdown,})return true}@@ -6333,7 +6344,7 @@ function MarkdownNotebookEditor({setBlockStyle={setSelectedBlockStyle}copySelection={copyFloatingToolbarSelection}askAIAboutSelection={onAskAI ? askAIAboutSelection : undefined}- isAskAIDisabled={false}+ askAIDisabledReason={askAIDisabledReason}startInlineCommentAtSelection={canStartInlineCommentAtSelection() ? startInlineCommentAtSelection : undefined}diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.tsindex 082f91959938..ce4ce3ccc1b3 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts@@ -1,5 +1,6 @@import {insertNotebookAIFollowUpPromptAfterResponse,+ preserveNotebookAIQuestion,rebaseNotebookAIResponseRange,replaceNotebookAIResponseMarkdown,streamNotebookAIResponseMarkdown,@@ -20,6 +21,14 @@ function replaceMarkdown(}describe('notebookAI', () => {+ it.each([true, false])('preserves the prompt in a full artifact only when requested: %s', (keepQuestion) => {+ const content = '# Chart notes\n\n---\n\n<SQLV2 code="SELECT 1" />\n\n<Widget prompt="Plot the results" />'+ const question = '**You:** Add a chart section'+ const result = preserveNotebookAIQuestion(content, keepQuestion ? question : undefined)+ expect(result).toBe(keepQuestion ? content.replace('# Chart notes', `# Chart notes\n\n${question}`) : content)+ expect(preserveNotebookAIQuestion(result, keepQuestion ? question : undefined)).toBe(result)+ expect(result).not.toContain('Thinking...')+ })it.each([['SQLV2', ['Widget'], false],['PythonV2', ['Widget'], false],diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.tsindex c275294f4a0d..9972cf4d9324 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts@@ -4,6 +4,28 @@ import { getNodeFingerprint, getNodeSignature, getNodeText } from './utils'export const NOTEBOOK_AI_WRITING_PLACEHOLDER = 'Thinking...'+export function preserveNotebookAIQuestion(markdown: string, retainedQuestionMarkdown?: string): string {+ if (!retainedQuestionMarkdown) {+ return markdown+ }+ const document = parseMarkdownNotebook(markdown)+ const questionNodes = parseMarkdownNotebook(retainedQuestionMarkdown).nodes+ const existingFingerprints = new Set(document.nodes.map(getNodeFingerprint))+ const missingQuestionNodes = questionNodes.filter((node) => !existingFingerprints.has(getNodeFingerprint(node)))+ if (!missingQuestionNodes.length) {+ return markdown+ }+ const insertionIndex = document.nodes[0]?.type === 'heading' ? 1 : 0+ return serializeMarkdownNotebook({+ ...document,+ nodes: [+ ...document.nodes.slice(0, insertionIndex),+ ...missingQuestionNodes,+ ...document.nodes.slice(insertionIndex),+ ],+ })+}+export type NotebookAIResponseMarkdownResult = {markdown: stringresponseNodeIndex: numberdiff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex ab11f11a4b23..49c2d24c0b91 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -19,6 +19,7 @@ import type {import { makeEmptyParagraph } from 'lib/components/MarkdownNotebook/markdown'import {insertNotebookAIFollowUpPromptAfterResponse,+ preserveNotebookAIQuestion,rebaseNotebookAIResponseRange,replaceNotebookAIResponseMarkdown,streamNotebookAIResponseMarkdown,@@ -29,6 +30,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 { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { userLogic } from 'scenes/userLogic'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'@@ -94,6 +96,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot} = useValues(notebookLogic)const { featureFlags } = useValues(featureFlagLogic)const { user } = useValues(userLogic)+ const { dataProcessingAccepted } = useValues(aiConsentLogic)const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])const enabledAIComponentTags = useMemo(() => [@@ -364,6 +367,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotmarkdownWithResponse,selectedMarkdown,selectedRefId,+ retainedQuestionMarkdown,}: MarkdownNotebookAskAIRequest): void => {markAIPresenceActive(conversationId)setAICaretPosition(getNotebookAICaretPosition(markdownWithResponse, responseNodeIndex))@@ -389,6 +393,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotmarkdownWithResponse,selectedMarkdown,selectedRefId,+ retainedQuestionMarkdown,uiContext,}setInlineAIRequests((currentRequests) => [@@ -425,10 +430,12 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot): void => {const inlineAIRequest = getInlineAIRequest(conversationId)if (inlineAIRequest) {- const artifactMarkdown = notebookArtifactContentToMarkdown(content)+ const artifactMarkdown = preserveNotebookAIQuestion(+ notebookArtifactContentToMarkdown(content),+ mode === 'replace' ? inlineAIRequest.retainedQuestionMarkdown : undefined+ )if (mode === 'replace') {- markdownEditorValueRef.current = artifactMarkdown- applyNotebookArtifactMarkdown(content, conversationId, mode)+ updateMarkdownEditorValue(() => artifactMarkdown)inlineAIResponseNodeCountsRef.current[inlineAIRequest.conversationId] = 1const responseNodeIndex = Math.max(0, getMarkdownBlockCount(artifactMarkdown) - 1)inlineAIResponseNodeIndicesRef.current[inlineAIRequest.conversationId] = responseNodeIndex@@ -756,6 +763,11 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotonAskAI={isEditable ? handleAskAI : undefined}convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}isAskAIDisabled={inlineAIRequests.length > 0}+ askAIDisabledReason={+ dataProcessingAccepted+ ? undefined+ : 'Approve AI data processing in organization settings to use Ask AI.'+ }createAIConversationId={uuid}deferRemoteValue={markdownEditorInteractionActive}onInteractionStateChange={setMarkdownEditorInteractionActive}