: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): track markdown saves and default wide mode (#66937)
Marius Andra8a6d7f9a5dca
diff --git a/ee/urls.py b/ee/urls.pyindex 3316f64426c1..a53ce8d233c0 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -115,6 +115,11 @@ if settings.ADMIN_PORTAL_ENABLED:health_check_runs_fragment_view,health_check_trigger_view,)+ from posthog.admin.admins.notebook_markdown_migration_admin import (+ notebook_markdown_migration_run_view,+ notebook_markdown_migration_stats_view,+ notebook_markdown_migration_view,+ )from posthog.admin.admins.radar_bypass_admin import RadarBypassViewSet, radar_bypass_viewfrom posthog.admin.admins.realtime_cohort_calculation_admin import analyze_realtime_cohort_calculation_viewfrom posthog.admin.admins.resave_cohorts_admin import resave_cohorts_view@@ -209,6 +214,21 @@ if settings.ADMIN_PORTAL_ENABLED:admin.site.admin_view(health_check_runs_fragment_view),name="health-check-runs",),+ path(+ "admin/notebook-markdown-migration/",+ admin.site.admin_view(notebook_markdown_migration_view),+ name="notebook-markdown-migration",+ ),+ path(+ "admin/notebook-markdown-migration/stats/",+ admin.site.admin_view(notebook_markdown_migration_stats_view),+ name="notebook-markdown-migration-stats",+ ),+ path(+ "admin/notebook-markdown-migration/run/",+ admin.site.admin_view(notebook_markdown_migration_run_view),+ name="notebook-markdown-migration-run",+ ),path("admin/logout/",impersonated_session_logout,diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsxindex 931ef4f4a6a7..ae24c02626da 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2RendererUI.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render } from '@testing-library/react'+import { act, fireEvent, render } from '@testing-library/react'import { BindLogic } from 'kea'import { expectLogic } from 'kea-test-utils'import { useState } from 'react'@@ -13,8 +13,9 @@ import { AccessControlLevel } from '~/types'import { NotebookType } from '../types'import { buildMarkdownNotebookContent } from './markdownNotebookV2'import { MarkdownNotebookV2 } from './MarkdownNotebookV2Renderer'+import { Notebook } from './Notebook'import { NotebookLogicProps, notebookLogic } from './notebookLogic'-import { NotebookKernelInfoButton } from './NotebookMeta'+import { NotebookExpandButton, NotebookKernelInfoButton } from './NotebookMeta'import { notebookSettingsLogic } from './notebookSettingsLogic'jest.mock('./migrations/migrate', () => {@@ -113,4 +114,35 @@ describe('MarkdownNotebookV2Renderer UI', () => {expect(settingsLogic.values.showKernelInfo).toBe(true)expect(container.querySelector('.MarkdownNotebook__debug-drawer')).toBeNull()})++ it('renders markdown notebooks at expanded width by default and respects the markdown collapse setting', () => {+ const { container } = render(<Notebook shortId={SHORT_ID} mode="notebook" cachedNotebook={cachedNotebook} />)+ const notebookElement = container.querySelector('.Notebook')++ expect(notebookElement?.classList.contains('Notebook--expanded')).toBe(true)+ expect(notebookElement?.classList.contains('Notebook--compact')).toBe(false)++ act(() => {+ settingsLogic.actions.setIsMarkdownExpanded(false)+ })++ expect(notebookElement?.classList.contains('Notebook--compact')).toBe(true)+ expect(notebookElement?.classList.contains('Notebook--expanded')).toBe(false)+ })++ it('collapses markdown content width without changing the legacy notebook width setting', () => {+ const { container } = render(+ <NotebookExpandButton type="secondary" size="small" inPanel={false} isMarkdownNotebook />+ )+ const button = container.querySelector('button')++ expect(settingsLogic.values.isMarkdownExpanded).toBe(true)+ expect(settingsLogic.values.isExpanded).toBe(false)+ expect(button).toBeInstanceOf(HTMLButtonElement)++ fireEvent.click(button as HTMLButtonElement)++ expect(settingsLogic.values.isMarkdownExpanded).toBe(false)+ expect(settingsLogic.values.isExpanded).toBe(false)+ })})diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex 676a24de14f2..c5856658fd76 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -75,7 +75,7 @@ export function Notebook({comments,} = useValues(logic)const { duplicateNotebook, loadNotebook, setEditable, setLocalContent, setContainerSize } = useActions(logic)- const { isExpanded } = useValues(notebookSettingsLogic)+ const { isExpanded, isMarkdownExpanded } = useValues(notebookSettingsLogic)const { isCommandOpen } = useValues(commandLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -116,6 +116,7 @@ export function Notebook({}, [size]) // oxlint-disable-line exhaustive-depsconst isMarkdownNotebook = isMarkdownNotebookContent(content)+ const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpandedconst canUpgradeToMarkdownNotebooks = !!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]const upgradeToMarkdownNotebook = (): void => {openUpgradeToMarkdownNotebookDialog({ content, comments, setLocalContent })@@ -133,8 +134,8 @@ export function Notebook({<divclassName={clsx('Notebook',- !isExpanded && 'Notebook--compact',- isExpanded && 'Notebook--expanded',+ !isContentWidthExpanded && 'Notebook--compact',+ isContentWidthExpanded && 'Notebook--expanded',mode && `Notebook--${mode}`,size === 'small' && `Notebook--single-column`,isEditable && 'Notebook--editable',diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsxindex 69a88380757d..4940f867ed03 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookHistory.test.tsx@@ -3,12 +3,13 @@ import * as PMCollab from '@tiptap/pm/collab'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { AccessControlLevel } from '~/types'+import { AccessControlLevel, ActivityScope } from '~/types'import { NotebookEditor, NotebookType } from '../types'import { buildMarkdownNotebookContent } from './markdownNotebookV2'@@ -68,6 +69,9 @@ describe('Notebook history revert flow', () => {let editorContent: JSONContent | nulllet apiCreateSpy: jest.SpyInstancelet apiUpdateSpy: jest.SpyInstance+ let apiMarkdownSaveSpy: jest.SpyInstance+ let apiActivityListLegacySpy: jest.SpyInstance+ let historyLogic: ReturnType<typeof activityLogLogic.build> | null// The stub tracks its own content so getJSON() reflects the result of setContent// calls. Otherwise the collab path's wire payload (which is editor.getJSON()) would@@ -90,10 +94,12 @@ describe('Notebook history revert flow', () => {}) as unknown as NotebookEditorbeforeEach(() => {+ historyLogic = nulleditorContent = nulluseMocks({get: {[`/api/projects/@current/notebooks/${SHORT_ID}/`]: () => [200, cachedNotebook],+ [`/api/projects/:project_id/notebooks/${SHORT_ID}/`]: () => [200, cachedNotebook],[`/api/projects/:project_id/notebooks/${SHORT_ID}/kernel/status/`]: () => [200, { backend: null }],},})@@ -104,6 +110,10 @@ describe('Notebook history revert flow', () => {apiUpdateSpy = jest.spyOn(api.notebooks, 'update').mockResolvedValue({ ...cachedNotebook, version: 2, content: HISTORICAL_DOC })+ apiMarkdownSaveSpy = jest+ .spyOn(api.notebooks, 'markdownSave')+ .mockResolvedValue({ ...cachedNotebook, version: 2, content: HISTORICAL_DOC })+ apiActivityListLegacySpy = jest.spyOn(api.activity, 'listLegacy').mockResolvedValue({ results: [], count: 0 })// collabStream opens an SSE connection that never resolves in production —// resolve immediately in tests so the listener doesn't dangle.jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)@@ -111,6 +121,7 @@ describe('Notebook history revert flow', () => {afterEach(() => {logic?.unmount()+ historyLogic?.unmount()jest.restoreAllMocks();(PMCollab.sendableSteps as jest.Mock).mockReset()})@@ -160,6 +171,61 @@ describe('Notebook history revert flow', () => {)})+ it('saves legacy to markdown conversion through the versioned notebook update path', async () => {+ const convertedContent = buildMarkdownNotebookContent(`# Test++converted`)+ apiUpdateSpy.mockResolvedValueOnce({+ ...cachedNotebook,+ version: 2,+ content: convertedContent,+ text_content: '# Test\n\nconverted',+ })++ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()++ logic.actions.setLocalContent(convertedContent)++ await expectLogic(logic)+ .delay(SYNC_DELAY + 100)+ .toFinishAllListeners()++ expect(apiUpdateSpy).toHaveBeenCalledWith(+ SHORT_ID,+ expect.objectContaining({+ content: convertedContent,+ text_content: '# Test\n\nconverted',+ version: 1,+ })+ )+ expect(apiMarkdownSaveSpy).not.toHaveBeenCalled()+ })++ it('refreshes notebook activity after a save when history is open', async () => {+ historyLogic = activityLogLogic({ scope: ActivityScope.NOTEBOOK, id: SHORT_ID })+ historyLogic.mount()+ await expectLogic(historyLogic).toDispatchActions(['fetchActivitySuccess']).toFinishAllListeners()+ apiActivityListLegacySpy.mockClear()++ logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook', cachedNotebook })+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setShowHistory(true)++ await expectLogic(logic, () => {+ logic.actions.saveNotebook({ content: HISTORICAL_DOC, title: 'Test' })+ })+ .toDispatchActions(['saveNotebookSuccess'])+ .toFinishAllListeners()+ await expectLogic(historyLogic).toFinishAllListeners()++ expect(apiActivityListLegacySpy).toHaveBeenCalledWith({ scope: [ActivityScope.NOTEBOOK], id: SHORT_ID }, 1)+ })+it('does not enable ProseMirror collaboration for markdown v2 notebooks', async () => {featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.NOTEBOOKS_COLLABORATION], {[FEATURE_FLAGS.NOTEBOOKS_COLLABORATION]: true,diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsxindex 4f1a4ddad536..e5d68f364893 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx@@ -194,33 +194,47 @@ export const NotebookPresence = (props: NotebookLogicProps): JSX.Element | nullinterface NotebookExpandButtonProps extends Pick<LemonButtonProps, 'size' | 'type'> {inPanel: boolean+ isMarkdownNotebook?: boolean}-export const NotebookExpandButton = (props: NotebookExpandButtonProps): JSX.Element => {- const { isExpanded } = useValues(notebookSettingsLogic)- const { setIsExpanded } = useActions(notebookSettingsLogic)+export const NotebookExpandButton = ({+ inPanel,+ isMarkdownNotebook = false,+ ...buttonProps+}: NotebookExpandButtonProps): JSX.Element => {+ const { isExpanded, isMarkdownExpanded } = useValues(notebookSettingsLogic)+ const { setIsExpanded, setIsMarkdownExpanded } = useActions(notebookSettingsLogic)+ const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpanded+ const toggleContentWidth = (): void => {+ const nextIsExpanded = !isContentWidthExpanded+ if (isMarkdownNotebook) {+ setIsMarkdownExpanded(nextIsExpanded)+ } else {+ setIsExpanded(nextIsExpanded)+ }+ }- if (props.inPanel) {+ if (inPanel) {return (<ButtonPrimitive- onClick={() => setIsExpanded(!isExpanded)}+ onClick={toggleContentWidth}iconOnly- tooltip={isExpanded ? 'Fix content width' : 'Fill content width'}+ tooltip={isContentWidthExpanded ? 'Fix content width' : 'Fill content width'}tooltipPlacement="left"><IconDocumentExpandclassName="text-tertiary size-4 group-hover:text-primary z-10"- mode={isExpanded ? 'expand' : 'collapse'}+ mode={isContentWidthExpanded ? 'expand' : 'collapse'}/></ButtonPrimitive>)}return (<LemonButton- {...props}- onClick={() => setIsExpanded(!isExpanded)}- icon={<IconDocumentExpand mode={isExpanded ? 'expand' : 'collapse'} />}- tooltip={isExpanded ? 'Fix content width' : 'Fill content width'}+ {...buttonProps}+ onClick={toggleContentWidth}+ icon={<IconDocumentExpand mode={isContentWidthExpanded ? 'expand' : 'collapse'} />}+ tooltip={isContentWidthExpanded ? 'Fix content width' : 'Fill content width'}tooltipPlacement="left"/>)diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 2e1d894057a6..57fd1fcdf2cd 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -24,6 +24,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { getSeriesColor } from 'lib/colors'+import { activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'import {markdownCrc,mergeNotebookMarkdownChanges,@@ -943,19 +944,18 @@ export const notebookLogic = kea<notebookLogicType>([!isMarkdownNotebookContent(localContent || notebook?.content),],markdownRealtimeEnabled: [- (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.content, s.notebook],+ (s) => [(_, props) => props, s.mode, s.isLocalOnly, s.notebook],(props: NotebookLogicProps,mode: NotebookLogicMode,isLocalOnly: boolean,- content: JSONContent,notebook: NotebookType | null): boolean =>mode === 'notebook' &&!props.cachedNotebook &&!isLocalOnly &&!!notebook &&- isMarkdownNotebookContent(content),+ isMarkdownNotebookContent(notebook.content),],notebookMissing: [(s) => [s.notebook, s.notebookLoading, s.mode],@@ -1833,6 +1833,9 @@ export const notebookLogic = kea<notebookLogicType>([actions.clearLocalContent()}actions.scheduleNotebookRefresh()+ if (values.showHistory) {+ activityLogLogic({ scope: ActivityScope.NOTEBOOK, id: values.shortId }).actions.fetchActivity()+ }actions.processPendingMarkdownStreamEvents()},saveNotebookFailure: () => {diff --git a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.tsindex 8702c5664f62..99fadfaf1107 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookSettingsLogic.ts@@ -7,6 +7,7 @@ export const notebookSettingsLogic = kea<notebookSettingsLogicType>([path(['scenes', 'notebooks', 'notebooks', 'notebookSettingsLogic']),actions({setIsExpanded: (expanded: boolean) => ({ expanded }),+ setIsMarkdownExpanded: (expanded: boolean) => ({ expanded }),setShowKernelInfo: (showKernelInfo: boolean) => ({ showKernelInfo }),setShowTableOfContents: (showTOC: boolean) => ({ showTOC }),}),@@ -18,6 +19,13 @@ export const notebookSettingsLogic = kea<notebookSettingsLogicType>([setIsExpanded: (_, { expanded }) => expanded,},],+ isMarkdownExpanded: [+ true,+ { persist: true },+ {+ setIsMarkdownExpanded: (_, { expanded }) => expanded,+ },+ ],showKernelInfo: [false,{diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsxindex 3ddc1bc21f88..0578ea733ac8 100644--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx@@ -12,6 +12,7 @@ import { urls } from 'scenes/urls'import { SidePanelPaneHeader } from '~/layout/navigation-3000/sidepanel/components/SidePanelPaneHeader'import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/SidePanelContentContainer'+import { isMarkdownNotebookContent } from '../Notebook/markdownNotebookV2'import { Notebook } from '../Notebook/Notebook'import { NotebookListMini } from '../Notebook/NotebookListMini'import { notebookLogic } from '../Notebook/notebookLogic'@@ -31,6 +32,7 @@ export function NotebookPanel(): JSX.Element | null {const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)const { notebook } = useValues(notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover }))const editable = !notebook?.is_template+ const isMarkdownNotebook = isMarkdownNotebookContent(notebook?.content)const { ref, size } = useResizeBreakpoints({0: 'small',832: 'medium',@@ -65,7 +67,13 @@ export function NotebookPanel(): JSX.Element | null {<div className="flex items-center gap-1">{selectedNotebook && <NotebookPresence shortId={selectedNotebook} />}<NotebookMenu shortId={selectedNotebook} />- {contentWidthHasEffect && <NotebookExpandButton size="small" inPanel={true} />}+ {contentWidthHasEffect && (+ <NotebookExpandButton+ size="small"+ inPanel={true}+ isMarkdownNotebook={isMarkdownNotebook}+ />+ )}<LinkbuttonProps={{iconOnly: true,diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsxindex a9805cf1a6aa..c979716255f0 100644--- a/frontend/src/scenes/notebooks/NotebookScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx@@ -181,9 +181,13 @@ export function NotebookScene(): JSX.Element {}/>)}- {/* Markdown notebooks have no width toggle — they always fill the content width. */}- {!sceneMenuBarEnabled && !isMarkdownNotebook && (- <NotebookExpandButton type="secondary" size="small" inPanel={false} />+ {!sceneMenuBarEnabled && (+ <NotebookExpandButton+ type="secondary"+ size="small"+ inPanel={false}+ isMarkdownNotebook={isMarkdownNotebook}+ />)}{!sceneMenuBarEnabled && (<LemonButtondiff --git a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsxindex 921c65202a95..c7fac42f3f16 100644--- a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx+++ b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx@@ -38,12 +38,15 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Elemenconst { openShareModal, duplicateNotebook, exportJSON, downloadMarkdown, copyMarkdown, setShowHistory } =useActions(logic)const { featureFlags } = useValues(featureFlagLogic)- const { showTableOfContents, isExpanded, showKernelInfo } = useValues(notebookSettingsLogic)- const { setShowTableOfContents, setIsExpanded, setShowKernelInfo } = useActions(notebookSettingsLogic)+ const { showTableOfContents, isExpanded, isMarkdownExpanded, showKernelInfo } = useValues(notebookSettingsLogic)+ const { setShowTableOfContents, setIsExpanded, setIsMarkdownExpanded, setShowKernelInfo } =+ useActions(notebookSettingsLogic)const { selectNotebook } = useActions(notebookPanelLogic)const isMarkdownNotebook = isMarkdownNotebookContent(content)const canDelete = !isLocalOnly && !notebook?.is_templateconst showKernelToggle = !!featureFlags[FEATURE_FLAGS.NOTEBOOK_PYTHON]+ const isContentWidthExpanded = isMarkdownNotebook ? isMarkdownExpanded : isExpanded+ const setContentWidthExpanded = isMarkdownNotebook ? setIsMarkdownExpanded : setIsExpandedreturn (<SceneMenuBar>@@ -127,8 +130,8 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Elemen</SceneMenuBarCheckboxItem>)}<SceneMenuBarCheckboxItem- checked={isExpanded}- onCheckedChange={(checked) => setIsExpanded(checked)}+ checked={isContentWidthExpanded}+ onCheckedChange={(checked) => setContentWidthExpanded(checked)}data-attr={`${RESOURCE_TYPE}-menubar-fill-width`}>Fill content widthdiff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsxindex 38c67371a109..f2dbfa066426 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFilterAddFilterPopover.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'kea'@@ -88,7 +88,7 @@ describe('RecordingsUniversalFilterAddFilterPopover (pill category dropdown)', (// Type a query so we can prove the surrounding popover is not dismissed by the pick:// the bug routed the menu click through the parent popover's outside-press handler,// which cleared the query and collapsed the filter.- await userEvent.type(input, 'email')+ fireEvent.change(input, { target: { value: 'email' } })expect(input).toHaveValue('email')// Open the pill menu and select a visible option. Re-query the trigger — typingdiff --git a/posthog/admin/admins/notebook_markdown_migration_admin.py b/posthog/admin/admins/notebook_markdown_migration_admin.pynew file mode 100644index 000000000000..ad9e7499511e--- /dev/null+++ b/posthog/admin/admins/notebook_markdown_migration_admin.py@@ -0,0 +1,89 @@+import json+from dataclasses import asdict+from typing import TYPE_CHECKING, Any, cast++from django import forms+from django.contrib import admin+from django.http import HttpRequest, HttpResponse, JsonResponse+from django.shortcuts import render+from django.views.decorators.http import require_GET, require_POST++from products.notebooks.backend.facade import api as notebooks_api++if TYPE_CHECKING:+ from posthog.models import User+++class NotebookMarkdownMigrationForm(forms.Form):+ team_id = forms.IntegerField(+ required=False,+ min_value=1,+ help_text="Only count and convert notebooks for this team id. Leave blank to target all teams.",+ )+ dry_run = forms.BooleanField(+ required=False,+ initial=True,+ help_text="Preview the notebooks that would be converted without saving anything.",+ )+++def notebook_markdown_migration_view(request: HttpRequest) -> HttpResponse:+ context = {+ **admin.site.each_context(request),+ "form": NotebookMarkdownMigrationForm(),+ "title": "Markdown notebook migration",+ }+ return render(request, "admin/notebook_markdown_migration.html", context)+++@require_GET+def notebook_markdown_migration_stats_view(request: HttpRequest) -> JsonResponse:+ try:+ team_id = _parse_team_id(request.GET.get("team_id"))+ stats = notebooks_api.get_markdown_notebook_migration_stats(team_id)+ except ValueError as err:+ return JsonResponse({"error": str(err)}, status=400)++ return JsonResponse(asdict(stats))+++@require_POST+def notebook_markdown_migration_run_view(request: HttpRequest) -> JsonResponse:+ try:+ payload = json.loads(request.body.decode("utf-8") or "{}")+ except json.JSONDecodeError:+ return JsonResponse({"error": "Invalid JSON body"}, status=400)+ if not isinstance(payload, dict):+ return JsonResponse({"error": "JSON body must be an object"}, status=400)++ try:+ team_id = _parse_team_id(payload.get("team_id"))+ dry_run = bool(payload.get("dry_run", True))+ result = notebooks_api.migrate_notebooks_to_markdown(+ user=cast("User", request.user),+ team_id=team_id,+ dry_run=dry_run,+ )+ except ValueError as err:+ return JsonResponse({"error": str(err)}, status=400)++ return JsonResponse(_result_to_response(result))+++def _parse_team_id(raw_team_id: Any) -> int | None:+ if raw_team_id is None or raw_team_id == "":+ return None+ try:+ return int(raw_team_id)+ except (TypeError, ValueError):+ raise ValueError("Team id must be an integer")+++def _result_to_response(result: Any) -> dict[str, Any]:+ data = asdict(result)+ data["message"] = (+ f"Dry run found {result.converted} notebook(s) to convert."+ if result.dry_run+ else f"Converted {result.converted} notebook(s) to markdown."+ )+ return datadiff --git a/posthog/templates/admin/notebook_markdown_migration.html b/posthog/templates/admin/notebook_markdown_migration.htmlnew file mode 100644index 000000000000..d4a92bad4ebb--- /dev/null+++ b/posthog/templates/admin/notebook_markdown_migration.html@@ -0,0 +1,279 @@+{% extends "admin/base_site.html" %}+{% load i18n admin_urls static %}++{% block extrastyle %}+{{ block.super }}+<style>+ .notebook-migration-layout {+ display: grid;+ gap: 16px;+ max-width: 960px;+ }+ .notebook-migration-card {+ background: var(--body-bg);+ border: 1px solid var(--hairline-color);+ border-radius: 4px;+ padding: 16px;+ }+ .notebook-migration-stats {+ display: grid;+ gap: 12px;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ margin-top: 12px;+ }+ .notebook-migration-stat {+ border: 1px solid var(--hairline-color);+ border-radius: 4px;+ padding: 12px;+ }+ .notebook-migration-stat strong {+ display: block;+ font-size: 24px;+ line-height: 1.2;+ }+ .notebook-migration-row {+ margin-bottom: 14px;+ }+ .notebook-migration-row label {+ display: block;+ font-weight: 600;+ margin-bottom: 4px;+ }+ .notebook-migration-help {+ color: var(--body-quiet-color);+ font-size: 12px;+ margin: 4px 0 0;+ }+ .notebook-migration-actions {+ align-items: center;+ display: flex;+ gap: 8px;+ margin-top: 16px;+ }+ .notebook-migration-message {+ border-radius: 4px;+ display: none;+ margin-top: 12px;+ padding: 10px;+ white-space: pre-wrap;+ }+ .notebook-migration-message.is-visible {+ display: block;+ }+ .notebook-migration-message.is-error {+ background: #fdecea;+ border: 1px solid #f5c2c7;+ color: #842029;+ }+ .notebook-migration-message.is-success {+ background: #eaf7ea;+ border: 1px solid #b8dfb8;+ color: #1f5f1f;+ }+ .notebook-migration-previews {+ margin-top: 16px;+ }+ .notebook-migration-preview {+ border-top: 1px solid var(--hairline-color);+ padding: 12px 0;+ }+ .notebook-migration-preview pre {+ max-height: 180px;+ overflow: auto;+ white-space: pre-wrap;+ }+</style>+{% endblock %}++{% block content %}+<div class="notebook-migration-layout">+ <div class="notebook-migration-card">+ <h2>Migration status</h2>+ <p>+ Counts include every notebook row in scope, including internal, account-linked, and deleted notebooks.+ </p>+ <div class="notebook-migration-actions">+ <button type="button" class="button" id="notebook-migration-refresh">Refresh</button>+ <span id="notebook-migration-status">Loading…</span>+ </div>+ <div class="notebook-migration-stats">+ <div class="notebook-migration-stat">+ <span>Total notebooks</span>+ <strong id="notebook-migration-total">-</strong>+ </div>+ <div class="notebook-migration-stat">+ <span>Converted</span>+ <strong id="notebook-migration-converted">-</strong>+ </div>+ <div class="notebook-migration-stat">+ <span>Pending</span>+ <strong id="notebook-migration-pending">-</strong>+ </div>+ </div>+ </div>++ <div class="notebook-migration-card">+ <h2>Run migration</h2>+ <p>+ This rewrites rich notebooks into the markdown notebook format using the backend converter,+ increments the notebook version, publishes an update event, and writes a notebook history entry+ with the before/after content diff.+ </p>+ <form id="notebook-migration-form">+ {% csrf_token %}+ <div class="notebook-migration-row">+ <label for="{{ form.team_id.id_for_label }}">{{ form.team_id.label }}</label>+ {{ form.team_id }}+ <p class="notebook-migration-help">{{ form.team_id.help_text }}</p>+ </div>+ <div class="notebook-migration-row">+ <label for="{{ form.dry_run.id_for_label }}">+ {{ form.dry_run }}+ {{ form.dry_run.label }}+ </label>+ <p class="notebook-migration-help">{{ form.dry_run.help_text }}</p>+ </div>+ <div class="notebook-migration-actions">+ <button type="submit" class="default" id="notebook-migration-submit">Run migration</button>+ </div>+ </form>+ <div id="notebook-migration-message" class="notebook-migration-message"></div>+ <div id="notebook-migration-previews" class="notebook-migration-previews"></div>+ </div>+</div>++<script nonce="{{ request.csp_nonce }}">+ (function () {+ const statsUrl = "{% url 'notebook-markdown-migration-stats' %}"+ const runUrl = "{% url 'notebook-markdown-migration-run' %}"+ const form = document.getElementById("notebook-migration-form")+ const teamInput = document.getElementById("id_team_id")+ const dryRunInput = document.getElementById("id_dry_run")+ const refreshButton = document.getElementById("notebook-migration-refresh")+ const submitButton = document.getElementById("notebook-migration-submit")+ const status = document.getElementById("notebook-migration-status")+ const message = document.getElementById("notebook-migration-message")+ const previews = document.getElementById("notebook-migration-previews")++ function csrfToken() {+ return document.querySelector("[name=csrfmiddlewaretoken]").value+ }++ function teamQuery() {+ const value = teamInput.value.trim()+ return value ? "?team_id=" + encodeURIComponent(value) : ""+ }++ function setMessage(text, isError) {+ message.textContent = text+ message.classList.toggle("is-visible", !!text)+ message.classList.toggle("is-error", !!isError)+ message.classList.toggle("is-success", !!text && !isError)+ }++ async function readJson(response) {+ const contentType = response.headers.get("content-type") || ""+ if (!contentType.includes("application/json")) {+ throw new Error("Expected a JSON response from the migration endpoint.")+ }+ return await response.json()+ }++ function renderStats(data) {+ document.getElementById("notebook-migration-total").textContent = data.total+ document.getElementById("notebook-migration-converted").textContent = data.converted+ document.getElementById("notebook-migration-pending").textContent = data.pending+ }++ function renderPreviews(items) {+ previews.innerHTML = ""+ if (!items || !items.length) {+ return+ }+ const heading = document.createElement("h3")+ heading.textContent = "Dry-run preview"+ previews.appendChild(heading)+ for (const item of items) {+ const wrapper = document.createElement("div")+ wrapper.className = "notebook-migration-preview"+ const title = document.createElement("strong")+ title.textContent = `${item.short_id} · ${item.title || "Untitled"} · version ${item.before_version}`+ const pre = document.createElement("pre")+ pre.textContent = item.markdown_preview+ wrapper.appendChild(title)+ wrapper.appendChild(pre)+ previews.appendChild(wrapper)+ }+ }++ async function refreshStats() {+ status.textContent = "Loading…"+ refreshButton.disabled = true+ try {+ const response = await fetch(statsUrl + teamQuery(), { headers: { "Accept": "application/json" } })+ const data = await readJson(response)+ if (!response.ok) {+ status.textContent = "Could not load stats"+ setMessage(data.error || "Could not load migration stats.", true)+ return+ }+ renderStats(data)+ status.textContent = "Updated"+ } catch (error) {+ status.textContent = "Could not load stats"+ setMessage(String(error), true)+ } finally {+ refreshButton.disabled = false+ }+ }++ refreshButton.addEventListener("click", refreshStats)+ teamInput.addEventListener("change", refreshStats)+ form.addEventListener("submit", async function (event) {+ event.preventDefault()+ setMessage("", false)+ previews.innerHTML = ""+ submitButton.disabled = true+ submitButton.textContent = "Running…"+ try {+ const response = await fetch(runUrl, {+ method: "POST",+ headers: {+ "Accept": "application/json",+ "Content-Type": "application/json",+ "X-CSRFToken": csrfToken(),+ },+ body: JSON.stringify({+ team_id: teamInput.value.trim(),+ dry_run: dryRunInput.checked,+ }),+ })+ const data = await readJson(response)+ if (!response.ok) {+ setMessage(data.error || "Migration failed.", true)+ return+ }+ const details = [+ data.message,+ `Total: ${data.total}`,+ `Already converted: ${data.already_converted}`,+ `${data.dry_run ? "Would convert" : "Converted"}: ${data.converted}`,+ `Skipped: ${data.skipped}`,+ `Errored: ${data.errored}`,+ ...(data.errors || []),+ ].join("\n")+ setMessage(details, data.errored > 0)+ renderPreviews(data.previews)+ await refreshStats()+ } catch (error) {+ setMessage(String(error), true)+ } finally {+ submitButton.disabled = false+ submitButton.textContent = "Run migration"+ }+ })++ refreshStats()+ })()+</script>+{% endblock %}diff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.htmlindex 2580975ff627..e71034f364e2 100644--- a/posthog/templates/custom_tools/app.html+++ b/posthog/templates/custom_tools/app.html@@ -66,5 +66,11 @@</td><td>View and trigger Temporal health check workflows</td></tr>+ <tr class="model-notebookmarkdownmigration">+ <td scope="row">+ <a href="{% url 'notebook-markdown-migration' %}">Markdown notebook migration</a>+ </td>+ <td>Convert legacy rich notebooks to markdown notebooks with dry-run support and history entries</td>+ </tr></table></div>diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.pyindex d6ae34afcf33..8e9858ba7216 100644--- a/products/notebooks/backend/facade/api.py+++ b/products/notebooks/backend/facade/api.py@@ -15,11 +15,12 @@ lives in ``facade.collab``.from typing import TYPE_CHECKING, Anyfrom uuid import UUID-from .. import logic+from .. import logic, markdown_migrationfrom ..models import Notebookfrom . import contractsif TYPE_CHECKING:+ from posthog.models import Userfrom posthog.rbac.user_access_control import UserAccessControl@@ -80,6 +81,12 @@ def get_notebook_activity_summary(team_id: int, limit: int) -> contracts.Noteboo)+def get_markdown_notebook_migration_stats(+ team_id: int | None = None,+) -> contracts.MarkdownNotebookMigrationStats:+ return markdown_migration.get_markdown_notebook_migration_stats(team_id)++# --- Access control ---@@ -152,6 +159,21 @@ def create_notebook(return _to_notebook_data(notebook)+def migrate_notebooks_to_markdown(+ *,+ user: "User",+ team_id: int | None = None,+ dry_run: bool = True,+ max_previews: int = 5,+) -> contracts.MarkdownNotebookMigrationResult:+ return markdown_migration.migrate_notebooks_to_markdown(+ user=user,+ team_id=team_id,+ dry_run=dry_run,+ max_previews=max_previews,+ )++# --- Resource links (groups, accounts) ---diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.pyindex f81bb19da404..6f49c5c3e574 100644--- a/products/notebooks/backend/facade/contracts.py+++ b/products/notebooks/backend/facade/contracts.py@@ -56,6 +56,41 @@ class NotebookActivitySummary:recent: list[NotebookRecent] = field(default_factory=list)+@dataclass(frozen=True)+class MarkdownNotebookMigrationStats:+ """Markdown migration status for notebooks in an optional team scope."""++ total: int+ converted: int+ pending: int+ team_id: int | None = None+++@dataclass(frozen=True)+class MarkdownNotebookMigrationPreview:+ """A dry-run preview of one notebook conversion."""++ short_id: str+ title: str | None+ before_version: int+ markdown_preview: str+++@dataclass(frozen=True)+class MarkdownNotebookMigrationResult:+ """Result of a markdown notebook migration run."""++ dry_run: bool+ team_id: int | None+ total: int+ already_converted: int+ converted: int+ skipped: int+ errored: int+ previews: list[MarkdownNotebookMigrationPreview] = field(default_factory=list)+ errors: list[str] = field(default_factory=list)++@dataclass(frozen=True)class AccountNote:"""An internal notebook linked to a customer-analytics account, for context rendering."""diff --git a/products/notebooks/backend/markdown_conversion.py b/products/notebooks/backend/markdown_conversion.pynew file mode 100644index 000000000000..20fb5f749aee--- /dev/null+++ b/products/notebooks/backend/markdown_conversion.py@@ -0,0 +1,657 @@+import re+import json+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Any, cast+from urllib.parse import urlparse++MARKDOWN_NOTEBOOK_NODE_TYPE = "ph-markdown-notebook"+MARKDOWN_NOTEBOOK_NODE_ID = "markdown-notebook-v2"+MENTION_NODE_TYPE = "ph-mention"++NotebookPropValue = str | int | float | bool | None | list["NotebookPropValue"] | dict[str, "NotebookPropValue"]+JSONContent = dict[str, Any]++NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Mapping[str, str] = {+ "ph-query": "Query",+ "ph-python": "Python",+ "ph-duck-sql": "DuckSQL",+ "ph-hogql-sql": "HogQLSQL",+ "ph-recording": "Recording",+ "ph-recording-playlist": "RecordingPlaylist",+ "ph-feature-flag": "FeatureFlag",+ "ph-feature-flag-code-example": "FeatureFlagCodeExample",+ "ph-experiment": "Experiment",+ "ph-early-access-feature": "EarlyAccessFeature",+ "ph-survey": "Survey",+ "ph-person": "Person",+ "ph-group": "Group",+ "ph-cohort": "Cohort",+ "ph-backlink": "Backlink",+ "ph-replay-timestamp": "ReplayTimestamp",+ "ph-image": "Image",+ "ph-person-feed": "PersonFeed",+ "ph-person-properties": "PersonProperties",+ "ph-group-properties": "GroupProperties",+ "ph-map": "Map",+ "ph-embed": "Embed",+ "ph-latex": "Latex",+ "ph-task-create": "TaskCreate",+ "ph-llm-trace": "LLMTrace",+ "ph-issues": "Issues",+ "ph-usage-metrics": "UsageMetrics",+ "ph-zendesk-tickets": "ZendeskTickets",+ "ph-related-groups": "RelatedGroups",+ "ph-customer-journey": "CustomerJourney",+ "ph-support-tickets": "SupportTickets",+}++LIST_NODE_TYPES = {"bulletList", "orderedList", "taskList"}+LIST_ITEM_NODE_TYPES = {"listItem", "taskItem"}+_SERIALIZATION_OMIT = object()+++@dataclass(frozen=True)+class NotebookMarkdownConversionOptions:+ comment_replies_by_mark_id: Mapping[str, list[NotebookPropValue]] | None = None+ get_mention_label: Callable[[int], str | None] | None = None+++def is_markdown_notebook_content(content: Any) -> bool:+ return _get_markdown_notebook_node(content) is not None+++def get_markdown_notebook_markdown(content: Any) -> str:+ node = _get_markdown_notebook_node(content)+ if node is None:+ return ""+ attrs = node.get("attrs")+ if not isinstance(attrs, dict):+ return ""+ markdown = attrs.get("markdown")+ return markdown if isinstance(markdown, str) else ""+++def build_markdown_notebook_content(markdown: str, node_id: str = MARKDOWN_NOTEBOOK_NODE_ID) -> JSONContent:+ return {+ "type": "doc",+ "content": [+ {+ "type": MARKDOWN_NOTEBOOK_NODE_TYPE,+ "attrs": {+ "nodeId": node_id,+ "markdown": markdown,+ },+ }+ ],+ }+++def convert_notebook_content_to_markdown(content: Any, options: NotebookMarkdownConversionOptions | None = None) -> str:+ options = options or NotebookMarkdownConversionOptions()+ normalized_content = _normalize_notebook_content_for_markdown_conversion(content)++ if isinstance(normalized_content, str):+ return normalized_content++ if is_markdown_notebook_content(normalized_content):+ return get_markdown_notebook_markdown(normalized_content)++ blocks: list[str] = []+ emitted_comment_mark_ids: set[str] = set()+ for node in _content_list(normalized_content):+ for mark_id in _collect_comment_mark_ids(node):+ if mark_id in emitted_comment_mark_ids:+ continue+ emitted_comment_mark_ids.add(mark_id)+ blocks.append(+ _serialize_component_node(+ "Comment",+ {+ "ref": mark_id,+ "replies": (options.comment_replies_by_mark_id or {}).get(mark_id, []),+ },+ )+ )++ markdown = _serialize_rich_content_node(node, 0, options)+ if markdown.strip():+ blocks.append(markdown)++ return "\n\n".join(blocks)+++def _normalize_notebook_content_for_markdown_conversion(content: Any) -> JSONContent | str | None:+ if isinstance(content, str):+ parsed_content = _parse_json_encoded_notebook_content(content)+ return parsed_content if parsed_content is not None else content++ if isinstance(content, list):+ return {"type": "doc", "content": content}++ if isinstance(content, dict) or content is None:+ return content++ return None+++def _parse_json_encoded_notebook_content(content: str) -> JSONContent | str | None:+ trimmed_content = content.strip()+ if not trimmed_content or trimmed_content[0] not in ("{", "[", '"'):+ return None++ try:+ parsed_content = json.loads(trimmed_content)+ except json.JSONDecodeError:+ return None++ if isinstance(parsed_content, str):+ nested = _parse_json_encoded_notebook_content(parsed_content)+ return nested if nested is not None else parsed_content++ if isinstance(parsed_content, list):+ return {"type": "doc", "content": parsed_content}++ if isinstance(parsed_content, dict):+ return parsed_content++ return None+++def _get_markdown_notebook_node(content: Any) -> JSONContent | None:+ if not isinstance(content, dict):+ return None+ nodes = content.get("content")+ if not isinstance(nodes, list) or len(nodes) != 1:+ return None+ node = nodes[0]+ if not isinstance(node, dict) or node.get("type") != MARKDOWN_NOTEBOOK_NODE_TYPE:+ return None+ attrs = node.get("attrs")+ markdown = attrs.get("markdown") if isinstance(attrs, dict) else None+ return node if isinstance(markdown, str) else None+++def _content_list(content: JSONContent | str | None) -> list[JSONContent]:+ if not isinstance(content, dict):+ return []+ nodes = content.get("content")+ return [node for node in nodes if isinstance(node, dict)] if isinstance(nodes, list) else []+++def _collect_comment_mark_ids(node: JSONContent) -> list[str]:+ mark_ids: list[str] = []++ def visit(current: JSONContent) -> None:+ for mark in current.get("marks") or []:+ if not isinstance(mark, dict):+ continue+ attrs = mark.get("attrs")+ mark_id = attrs.get("id") if isinstance(attrs, dict) else None+ if mark.get("type") == "comment" and isinstance(mark_id, str) and mark_id:+ mark_ids.append(mark_id)+ for child in _content_list(current):+ visit(child)++ visit(node)+ return mark_ids+++def _serialize_rich_content_node(+ node: JSONContent,+ list_depth: int = 0,+ options: NotebookMarkdownConversionOptions | None = None,+) -> str:+ options = options or NotebookMarkdownConversionOptions()+ node_type = node.get("type")++ if node_type == "text":+ return escape_markdown_block_lines(_serialize_inline_node(node, options))++ if node_type == "heading":+ level = node.get("attrs", {}).get("level") if isinstance(node.get("attrs"), dict) else None+ level = min(max(level, 1), 6) if isinstance(level, int) else 1+ return f"{'#' * level} {_serialize_inline_content(_content_list(node), options)}"++ if node_type == "paragraph":+ return escape_markdown_block_lines(_serialize_inline_content(_content_list(node), options))++ if node_type == "blockquote":+ return "\n".join(+ f"> {line}"+ for line in "\n".join(+ _serialize_rich_content_node(child, list_depth, options) for child in _content_list(node)+ ).split("\n")+ )++ if node_type in LIST_NODE_TYPES:+ return _serialize_list(node, node_type == "orderedList", list_depth, options)++ if node_type == "horizontalRule":+ return "---"++ if node_type == "codeBlock":+ attrs = node.get("attrs")+ language = attrs.get("language") if isinstance(attrs, dict) and isinstance(attrs.get("language"), str) else ""+ text = "".join(+ "\n" if child.get("type") == "hardBreak" else str(child.get("text") or "") for child in _content_list(node)+ )+ return _serialize_code_node(text, language or None)++ if node_type == "table":+ return _serialize_table(node, options)++ if node_type == "ph-text":+ return _serialize_legacy_text_node(node)++ if node_type == "ph-insight":+ return _serialize_legacy_insight_node(node)++ if node_type == "ph-dashboard":+ return _serialize_legacy_dashboard_node(node)++ if node_type == "query":+ return _serialize_legacy_query_node(node)++ if isinstance(node_type, str) and node_type in NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG:+ return _serialize_component_node(+ NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[node_type],+ _get_serializable_attrs(node.get("attrs") if isinstance(node.get("attrs"), dict) else None),+ )++ child_markdown = "\n\n".join(+ block+ for block in (_serialize_rich_content_node(child, list_depth, options) for child in _content_list(node))+ if block+ )+ if child_markdown or not node_type:+ return child_markdown++ return _serialize_unknown_rich_content_node(node)+++def _serialize_legacy_text_node(node: JSONContent) -> str:+ attrs = node.get("attrs")+ body = attrs.get("body") if isinstance(attrs, dict) else None+ return body if isinstance(body, str) else _serialize_unknown_rich_content_node(node)+++def _serialize_legacy_insight_node(node: JSONContent) -> str:+ attrs = node.get("attrs")+ if not isinstance(attrs, dict):+ return _serialize_unknown_rich_content_node(node)+ insight_short_id = attrs.get("short_id") if isinstance(attrs.get("short_id"), str) else attrs.get("id")+ if not isinstance(insight_short_id, str) or not insight_short_id:+ return _serialize_unknown_rich_content_node(node)+ return _serialize_component_node("Query", {"query": {"kind": "SavedInsightNode", "shortId": insight_short_id}})+++def _serialize_legacy_dashboard_node(node: JSONContent) -> str:+ attrs = node.get("attrs")+ dashboard_id = attrs.get("id") if isinstance(attrs, dict) else None+ if not isinstance(dashboard_id, str | int):+ return _serialize_unknown_rich_content_node(node)+ return escape_markdown_block_lines(escape_inline_markdown_text(f"Dashboard {dashboard_id}"))+++def _serialize_legacy_query_node(node: JSONContent) -> str:+ props = _get_serializable_attrs(node.get("attrs") if isinstance(node.get("attrs"), dict) else None)+ query = props.get("query")+ if isinstance(query, dict) and query.get("kind") == "HogQLQuery":+ props["query"] = {"kind": "DataVisualizationNode", "source": query}+ return _serialize_component_node("Query", props)+++def _serialize_unknown_rich_content_node(node: JSONContent) -> str:+ attrs = _get_serializable_attrs(node.get("attrs") if isinstance(node.get("attrs"), dict) else None)+ node_type = node.get("type")+ props: dict[str, NotebookPropValue] = dict(attrs)+ if isinstance(node_type, str) and node_type:+ props = {"nodeType": node_type, **props}+ return _serialize_component_node("UnknownNode", props)+++def _serialize_inline_content(+ content: list[JSONContent],+ options: NotebookMarkdownConversionOptions | None = None,+) -> str:+ return "".join(_serialize_inline_node(node, options) for node in content)+++def _serialize_inline_node(node: JSONContent, options: NotebookMarkdownConversionOptions | None = None) -> str:+ options = options or NotebookMarkdownConversionOptions()+ node_type = node.get("type")++ if node_type == "text":+ marks = _mark_list(node)+ is_code_text = any(mark.get("type") == "code" for mark in marks)+ text = str(node.get("text") or "")+ escaped_text = escape_code_span_text(text) if is_code_text else escape_inline_markdown_text(text)+ return _apply_marks(escaped_text, marks)++ if node_type == "hardBreak":+ return "\n"++ if node_type == MENTION_NODE_TYPE:+ return _serialize_mention_node(node, options)++ return _serialize_inline_content(_content_list(node), options)+++def _serialize_mention_node(node: JSONContent, options: NotebookMarkdownConversionOptions) -> str:+ attrs = node.get("attrs")+ member_id = attrs.get("id") if isinstance(attrs, dict) else None+ attr_label = attrs.get("label") if isinstance(attrs, dict) else None+ label = attr_label.strip() if isinstance(attr_label, str) and attr_label.strip() else None+ looked_up_label = (+ options.get_mention_label(member_id) if isinstance(member_id, int) and options.get_mention_label else None+ )+ display_label = label or looked_up_label or "@member"+ if not display_label.startswith("@"):+ display_label = f"@{display_label}"+ if not isinstance(member_id, int):+ return escape_inline_markdown_text(display_label)+ return f"<mention id={json.dumps(str(member_id))}>{escape_inline_markdown_text(display_label)}</mention>"+++def _apply_marks(text: str, marks: list[JSONContent]) -> str:+ comment_mark_ids = [+ mark.get("attrs", {}).get("id")+ for mark in marks+ if mark.get("type") == "comment"+ and isinstance(mark.get("attrs"), dict)+ and isinstance(mark.get("attrs", {}).get("id"), str)+ and mark.get("attrs", {}).get("id")+ ]+ formatted_text = _apply_formatting_marks(text, marks)+ for mark_id in comment_mark_ids:+ formatted_text = f"<ref id={json.dumps(mark_id)}>{formatted_text}</ref>"+ return formatted_text+++def _apply_formatting_marks(text: str, marks: list[JSONContent]) -> str:+ marked_text = text+ for mark in marks:+ mark_type = mark.get("type")+ if mark_type == "bold":+ marked_text = f"**{marked_text}**"+ elif mark_type == "italic":+ marked_text = f"*{marked_text}*"+ elif mark_type == "underline":+ marked_text = f"<u>{marked_text}</u>"+ elif mark_type == "strike":+ marked_text = f"~~{marked_text}~~"+ elif mark_type == "code":+ marked_text = f"`{marked_text}`"+ elif mark_type == "link" and isinstance(mark.get("attrs"), dict):+ href = mark["attrs"].get("href")+ sanitized = sanitize_notebook_link_href(href) if isinstance(href, str) else None+ if sanitized:+ marked_text = f"[{marked_text}]({sanitized})"+ return marked_text+++def _serialize_list(+ node: JSONContent,+ ordered: bool,+ depth: int,+ options: NotebookMarkdownConversionOptions | None = None,+) -> str:+ options = options or NotebookMarkdownConversionOptions()+ blocks: list[str] = []+ pending_list_lines: list[str] = []++ def flush_list_lines() -> None:+ nonlocal pending_list_lines+ if pending_list_lines:+ blocks.append("\n".join(pending_list_lines))+ pending_list_lines = []++ items = [child for child in _content_list(node) if child.get("type") in LIST_ITEM_NODE_TYPES]+ for index, item in enumerate(items):+ list_lines, trailing_blocks = _serialize_list_item(item, ordered, depth, index, options)+ pending_list_lines.extend(list_lines)+ if trailing_blocks:+ flush_list_lines()+ blocks.extend(trailing_blocks)+ flush_list_lines()++ return "\n\n".join(blocks)+++def _serialize_list_item(+ item: JSONContent,+ ordered: bool,+ depth: int,+ index: int,+ options: NotebookMarkdownConversionOptions,+) -> tuple[list[str], list[str]]:+ marker = f"{index + 1}." if ordered else "-"+ children = _content_list(item)+ first_paragraph = next((child for child in children if child.get("type") == "paragraph"), None)+ nested_lists = [child for child in children if child.get("type") in LIST_NODE_TYPES]+ extra_blocks = [+ child for child in children if child is not first_paragraph and child.get("type") not in LIST_NODE_TYPES+ ]+ checked = item.get("attrs", {}).get("checked") if isinstance(item.get("attrs"), dict) else False+ checkbox = (+ "[x] " if item.get("type") == "taskItem" and checked else "[ ] " if item.get("type") == "taskItem" else ""+ )+ item_text = re.sub(+ r"\s*\n\s*", " ", _serialize_inline_content(_content_list(first_paragraph), options) if first_paragraph else ""+ )+ list_lines = [f"{' ' * depth}{marker} {checkbox}{item_text}".rstrip()]++ for nested_list in nested_lists:+ nested_markdown = _serialize_rich_content_node(nested_list, depth + 1, options)+ if nested_markdown:+ list_lines.append(nested_markdown)++ trailing_blocks = [+ block for block in (_serialize_rich_content_node(child, 0, options) for child in extra_blocks) if block.strip()+ ]+ return list_lines, trailing_blocks+++def _serialize_table(node: JSONContent, options: NotebookMarkdownConversionOptions | None = None) -> str:+ options = options or NotebookMarkdownConversionOptions()+ rows = [child for child in _content_list(node) if child.get("type") == "tableRow"]+ if not rows:+ return ""++ serialized_rows: list[list[str]] = []+ for row in rows:+ cells = [cell for cell in _content_list(row) if cell.get("type") in ("tableCell", "tableHeader")]+ serialized_cells: list[str] = []+ for cell in cells:+ cell_text = " ".join(_serialize_rich_content_node(child, 0, options) for child in _content_list(cell))+ cell_text = re.sub(r"\s*\n\s*", " ", cell_text)+ serialized_cells.append(_escape_table_cell(cell_text))+ serialized_rows.append(serialized_cells)++ column_count = max(len(row) for row in serialized_rows)+ header = _normalize_table_row(serialized_rows[0], column_count)+ body = [_normalize_table_row(row, column_count) for row in serialized_rows[1:]]+ separator = ["---"] * column_count+ rows_to_render = [header, separator, *body]+ return "\n".join(f"| {' | '.join(row)} |" for row in rows_to_render)+++def _normalize_table_row(row: list[str] | None, column_count: int) -> list[str]:+ return [(row or [])[index] if index < len(row or []) else "" for index in range(column_count)]+++def _escape_table_cell(text: str) -> str:+ output: list[str] = []+ index = 0+ while index < len(text):+ if text[index] == "\\" and index + 1 < len(text):+ output.append(text[index : index + 2])+ index += 2+ continue+ if text[index] == "|":+ output.append("\\|")+ else:+ output.append(text[index])+ index += 1+ return "".join(output)+++def _get_serializable_attrs(attrs: Mapping[str, Any] | None) -> dict[str, NotebookPropValue]:+ props: dict[str, NotebookPropValue] = {}+ for key, value in (attrs or {}).items():+ serializable_value = _to_serializable_prop_value(_revive_json_encoded_attr(value))+ if serializable_value is not _SERIALIZATION_OMIT:+ props[key] = cast(NotebookPropValue, serializable_value)+ return props+++def _revive_json_encoded_attr(value: Any) -> Any:+ if not isinstance(value, str):+ return value+ trimmed = value.strip()+ if not trimmed.startswith(("{", "[")):+ return value+ try:+ parsed = json.loads(trimmed)+ except json.JSONDecodeError:+ return value+ return parsed if isinstance(parsed, dict | list) else value+++def _to_serializable_prop_value(value: Any) -> NotebookPropValue | object:+ try:+ serialized = json.dumps(value, allow_nan=False, ensure_ascii=False, separators=(",", ":"))+ except (TypeError, ValueError):+ return _SERIALIZATION_OMIT+ return json.loads(serialized)+++def _serialize_component_node(tag_name: str, props: Mapping[str, NotebookPropValue]) -> str:+ if tag_name == "Image":+ raw_src = props.get("src")+ raw_alt = props.get("alt")+ src = raw_src if isinstance(raw_src, str) else ""+ alt = raw_alt if isinstance(raw_alt, str) else ""+ return f"})"+ return f"<{tag_name}{_serialize_component_props(props)} />"+++def _serialize_component_props(props: Mapping[str, NotebookPropValue]) -> str:+ serializable_props = _get_serializable_component_props(props)+ entries = _get_ordered_component_prop_entries(serializable_props)+ return "".join(f" {key}" if value is True else f" {key}={_serialize_prop_value(value)}" for key, value in entries)+++def _get_serializable_component_props(props: Mapping[str, NotebookPropValue]) -> dict[str, NotebookPropValue]:+ next_props = {+ key: value for key, value in props.items() if key not in ("view", "edit", "hideFilters", "hideResults")+ }+ legacy_view_panel_visible = props.get("view") if isinstance(props.get("view"), bool) else None+ legacy_edit_panel_visible = props.get("edit") if isinstance(props.get("edit"), bool) else None+ hide_filters = (+ props.get("hideFilters") if isinstance(props.get("hideFilters"), bool) else legacy_edit_panel_visible is False+ )+ hide_results = (+ props.get("hideResults") if isinstance(props.get("hideResults"), bool) else legacy_view_panel_visible is False+ )++ if hide_filters:+ next_props["hideFilters"] = True+ if hide_results:+ next_props["hideResults"] = True+ return next_props+++def _get_ordered_component_prop_entries(props: Mapping[str, NotebookPropValue]) -> list[tuple[str, NotebookPropValue]]:+ entries = list(props.items())+ ordered_keys = ["hideFilters", "hideResults"]+ return [+ *[(key, props[key]) for key in ordered_keys if key in props],+ *[(key, value) for key, value in entries if key not in ordered_keys],+ ]+++def _serialize_prop_value(value: NotebookPropValue) -> str:+ if isinstance(value, str):+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))+ return "{" + json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "}"+++def _serialize_code_node(text: str, language: str | None = None) -> str:+ fence = _get_code_block_fence(text)+ return f"{fence}{language or ''}\n{text}\n{fence}"+++def _get_code_block_fence(text: str) -> str:+ longest_run = max((len(match.group(0)) for match in re.finditer(r"`+", text)), default=0)+ return "`" * max(3, longest_run + 1)+++def _mark_list(node: JSONContent) -> list[JSONContent]:+ marks = node.get("marks")+ return [mark for mark in marks if isinstance(mark, dict)] if isinstance(marks, list) else []+++def sanitize_notebook_link_href(href: str) -> str | None:+ trimmed_href = href.strip()+ if not re.match(r"^https?://\S+$", trimmed_href, flags=re.IGNORECASE):+ return None+ parsed = urlparse(trimmed_href)+ return trimmed_href if parsed.scheme in ("http", "https") and parsed.netloc else None+++def escape_inline_markdown_text(text: str) -> str:+ escaped = re.sub(r"[\\`*\[\]|]", lambda match: f"\\{match.group(0)}", text)+ escaped = re.sub(r"~~+", lambda match: "\\~" * len(match.group(0)), escaped)+ escaped = _escape_non_intraword_underscores(escaped)+ return re.sub(r"<(?=\/?(?:u>|ref[\s>]|mention[\s>]))", r"\\<", escaped)+++def _escape_non_intraword_underscores(text: str) -> str:+ output: list[str] = []+ for index, character in enumerate(text):+ if character != "_":+ output.append(character)+ continue+ previous_character = text[index - 1] if index > 0 else ""+ next_character = text[index + 1] if index + 1 < len(text) else ""+ output.append(+ "_" if _is_ascii_alphanumeric(previous_character) and _is_ascii_alphanumeric(next_character) else "\\_"+ )+ return "".join(output)+++def _is_ascii_alphanumeric(character: str) -> bool:+ return bool(character) and character.isascii() and character.isalnum()+++def escape_code_span_text(text: str) -> str:+ return re.sub(r"[\\`]", lambda match: f"\\{match.group(0)}", text)+++def escape_markdown_block_lines(serialized: str) -> str:+ return "\n".join(escape_markdown_line_start(line) for line in serialized.split("\n"))+++def escape_markdown_line_start(line: str) -> str:+ leading_whitespace_match = re.match(r"^\s*", line)+ leading_whitespace = leading_whitespace_match.group(0) if leading_whitespace_match else ""+ content = line[len(leading_whitespace) :]++ ordered_list_match = re.match(r"^(\d+)([.)])(\s|$)", content)+ if ordered_list_match:+ return f"{leading_whitespace}{ordered_list_match.group(1)}\\{content[len(ordered_list_match.group(1)) :]}"++ if re.match(r"^(#{1,6}\s|>|[-+•](\s|$)|-{3,}\s*$|<[A-Z]|<!--)", content):+ return f"{leading_whitespace}\\{content}"++ return line+++def _escape_markdown_image_alt(text: str) -> str:+ return text.replace("\\", "\\\\").replace("]", "\\]")+++def _escape_markdown_image_src(text: str) -> str:+ return text.replace("\\", "\\\\").replace(")", "\\)")diff --git a/products/notebooks/backend/markdown_migration.py b/products/notebooks/backend/markdown_migration.pynew file mode 100644index 000000000000..9c5b01afa746--- /dev/null+++ b/products/notebooks/backend/markdown_migration.py@@ -0,0 +1,233 @@+from collections.abc import Callable+from typing import Any, cast++from django.db import transaction+from django.db.models import QuerySet+from django.utils.timezone import now++from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import changes_between+from posthog.models.comment import Comment+from posthog.models.utils import UUIDT++from products.notebooks.backend import markdown_collab+from products.notebooks.backend.activity_logging import log_notebook_activity+from products.notebooks.backend.facade.contracts import (+ MarkdownNotebookMigrationPreview,+ MarkdownNotebookMigrationResult,+ MarkdownNotebookMigrationStats,+)+from products.notebooks.backend.markdown_conversion import (+ NotebookMarkdownConversionOptions,+ build_markdown_notebook_content,+ convert_notebook_content_to_markdown,+ is_markdown_notebook_content,+)+from products.notebooks.backend.models import Notebook+from products.notebooks.backend.python_analysis import annotate_python_nodes+++def get_markdown_notebook_migration_stats(team_id: int | None = None) -> MarkdownNotebookMigrationStats:+ _validate_team_id(team_id)+ queryset = _notebook_scope(team_id)+ total = queryset.count()+ converted = queryset.filter(content__content__0__type=markdown_collab.MARKDOWN_NOTEBOOK_NODE_TYPE).count()+ return MarkdownNotebookMigrationStats(total=total, converted=converted, pending=total - converted, team_id=team_id)+++def migrate_notebooks_to_markdown(+ *,+ user: User,+ team_id: int | None = None,+ dry_run: bool = True,+ max_previews: int = 5,+) -> MarkdownNotebookMigrationResult:+ stats = get_markdown_notebook_migration_stats(team_id)+ converted = 0+ skipped = 0+ errored = 0+ previews: list[MarkdownNotebookMigrationPreview] = []+ errors: list[str] = []++ for notebook in _notebook_scope(team_id).select_related("team").order_by("team_id", "id").iterator(chunk_size=100):+ if is_markdown_notebook_content(notebook.content):+ skipped += 1+ continue++ try:+ markdown = convert_notebook_content_to_markdown(+ notebook.content,+ NotebookMarkdownConversionOptions(+ comment_replies_by_mark_id=_build_comment_replies_by_mark_id(notebook),+ get_mention_label=_build_mention_label_getter(notebook),+ ),+ )+ next_content = build_markdown_notebook_content(markdown)+ if dry_run:+ converted += 1+ if len(previews) < max_previews:+ previews.append(+ MarkdownNotebookMigrationPreview(+ short_id=str(notebook.short_id),+ title=notebook.title,+ before_version=notebook.version,+ markdown_preview=markdown[:500],+ )+ )+ continue++ _convert_notebook(notebook, user=user, content=next_content, text_content=markdown)+ converted += 1+ except Exception as err:+ errored += 1+ errors.append(f"{notebook.short_id}: {err}")++ return MarkdownNotebookMigrationResult(+ dry_run=dry_run,+ team_id=team_id,+ total=stats.total,+ already_converted=stats.converted,+ converted=converted,+ skipped=skipped,+ errored=errored,+ previews=previews,+ errors=errors[:20],+ )+++def _validate_team_id(team_id: int | None) -> None:+ if team_id is not None and not Team.objects.filter(id=team_id).exists():+ raise ValueError(f"Team {team_id} does not exist")+++def _notebook_scope(team_id: int | None) -> QuerySet[Notebook]:+ queryset = Notebook.objects.all()+ return queryset.filter(team_id=team_id) if team_id is not None else queryset+++def _convert_notebook(notebook: Notebook, *, user: User, content: dict[str, Any], text_content: str) -> None:+ with transaction.atomic():+ locked_notebook = Notebook.objects.select_for_update().select_related("team").get(pk=notebook.pk)+ if is_markdown_notebook_content(locked_notebook.content):+ return++ before_update = Notebook.objects.get(pk=locked_notebook.pk)+ annotated_content = annotate_python_nodes(content)+ locked_notebook.content = annotated_content+ locked_notebook.text_content = text_content+ locked_notebook.version += 1+ locked_notebook.last_modified_at = now()+ locked_notebook.last_modified_by = user+ locked_notebook.save(+ update_fields=[+ "content",+ "text_content",+ "version",+ "last_modified_at",+ "last_modified_by",+ ]+ )++ notify_team_id = locked_notebook.team_id+ notify_notebook_id = str(locked_notebook.short_id)+ notify_version = locked_notebook.version+ transaction.on_commit(+ lambda: markdown_collab.publish_notebook_update(+ notify_team_id,+ notify_notebook_id,+ notify_version,+ diff=None,+ )+ )++ changes = changes_between("Notebook", previous=before_update, current=locked_notebook)+ log_notebook_activity(+ activity="updated",+ notebook=locked_notebook,+ organization_id=cast(UUIDT, locked_notebook.team.organization_id),+ team_id=locked_notebook.team_id,+ user=user,+ was_impersonated=False,+ changes=changes,+ )+++def _build_comment_replies_by_mark_id(notebook: Notebook) -> dict[str, list[Any]]:+ root_comments = list(+ Comment.objects.filter(team_id=notebook.team_id, scope="Notebook", item_id=notebook.short_id)+ .filter(deleted=False, source_comment_id__isnull=True)+ .select_related("created_by")+ .order_by("created_at")+ )+ root_ids = [comment.id for comment in root_comments]+ replies_by_source_id: dict[Any, list[Comment]] = {comment.id: [] for comment in root_comments}+ if root_ids:+ for reply in (+ Comment.objects.filter(team_id=notebook.team_id, source_comment_id__in=root_ids)+ .filter(deleted=False)+ .select_related("created_by")+ .order_by("created_at")+ ):+ if isinstance(reply.item_context, dict) and reply.item_context.get("is_emoji"):+ continue+ replies_by_source_id.setdefault(reply.source_comment_id, []).append(reply)++ replies_by_mark_id: dict[str, list[Any]] = {}+ for comment in root_comments:+ item_context = comment.item_context+ mark_id = (+ item_context.get("id") if isinstance(item_context, dict) and item_context.get("type") == "mark" else None+ )+ if not isinstance(mark_id, str):+ continue+ thread = sorted([comment, *replies_by_source_id.get(comment.id, [])], key=lambda item: item.created_at)+ replies_by_mark_id[mark_id] = [_comment_to_reply(comment) for comment in thread]+ return replies_by_mark_id+++def _comment_to_reply(comment: Comment) -> dict[str, Any]:+ author = None+ if comment.created_by:+ author = comment.created_by.first_name or comment.created_by.email+ return {+ "id": str(comment.id),+ "text": comment.content or "",+ **({"author": author} if author else {}),+ **({"authorId": comment.created_by_id} if comment.created_by_id else {}),+ "at": comment.created_at.isoformat(),+ }+++def _build_mention_label_getter(notebook: Notebook) -> Callable[[int], str | None]:+ user_ids = _collect_mention_user_ids(notebook.content)+ if not user_ids:+ return lambda user_id: None++ users = User.objects.filter(+ id__in=user_ids,+ organization_membership__organization_id=notebook.team.organization_id,+ ).only("id", "first_name", "email")+ labels_by_user_id = {+ user.id: f"@{user.first_name or user.email}" for user in users if user.first_name or user.email+ }+ return lambda user_id: labels_by_user_id.get(user_id)+++def _collect_mention_user_ids(content: Any) -> set[int]:+ user_ids: set[int] = set()++ def visit(node: Any) -> None:+ if isinstance(node, dict):+ if node.get("type") == "ph-mention":+ attrs = node.get("attrs")+ user_id = attrs.get("id") if isinstance(attrs, dict) else None+ if isinstance(user_id, int):+ user_ids.add(user_id)+ for value in node.values():+ visit(value)+ elif isinstance(node, list):+ for child in node:+ visit(child)++ visit(content)+ return user_idsdiff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.pynew file mode 100644index 000000000000..357a84892158--- /dev/null+++ b/products/notebooks/backend/test/test_markdown_migration.py@@ -0,0 +1,194 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.models import Organization, Team, User+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.comment import Comment++from products.notebooks.backend.markdown_conversion import (+ NotebookMarkdownConversionOptions,+ build_markdown_notebook_content,+ convert_notebook_content_to_markdown,+)+from products.notebooks.backend.markdown_migration import (+ get_markdown_notebook_migration_stats,+ migrate_notebooks_to_markdown,+)+from products.notebooks.backend.models import Notebook+++class TestNotebookMarkdownConversion(BaseTest):+ def test_converts_rich_content_to_markdown_with_comments_mentions_and_widgets(self) -> None:+ content = {+ "type": "doc",+ "content": [+ {+ "type": "heading",+ "attrs": {"level": 1},+ "content": [{"type": "text", "text": "Launch notes"}],+ },+ {+ "type": "paragraph",+ "content": [+ {+ "type": "text",+ "text": "Ask ",+ },+ {+ "type": "ph-mention",+ "attrs": {"id": self.user.id},+ },+ {+ "type": "text",+ "text": " about activation",+ "marks": [{"type": "bold"}, {"type": "comment", "attrs": {"id": "mark-1"}}],+ },+ ],+ },+ {+ "type": "query",+ "attrs": {"query": '{"kind":"HogQLQuery","query":"select 1"}', "view": True, "edit": False},+ },+ ],+ }++ markdown = convert_notebook_content_to_markdown(+ content,+ NotebookMarkdownConversionOptions(+ comment_replies_by_mark_id={},+ get_mention_label=lambda user_id: f"@user-{user_id}",+ ),+ )++ assert "# Launch notes" in markdown+ assert f'<mention id="{self.user.id}">@user-{self.user.id}</mention>' in markdown+ assert '<ref id="mark-1">** about activation**</ref>' in markdown+ assert '<Comment ref="mark-1" replies={[]} />' in markdown+ assert 'query={{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"select 1"}}}' in markdown+ assert "hideFilters" in markdown+++class TestNotebookMarkdownMigration(BaseTest):+ def test_stats_count_all_notebooks_for_optional_team_scope(self) -> None:+ Notebook.objects.create(team=self.team, content={"type": "doc", "content": []})+ Notebook.objects.create(team=self.team, content=build_markdown_notebook_content("done"))+ other_team = Team.objects.create(organization=self.organization, name="other")+ Notebook.objects.create(team=other_team, content={"type": "doc", "content": []})++ all_stats = get_markdown_notebook_migration_stats()+ team_stats = get_markdown_notebook_migration_stats(self.team.id)++ assert all_stats.total == 3+ assert all_stats.converted == 1+ assert all_stats.pending == 2+ assert team_stats.total == 2+ assert team_stats.converted == 1+ assert team_stats.pending == 1++ def test_dry_run_does_not_mutate_or_log_activity(self) -> None:+ notebook = Notebook.objects.create(+ team=self.team,+ title="Dry run",+ content={"type": "doc", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "body"}]}]},+ version=3,+ )++ result = migrate_notebooks_to_markdown(user=self.user, team_id=self.team.id, dry_run=True)+ notebook.refresh_from_db()++ assert result.dry_run is True+ assert result.converted == 1+ assert notebook.version == 3+ assert notebook.content == {+ "type": "doc",+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "body"}]}],+ }+ assert not ActivityLog.objects.filter(scope="Notebook", item_id=notebook.short_id).exists()++ @patch("products.notebooks.backend.markdown_collab.publish_notebook_update")+ def test_apply_converts_team_notebooks_and_logs_before_after_history(self, mock_publish) -> None:+ rich_content = {+ "type": "doc",+ "content": [+ {+ "type": "paragraph",+ "content": [+ {+ "type": "text",+ "text": "Important",+ "marks": [{"type": "comment", "attrs": {"id": "mark-1"}}],+ }+ ],+ }+ ],+ }+ notebook = Notebook.objects.create(team=self.team, title="Convert me", content=rich_content, version=7)+ Comment.objects.create(+ team=self.team,+ scope="Notebook",+ item_id=notebook.short_id,+ content="keep this",+ item_context={"type": "mark", "id": "mark-1"},+ created_by=self.user,+ )+ other_team = Team.objects.create(organization=self.organization, name="other")+ other_notebook = Notebook.objects.create(+ team=other_team,+ content={"type": "doc", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "other"}]}]},+ )++ with self.captureOnCommitCallbacks(execute=True):+ result = migrate_notebooks_to_markdown(user=self.user, team_id=self.team.id, dry_run=False)++ notebook.refresh_from_db()+ other_notebook.refresh_from_db()+ assert result.converted == 1+ assert notebook.version == 8+ assert notebook.text_content is not None+ assert "<Comment" in notebook.text_content+ assert "keep this" in notebook.text_content+ assert notebook.content == build_markdown_notebook_content(notebook.text_content)+ assert other_notebook.content["content"][0]["type"] == "paragraph"++ log = ActivityLog.objects.get(scope="Notebook", item_id=notebook.short_id, activity="updated")+ detail = log.detail+ assert isinstance(detail, dict)+ changes = detail["changes"]+ assert isinstance(changes, list)+ changes_by_field = {change["field"]: change for change in changes if isinstance(change, dict)}+ assert changes_by_field["content"]["before"] == rich_content+ assert changes_by_field["content"]["after"] == notebook.content+ assert changes_by_field["version"]["before"] == 7+ assert changes_by_field["version"]["after"] == 8+ mock_publish.assert_called_once_with(self.team.id, notebook.short_id, 8, diff=None)++ def test_apply_scopes_mention_label_lookup_to_notebook_organization(self) -> None:+ same_org_user = self._create_user("[email protected]", first_name="Same")+ outside_org = Organization.objects.create(name="Outside")+ outside_user = User.objects.create_and_join(outside_org, "[email protected]", None, "Leaked")+ notebook = Notebook.objects.create(+ team=self.team,+ title="Mentions",+ content={+ "type": "doc",+ "content": [+ {+ "type": "paragraph",+ "content": [+ {"type": "ph-mention", "attrs": {"id": same_org_user.id}},+ {"type": "text", "text": " "},+ {"type": "ph-mention", "attrs": {"id": outside_user.id}},+ ],+ }+ ],+ },+ )++ migrate_notebooks_to_markdown(user=self.user, team_id=self.team.id, dry_run=False)++ notebook.refresh_from_db()+ assert notebook.text_content is not None+ assert f'<mention id="{same_org_user.id}">@Same</mention>' in notebook.text_content+ assert f'<mention id="{outside_user.id}">@member</mention>' in notebook.text_content+ assert "Leaked" not in notebook.text_content+ assert "[email protected]" not in notebook.text_content