: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): improve markdown notebooks (#63556)
Marius Andra3114a02aba47
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3b3df6c44c05..c0a0286db8fb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -969,61 +969,61 @@ snapshots:components-markdown-editor-rich--with-markdown--light:hash: v1.k794b7964.a73d574094e4664a4cfe8a28bbb74d6bf7d6b7cbe0b5f05aeb3a11fc42a8109e.fHAFZolNByYE1LYlKSbW0YVDUxDdmt31lCq06SkXjYAcomponents-markdown-notebook--component-catalog--dark:- hash: v1.k794b7964.1e29e311559f3a62ad3ff3b2a159b6b7dd7c6aa592dd0d0e6912b6c64ad7281c.luYAv9uhYq9QLK_0qcZm4WhZltnpjD4dlG7WQ4P2lK4+ hash: v1.k794b7964.27bd8ff6aa953fd3dcc74695bcf994ee61de119f68852725380df0525c3ec960.6WCCFdPAmO2Nkdx9Q2vJlmNPXlFC8uFuLnUCUSyIM2Acomponents-markdown-notebook--component-catalog--light:- hash: v1.k794b7964.811acc078f2719939b755005a43049a4dfe40d6ff2ef1df067f5e8ae56b760ff.1cWue6jgvi8msqFE6Q6aBeP3DmMs550VjOk4R1nICyQ+ hash: v1.k794b7964.84c3716bef05c668b7ce7194a856a4f5df9820d47333efa7ae00acfd6f6826fd.pNhIsfx3QvBZ9YZ8GM2Tp06iZB1YRqembS7JgeFmBwccomponents-markdown-notebook--edit-mode--dark:- hash: v1.k794b7964.1e29e311559f3a62ad3ff3b2a159b6b7dd7c6aa592dd0d0e6912b6c64ad7281c.sel1o1tApXYbWuPySddNegrWK9vLYT-zwKTC6XkWfoA+ hash: v1.k794b7964.27bd8ff6aa953fd3dcc74695bcf994ee61de119f68852725380df0525c3ec960.5_27sycZRuQzxvpTC7UHOW5Iqe1wJ4d4wJuJDt8bNyAcomponents-markdown-notebook--edit-mode--light:- hash: v1.k794b7964.811acc078f2719939b755005a43049a4dfe40d6ff2ef1df067f5e8ae56b760ff.N5QAiXnj5Q3AsiH_HH5Q5wL01m3cbB7P5fygYFyqEHo+ hash: v1.k794b7964.84c3716bef05c668b7ce7194a856a4f5df9820d47333efa7ae00acfd6f6826fd.4Tv7LGH8O8aJmIw3k_rxBDzpNP39MUZ8Nv_Ijyz7n-gcomponents-markdown-notebook--embeds--dark:- hash: v1.k794b7964.e2e05397c0118cf3aeb137faa8d6c44d82f3ddcfe93d02405f829661c2d72d5f.UwqLWuEKReI70c5tutlxFHreJMQQryLHV70JAEHumwI+ hash: v1.k794b7964.17115b09f002d886640e3a80269cbfeda6a84e75d0903c5f8b33949a82b2c40d.jINuVHXjXymhV1EIZOVpCROJUy7VcBh6zEbwRR0csE4components-markdown-notebook--embeds--light:- hash: v1.k794b7964.09a5bcc27ae6ebb530a7cd582f5df8a26c88ad3ba40dcf1e445a1d9cfd3469f4.2e1vzHeicDSdXzxjAjYVdrTDE7fwt5lHNpqOtGlnbGw+ hash: v1.k794b7964.bb9c9ce02d3863c71e98dcbd000e90899fa627943418d8cdf5b6dfa26fbb8073.h7ZHGpzKgRxrek7-utCz05YjSjdcDWKGeQ7duje8lsAcomponents-markdown-notebook--empty-notebook--dark:- hash: v1.k794b7964.7cbb426de8251a2f8900f5f337a12700fed06f62d0183b036fdf440f1eaf834c.ybu_f4PLUm4LpIkQjQxmXIuGfJuTYgAk-bayazPjuV4+ hash: v1.k794b7964.f45a026eff4c07da6e39e1e015a8407aa5eb485749b9f4268da8c1ae99338c55.StnViUT9OnBu1CdVk3iOI6rJEQyxa0Xq6w922SJkQQUcomponents-markdown-notebook--empty-notebook--light:- hash: v1.k794b7964.8507d86783b916083379c574e8442ed13aa4a56fd53754ba04dfeb35f9a29b9a.o23DG2q59zuGo1S-waZNnwHQw_zpQjqK6jr9jf9MPBw+ hash: v1.k794b7964.5635cf9d8f5761161382f2120f7a8faaa150531585c3a5e8b14850a2458411d7.p0iOicVpkHYt-cg9K8V-cRleN2A2VBr1nxkkWrDlyaocomponents-markdown-notebook--headings-and-inline-formatting--dark:- hash: v1.k794b7964.28d37a32c1ae05766ff540240a3ee74e68dda68869edfe23220f580f2f06f9c7.drrZHAJqA1V_cTcpKGgJRRALw9Pp_PzwGGdNg7IiYXQ+ hash: v1.k794b7964.7b7ff2425c1881a79ec4c7ffec25d224348f1c76b42c8a1f7e62fe3a15aa747d.rp-WHgB4eEVKewCB7ZS8ETwbDN0NWxSvf2mcI-mKb0ccomponents-markdown-notebook--headings-and-inline-formatting--light:- hash: v1.k794b7964.9888596d00b9118969f20922a0b9aa8ed5f3d4d68aeba808135d874ce4cca75a.j7WtT6se9xAQ2fuaVFTxyDEmUkU2rQf5nSNZ0E_TUXc+ hash: v1.k794b7964.ff6f3c294683fb9d44afdf77803b00e06f36ffc8fb2a257fd5b027066316080f.wdMHkFjgbn4YshXVR1z_q-9ZKoTgkJShGxNaQtsuIPUcomponents-markdown-notebook--invalid-component-props--dark:- hash: v1.k794b7964.3ec50ff3704d240455077fcc0a6d5afbcec8b5caa14b14232126531e512a2e0b.WxLpCScEuKCM6kkcDzy6v_4Tr3V4Sk3bZwBJ4ztvvp8+ hash: v1.k794b7964.0def61d49476150a6c148337a39778fcc7b749a1d193de9cd7eb70f2cfeffe9d.WKcJWHDs5gYMbmwCiPm-agMoyS44uuuO-cT4Hfs-goMcomponents-markdown-notebook--invalid-component-props--light:- hash: v1.k794b7964.a0f81daf461faf93c867c077248b946287a439398dd099fe7e0896645a81d278.QJbiVYwNj2gJ2Q7zZlK91DZu72dTwuLpQqcqSQ_f3Ls+ hash: v1.k794b7964.815eed2c70430ccc62fe8f7579615a0ed6431baa86c9b0c9946f2ed5619f6f7d.tj_fVvy4MBsiqUs31h3M086Z6vTHudkiTYdHODpvpHAcomponents-markdown-notebook--lists-and-links--dark:- hash: v1.k794b7964.3858121270db1e00d8c8a51b6aae447c9281ff262a313ca715c7ba5c64e950dd.0RuqWjHaOZOXUQCcWrKYjJh9KeuJGkKGxudLQR_SLFg+ hash: v1.k794b7964.6b56b6a4cd77693e7dc2088be87b6b38b49fde4da6bc821daeb6cd8f4e8f2d0b.WqkdLYt_2cnLIF4lmLUqQO9C_CKGGowmoyil4zw1QdUcomponents-markdown-notebook--lists-and-links--light:- hash: v1.k794b7964.29dbeae01ed0803f3c9838ba2dbaf2e7f824fccb443c36ced60511ec78ad08bc.2sxyRNkZutPI04EoDMgkkwN5e8ARuibPE0gGgyWALhI+ hash: v1.k794b7964.73248b9617ad53b53ad9488daa521868f88c8dcf572108095b0f4cfe1c2049fe.DcdBygZ0KxdyxdlzhNy4UzGsC6P2zW-tncDpSEQ72fYcomponents-markdown-notebook--malformed-markdown-recovery--dark:- hash: v1.k794b7964.52d7777de0917b35b334a9b384fafff389562bf1a19cfc951fe6237a54f0eb83.KAPga8GO3wSl5G64hoJPHUoqm5yEozhVTV1lsrxCSEM+ hash: v1.k794b7964.3a4081377e7e7c1b93b5478289a6e6202f57bec7f156c5c12b5e0efbcca74466.5P_oEi83fXKV0-Qgvh-m1-i1RZGgJZ3DCY1AYbqINOccomponents-markdown-notebook--malformed-markdown-recovery--light:- hash: v1.k794b7964.4085234d80d5775b0325e8167e1897ba0e7d2d10f063dda1572d5dc0d5bd9cca.A-kA9v8XIANObJcvG06bPMlodjwvrxfe1iYK2xMJwWs+ hash: v1.k794b7964.a880e55028ccd676b92ea293a31a5166b2f8041d3365831a5bd98bc103fcaaaa.5a2FMVr7U1kM-ZCKavYwM8jBBBaSQ8_NZ8BvoithE90components-markdown-notebook--mocked-collaboration--dark:- hash: v1.k794b7964.4ab36b0926c112ec9811f610705add99e45384d8daf2f65898379764daedffbc.yfnAmvNCRFmrWzZU6LzG1inw6fXuDvLb8IHqDKT0A5s+ hash: v1.k794b7964.362c97f3b5d2ecac972a8c0740f1b6672901d5f789ad8329e9e79c2011fe2d8b.PrqV560hl4p_ko3RWSNjYgKbwTb2UCxdC0ABSI34MZQcomponents-markdown-notebook--mocked-collaboration--light:- hash: v1.k794b7964.555af845b4e3c034ab539dc8d3f848634384ac52bc3ad33d8853cf81dc4f961f.Z6tTedgGI3CKh_IqC_v9sLJkeXE4gM382-9GTcXzLm4+ hash: v1.k794b7964.c928d04db6f795ec3d4528297df85598cba9231b9856d006ff3c30fc92d48d67.4wci5wIse5Xqr1ZcMG_XDvyZgMsWlCJypKgLWYjEQagcomponents-markdown-notebook--query-block--dark:- hash: v1.k794b7964.753e218f374e46381ff687defb3f9f5decf7709684352a5156151c27fa218a3d.fKdXklO2rLYekX4mRs9dZ07EPgtwF9vYID9Vp5O9XGg+ hash: v1.k794b7964.3f8ca70230ca39568ba424d6fffa9c2e0da376313779f43d6d0829fc652a13f0.JedE3uQD9JRVOvgLId_FxrgnsQ3TeMgZc3Y9_-yJQ4Ucomponents-markdown-notebook--query-block--light:- hash: v1.k794b7964.abb371f06091dde16e1c7d1679476b561d3288011efee1519c0d6e0c21250c84.d-ASypB9T-8Wc2x68pbu0RIWzDfEQV6cmOKHCdi1fpc+ hash: v1.k794b7964.d0733969bf320666bb33890fda5cac1e1a2cf83ef0dd4d75ca5ecaf17a630899.rzwsiPQU9ynF78SElibw7hEPuHHwPDHNVn-YvXCVeGgcomponents-markdown-notebook--selection-toolbar-state--dark:- hash: v1.k794b7964.1876a07a52dc178b35cb6b3f7bdcc74abc969388870ec43628ffebe3d7215002.1z3a27YZfbYj3emxVsYe6kzYl7aPTKEiHZe41Ntqqu0+ hash: v1.k794b7964.c4339d9346b15aa8d1a0deee6232f6acc043226932d634ae752a6c6aaf47a457.iB4WHAMVXDoIohG7lKbwouG0rV5btUOIvdPnoImfNq8components-markdown-notebook--selection-toolbar-state--light:- hash: v1.k794b7964.559a8c39cc81a311501c0092908afbb7f9fcbd94c97c0f2aad60d901a7a40660.bexLivfwoF6qOLx-b3EpM4PLFqks9RvpyB_YdQ-Bq9k+ hash: v1.k794b7964.cbd6bebae221a83d57eb158271b6d0392c4a97ba0cbb264e45896238e0ca825c.9D71IPyqQKoLthL1YI5cO9ABW4GLINhnnsavm4Uvdb0components-markdown-notebook--slash-menu-and-insertion--dark:- hash: v1.k794b7964.fcf994a3b3e0dbb80444cb08fee58d72437a83a4d749736f7ddd0a1d8ee15a8e.EGEDRc0h3DxW1E12tBF6TE0oHC_1YWSKjb6d8I_8jkM+ hash: v1.k794b7964.d968ec2027556c62829dbc185ee39a445893c3e568e5771c2d59f82d1425250c.TtoOAbdXyswGkLnD7XvSLHiD5wjXgzl4IhQcT_3vqh8components-markdown-notebook--slash-menu-and-insertion--light:- hash: v1.k794b7964.8320b3a0682639a76b440a707c137e35e4d0803f503a9458cc1bdd0487a16951.viEJl7kqEnOsdT2-hjF4tbZhgvFBlN6LIvbLzH0EOOQ+ hash: v1.k794b7964.4ffa5e775ebb0d86e154af8c066e771c8bce1c6ee81718e8c32485d8e9a3b5d1.1oNLmFcGrrhK3lR23o8NPa5__PDMtdXhArlbQTSG8Wscomponents-markdown-notebook--text-only-notebook--dark:- hash: v1.k794b7964.298a1e2473f9147f7a7ba29b7031f78de546dc7f6cd43ec114704d470a2eda4d.UmxAr-vuRtRwDc2unArm5A6OXTLjn7LR-CJPzx2kCR8+ hash: v1.k794b7964.e7c323cba26ac4231d435e150644c28a9511019b5f181850f631f3e967301cff.CCxOgPJHfDvj3CLrkAJqOWLdWs2egkkGI1jLAjU-V0Ucomponents-markdown-notebook--text-only-notebook--light:- hash: v1.k794b7964.89af8ce1d2e6e3afc514da924859c879202ac9e111f6b4891a0f23652281bf83.J2dE30jjUPG_uqTDim-GjmL3lstX9-QA2ah6ovGh1mI+ hash: v1.k794b7964.a6cb871fd1f2544b5630b89ba9d6277d985af49112ef06d6b809976faf09cbcb.oec-LSlj5Ik0k_4lHcVHWSpMYmyQ6PpsYTJ0f0pO8Rgcomponents-markdown-notebook--view-mode--dark:- hash: v1.k794b7964.38b4da41bef1b65ec0ad205bec9eb73ed90617bfa2d4ca49755fd581df92fe34.tDsWlsKQmyt-dRdzq6sPAKiL6UivKXRmsfp5T0j9WZw+ hash: v1.k794b7964.70e32e5d171e23a932c7f6ddc2faf4f49a5289e48524ce5ab3676bb7c7de1a4e.K26Rsz1hJOocOeUD9MwVZt1tG81WjDlIqDSOSb6BqkEcomponents-markdown-notebook--view-mode--light:- hash: v1.k794b7964.d79b7f3c495c5d9b19b9b609f2f86655502223cce703c53846d37063183bc753.W9taJXUyY9fDpp1l5JNF4pnffUaavEM8SmRGP3lWhQI+ hash: v1.k794b7964.ae0ca59cf6500df5746d0e24378e968539efe52cefb573d75d28cc177de342e1.sOeMSWpIyorzGikdOhqaVMyNxaeMhK-501u_03XW24Ycomponents-mcp-hint-toast--annotations-create--dark:hash: v1.k794b7964.bef4544b1170fd5d46af679c869c7d962143786c2329058cba6488c441c65f26.3QVsYYxpE1AngWtWDNxi7cub9Vl59GlkiaNk3974Srgcomponents-mcp-hint-toast--annotations-create--light:@@ -5507,9 +5507,9 @@ snapshots:scenes-app-notebooks--numbered-list--light:hash: v1.k794b7964.70eadeb962d410add11648f7ba0939a5e5134c297e6467439aeb72f9e22b1504.MtRYdPpUsMVbKGiSvE2DCK6AQ9FVFhg44Y4_1g-Y81cscenes-app-notebooks--recordings-playlist--dark:- hash: v1.k794b7964.98c49d6b24ca6df18b009a337dde8950bc26be2d85c46ee74aa907763d7f7b8f.amgp-YwT_1y1Rn_-Cgf5GV0HWdLUI9WAPiAEQrg3FB0+ hash: v1.k794b7964.45832bc6ffc3fc1b07e1f44fd4310cc991cff24c8874f9d67d071b33d55a7005.yplm_e0hoiU0dzulGRxy0weTNq65BpQYbgikXlhwIKgscenes-app-notebooks--recordings-playlist--light:- hash: v1.k794b7964.43d83304243555e8289803c97eee4032ce2f1ec9de3a6dfbc7c2866e8b112138.rLVv-YWxkRjlmhH7nOpT0-8VHFdz_dKQdc1H27ESyac+ hash: v1.k794b7964.1261cba70925710c7fc821124c650aeada17fb6c5551190a6e5db02c58f24f8b.xg17fv2o9pL-mGTvw8zXRvlHVADrCMgNbAjJ1Ii6seUscenes-app-notebooks--text-formats--dark:hash: v1.k794b7964.18a89e84a3d1023246de21577eb15c78d44eaa252d6856a347ca8fec65154261.1f-7Wr58KvWTAUOob23JEU24MSDBz33i0xyzElngIS0scenes-app-notebooks--text-formats--light:diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex 06260c10c66d..d1ec873af68e 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -126,9 +126,9 @@.MarkdownNotebook__debug-toolbar {position: absolute;- // Sit in the first surface's top-right corner, matching where component blocks show their delete button.+ // Sit in the first text surface's top-right corner, matching where component blocks show their delete button.top: 0.375rem;- right: calc(max(calc((100% - var(--markdown-notebook-canvas-max-width)) / 2), 0px) + 0.5rem);+ right: 0.5rem;z-index: var(--z-raised);display: flex;justify-content: flex-end;@@ -197,6 +197,10 @@margin: 0 auto;}+.MarkdownNotebook--edit .MarkdownNotebook__canvas {+ padding-bottom: 18rem;+}+.MarkdownNotebook__canvas:focus {outline: none;}@@ -438,6 +442,7 @@}.MarkdownNotebook__text-group {+ position: relative;box-sizing: border-box;width: calc(100% - var(--markdown-notebook-content-offset));padding: 1.75rem 1rem;@@ -451,6 +456,10 @@box-shadow: var(--markdown-notebook-text-group-shadow);}+.MarkdownNotebook__text-group--with-debug-toolbar > .MarkdownNotebook__row:first-of-type .MarkdownNotebook__text-block {+ padding-right: 2.25rem;+}+// The notebook must start flush with the page top like every other scene: collapse the// first insert boundary (its hover zone still reaches above) and the first surface's top margin..MarkdownNotebook__canvas > .MarkdownNotebook__insert-boundary:first-child {@@ -1726,6 +1735,7 @@ button.MarkdownNotebook__component-title:focus-visible {}.MarkdownNotebook__real-node-content {+ position: relative;display: flex;flex: 1;flex-direction: column;@@ -1737,6 +1747,21 @@ button.MarkdownNotebook__component-title:focus-visible {resize: vertical;}+.MarkdownNotebook__real-node-resize-handle {+ position: absolute;+ right: 0.125rem;+ bottom: 0.125rem;+ z-index: 1;+ width: 1.25rem;+ height: 1.25rem;+ cursor: ns-resize;+ background:+ linear-gradient(135deg, transparent 0 45%, var(--color-border-bold) 45% 50%, transparent 50% 100%),+ linear-gradient(135deg, transparent 0 62%, var(--color-border-bold) 62% 67%, transparent 67% 100%);+ border-radius: 0.125rem;+ opacity: 0.6;+}+/* Inline ref highlights: text a chat thread is anchored to. */.MarkdownNotebook__ref {background: var(--color-bg-fill-highlight-100, rgb(235 145 0 / 15%));@@ -1778,18 +1803,6 @@ button.MarkdownNotebook__component-title:focus-visible {box-shadow: none;}-/* The gutter widens the effective canvas, so the source button must shift along with it- instead of floating over the comment column. */-.MarkdownNotebook--comments-margin .MarkdownNotebook__debug-toolbar {- right: calc(- max(- calc((100% - var(--markdown-notebook-canvas-max-width) - var(--markdown-notebook-comment-gutter)) / 2),- 0px- ) +- 0.5rem- );-}-/* With comment threads present and enough room, the canvas reserves a right gutter wideenough for the whole thread column, pushing the text content left. */.MarkdownNotebook--comments-margin .MarkdownNotebook__canvas {diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex 998c44417893..58f2fe670afa 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -13,6 +13,7 @@ import {import { MarkdownNotebook } from './MarkdownNotebook'import { reconcileNotebookDocuments } from './reconcile'import { createMarkdownNotebookRegistry } from './registry'+import type { NotebookComponentRenderProps } from './types'// Monaco cannot run in jsdom; stand in with a plain textarea that honors value/onChange.jest.mock('lib/monaco/CodeEditor', () => {@@ -141,6 +142,40 @@ function createHistoryTestRegistry(): ReturnType<typeof createMarkdownNotebookRe])}+function createDiscussionCommentTestRegistry(): ReturnType<typeof createMarkdownNotebookRegistry> {+ return createMarkdownNotebookRegistry([+ {+ tagName: 'Comment',+ label: 'Comment',+ category: 'Text',+ ViewComponent: TestDiscussionComment,+ EditComponent: TestDiscussionComment,+ hideModeActions: true,+ exclusiveEditPanel: true,+ },+ ])+}++function TestDiscussionComment({ node, updateProps }: NotebookComponentRenderProps): JSX.Element {+ const [draft, setDraft] = useState('')+ const replies = Array.isArray(node.props.replies) ? node.props.replies : []+ const submitReply = (): void => {+ updateProps({ replies: [...replies, { id: `r${replies.length + 1}`, text: draft }] })+ setDraft('')+ }++ return createElement(+ 'div',+ { 'data-attr': 'notebook-discussion-comment' },+ createElement('textarea', {+ 'data-attr': 'notebook-discussion-comment-input',+ value: draft,+ onChange: (event: ChangeEvent<HTMLTextAreaElement>) => setDraft(event.target.value),+ }),+ createElement('button', { type: 'button', 'aria-label': 'Send reply', onClick: submitReply }, 'Send')+ )+}+function getEditableTextBlocks(container: HTMLElement): HTMLElement[] {return Array.from(container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)) as HTMLElement[]}@@ -2320,6 +2355,23 @@ Tail paragraph`expect(flashedShell?.closest('.MarkdownNotebook__row--margin-comment')).toBeInstanceOf(HTMLElement)})+ it('renders the source button inside the first text group when comments are present', () => {+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle(+ '<Comment replies={[{"id":"r1","text":"First comment"}]} />\n\n<Query query={{"kind":"DataTableNode"}} />'+ ),+ showDebug: true,+ })+ )+ const firstTextGroup = container.querySelector('.MarkdownNotebook__text-group')+ const debugToolbar = container.querySelector('.MarkdownNotebook__debug-toolbar')++ expect(firstTextGroup).toBeInstanceOf(HTMLElement)+ expect(debugToolbar).toBeInstanceOf(HTMLElement)+ expect(firstTextGroup?.contains(debugToolbar)).toBe(true)+ })+it('opens a synced markdown source drawer from the source button', async () => {const { container } = render(createElement(MarkdownNotebook, { value: 'First paragraph', showDebug: true }))const debugButton = container.querySelector('button[aria-label="Edit markdown source"]')@@ -3817,6 +3869,41 @@ Body text`)<Query query={{"kind":"DataTableNode"}} />`)})+ it('reuses an existing block comment thread above a component from the gutter button', async () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle(+ '<Comment replies={[{"id":"r1","text":"First comment"}]} />\n\n<Query query={{"kind":"DataTableNode"}} />'+ ),+ registry: createDiscussionCommentTestRegistry(),+ onChange,+ })+ )+ const commentButtons = Array.from(+ container.querySelectorAll('[data-attr="markdown-notebook-block-comment-button"]')+ )++ expect(commentButtons).toHaveLength(1)++ fireEvent.click(commentButtons[0] as HTMLElement)++ const commentInput = container.querySelector(+ '[data-attr="notebook-discussion-comment-input"] textarea, textarea[data-attr="notebook-discussion-comment-input"]'+ ) as HTMLTextAreaElement+ expect(commentInput).toBeInstanceOf(HTMLTextAreaElement)+ await waitFor(() => expect(document.activeElement).toEqual(commentInput))++ fireEvent.change(commentInput, { target: { value: 'Second comment' } })+ fireEvent.click(container.querySelector('button[aria-label="Send reply"]') as HTMLButtonElement)++ const markdown = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string+ expect(markdown.match(/<Comment/g)).toHaveLength(1)+ expect(markdown).toContain('"text":"First comment"')+ expect(markdown).toContain('"text":"Second comment"')+ expect(markdown).toContain('<Query query={{"kind":"DataTableNode"}} />')+ })+it('does not offer the block comment button in view mode', () => {const { container } = render(createElement(MarkdownNotebook, {@@ -7996,6 +8083,25 @@ After component`,expect(container.querySelector('button[aria-label="Delete component"]')).toBeInstanceOf(HTMLButtonElement)})+ it('passes the outer notebook mode into component previews', () => {+ const modes: Array<Pick<NotebookComponentRenderProps, 'mode' | 'notebookMode'>> = []+ const registry = createMarkdownNotebookRegistry([+ {+ tagName: 'Embed',+ label: 'Embed',+ category: 'Media',+ ViewComponent: ({ mode, notebookMode }) => {+ modes.push({ mode, notebookMode })+ return createElement('div', { 'data-testid': 'component-output' }, 'Embedded output')+ },+ },+ ])++ render(createElement(MarkdownNotebook, { value: '<Embed />', registry, mode: 'edit' }))++ expect(modes).toContainEqual({ mode: 'view', notebookMode: 'edit' })+ })+it('opens both panels for component blocks inserted through a value update', () => {const { container, rerender } = render(createElement(MarkdownNotebook, { value: 'Intro paragraph' }))diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex 3449d824ae77..39f68ea75acf 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -3293,6 +3293,21 @@ export function MarkdownNotebook({window.setTimeout(() => element.classList.remove('MarkdownNotebook__component-shell--comment-flash'), 1600)}+ const focusDiscussionCommentComposer = (nodeId: string): void => {+ window.setTimeout(() => {+ const element = blockRefs.current[nodeId]+ const textarea = element?.querySelector(+ '[data-attr="notebook-discussion-comment-input"] textarea, textarea[data-attr="notebook-discussion-comment-input"]'+ )+ if (textarea instanceof HTMLTextAreaElement) {+ textarea.focus()+ textarea.setSelectionRange(textarea.value.length, textarea.value.length)+ return+ }+ element?.focus()+ }, 0)+ }+const handleCanvasClick = (event: ReactMouseEvent<HTMLDivElement>): void => {const refElement = event.target instanceof Element ? event.target.closest('[data-notebook-ref]') : nullconst refId = refElement?.getAttribute('data-notebook-ref')@@ -3311,13 +3326,23 @@ export function MarkdownNotebook({return}+ const insertIndex = Math.max(targetIndex, 1)+ const existingCommentNode = nodes[insertIndex - 1]+ if (+ existingCommentNode &&+ isDiscussionCommentNode(existingCommentNode) &&+ !getDiscussionCommentRefId(existingCommentNode)+ ) {+ focusDiscussionCommentComposer(existingCommentNode.id)+ return+ }+const commentNode: NotebookComponentBlockNode = {id: makeEmptyParagraph(`comment-${nodeId}`).id,type: 'component',tagName: 'Comment',props: { replies: [] },}- const insertIndex = Math.max(targetIndex, 1)markNotebookNodeFreshlyInserted(commentNode.id)commitDocument({...currentDocument,@@ -4818,6 +4843,27 @@ export function MarkdownNotebook({)}+ const renderDebugToolbar = (): JSX.Element | null => {+ if (!showDebug) {+ return null+ }++ return (+ <div className="MarkdownNotebook__debug-toolbar" contentEditable={false}>+ <LemonButton+ size="small"+ icon={<IconCode />}+ active={isDebugOpen}+ tooltip="Edit markdown source"+ aria-label="Edit markdown source"+ aria-controls={debugDrawerId}+ aria-expanded={isDebugOpen}+ onClick={() => setIsDebugOpen((isOpen) => !isOpen)}+ />+ </div>+ )+ }+const renderNotebookRow = (node: NotebookBlockNode, index: number): JSX.Element => {const isTitleRow = index === 0const isInsertMenuOpen = insertMenu?.nodeId === node.id@@ -5025,11 +5071,14 @@ export function MarkdownNotebook({)}+ const firstTextGroupKey = renderedNodeGroups.find((group) => group.type === 'text')?.key+return (<divclassName={clsx('MarkdownNotebook',isDebugOpen && 'MarkdownNotebook--debug-open',+ mode === 'edit' && 'MarkdownNotebook--edit',hasDiscussionComments &&(fitsCommentGutter ? 'MarkdownNotebook--comments-margin' : 'MarkdownNotebook--comments-inline'),className@@ -5043,20 +5092,6 @@ export function MarkdownNotebook({><div className="MarkdownNotebook__debug-layout"><div className="MarkdownNotebook__main" ref={mainRef} onMouseDown={handleMainMouseDown}>- {showDebug ? (- <div className="MarkdownNotebook__debug-toolbar">- <LemonButton- size="small"- icon={<IconCode />}- active={isDebugOpen}- tooltip="Edit markdown source"- aria-label="Edit markdown source"- aria-controls={debugDrawerId}- aria-expanded={isDebugOpen}- onClick={() => setIsDebugOpen((isOpen) => !isOpen)}- />- </div>- ) : null}{document.errors.length ? (<div className="MarkdownNotebook__parse-errors">{document.errors.map((error) => (@@ -5096,7 +5131,15 @@ export function MarkdownNotebook({return (<Fragment key={group.key}>- <div className="MarkdownNotebook__text-group">+ <div+ className={clsx(+ 'MarkdownNotebook__text-group',+ group.key === firstTextGroupKey &&+ showDebug &&+ 'MarkdownNotebook__text-group--with-debug-toolbar'+ )}+ >+ {group.key === firstTextGroupKey ? renderDebugToolbar() : null}{chunks.map((chunk) => {const chunkLastIndex = chunk.items[chunk.items.length - 1].indexconst rows = chunk.items.map(({ node, index }) => (diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsxindex 5fb1d6c37423..d29580035264 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx@@ -260,13 +260,25 @@ export function NotebookComponentShell({) : null}{showEditPanel && EditComponent ? (<div className="MarkdownNotebook__component-panel">- <EditComponent node={node} mode="edit" updateProps={updateProps} deleteNode={deleteNode} />+ <EditComponent+ node={node}+ mode="edit"+ notebookMode={mode}+ updateProps={updateProps}+ deleteNode={deleteNode}+ /></div>) : null}{showViewPanel ? (<div className="MarkdownNotebook__component-panel">{ViewComponent ? (- <ViewComponent node={node} mode="view" updateProps={updateProps} deleteNode={deleteNode} />+ <ViewComponent+ node={node}+ mode="view"+ notebookMode={mode}+ updateProps={updateProps}+ deleteNode={deleteNode}+ />) : (<UnknownComponentView node={node} />)}diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.tsindex 739bd706e852..72a07cb761f7 100644--- a/frontend/src/lib/components/MarkdownNotebook/types.ts+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts@@ -121,6 +121,7 @@ export type NotebookTextSelectionRange = {export type NotebookComponentRenderProps = {node: NotebookComponentBlockNodemode: NotebookMode+ notebookMode?: NotebookModeupdateProps: (props: Partial<NotebookComponentProps>) => voiddeleteNode: () => void}diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.scss b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.scssindex c1bce8764de0..25adda748dc6 100644--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.scss+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.scss@@ -42,6 +42,21 @@z-index: 1;transition: box-shadow 150ms ease-out;}++ .NotebookNode__resize-handle {+ position: absolute;+ right: 0.125rem;+ bottom: 0.125rem;+ z-index: 2;+ width: 1.5rem;+ height: 1.5rem;+ cursor: ns-resize;+ background:+ linear-gradient(135deg, transparent 0 45%, var(--color-border-bold) 45% 50%, transparent 50% 100%),+ linear-gradient(135deg, transparent 0 62%, var(--color-border-bold) 62% 67%, transparent 67% 100%);+ border-radius: 0.125rem;+ opacity: 0.65;+ }}.NotebookNode__gap {diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsxindex 3cd4c427ee73..3c02adb4fcc2 100644--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx@@ -8,7 +8,7 @@ import {NodeViewProps,getExtensionField,} from '@tiptap/react'-import { memo, useCallback, useEffect, useRef, useState } from 'react'+import { memo, type PointerEvent as ReactPointerEvent, useCallback, useEffect, useRef, useState } from 'react'import clsx from 'clsx'import { IconDragHandle, IconLink } from 'lib/lemon-ui/icons'import { LemonButton, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'@@ -168,6 +168,42 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP// Element is resizable if resizable is set to true. If expandable is set to true then is is only resizable if expanded is trueconst isResizeable = resizeable && (!expandable || expanded)+ const onResizeHandlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>): void => {+ if (!isEditable || !isResizeable || !contentRef.current) {+ return+ }++ event.preventDefault()+ event.stopPropagation()++ const element = contentRef.current+ const startY = event.clientY+ const startHeight = element.getBoundingClientRect().height+ const parsedMinHeight = Number.parseFloat(window.getComputedStyle(element).minHeight)+ const minResizeHeight = Number.isFinite(parsedMinHeight) ? parsedMinHeight : 0++ const onPointerMove = (moveEvent: PointerEvent): void => {+ moveEvent.preventDefault()+ const nextHeight = Math.max(minResizeHeight, startHeight + moveEvent.clientY - startY)+ element.style.height = `${Math.round(nextHeight)}px`+ }++ const onPointerUp = (): void => {+ window.removeEventListener('pointermove', onPointerMove)+ window.removeEventListener('pointerup', onPointerUp)++ updateAttributes({+ height: element.clientHeight,+ ...(nodeType === NotebookNodeType.Python ? { autoHeight: false } : {}),+ } as any)+ }++ window.addEventListener('pointermove', onPointerMove)+ window.addEventListener('pointerup', onPointerUp)+ },+ [isEditable, isResizeable, nodeType, updateAttributes]+ )const isDraggable = !!(isEditable && getPos)const isPythonNode = nodeType === NotebookNodeType.Pythonconst isDuckSqlNode = nodeType === NotebookNodeType.DuckSQL@@ -414,6 +450,13 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPattributes={attributes}updateAttributes={updateAttributes}/>+ {isEditable && isResizeable ? (+ <div+ className="NotebookNode__resize-handle"+ aria-hidden="true"+ onPointerDown={onResizeHandlePointerDown}+ />+ ) : null}</ErrorBoundary></div></>diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.scss b/frontend/src/scenes/notebooks/Notebook/Notebook.scssindex 519a356ea9cd..24e55db1633a 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.scss+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.scss@@ -550,7 +550,11 @@flex: 1;// Add some padding to help clicking below the last element- padding-bottom: 10rem;+ padding-bottom: 6rem;+ }++ .Notebook__markdown-v2 .MarkdownNotebook__canvas {+ padding-bottom: 6rem;}.NotebookColumn--left.NotebookColumn--showing {diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsxindex 5fc45f60e2fd..091ce3c27fff 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx@@ -11,23 +11,28 @@ import { ErrorBoundary } from '~/layout/ErrorBoundary'import { notebookNodeLogic } from '../Nodes/notebookNodeLogic'import { notebookNodeLogicType } from '../Nodes/notebookNodeLogicType'+import { isMarkdownNotebookContent } from './markdownNotebookV2'import { NotebookHistory } from './NotebookHistory'import { NotebookKernelInfo } from './NotebookKernelInfo'import { notebookLogic } from './notebookLogic'import { NotebookTableOfContents } from './NotebookTableOfContents'export const NotebookColumnLeft = (): JSX.Element | null => {- const { editingNodeLogicsForLeft, isShowingLeftColumn, showHistory, showKernelInfo, showTableOfContents } =+ const { content, editingNodeLogicsForLeft, isShowingLeftColumn, showHistory, showKernelInfo, showTableOfContents } =useValues(notebookLogic)+ const shouldShowTableOfContents = showTableOfContents && !isMarkdownNotebookContent(content)+ const isShowingEffectiveLeftColumn =+ isShowingLeftColumn &&+ (editingNodeLogicsForLeft.length > 0 || showHistory || shouldShowTableOfContents || showKernelInfo)return (<divclassName={clsx('NotebookColumn NotebookColumn--left', {- 'NotebookColumn--showing': isShowingLeftColumn,+ 'NotebookColumn--showing': isShowingEffectiveLeftColumn,})}><div className="NotebookColumn__content">- {isShowingLeftColumn ? (+ {isShowingEffectiveLeftColumn ? (<>{editingNodeLogicsForLeft.map((logic) => (<div key={logic.values.nodeId}>@@ -36,7 +41,7 @@ export const NotebookColumnLeft = (): JSX.Element | null => {</div>))}{showHistory ? <NotebookHistory /> : null}- {showTableOfContents ? <NotebookTableOfContents /> : null}+ {shouldShowTableOfContents ? <NotebookTableOfContents /> : null}{showKernelInfo ? <NotebookKernelInfo /> : null}</>) : null}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsxindex ec48aa395720..62d978557f40 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx@@ -6,16 +6,21 @@ import { LemonButton, LemonButtonProps, LemonTag } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'import { IconDocumentExpand } from 'lib/lemon-ui/icons'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Spinner } from 'lib/lemon-ui/Spinner'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { userLogic } from 'scenes/userLogic'import { NotebookSyncStatus } from '../types'import { notebookCollabLogic } from './notebookCollabLogic'import { NotebookLogicProps, notebookLogic } from './notebookLogic'+import { getNotebookPresenceParticipants, type NotebookPresenceParticipant } from './notebookPresence'import { notebookSettingsLogic } from './notebookSettingsLogic'+const MAX_PRESENCE_BUBBLES = 6+const syncStatusMap: Record<NotebookSyncStatus, { content: React.ReactNode; tooltip: React.ReactNode }> = {synced: {content: 'Saved',@@ -111,6 +116,74 @@ export const NotebookCollabStatus = (props: NotebookLogicProps): JSX.Element | n)}+function notebookPresenceTooltip(participants: NotebookPresenceParticipant[]): string {+ const visibleNames = participants.slice(0, MAX_PRESENCE_BUBBLES).map((participant) => participant.userName)+ const overflowCount = participants.length - visibleNames.length+ const names =+ overflowCount > 0+ ? `${formatNotebookPresenceNames(visibleNames)} and ${overflowCount} more`+ : formatNotebookPresenceNames(visibleNames)+ const verb = participants.length === 1 && !participants[0].isCurrentUser ? 'is' : 'are'+ return `${names} ${verb} viewing this notebook`+}++function formatNotebookPresenceNames(names: string[]): string {+ if (names.length <= 1) {+ return names[0] ?? ''+ }+ if (names.length === 2) {+ return `${names[0]} and ${names[1]}`+ }+ return `${names.slice(0, -1).join(', ')}, and ${names[names.length - 1]}`+}++export const NotebookPresence = (props: NotebookLogicProps): JSX.Element | null => {+ const { user } = useValues(userLogic)+ const { markdownRemoteParticipants } = useValues(notebookLogic(props))+ const { remoteParticipants } = useValues(notebookCollabLogic({ shortId: props.shortId }))+ const participants = getNotebookPresenceParticipants(+ user,+ markdownRemoteParticipants.length > 0 ? markdownRemoteParticipants : remoteParticipants+ )++ if (!participants.length) {+ return null+ }++ const shownParticipants = participants.slice(0, MAX_PRESENCE_BUBBLES)+ const overflowCount = participants.length - shownParticipants.length+ const overflowTitle =+ overflowCount > 0+ ? participants+ .slice(MAX_PRESENCE_BUBBLES)+ .map((participant) => participant.userName)+ .join(', ')+ : undefined+ const tooltip = notebookPresenceTooltip(participants)++ return (+ <Tooltip title={tooltip} placement="left">+ <div className="ProfileBubbles" aria-label={tooltip}>+ {shownParticipants.map((participant) => (+ <ProfilePicture+ key={`${participant.userId}-${participant.clientId}`}+ user={participant.profileUser}+ name={participant.userName}+ title={participant.userName}+ size="md"+ index={participant.userId}+ />+ ))}+ {overflowCount > 0 ? (+ <div className="ProfileBubbles__more" title={overflowTitle}>+ +{overflowCount}+ </div>+ ) : null}+ </div>+ </Tooltip>+ )+}+interface NotebookExpandButtonProps extends Pick<LemonButtonProps, 'size' | 'type'> {inPanel: boolean}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex cc1f53c50afd..f54c1165bd12 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -32,7 +32,14 @@ import '../Nodes/NotebookNodeZendeskTickets'import clsx from 'clsx'import { BindLogic, useActions, useMountedLogic } from 'kea'-import { type CSSProperties, useCallback, useEffect, useMemo, useRef } from 'react'+import {+ type CSSProperties,+ type PointerEvent as ReactPointerEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+} from 'react'import { IconComment, IconSparkles } from '@posthog/icons'import { LemonInput, LemonTextArea } from '@posthog/lemon-ui'@@ -343,6 +350,7 @@ export function RealNotebookNodeComponent({export function MountedRealNotebookNodeComponent({node,mode,+ notebookMode,updateProps,editOnly,forceEditing,@@ -398,8 +406,9 @@ export function MountedRealNotebookNodeComponent({const Settings = options.Settingsconst showSettings = forceEditing && Settingsconst showContent = !editOnly || !Settings+ const isNotebookEditable = (notebookMode ?? mode) === 'edit'const isResizeable =- mode === 'edit' &&+ isNotebookEditable &&(typeof options.resizeable === 'function' ? options.resizeable(attributes) : (options.resizeable ?? true))const contentStyle: CSSProperties | undefined =isResizeable || attributes.height@@ -424,6 +433,39 @@ export function MountedRealNotebookNodeComponent({window.addEventListener('mouseup', handleResizeEnd)}, [isResizeable, updateAttributes])+ const handleResizeHandlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>): void => {+ if (!isResizeable || !contentRef.current) {+ return+ }++ event.preventDefault()+ event.stopPropagation()++ const element = contentRef.current+ const startY = event.clientY+ const startHeight = element.getBoundingClientRect().height+ const parsedMinHeight = Number.parseFloat(window.getComputedStyle(element).minHeight)+ const minHeight = Number.isFinite(parsedMinHeight) ? parsedMinHeight : 0++ const handlePointerMove = (moveEvent: PointerEvent): void => {+ moveEvent.preventDefault()+ const nextHeight = Math.max(minHeight, startHeight + moveEvent.clientY - startY)+ element.style.height = `${Math.round(nextHeight)}px`+ }++ const handlePointerUp = (): void => {+ window.removeEventListener('pointermove', handlePointerMove)+ window.removeEventListener('pointerup', handlePointerUp)+ updateAttributes({ height: element.clientHeight })+ }++ window.addEventListener('pointermove', handlePointerMove)+ window.addEventListener('pointerup', handlePointerUp)+ },+ [isResizeable, updateAttributes]+ )+return (<NotebookNodeContext.Provider value={nodeLogic}><BindLogic logic={notebookNodeLogic} props={logicProps}>@@ -444,6 +486,13 @@ export function MountedRealNotebookNodeComponent({onMouseDown={handleResizeStart}><Component attributes={attributes} updateAttributes={updateAttributes} />+ {isResizeable ? (+ <div+ className="MarkdownNotebook__real-node-resize-handle"+ aria-hidden="true"+ onPointerDown={handleResizeHandlePointerDown}+ />+ ) : null}</div>) : null}</div>diff --git a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.tsindex d58deeb69bce..a5bec7ba952a 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts@@ -1,7 +1,7 @@import { EventSourceMessage } from '@microsoft/fetch-event-source'import { getVersion, receiveTransaction, sendableSteps } from '@tiptap/pm/collab'import { Step } from '@tiptap/pm/transform'-import { actions, beforeUnmount, kea, key, listeners, path, props, reducers } from 'kea'+import { actions, beforeUnmount, kea, key, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'import api from 'lib/api'@@ -12,8 +12,15 @@ import { getCurrentTeamId } from 'lib/utils/getAppContext'import { notebooksCollabPresenceCreate } from 'products/notebooks/frontend/generated/api'import type { notebookCollabLogicType } from './notebookCollabLogicType'+import {+ getNotebookRemoteParticipants,+ type NotebookRemoteParticipant,+ pruneNotebookRemotePresence,+} from './notebookPresence'import { ClientPresence, REMOTE_PRESENCE_META } from './RemotePresenceExtension'+const PRESENCE_TTL_MS = 30_000+const PRESENCE_PRUNE_INTERVAL_MS = 5_000const PRESENCE_HEARTBEAT_MS = 10_000const PRESENCE_PUBLISH_DEBOUNCE_MS = 250@@ -98,6 +105,8 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([rebaseFailed: (params: { localContent: JSONContent; localText: string }) => params,/** Broadcast the local caret so it moves for others even without typing. */publishPresence: true,+ handleRemotePresence: (presence: ClientPresence) => ({ presence }),+ pruneRemotePresence: (now: number = Date.now()) => ({ now }),connectStream: true,disconnectStream: true,streamOpened: true,@@ -139,11 +148,27 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([disconnectStream: () => null,},],+ remotePresence: [+ {} as Record<string, ClientPresence>,+ {+ handleRemotePresence: (state, { presence }) => ({ ...state, [presence.clientId]: presence }),+ pruneRemotePresence: (state, { now }) => pruneNotebookRemotePresence(state, now, PRESENCE_TTL_MS),+ unbindEditor: () => ({}),+ },+ ],+ }),++ selectors({+ remoteParticipants: [+ (s) => [s.remotePresence],+ (remotePresence): NotebookRemoteParticipant[] => getNotebookRemoteParticipants(remotePresence),+ ],}),listeners(({ actions, values, props, cache }) => ({bindEditor: ({ editor }) => {actions.connectStream()+ actions.publishPresence()cache.disposables.add(() => {const onSelectionUpdate = (): void => actions.publishPresence()@@ -159,12 +184,18 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([const intervalId = window.setInterval(() => actions.publishPresence(), PRESENCE_HEARTBEAT_MS)return () => window.clearInterval(intervalId)}, 'presenceHeartbeat')++ cache.disposables.add(() => {+ const intervalId = window.setInterval(() => actions.pruneRemotePresence(), PRESENCE_PRUNE_INTERVAL_MS)+ return () => window.clearInterval(intervalId)+ }, 'presencePrune')},unbindEditor: () => {actions.disconnectStream()cache.disposables.dispose('presenceSelectionUpdate')cache.disposables.dispose('presenceHeartbeat')+ cache.disposables.dispose('presencePrune')},publishPresence: async (_, breakpoint) => {@@ -233,6 +264,13 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([continue}try {+ if (remote.presence) {+ actions.handleRemotePresence({+ clientId: remote.clientId,+ ...remote.presence,+ lastSeenAt: Date.now(),+ })+ }applyRemoteStep(editor, remote)} catch (e) {posthog.captureException(e as Error, { action: 'notebook collab apply remote step' })@@ -276,6 +314,7 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([head: payload.cursor.head,lastSeenAt: Date.now(),}+ actions.handleRemotePresence(presence)// The extension clamps positions, so a briefly skewed version is safe.editor.view.dispatch(editor.state.tr.setMeta(REMOTE_PRESENCE_META, presence))} catch (e) {@@ -311,15 +350,21 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([const localContent = editor.getJSON()const localText = editor.getText()try {+ const remotePresence = {+ userId: parsed.user_id,+ userName: parsed.user_name,+ head: parsed.cursor_head,+ }+ actions.handleRemotePresence({+ clientId: parsed.client_id,+ ...remotePresence,+ lastSeenAt: Date.now(),+ })applyRemoteStep(editor, {step: parsed.step,clientId: parsed.client_id,version,- presence: {- userId: parsed.user_id,- userName: parsed.user_name,- head: parsed.cursor_head,- },+ presence: remotePresence,})} catch (e) {posthog.captureException(e as Error, { action: 'notebook collab apply remote step' })diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 8328da9ada95..68112f5371a6 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -37,6 +37,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { base64Decode, base64Encode, downloadFile, objectsEqual, slugify, uuid } from 'lib/utils'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'+import { copyToClipboard } from 'lib/utils/copyToClipboard'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { commentsLogic } from 'scenes/comments/commentsLogic'import { urls } from 'scenes/urls'@@ -106,6 +107,12 @@ import { shouldWarnBeforeLeavingNotebook } from './notebookBeforeUnload'import { notebookCollabLogic } from './notebookCollabLogic'import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'import type { notebookLogicType } from './notebookLogicType'+import {+ getNotebookRemoteParticipants,+ type NotebookPresenceState,+ type NotebookRemoteParticipant,+ pruneNotebookRemotePresence,+} from './notebookPresence'import { notebookSettingsLogic } from './notebookSettingsLogic'export const SYNC_DELAY = 1000@@ -134,13 +141,9 @@ export type MarkdownStreamEvent = {}/** Latest known caret of another client, from presence pings or update events. */-export type NotebookRemotePresenceState = {- clientId: string- userId: number- userName: string+export type NotebookRemotePresenceState = NotebookPresenceState & {version: numbercursor: NotebookCollabCursorApi- lastSeenAt: number}/** Remote carets older than this stop rendering; senders heartbeat well within it. */@@ -320,6 +323,8 @@ export const notebookLogic = kea<notebookLogicType>([renameNotebook: (title: string) => ({ title }),setEditingNodeEditing: (nodeId: string, editing: boolean) => ({ nodeId, editing }),exportJSON: true,+ downloadMarkdown: true,+ copyMarkdown: true,showConflictWarning: true,onUpdateEditor: true,registerNodeLogic: (nodeId: string, nodeLogic: BuiltLogic<notebookNodeLogicType>) => ({ nodeId, nodeLogic }),@@ -456,10 +461,7 @@ export const notebookLogic = kea<notebookLogicType>([...state,[presence.clientId]: { ...presence, lastSeenAt: receivedAt },}),- pruneRemotePresence: (state, { now }) => {- const fresh = Object.entries(state).filter(([, p]) => now - p.lastSeenAt <= PRESENCE_TTL_MS)- return fresh.length === Object.keys(state).length ? state : Object.fromEntries(fresh)- },+ pruneRemotePresence: (state, { now }) => pruneNotebookRemotePresence(state, now, PRESENCE_TTL_MS),disconnectMarkdownUpdateStream: () => ({}),},],@@ -952,6 +954,11 @@ export const notebookLogic = kea<notebookLogicType>([return carets},],+ markdownRemoteParticipants: [+ (s) => [s.markdownRemotePresence],+ (markdownRemotePresence): NotebookRemoteParticipant[] =>+ getNotebookRemoteParticipants(markdownRemotePresence),+ ],content: [(s) => [s.notebook, s.localContent, s.previewContent],(notebook, localContent, previewContent): JSONContent => {@@ -1774,6 +1781,18 @@ export const notebookLogic = kea<notebookLogicType>([downloadFile(file)},+ downloadMarkdown: () => {+ const file = new File(+ [getMarkdownNotebookMarkdown(values.content)],+ `${slugify(values.title ?? 'untitled')}.md`,+ { type: 'text/markdown' }+ )++ downloadFile(file)+ },+ copyMarkdown: async () => {+ await copyToClipboard(getMarkdownNotebookMarkdown(values.content), 'markdown')+ },discardLocalChanges: () => {// Reload remounts the editor so it re-initialises with the server's content.diff --git a/frontend/src/scenes/notebooks/Notebook/notebookPresence.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookPresence.test.tsnew file mode 100644index 000000000000..0cf1721a1900--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookPresence.test.ts@@ -0,0 +1,118 @@+import {+ getNotebookPresenceParticipants,+ getNotebookRemoteParticipants,+ pruneNotebookRemotePresence,+} from './notebookPresence'++describe('notebookPresence', () => {+ it('shows people instead of client tabs by keeping the latest presence for each user', () => {+ const participants = getNotebookRemoteParticipants({+ oldTab: {+ clientId: 'oldTab',+ userId: 1,+ userName: 'Zoe',+ lastSeenAt: 10,+ },+ bob: {+ clientId: 'bob',+ userId: 2,+ userName: 'Bob',+ lastSeenAt: 30,+ },+ newTab: {+ clientId: 'newTab',+ userId: 1,+ userName: 'Zoe',+ lastSeenAt: 20,+ },+ })++ expect(participants).toEqual([+ {+ clientId: 'bob',+ userId: 2,+ userName: 'Bob',+ lastSeenAt: 30,+ },+ {+ clientId: 'newTab',+ userId: 1,+ userName: 'Zoe',+ lastSeenAt: 20,+ },+ ])+ })++ it('prunes stale presence and preserves state identity when nothing expires', () => {+ const state = {+ stale: {+ clientId: 'stale',+ userId: 1,+ userName: 'Stale user',+ lastSeenAt: 60,+ },+ fresh: {+ clientId: 'fresh',+ userId: 2,+ userName: 'Fresh user',+ lastSeenAt: 90,+ },+ }++ expect(pruneNotebookRemotePresence(state, 100, 40)).toBe(state)+ expect(pruneNotebookRemotePresence(state, 100, 29)).toEqual({+ fresh: {+ clientId: 'fresh',+ userId: 2,+ userName: 'Fresh user',+ lastSeenAt: 90,+ },+ })+ })++ it('prepends the current user and removes remote echoes of the same user', () => {+ expect(+ getNotebookPresenceParticipants(+ {+ id: 1,+ first_name: 'Current User',+ email: '[email protected]',+ },+ [+ {+ clientId: 'sameUserOtherTab',+ userId: 1,+ userName: 'Current User',+ lastSeenAt: 20,+ },+ {+ clientId: 'otherUser',+ userId: 2,+ userName: 'Other User',+ lastSeenAt: 30,+ },+ ],+ 40+ )+ ).toEqual([+ {+ clientId: 'current-user',+ userId: 1,+ userName: 'You',+ lastSeenAt: 40,+ isCurrentUser: true,+ profileUser: {+ id: 1,+ first_name: 'Current User',+ email: '[email protected]',+ },+ },+ {+ clientId: 'otherUser',+ userId: 2,+ userName: 'Other User',+ lastSeenAt: 30,+ },+ ])+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/notebookPresence.ts b/frontend/src/scenes/notebooks/Notebook/notebookPresence.tsnew file mode 100644index 000000000000..c6255fde09f9--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookPresence.ts@@ -0,0 +1,67 @@+import type { UserType } from '~/types'++export type NotebookPresenceState = {+ clientId: string+ userId: number+ userName: string+ lastSeenAt: number+}++export type NotebookRemoteParticipant = NotebookPresenceState++export type NotebookPresenceParticipant = NotebookPresenceState & {+ isCurrentUser?: boolean+ profileUser?: Pick<UserType, 'email' | 'first_name' | 'hedgehog_config'>+}++export function getNotebookRemoteParticipants<T extends NotebookPresenceState>(+ presenceByClientId: Record<string, T>+): NotebookRemoteParticipant[] {+ const latestPresenceByUserId = new Map<number, T>()++ for (const presence of Object.values(presenceByClientId)) {+ const currentPresence = latestPresenceByUserId.get(presence.userId)+ if (!currentPresence || presence.lastSeenAt > currentPresence.lastSeenAt) {+ latestPresenceByUserId.set(presence.userId, presence)+ }+ }++ return Array.from(latestPresenceByUserId.values())+ .sort((a, b) => a.userName.localeCompare(b.userName) || a.userId - b.userId)+ .map((presence) => ({ ...presence }))+}++export function getNotebookPresenceParticipants(+ currentUser: Pick<UserType, 'email' | 'first_name' | 'hedgehog_config' | 'id'> | null,+ remoteParticipants: NotebookRemoteParticipant[],+ now: number = Date.now()+): NotebookPresenceParticipant[] {+ if (!currentUser) {+ return remoteParticipants+ }++ return [+ {+ clientId: 'current-user',+ userId: currentUser.id,+ userName: 'You',+ lastSeenAt: now,+ isCurrentUser: true,+ profileUser: currentUser,+ },+ ...remoteParticipants.filter((participant) => participant.userId !== currentUser.id),+ ]+}++export function pruneNotebookRemotePresence<T extends NotebookPresenceState>(+ presenceByClientId: Record<string, T>,+ now: number,+ ttlMs: number+): Record<string, T> {+ const freshPresence = Object.entries(presenceByClientId).filter(+ ([, presence]) => now - presence.lastSeenAt <= ttlMs+ )+ return freshPresence.length === Object.keys(presenceByClientId).length+ ? presenceByClientId+ : (Object.fromEntries(freshPresence) as Record<string, T>)+}diff --git a/frontend/src/scenes/notebooks/NotebookMenu.tsx b/frontend/src/scenes/notebooks/NotebookMenu.tsxindex d1c541f2f0ad..0cce67f40738 100644--- a/frontend/src/scenes/notebooks/NotebookMenu.tsx+++ b/frontend/src/scenes/notebooks/NotebookMenu.tsx@@ -15,11 +15,14 @@ import { urls } from 'scenes/urls'import { notebooksModel } from '~/models/notebooksModel'+import { isMarkdownNotebookContent } from './Notebook/markdownNotebookV2'import { NotebookLogicProps, notebookLogic } from './Notebook/notebookLogic'export function NotebookMenu({ shortId }: NotebookLogicProps): JSX.Element {- const { notebook, showHistory, isLocalOnly } = useValues(notebookLogic({ shortId }))- const { openShareModal, duplicateNotebook, exportJSON, setShowHistory } = useActions(notebookLogic({ shortId }))+ const { notebook, showHistory, isLocalOnly, content } = useValues(notebookLogic({ shortId }))+ const { openShareModal, duplicateNotebook, exportJSON, downloadMarkdown, copyMarkdown, setShowHistory } =+ useActions(notebookLogic({ shortId }))+ const isMarkdownNotebook = isMarkdownNotebookContent(content)return (<DropdownMenu>@@ -37,11 +40,26 @@ export function NotebookMenu({ shortId }: NotebookLogicProps): JSX.Element {</ButtonPrimitive></DropdownMenuItem><DropdownMenuItem asChild>- <ButtonPrimitive onClick={() => exportJSON()} menuItem>- <IconDownload />- Export JSON- </ButtonPrimitive>+ {isMarkdownNotebook ? (+ <ButtonPrimitive onClick={() => downloadMarkdown()} menuItem>+ <IconDownload />+ Download+ </ButtonPrimitive>+ ) : (+ <ButtonPrimitive onClick={() => exportJSON()} menuItem>+ <IconDownload />+ Export JSON+ </ButtonPrimitive>+ )}</DropdownMenuItem>+ {isMarkdownNotebook ? (+ <DropdownMenuItem asChild>+ <ButtonPrimitive onClick={() => copyMarkdown()} menuItem>+ <IconCopy />+ Copy markdown+ </ButtonPrimitive>+ </DropdownMenuItem>+ ) : null}<DropdownMenuItem asChild><ButtonPrimitive onClick={() => setShowHistory(!showHistory)} menuItem><IconClock />diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsxindex 43fb1225a2da..832e6155f612 100644--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx@@ -17,7 +17,12 @@ import { isMarkdownNotebookContent } from '../Notebook/markdownNotebookV2'import { Notebook } from '../Notebook/Notebook'import { NotebookListMini } from '../Notebook/NotebookListMini'import { notebookLogic } from '../Notebook/notebookLogic'-import { NotebookCollabStatus, NotebookExpandButton, NotebookSyncInfo } from '../Notebook/NotebookMeta'+import {+ NotebookCollabStatus,+ NotebookExpandButton,+ NotebookPresence,+ NotebookSyncInfo,+} from '../Notebook/NotebookMeta'import { NotebookMenu } from '../NotebookMenu'import { NotebookTarget } from '../types'import { NotebookPanelDropzone } from './NotebookPanelDropzone'@@ -66,6 +71,7 @@ export function NotebookPanel(): JSX.Element | null {<div className="flex-1" /><div className="flex items-center gap-1">+ {selectedNotebook && <NotebookPresence shortId={selectedNotebook} />}<NotebookMenu shortId={selectedNotebook} />{contentWidthHasEffect && <NotebookExpandButton size="small" inPanel={true} />}<Linkdiff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsxindex ccc18bcf4057..ba930ff9bfcb 100644--- a/frontend/src/scenes/notebooks/NotebookScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx@@ -22,6 +22,7 @@ import {NotebookCollabStatus,NotebookExpandButton,NotebookKernelInfoButton,+ NotebookPresence,NotebookSyncInfo,NotebookTableOfContentsButton,} from './Notebook/NotebookMeta'@@ -129,27 +130,35 @@ export function NotebookScene(): JSX.Element {<div className="flex gap-2 items-center"><NotebookCollabStatus shortId={notebookId} /><NotebookSyncInfo shortId={notebookId} />+ <NotebookPresence shortId={notebookId} /><NotebookMenu shortId={notebookId} />- <LemonButton- type="secondary"- icon={<IconInfo />}- size="small"- onClick={() => {- if (selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id && visibility === 'visible') {- closeSidePanel()- } else {- selectNotebook(LOCAL_NOTEBOOK_TEMPLATES[0].short_id)- }- }}- >- {selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id && visibility === 'visible'- ? 'Close '- : ''}- Guide- </LemonButton>- <NotebookTableOfContentsButton type="secondary" size="small" />+ {!isMarkdownNotebook ? (+ <>+ <LemonButton+ type="secondary"+ icon={<IconInfo />}+ size="small"+ onClick={() => {+ if (+ selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id &&+ visibility === 'visible'+ ) {+ closeSidePanel()+ } else {+ selectNotebook(LOCAL_NOTEBOOK_TEMPLATES[0].short_id)+ }+ }}+ >+ {selectedNotebook === LOCAL_NOTEBOOK_TEMPLATES[0].short_id && visibility === 'visible'+ ? 'Close '+ : ''}+ Guide+ </LemonButton>+ <NotebookTableOfContentsButton type="secondary" size="small" />+ </>+ ) : null}<NotebookKernelInfoButton type="secondary" size="small" />{/* Markdown notebooks have no width toggle — they always fill the content width. */}{!isMarkdownNotebook && <NotebookExpandButton type="secondary" size="small" inPanel={false} />}