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.

fix(notebooks): Fixes the flow to add SavedInsights to markdown notebooks (#64512)

Sinan Kucukkoseler7f17a15e061b
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts
new file mode 100644
index 000000000000..15ec8be05905
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts
@@ -0,0 +1,43 @@
+import { InsertCommand } from './editorTypes'
+import { buildInsertCommands } from './InsertMenu'
+import { getMarkdownNotebookDefaultRegistry } from './registry'
+
+describe('buildInsertCommands', () => {
+ const noop = (): void => {}
+
+ const build = (
+ extraCommands?: InsertCommand[]
+ ): { commands: InsertCommand[]; replaceNodeWithInsertedComponent: jest.Mock } => {
+ const replaceNodeWithInsertedComponent = jest.fn()
+ const commands = buildInsertCommands(
+ getMarkdownNotebookDefaultRegistry(),
+ replaceNodeWithInsertedComponent,
+ noop,
+ noop,
+ noop,
+ noop,
+ undefined,
+ undefined,
+ extraCommands
+ )
+ return { commands, replaceNodeWithInsertedComponent }
+ }
+
+ it('appends caller-supplied commands and runs their callbacks untouched', () => {
+ const run = jest.fn()
+ const extraCommand: InsertCommand = { key: 'custom', label: 'Custom', category: 'Insight', run }
+ const { commands, replaceNodeWithInsertedComponent } = build([extraCommand])
+
+ const command = commands.find((candidate) => candidate.key === 'custom')
+ command?.run('node-1')
+
+ expect(command).toBe(extraCommand)
+ expect(run).toHaveBeenCalledWith('node-1')
+ expect(replaceNodeWithInsertedComponent).not.toHaveBeenCalled()
+ })
+
+ it('omits caller-supplied commands when none are provided', () => {
+ const { commands } = build()
+ expect(commands.find((candidate) => candidate.key === 'custom')).toBeUndefined()
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
index d657709b26ed..d3b4cbca3ffa 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
@@ -172,7 +172,8 @@ export function buildInsertCommands(
focusInsertedTable: (nodeId: string) => void,
focusInsertedCode: (nodeId: string) => void,
openAIPrompt?: (nodeId: string) => void,
- isAskAIDisabled?: boolean
+ isAskAIDisabled?: boolean,
+ extraCommands: InsertCommand[] = []
): InsertCommand[] {
const commonCategory = 'Common'
@@ -276,19 +277,6 @@ export function buildInsertCommands(
},
}),
},
- {
- key: 'query-saved-insight',
- label: 'Saved insight',
- category: 'Insight',
- icon: <IconGraph />,
- run: (targetNodeId) =>
- insertComponent(targetNodeId, 'Query', {
- query: {
- kind: 'SavedInsightNode',
- shortId: '',
- },
- }),
- },
]
const sqlCommands: InsertCommand[] = [
@@ -496,6 +484,7 @@ export function buildInsertCommands(
...mediaCommands,
...componentCommands,
...textStyleCommands,
+ ...extraCommands,
]
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
index a766d62bf3b6..bb728cd6c196 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
@@ -1,6 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react'
import { useState } from 'react'
+import { IconGraph } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { MarkdownNotebook, MarkdownNotebookProps } from './MarkdownNotebook'
@@ -244,6 +245,17 @@ export const SlashMenuAndInsertion: Story = {
args: {
value: '',
initialInsertMenu: { nodeIndex: 0, query: '' },
+ // Extra commands are injected by the caller (the scenes layer wires up "Saved insight"); a stub
+ // command keeps that row present in the menu snapshot without mounting any real modal.
+ extraInsertCommands: () => [
+ {
+ key: 'query-saved-insight',
+ label: 'Saved insight',
+ category: 'Insight',
+ icon: <IconGraph />,
+ run: () => {},
+ },
+ ],
},
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 40746f746939..a1c1d65b92fb 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -111,9 +111,11 @@ import {
FloatingToolbarState,
FloatingToolbarTextRange,
INSERT_MENU_PLACEHOLDER,
+ InsertCommand,
InsertMenuPosition,
InsertMenuSelectionDirection,
InsertMenuState,
+ MarkdownNotebookInsertMenuApi,
MAX_UNDO_HISTORY_ENTRIES,
NOTEBOOK_TITLE_PLACEHOLDER,
RestoreSelectionRequest,
@@ -220,6 +222,9 @@ export type MarkdownNotebookProps = {
createAIChatId?: () => string
mode?: NotebookMode
registry?: NotebookComponentRegistry
+ /** Caller-supplied insert-menu commands. Receives an API for inserting blocks so the command's
+ * behavior (e.g. opening a picker modal) and labeling stay in the caller, not this component. */
+ extraInsertCommands?: (api: MarkdownNotebookInsertMenuApi) => InsertCommand[]
remoteValue?: string
/** Notebook version `remoteValue` corresponds to, for version-aware caret mapping. */
remoteVersion?: number
@@ -391,6 +396,7 @@ export function MarkdownNotebook({
createAIChatId = createDefaultAIChatId,
mode = 'edit',
registry,
+ extraInsertCommands,
remoteValue,
remoteVersion,
deferRemoteValue = false,
@@ -2222,6 +2228,19 @@ export function MarkdownNotebook({
[mergedRegistry, replaceNode]
)
+ const insertMenuApi = useMemo<MarkdownNotebookInsertMenuApi>(
+ () => ({
+ insertComponent: (targetNodeId, tagName, props) =>
+ replaceNodeWithInsertedComponent(targetNodeId, {
+ id: makeEmptyParagraph(`component-${tagName}`).id,
+ type: 'component',
+ tagName,
+ props,
+ }),
+ }),
+ [replaceNodeWithInsertedComponent]
+ )
+
const replaceNodeWithNodes = useCallback(
(nodeId: string, replacementNodes: NotebookBlockNode[]): void => {
const currentDocument = documentRef.current
@@ -2435,9 +2454,19 @@ export function MarkdownNotebook({
restoreSelectionRef.current = { nodeId, start: 0, end: 0 }
},
onAskAI ? openAIPrompt : undefined,
- isAskAIInsertionDisabled
+ isAskAIInsertionDisabled,
+ extraInsertCommands ? extraInsertCommands(insertMenuApi) : []
),
- [mergedRegistry, replaceNodeWithInsertedComponent, replaceNode, onAskAI, openAIPrompt, isAskAIInsertionDisabled]
+ [
+ mergedRegistry,
+ replaceNodeWithInsertedComponent,
+ replaceNode,
+ onAskAI,
+ openAIPrompt,
+ isAskAIInsertionDisabled,
+ extraInsertCommands,
+ insertMenuApi,
+ ]
)
function getRenderedNodes(): NotebookBlockNode[] {
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
index d29580035264..20fb5b2b47d3 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
@@ -365,6 +365,12 @@ export function getComponentToolbarTitle(
definition: NotebookComponentDefinition | null,
label: string
): string | null {
+ if (
+ node.tagName === 'Query' &&
+ getNotebookStringProp(getNotebookObjectProp(node.props.query)?.kind) === 'SavedInsightNode'
+ ) {
+ return null
+ }
const title = definition?.getTitle?.(node) ?? getNotebookStringProp(node.props.title)
const trimmedTitle = title?.trim()
return trimmedTitle && trimmedTitle !== label ? trimmedTitle : null
diff --git a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts b/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
index 2dbfce72018a..25e8d61adc0a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
@@ -7,6 +7,7 @@ import {
import {
NotebookCodeBlockNode,
+ NotebookComponentProps,
NotebookInlineNode,
NotebookListBlockNode,
NotebookTextBlockNode,
@@ -44,6 +45,12 @@ export type InsertCommand = {
run: (targetNodeId: string) => void
}
+/** Insertion primitives handed to caller-supplied insert commands so they can add blocks without
+ * reaching into the editor's internals. The caller owns the command's label, icon, and behavior. */
+export type MarkdownNotebookInsertMenuApi = {
+ insertComponent: (targetNodeId: string, tagName: string, props: NotebookComponentProps) => void
+}
+
export type InsertMenuState = {
nodeId: string
query: string
diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.ts
index dc4fa6a326a1..5b2acc08a326 100644
--- a/frontend/src/lib/components/MarkdownNotebook/index.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts
@@ -1,5 +1,6 @@
export { MarkdownNotebook } from './MarkdownNotebook'
export type { MarkdownNotebookAskAIRequest, MarkdownNotebookProps } from './MarkdownNotebook'
+export type { InsertCommand, MarkdownNotebookInsertMenuApi } from './editorTypes'
export {
getMarkdownNotebookDefaultRegistry,
createMarkdownNotebookRegistry,
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx
new file mode 100644
index 000000000000..abebf65b2c9e
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx
@@ -0,0 +1,36 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
+import { SavedInsightsTable } from 'scenes/saved-insights/SavedInsightsTable'
+
+export type MarkdownNotebookSavedInsightPickerProps = {
+ isOpen: boolean
+ onClose: () => void
+ onSelect: (shortId: string, title: string) => void
+}
+
+export function MarkdownNotebookSavedInsightPicker({
+ isOpen,
+ onClose,
+ onSelect,
+}: MarkdownNotebookSavedInsightPickerProps): JSX.Element {
+ const summarizeInsight = useSummarizeInsight()
+
+ return (
+ <LemonModal
+ title="Add insight to notebook"
+ onClose={onClose}
+ isOpen={isOpen}
+ footer={
+ <LemonButton type="secondary" data-attr="markdown-notebook-saved-insight-cancel" onClick={onClose}>
+ Close
+ </LemonButton>
+ }
+ >
+ <SavedInsightsTable
+ onToggle={(insight) => onSelect(insight.short_id, insight.name || summarizeInsight(insight.query))}
+ />
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 03a1d7974dcc..215967473ba3 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -1,8 +1,14 @@
import { useActions, useValues } from 'kea'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { IconGraph } from '@posthog/icons'
+
import { MarkdownNotebook, parseMarkdownNotebook } from 'lib/components/MarkdownNotebook'
-import type { MarkdownNotebookAskAIRequest } from 'lib/components/MarkdownNotebook'
+import type {
+ InsertCommand,
+ MarkdownNotebookAskAIRequest,
+ MarkdownNotebookInsertMenuApi,
+} from 'lib/components/MarkdownNotebook'
import {
insertNotebookAIFollowUpPromptAfterResponse,
replaceNotebookAIResponseMarkdown,
@@ -24,6 +30,7 @@ import {
getInlineNotebookAIPanelId,
getNotebookAIChatUIContext,
} from './markdownNotebookRuntime'
+import { MarkdownNotebookSavedInsightPicker } from './MarkdownNotebookSavedInsightPicker'
import { getMarkdownNotebookMarkdown, notebookArtifactContentToMarkdown } from './markdownNotebookV2'
import { notebookLogic } from './notebookLogic'
import {
@@ -321,6 +328,48 @@ export function MarkdownNotebookV2(): JSX.Element {
[applyNotebookArtifactMarkdown, getInlineAIRequest, updateMarkdownEditorValue]
)
+ const [savedInsightPickerTargetNodeId, setSavedInsightPickerTargetNodeId] = useState<string | null>(null)
+ // Insert API + target node captured when "Saved insight" is picked, so the modal's async selection
+ // can insert into the right node once an insight is chosen.
+ const savedInsightInsertRef = useRef<{ api: MarkdownNotebookInsertMenuApi; targetNodeId: string } | null>(null)
+
+ const buildSavedInsightInsertCommands = useCallback(
+ (api: MarkdownNotebookInsertMenuApi): InsertCommand[] => [
+ {
+ key: 'query-saved-insight',
+ label: 'Saved insight',
+ category: 'Insight',
+ icon: <IconGraph />,
+ run: (targetNodeId) => {
+ savedInsightInsertRef.current = { api, targetNodeId }
+ setSavedInsightPickerTargetNodeId(targetNodeId)
+ },
+ },
+ ],
+ []
+ )
+
+ const closeSavedInsightPicker = useCallback((): void => {
+ savedInsightInsertRef.current = null
+ setSavedInsightPickerTargetNodeId(null)
+ }, [])
+
+ const handleSavedInsightPicked = useCallback((shortId: string, title: string): void => {
+ const pending = savedInsightInsertRef.current
+ if (pending) {
+ pending.api.insertComponent(pending.targetNodeId, 'Query', {
+ query: { kind: 'SavedInsightNode', shortId },
+ // The insight is already configured via the picker, so render results-only — hiding the
+ // settings panel (the "Edit the insight" / "Detach from insight" controls) by default.
+ hideFilters: true,
+ // Label the node with the insight's name so the toolbar shows it instead of the short id.
+ ...(title ? { title } : {}),
+ })
+ }
+ savedInsightInsertRef.current = null
+ setSavedInsightPickerTargetNodeId(null)
+ }, [])
+
const runtimeContext = useMemo<MarkdownNotebookRuntimeContextValue>(
() => ({
notebookShortId: notebook?.short_id ?? null,
@@ -426,6 +475,7 @@ export function MarkdownNotebookV2(): JSX.Element {
remoteVersion={notebook?.version}
mode={isEditable ? 'edit' : 'view'}
registry={NOTEBOOK_MARKDOWN_REGISTRY}
+ extraInsertCommands={isEditable ? buildSavedInsightInsertCommands : undefined}
onChange={isEditable ? handleMarkdownEditorChange : undefined}
onConflict={reportMarkdownMergeConflicts}
remoteCarets={remoteCarets}
@@ -450,6 +500,13 @@ export function MarkdownNotebookV2(): JSX.Element {
onAssistantMessage={handleInlineAIAssistantMessage}
/>
))}
+ {isEditable && (
+ <MarkdownNotebookSavedInsightPicker
+ isOpen={savedInsightPickerTargetNodeId !== null}
+ onClose={closeSavedInsightPicker}
+ onSelect={handleSavedInsightPicked}
+ />
+ )}
</MarkdownNotebookRuntimeContext.Provider>
)
}