:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): add product widget views (#81368)
Marius Andra09d8eafa49ee
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5c869157550d..5782be89d511 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6041,7 +6041,7 @@ snapshots:scenes-app-experiments--experiment-with-funnel-metric--dark:hash: v1.k794b7964.f33abe58d4dc3c42ee0aa09fb9cec2a8d0b4e17a0642164ed913c6b4b87691a4.iDS3IMV59UC7uXmUOJUd8j-NXLUiLeN8j4D6YndOszgscenes-app-experiments--experiment-with-funnel-metric--light:- hash: v1.k794b7964.2879d4616c2be606f1ecd3fa9725dab0afa286eb1c2c3fa5641f2d80312acb12.Pq3YUGkLgF7JQpGYIx2ESbALZux5B7X_IfH764vLVK8+ hash: v1.k794b7964.189e0d10904e34237d13c3d281a93fc8280f80ab959bc4c52b9a302e0c312169.-ol38I5Gu8C4051FEwNLLMTCDy_xwChL9TTL9W2hRdUscenes-app-experiments--experiment-with-legacy-funnels-query--dark:hash: v1.k794b7964.6503cdfd33ae5f9d525d14dc8d43b047e8469beca7e5e489534347904efe1dec.2CtGz-wQvIwr_SQDthwlGJI5bVcJ7bFpetJricY-Lpsscenes-app-experiments--experiment-with-legacy-funnels-query--light:@@ -6391,7 +6391,7 @@ snapshots:scenes-app-inbox-scene--self-driving-onboarding-redesign--light:hash: v1.k794b7964.c2f7366b673e20e85513c454effae314d643958a3d2424e7902d572909f024fe.edek45zj8tVjVDjsqgddUJUnPKAHanQkzZwR5Ylr93Qscenes-app-inbox-scene--self-driving-paused--dark:- hash: v1.k794b7964.bd2bee28eee6668bfd9f1e5c00191e38189bc27ac734c8adf8ddc55da8381b1b.HFfADdkZDnQv2BGCHc-yzXZ4Z0Rpk-xn9cn7uRUXIyg+ hash: v1.k794b7964.92028573740590e09775ef9658859d39cdd27586aa87d58a0f0e640939e567de.MZizHJ2RxoNKJZSls9oD4rbqLflKx5MCcfUQ4yP2gXQscenes-app-inbox-scene--self-driving-paused--light:hash: v1.k794b7964.54f6835c7d4a343bd6c9efef4189805b8dc5ea3347380b5d772ce55abaad79be.P7Ramt_0TgHAl4YgBsBumQ1QVxkb2ds9GsTaxbNAKRQscenes-app-inbox-scene--self-driving-verdict-pending--dark:@@ -6790,14 +6790,26 @@ snapshots:hash: v1.k794b7964.d6c551c581824287879e157abaa61874713bb6389caaa015b1bac305a69c36cb.szC1MJRFAMY6z5Cr9uPHF3D39RLL7VUUFs3FiiemlsAscenes-app-notebooks-nodes-support-tickets--with-tickets--light:hash: v1.k794b7964.10a73c98dea8faa9011e00a7f44278e12216eb077e68ffefb4f2799f0ab519ad.yCkGWzRUKGODRvA_V0WHSn9Pdm5FhPyEfJVEcilSpP8+ scenes-app-notebooks-widget-views--action-views--dark:+ hash: v1.k794b7964.9a752af48c274e00d922b4491c01aaef874019b886d91f65e891a8d4ce18361a.a8f4IjMdEHKLV_5jRIII-5EsmnVYuCpmuohpIwZVNZw+ scenes-app-notebooks-widget-views--action-views--light:+ hash: v1.k794b7964.acacd9778acd50d8bdd19a72e832b5ad928d8b19b521d3351a40092da61761ef.B2zbSS1kO4fN0OvqNanW87Id7-F1INxhDhDFl6kbwJ8scenes-app-notebooks-widget-views--cohort-views--dark:hash: v1.k794b7964.6a87a3642aa629e7ff3c6a24c2e2ae99e3c8603632a269fe6a3f26fcce06c02f.6JLTYAgJWEQpMmzewJGy9_3heCCSQx0qHX8vUbdj4V0scenes-app-notebooks-widget-views--cohort-views--light:hash: v1.k794b7964.4d0085a9e284643ac1b101e4c32e9a36cc6b4507411086f13a3ef3a113bb6d97.f2wK3yMByUBnhBKWyAMm_dq3wxZihAXUeJbbhjiLUC8+ scenes-app-notebooks-widget-views--dashboard-views--dark:+ hash: v1.k794b7964.a7c878fe0c34aafe4fe8ee585b802bec19fc85694db7d6aea4ec0ebfaf1904d3.T9jGsQP2QkUF8Xq-SxEMZEzdEDYSBjJTaXCUH6oJ484+ scenes-app-notebooks-widget-views--dashboard-views--light:+ hash: v1.k794b7964.462a6bfd5eb375f20448a5947e4cd4e8e69c287b0863c80c83ca96e6844fc06d.EC5X5MSr0Dz5BifRSO9NlmCn-fZ6M9mFHgAk0xMCbxsscenes-app-notebooks-widget-views--early-access-feature-views--dark:hash: v1.k794b7964.080e4eb18a5bc5975a3796cb50f3a58e020fb5a0bd9dd5fa37c034861a8361f4.R8ZqTVM9LKrvh-VlgvnQWWlCKV9MsNffT8ovqJh6xOsscenes-app-notebooks-widget-views--early-access-feature-views--light:hash: v1.k794b7964.9debfd515f80070534706f211ea59e218fe0a959f27d24992f7ed3b87415a317.AMMNKNHC_BgUVotWrMdNhmBNEQ_bNsR3o8xAP_1_6mE+ scenes-app-notebooks-widget-views--error-tracking-issue-views--dark:+ hash: v1.k794b7964.6c346015a63b3076659613d2b69cb75f84666b22cebed5d5f6d86e8305b2112e.dGCtvijEXSPE6HgIe_VZAYRWeds5-fuARHT8XK-D5ys+ scenes-app-notebooks-widget-views--error-tracking-issue-views--light:+ hash: v1.k794b7964.2ff6b8884877008ffde646b74e967e2e808611366555db49f5a4e65a756e2c97.nivtpgSBY0yV62wPozXc-uzVm824nuwTdKKE06_ck3Escenes-app-notebooks-widget-views--experiment-views--dark:hash: v1.k794b7964.18e5f82b3c2cd8e799443906e92db7412a9b4859aec30c7227d01ae6b40d3bf4.IER7KczV1pRPGF7CuAEIXKAE_FwuxM6V9PvRT6Jx2icscenes-app-notebooks-widget-views--experiment-views--light:@@ -6806,10 +6818,38 @@ snapshots:hash: v1.k794b7964.03e11ebc2b3d64e75aeee7c7e6e7fefb447fe4dee7ae87382777349d715c3229.G3gCScDjPH3A2OP4vByYk2Vzbl8nOJYiM-7Ud3xUdyAscenes-app-notebooks-widget-views--feature-flag-views--light:hash: v1.k794b7964.3fb450c33fc8b53cff6d2297e2f1dfa8541b3b78710fcc1f9a024c1d38bd9430._Cbxuhq_opGeFh8v_hBOeWQRNNOu728aMhEzYQm3Yuk+ scenes-app-notebooks-widget-views--group-views--dark:+ hash: v1.k794b7964.dcceb542721da480037e72715ba0bba0d2bca53a393992f29409e3b0ec648087.oC_G7MirEPp1zwj9ZPPPaLhKeZuAXn5EJo9XDI4CD6o+ scenes-app-notebooks-widget-views--group-views--light:+ hash: v1.k794b7964.a622eda529140b0da26febf0295d5afe02224a095b690d699c90d37d189fd615.2nmLTPSj2A2MQ3TYzkrkcCOHhvvB3-4GiRvFJN_9tXI+ scenes-app-notebooks-widget-views--insight-views--dark:+ hash: v1.k794b7964.2f40e816554706d5dae9c0ff7db3b60f92d8c71d2265fa8bebeb302dd6540aaf.gpycsrw2HtMpduduhLjSrjC4JRb2P4ZoyO13tZRRj6I+ scenes-app-notebooks-widget-views--insight-views--light:+ hash: v1.k794b7964.597a6894eaa2e15be37d9c5131aa8a648a35b3b4415e6f8bf60d25d0326be57f.64f4C1oslCdLwXhLDCTVkocQjya4p0DH16mBBflRYHs+ scenes-app-notebooks-widget-views--llm-trace-views--dark:+ hash: v1.k794b7964.4e1ab634bae8a93e4e3c6fed3c379cd10791a8cdfaa37c551ffc10cbb5c2d738.zBi7T4pmBEu1EV1ID04nuFxNs7iSFBMDc-tCKVEmy70+ scenes-app-notebooks-widget-views--llm-trace-views--light:+ hash: v1.k794b7964.5ea0b08a632473328c05d164a1e756ba869f65fd4513a518d17e8d87f337db00.tKEfQQ8Zx_MevnV47TTxcctA5K5F6FdDOj6s9mloQOg+ scenes-app-notebooks-widget-views--person-views--dark:+ hash: v1.k794b7964.047e00389cf1891ef58caefeb8cd76489d87a93f382e227e96fb422af44d974c.dsIVmb8vhajsyOEOPdG37OjOzSP3aiO-6KJOZbkKKAc+ scenes-app-notebooks-widget-views--person-views--light:+ hash: v1.k794b7964.1dd5b786b96c3462886d42162b9703203977ede8d290bc7657632e3b4df8949b.oyLUpi8rxuFCKijnY6y58HN4M6aSuagvT18L8gTz2jY+ scenes-app-notebooks-widget-views--recording-playlist-views--dark:+ hash: v1.k794b7964.348e1cd39145cc74118e51b175e384003180756ed2e37f059d7377f4e59bc337.6_JpQpRvZD6qtG1waq0WNkr8zlUs-XVfX8rLLpds5Q0+ scenes-app-notebooks-widget-views--recording-playlist-views--light:+ hash: v1.k794b7964.e2a097fe1143c3f16117d9717fc3f2f13543d60af95bb4f2a318fa0e12756142.Qebra4kydzAMXZw6GyhD5anVCR7LhcBZW3DlGTUk2e4+ scenes-app-notebooks-widget-views--recording-views--dark:+ hash: v1.k794b7964.259dce75db7aac1d88ba03583682f29e6faf28144c437076b4481d37195d4137.l9JKm5ym6NOYKXCBZ38ZEiOan76omrE6tlZXtULabcY+ scenes-app-notebooks-widget-views--recording-views--light:+ hash: v1.k794b7964.175010d85ea006e6ca9ff0d3cecf1578f0d1ae3c149b0c4ff991096ec1e5f4de.kiLpAL__Nmiz3-reV8DIwGF_sRY3G1T6mXI9BNV9Nposcenes-app-notebooks-widget-views--survey-views--dark:hash: v1.k794b7964.88a8b74ffaa548541a5a1549ce34654b5306a0003ed2188032a28cf567df6568.lsAbu-IkwJcOI5B_5e22IMVBe2Ov1iRh8tNFQokgeh4scenes-app-notebooks-widget-views--survey-views--light:hash: v1.k794b7964.3dad7f9ff2bafb766aae416a754bb9830773e886993739e75339d6dc75d668d0.PlGQ57dwA4jzdVj-lXAcqVCY0YxNXkT0w0ZZrvYmI0Y+ scenes-app-notebooks-widget-views--workflow-views--dark:+ hash: v1.k794b7964.9f9da8402d368380cb5e5c369dfbfe271d10dca4b7da10ecb4c985f581d32580.X0UX9PxrvIZcRPxQ9Bi0c9qJVRqQ3GCGMHR8ubsB9KE+ scenes-app-notebooks-widget-views--workflow-views--light:+ hash: v1.k794b7964.8539569f6f314d8c6f7847f9791392edcb1d48345e37b231672f4b36bc579b3c.VlcXGpaH6yQ9ltXVpnnHUmQEHAY0k5k-UQLJ9fZ3cUkscenes-app-oauth-authorize--all-scopes-optional--dark:hash: v1.k794b7964.03746d2e3646b97e4af61e54557db2ccb6268512cda02721b819fa30980af155.ZPcclnqMQQh8Qi_v2Z3cnVA1_LaYFx8XXncRQ8NQAdcscenes-app-oauth-authorize--all-scopes-optional--light:@@ -7395,9 +7435,9 @@ snapshots:scenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.96846d7823357e89a9d91350f6f435373fe287f713250b59ccce2dbd31b6f69c.kl21kygOhH1SlNOJ6VekMMlGUuyNg5Ka7NXFoHcG6M0scenes-app-settings-user--settings-user-navigation--dark:- hash: v1.k794b7964.341940b9fa0d928eede78d3bfb88639fc3fab5aacf27f214fb16c7db2c242bbe.3N930aBs8a33duFvtnHC7-3ha1YW0D0Dy3_XSjl8rFM+ hash: v1.k794b7964.f1c0834efdf1ebf264e46ba2ef25c79266051f51ee4ddc70c939b1bfbedab033.1D-CrzTr7y6mQww6EZRG8VmOtNYW7cMvJ2t3RFc2E10scenes-app-settings-user--settings-user-navigation--light:- hash: v1.k794b7964.1720a78a3826f4c22f8768ef9f089b1f72b851db6993c9260245fd81db4c1c58.wjIskRgUABczrhV39b1Wxc8fqHRarlnkDmus1xn3Mnk+ hash: v1.k794b7964.81ca37a8d9427140b54c07c9c68d8b77001e956e6cf6f4fa66a4420d2adc0d02.VOWpKzNBO_d-f7SkK0G7tFxwGKj4TaRH-9n3BztTszIscenes-app-settings-user--settings-user-notifications--dark:hash: v1.k794b7964.a09a57f1c0bbcebf82942edebeba7772b2f684ba235bcef3a816aec2beb4cbce.AtQZhdZeeMVvpcmyBhPvprSMZawliTZaIFE5G8M_MVgscenes-app-settings-user--settings-user-notifications--light:diff --git a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.mdindex 5c16e52641ac..43177f10137e 100644--- a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md+++ b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md@@ -253,16 +253,16 @@ Use a specialized view when it directly answers the task.- [x] Experiments: `summary`, `detail`, `results`- [x] Early access features: `summary`, `detail`- [x] Cohorts: `summary`, `detail`-- [ ] Insights: `summary`, `detail`, `editor`, `results`-- [ ] Session recordings: `summary`, `detail`-- [ ] Recording playlists: `summary`, `detail`, `conditions`-- [ ] People: `summary`, `detail`, `activity`-- [ ] Groups: `summary`, `detail`, `activity`-- [ ] Error tracking issues: `summary`, `detail`, `activity`-- [ ] LLM traces: `summary`, `detail`, `activity`-- [ ] Dashboards: `summary`, `detail`-- [ ] Actions: `summary`, `detail`, `editor`-- [ ] Workflows: `summary`, `detail`, `editor`, `results`+- [x] Insights: `summary`, `detail`, `editor`, `results`+- [x] Session recordings: `summary`, `detail`+- [x] Recording playlists: `summary`, `detail`, `conditions`+- [x] People: `summary`, `detail`, `activity`+- [x] Groups: `summary`, `detail`, `activity`+- [x] Error tracking issues: `summary`, `detail`, `activity`+- [x] LLM traces: `summary`, `detail`, `activity`+- [x] Dashboards: `summary`, `detail`+- [x] Actions: `summary`, `detail`, `editor`+- [x] Workflows: `summary`, `detail`, `editor`, `results`Named views run trusted, compiled PostHog UI.Do not execute agent-generated React through this registry.diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.tsindex 2ac7b9ea0873..7ae60a9ff1e0 100644--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.test.ts@@ -50,16 +50,20 @@ describe('buildInsertCommands', () => {expect(insightLabels).toEqual(['Trend', 'Funnel', 'Retention', 'Paths', 'Stickiness', 'Lifecycle'])})- it('renders Products as the last category, merging caller-supplied product commands', () => {+ it('renders Products last, sorting caller-supplied product commands in by label', () => {// Grouping is first-occurrence order, so a command inserted in the wrong array// silently pulls the Products group up the menu.- const { commands } = build([{ key: 'product-flag', label: 'Feature flag', category: 'Products', run: noop }])+ const { commands } = build([+ { key: 'product-survey', label: 'Survey', category: 'Products', run: noop },+ { key: 'product-flag', label: 'Feature flag', category: 'Products', run: noop },+ ])const categories = Object.keys(groupInsertCommandsByCategory(commands))expect(categories[categories.length - 1]).toEqual('Products')expect(groupInsertCommandsByCategory(commands)['Products'].map((command) => command.label)).toEqual([- 'Session recordings','Feature flag',+ 'Session recordings',+ 'Survey',])})})diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsxindex 0f5f1f1aa84d..3035323f94cf 100644--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx@@ -55,6 +55,10 @@ export const QUERY_SQL_INSERT_COMMAND_KEY = 'query-sql'* without hard-coding the label, which would split into a second group if this were renamed. */export const COMMON_INSERT_COMMAND_CATEGORY = 'Common'+/** The menu's last group, sorted by label rather than by insertion order. Exported so a caller+ * merging product commands in can name it without hard-coding the label. */+export const PRODUCTS_INSERT_COMMAND_CATEGORY = 'Products'+export function omitInsertCommands(commands: InsertCommand[], hiddenKeys: string[] | undefined): InsertCommand[] {if (!hiddenKeys?.length) {return commands@@ -458,13 +462,13 @@ export function buildInsertCommands(},]- // Appended after every other built-in category so "Products" renders as the last group- // (grouping preserves first-occurrence order); scene-supplied product commands merge in.+ // Sorted and moved after every other category on the way out, so "Products" renders as the+ // last group (grouping preserves first-occurrence order); scene-supplied commands merge in.const productCommands: InsertCommand[] = [{key: 'data-session-recordings',label: 'Session recordings',- category: 'Products',+ category: PRODUCTS_INSERT_COMMAND_CATEGORY,aliases: ['replay', 'playlist'],icon: <IconRewindPlay />,run: (targetNodeId) => insertRegisteredComponent(targetNodeId, 'RecordingPlaylist'),@@ -610,7 +614,7 @@ export function buildInsertCommands(},]- return [+ return sortProductInsertCommandsLast([...aiCommands,...textCommands,...sqlCommands,@@ -621,7 +625,16 @@ export function buildInsertCommands(...textStyleCommands,...productCommands,...extraCommands,- ]+ ])+}++/** Every other category is hand-ordered, but products arrive in widget-catalog key order, which+ * reads as arbitrary. Sorting here rather than at render time keeps the order the arrow keys walk+ * in step with the order the menu paints. */+function sortProductInsertCommandsLast(commands: InsertCommand[]): InsertCommand[] {+ const products = commands.filter((command) => command.category === PRODUCTS_INSERT_COMMAND_CATEGORY)+ const rest = commands.filter((command) => command.category !== PRODUCTS_INSERT_COMMAND_CATEGORY)+ return [...rest, ...products.sort((a, b) => a.label.localeCompare(b.label))]}export function getInsertMenuPosition(anchorElement: HTMLElement): InsertMenuPosition {diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.tsindex 048ab0e5208c..740d0d4ab018 100644--- a/frontend/src/lib/components/MarkdownNotebook/index.ts+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts@@ -3,6 +3,7 @@ export type { MarkdownNotebookAskAIRequest, MarkdownNotebookProps } from './Markexport type { InsertCommand, MarkdownNotebookInsertMenuApi } from './editorTypes'export {COMMON_INSERT_COMMAND_CATEGORY,+ PRODUCTS_INSERT_COMMAND_CATEGORY,QUERY_SQL_INSERT_COMMAND_KEY,buildInsertCommands,omitInsertCommands,diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeAction.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeAction.tsxnew file mode 100644index 000000000000..86e9a1290cad--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeAction.tsx@@ -0,0 +1,29 @@+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'+import { urls } from 'scenes/urls'++import {+ ACTION_NOTEBOOK_WIDGET_VIEWS,+ ActionDetail,+ ActionNotebookWidgetAttributes,+} from 'products/actions/frontend/actionNotebookWidgetViews'++import { NotebookNodeType } from '../types'++export const NotebookNodeAction = createPostHogWidgetNode<ActionNotebookWidgetAttributes>({+ nodeType: NotebookNodeType.Action,+ titlePlaceholder: 'Action',+ editableTitle: false,+ Component: ActionDetail,+ heightEstimate: 320,+ minHeight: 160,+ href: (attributes) => urls.action(attributes.id),+ resizeable: true,+ attributes: {+ id: {},+ view: {},+ },+ defaultView: getNotebookWidgetDefaultView('Action'),+ views: ACTION_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Action',+})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeDashboard.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeDashboard.tsxnew file mode 100644index 000000000000..b5a0d61442f1--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeDashboard.tsx@@ -0,0 +1,30 @@+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'+import { urls } from 'scenes/urls'++import {+ DASHBOARD_NOTEBOOK_WIDGET_VIEWS,+ DashboardDetail,+ DashboardNotebookWidgetAttributes,+} from 'products/dashboards/frontend/dashboardNotebookWidgetViews'++import { NotebookNodeType } from '../types'++export const NotebookNodeDashboard = createPostHogWidgetNode<DashboardNotebookWidgetAttributes>({+ nodeType: NotebookNodeType.Dashboard,+ titlePlaceholder: 'Dashboard',+ editableTitle: false,+ Component: DashboardDetail,+ heightEstimate: 640,+ minHeight: 240,+ href: (attributes) => urls.dashboard(attributes.id),+ resizeable: true,+ expandable: false,+ attributes: {+ id: {},+ view: {},+ },+ defaultView: getNotebookWidgetDefaultView('Dashboard'),+ views: DASHBOARD_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Dashboard',+})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeErrorTrackingIssue.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeErrorTrackingIssue.tsxnew file mode 100644index 000000000000..5c4d81c2ebe2--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeErrorTrackingIssue.tsx@@ -0,0 +1,29 @@+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'+import { urls } from 'scenes/urls'++import {+ ERROR_TRACKING_ISSUE_NOTEBOOK_WIDGET_VIEWS,+ ErrorTrackingIssueDetail,+ ErrorTrackingIssueNotebookWidgetAttributes,+} from 'products/error_tracking/frontend/errorTrackingIssueNotebookWidgetViews'++import { NotebookNodeType } from '../types'++export const NotebookNodeErrorTrackingIssue = createPostHogWidgetNode<ErrorTrackingIssueNotebookWidgetAttributes>({+ nodeType: NotebookNodeType.ErrorTrackingIssue,+ titlePlaceholder: 'Error tracking issue',+ editableTitle: false,+ Component: ErrorTrackingIssueDetail,+ heightEstimate: 420,+ minHeight: 240,+ href: (attributes) => urls.errorTrackingIssue(attributes.id),+ resizeable: true,+ attributes: {+ id: {},+ view: {},+ },+ defaultView: getNotebookWidgetDefaultView('ErrorTrackingIssue'),+ views: ERROR_TRACKING_ISSUE_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Error tracking issue',+})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsxindex 8d91fb02c0c9..44c1c4255d9f 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx@@ -14,11 +14,13 @@ import { formatCurrency } from 'lib/utils/currency'import stringWithWBR from 'lib/utils/stringWithWBR'import { groupLogic } from 'scenes/groups/groupLogic'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'+import { Query } from '~/queries/Query/Query'import { CurrencyCode, NodeKind } from '~/queries/schema/schema-general'import { Group, PropertyFilterType, PropertyOperator } from '~/types'@@ -27,7 +29,14 @@ import { DataSourceIcon } from './components/DataSourceIcon'import { notebookNodeLogic } from './notebookNodeLogic'import { calculateMRRData, getPaidProducts } from './utils'-const Component = ({ attributes }: NotebookNodeProps<NotebookNodeGroupAttributes>): JSX.Element => {+const Component = (props: NotebookNodeProps<NotebookNodeGroupAttributes>): JSX.Element => {+ return <GroupCard {...props} compact={false} />+}++function GroupCard({+ attributes,+ compact,+}: NotebookNodeProps<NotebookNodeGroupAttributes> & { compact: boolean }): JSX.Element {const { id, groupTypeIndex, tabId, title } = attributesconst mountedGroupLogic = groupLogic({groupKey: id,@@ -107,13 +116,15 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeGroupAttributes</CopyToClipboardInline></div>- <GroupInfo- groupData={groupData}- mrr={effectiveMRR}- lifetimeValue={effectiveLifetimeValue}- isMRRLoading={groupRevenueAnalyticsDataLoading}- isLifetimeValueLoading={groupRevenueAnalyticsDataLoading}- />+ {!compact ? (+ <GroupInfo+ groupData={groupData}+ mrr={effectiveMRR}+ lifetimeValue={effectiveLifetimeValue}+ isMRRLoading={groupRevenueAnalyticsDataLoading}+ isLifetimeValueLoading={groupRevenueAnalyticsDataLoading}+ />+ ) : null}</>) : null}</div>@@ -266,10 +277,63 @@ export function PaidProducts({ groupData }: { groupData: Group }): JSX.Element |type NotebookNodeGroupAttributes = {id: stringgroupTypeIndex: number+ view?: stringtabId?: stringplacement?: string}+function GroupSummary(props: NotebookNodeProps<NotebookNodeGroupAttributes>): JSX.Element {+ return <GroupCard {...props} compact />+}++function GroupActivity({ attributes }: NotebookNodeProps<NotebookNodeGroupAttributes>): JSX.Element {+ const { notebookLogic } = useValues(notebookNodeLogic)+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)+ const { groupData } = useValues(+ groupLogic({+ groupKey: attributes.id,+ groupTypeIndex: attributes.groupTypeIndex,+ tabId: attributes.tabId,+ })+ )++ useEffect(() => {+ setTitlePlaceholder(groupData ? groupDisplayId(groupData.group_key, groupData.group_properties) : 'Group')+ }, [groupData, setTitlePlaceholder])++ return (+ <Query+ uniqueKey={`${attributes.nodeId}-activity`}+ attachTo={notebookLogic}+ query={{+ kind: NodeKind.DataTableNode,+ embedded: true,+ full: false,+ source: {+ kind: NodeKind.EventsQuery,+ select: defaultDataTableColumns(NodeKind.EventsQuery),+ after: '-30d',+ limit: 50,+ fixedProperties: [+ {+ key: `$group_${attributes.groupTypeIndex}`,+ value: attributes.id,+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ },+ ],+ },+ }}+ readOnly+ />+ )+}++const GROUP_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodeGroupAttributes, 'Group'>('Group', {+ summary: GroupSummary,+ activity: GroupActivity,+})+export const NotebookNodeGroup = createPostHogWidgetNode<NotebookNodeGroupAttributes>({nodeType: NotebookNodeType.Group,titlePlaceholder: 'Group',@@ -283,12 +347,11 @@ export const NotebookNodeGroup = createPostHogWidgetNode<NotebookNodeGroupAttribattributes: {id: {},groupTypeIndex: {},+ view: {},tabId: {},placement: {},},- serializedText: (attrs) => {- const title = attrs?.title || ''- const id = attrs?.id || ''- return `${title} ${id}`.trim()- },+ defaultView: getNotebookWidgetDefaultView('Group'),+ views: GROUP_NOTEBOOK_WIDGET_VIEWS,+ serializedText: (attrs) => attrs.title || 'Group',})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsxindex b0212a2e54fd..bb0514cfda38 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx@@ -1,8 +1,12 @@import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'+import { urls } from 'scenes/urls'import { groupsModel } from '~/models/groupsModel'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'@@ -18,8 +22,14 @@ import { TracesQuery } from '~/queries/schema/schema-general'import { isTracesQuery } from '~/queries/utils'import { aiObservabilitySharedLogic } from 'products/ai_observability/frontend/aiObservabilitySharedLogic'+import {+ aiObservabilityTraceDataLogic,+ type aiObservabilityTraceDataLogicValues,+} from 'products/ai_observability/frontend/aiObservabilityTraceDataLogic'import { useTracesQueryContext } from 'products/ai_observability/frontend/AIObservabilityTracesScene'+import { AIObservabilityTraceEvents } from 'products/ai_observability/frontend/components/AIObservabilityTraceEvents'import { aiObservabilityTracesTabLogic } from 'products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic'+import { formatLLMCost, formatLLMLatency, formatLLMUsage } from 'products/ai_observability/frontend/utils'import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/customer_analytics/frontend/constants'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'@@ -28,7 +38,11 @@ import { createPostHogWidgetNode } from './NodeWrapper'import { notebookNodeLogic } from './notebookNodeLogic'import { getLogicKey } from './utils'-const Component = ({ attributes }: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element | null => {+const Component = (props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element | null => {+ return props.attributes.id ? <SingleTraceDetail {...props} /> : <ContextualTraceList {...props} />+}++const ContextualTraceList = ({ attributes }: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element | null => {const { expanded, notebookLogic } = useValues(notebookNodeLogic)const { setMenuItems } = useActions(notebookNodeLogic)const { groupKey, groupTypeIndex, personId, tabId } = attributes@@ -89,7 +103,9 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeLLMTraceAttribu)}-const Settings = ({ attributes }: NotebookNodeAttributeProperties<NotebookNodeLLMTraceAttributes>): JSX.Element => {+const ContextualSettings = ({+ attributes,+}: NotebookNodeAttributeProperties<NotebookNodeLLMTraceAttributes>): JSX.Element => {const { personId, groupKey, groupTypeIndex, nodeId } = attributesconst group = groupKey && groupTypeIndex !== undefined ? { groupKey, groupTypeIndex } : undefinedconst sharedLogic = aiObservabilitySharedLogic({ logicKey: nodeId, personId, group })@@ -157,25 +173,130 @@ const Settings = ({ attributes }: NotebookNodeAttributeProperties<NotebookNodeLL)}+const Settings = (props: NotebookNodeAttributeProperties<NotebookNodeLLMTraceAttributes>): JSX.Element => {+ return props.attributes.id ? <></> : <ContextualSettings {...props} />+}+type NotebookNodeLLMTraceAttributes = {+ id?: string+ view?: stringpersonId?: stringgroupKey?: stringgroupTypeIndex?: numbertabId: string}+function useSingleTrace(attributes: NotebookNodeLLMTraceAttributes): aiObservabilityTraceDataLogicValues {+ return useValues(aiObservabilityTraceDataLogic({ traceId: attributes.id || '', searchQuery: '' }))+}++function SingleTraceMetadata({ attributes }: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): null {+ const { trace } = useSingleTrace(attributes)+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(trace?.traceName || trace?.id || 'LLM trace')+ setTitleStatus(trace?.errorCount ? { label: `${trace.errorCount} errors`, type: 'danger' } : null)+ }, [setTitlePlaceholder, setTitleStatus, trace])++ return null+}++function SingleTraceSummary(props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element {+ const { responseLoading, trace } = useSingleTrace(props.attributes)++ if (responseLoading && !trace) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ return (+ <>+ <SingleTraceMetadata {...props} />+ <div className="flex flex-wrap gap-x-4 gap-y-1 p-3 text-sm">+ <span>{trace ? formatLLMUsage(trace) || 'No token usage' : 'Trace not found'}</span>+ {trace?.totalLatency != null ? <span>{formatLLMLatency(trace.totalLatency)}</span> : null}+ {trace?.totalCost != null ? <span>{formatLLMCost(trace.totalCost)}</span> : null}+ </div>+ </>+ )+}++function SingleTraceDetail(props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element {+ const { responseLoading, trace } = useSingleTrace(props.attributes)+ const expandedEventIds = new Set(trace?.events.map((event) => event.id))++ return (+ <>+ <SingleTraceMetadata {...props} />+ <div className="flex flex-col gap-2 p-3">+ <AIObservabilityTraceEvents+ trace={trace}+ isLoading={responseLoading}+ expandedEventIds={expandedEventIds}+ onToggleEventExpand={() => {}}+ />+ </div>+ </>+ )+}++function SingleTraceActivity(props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element {+ const { responseLoading, trace } = useSingleTrace(props.attributes)++ return (+ <>+ <SingleTraceMetadata {...props} />+ <div className="flex flex-col gap-2 p-3">+ <AIObservabilityTraceEvents+ trace={trace}+ isLoading={responseLoading}+ expandedEventIds={new Set()}+ onToggleEventExpand={() => {}}+ />+ </div>+ </>+ )+}++function LLMTraceSummary(props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element | null {+ return props.attributes.id ? <SingleTraceSummary {...props} /> : <ContextualTraceList {...props} />+}++function LLMTraceActivity(props: NotebookNodeProps<NotebookNodeLLMTraceAttributes>): JSX.Element | null {+ return props.attributes.id ? <SingleTraceActivity {...props} /> : <ContextualTraceList {...props} />+}++const LLM_TRACE_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodeLLMTraceAttributes, 'LLMTrace'>(+ 'LLMTrace',+ {+ summary: LLMTraceSummary,+ activity: LLMTraceActivity,+ }+)+export const NotebookNodeLLMTrace = createPostHogWidgetNode<NotebookNodeLLMTraceAttributes>({nodeType: NotebookNodeType.LLMTrace,titlePlaceholder: 'Traces',+ editableTitle: false,Component,Settings,resizeable: false,expandable: true,startExpanded: true,attributes: {+ id: {},+ view: {},personId: {},groupKey: {},groupTypeIndex: {},tabId: {},},+ href: (attributes) => (attributes.id ? urls.aiObservabilityTrace(attributes.id) : undefined),+ defaultView: getNotebookWidgetDefaultView('LLMTrace'),+ views: LLM_TRACE_NOTEBOOK_WIDGET_VIEWS,+ serializedText: (attributes) => (attributes.id ? 'LLM trace' : 'LLM traces'),})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsxindex 92bdc804e69c..6d80ae9ea25b 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx@@ -13,12 +13,15 @@ import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { formatCurrency } from 'lib/utils/currency'import { compactNumber } from 'lib/utils/numbers'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { asDisplay } from 'scenes/persons/person-utils'import { PersonIcon } from 'scenes/persons/PersonDisplay'import { personLogic } from 'scenes/persons/personLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'+import { Query } from '~/queries/Query/Query'import { NodeKind } from '~/queries/schema/schema-general'import { PersonType } from '~/types'@@ -26,7 +29,14 @@ import { NotebookNodeProps, NotebookNodeType } from '../types'import { DataSourceIcon } from './components/DataSourceIcon'import { notebookNodeLogic } from './notebookNodeLogic'-const Component = ({ attributes }: NotebookNodeProps<NotebookNodePersonAttributes>): JSX.Element => {+const Component = (props: NotebookNodeProps<NotebookNodePersonAttributes>): JSX.Element => {+ return <PersonCard {...props} compact={false} />+}++function PersonCard({+ attributes,+ compact,+}: NotebookNodeProps<NotebookNodePersonAttributes> & { compact: boolean }): JSX.Element {const { id, distinctId } = attributesconst personLogicProps = { id, distinctId }@@ -127,7 +137,7 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodePersonAttribute<div>{propertyIcons}</div></div></div>- <PersonInfo />+ {!compact ? <PersonInfo /> : null}</>)}</div>@@ -271,8 +281,62 @@ function LifetimeValue(): JSX.Element | null {type NotebookNodePersonAttributes = {id: string | undefineddistinctId: string | undefined+ view?: string+}++function PersonSummary(props: NotebookNodeProps<NotebookNodePersonAttributes>): JSX.Element {+ return <PersonCard {...props} compact />+}++function PersonActivity({ attributes }: NotebookNodeProps<NotebookNodePersonAttributes>): JSX.Element {+ const personLogicProps = { id: attributes.id, distinctId: attributes.distinctId }+ const { person, personLoading } = useValues(personLogic(personLogicProps))+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)+ const { notebookLogic } = useValues(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(person ? asDisplay(person) : 'Person')+ }, [person, setTitlePlaceholder])++ if (!person && !personLoading) {+ return <NotFound object="person" />+ }+ if (!person) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ return (+ <BindLogic logic={personLogic} props={personLogicProps}>+ <Query+ uniqueKey={`${attributes.nodeId}-activity`}+ attachTo={notebookLogic}+ query={{+ kind: NodeKind.DataTableNode,+ embedded: true,+ full: false,+ source: {+ kind: NodeKind.EventsQuery,+ personId: person.uuid,+ select: defaultDataTableColumns(NodeKind.EventsQuery),+ after: '-30d',+ limit: 50,+ },+ }}+ readOnly+ />+ </BindLogic>+ )}+const PERSON_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodePersonAttributes, 'Person'>('Person', {+ summary: PersonSummary,+ activity: PersonActivity,+})+export const NotebookNodePerson = createPostHogWidgetNode<NotebookNodePersonAttributes>({nodeType: NotebookNodeType.Person,titlePlaceholder: 'Person',@@ -291,10 +355,9 @@ export const NotebookNodePerson = createPostHogWidgetNode<NotebookNodePersonAttrattributes: {id: {},distinctId: {},+ view: {},},- serializedText: (attrs) => {- const personTitle = attrs?.title || ''- const personId = attrs?.id || ''- return `${personTitle} ${personId}`.trim()- },+ defaultView: getNotebookWidgetDefaultView('Person'),+ views: PERSON_NOTEBOOK_WIDGET_VIEWS,+ serializedText: (attrs) => attrs.title || 'Person',})diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsxindex 20ca397f2136..3c4e63d27dd3 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePlaylist.tsx@@ -1,20 +1,26 @@import { BuiltLogic, useActions, useValues } from 'kea'import { useEffect, useMemo } from 'react'+import { LemonTag } from '@posthog/lemon-ui'import { PostHogErrorBoundary } from '@posthog/react'+import { NotFound } from 'lib/components/NotFound'import { JSONContent } from 'lib/components/RichContentEditor/types'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { RecordingsUniversalFiltersEmbed } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import type { sessionRecordingPlayerLogicType } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'import {+ asUniversalFilters,DEFAULT_RECORDING_FILTERS,SessionRecordingPlaylistLogicProps,sessionRecordingsPlaylistLogic,} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { sessionRecordingsPlaylistSceneLogic } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic'import { urls } from 'scenes/urls'import { FilterType, RecordingUniversalFilters } from '~/types'@@ -26,6 +32,17 @@ import { notebookNodeLogic } from './notebookNodeLogic'const Component = ({attributes,updateAttributes,+}: NotebookNodeProps<NotebookNodePlaylistAttributes>): JSX.Element => {+ if (attributes.id) {+ return <SavedPlaylistDetail attributes={attributes} updateAttributes={updateAttributes} />+ }++ return <PlaylistContent attributes={attributes} updateAttributes={updateAttributes} />+}++const PlaylistContent = ({+ attributes,+ updateAttributes,}: NotebookNodeProps<NotebookNodePlaylistAttributes>): JSX.Element => {const { pinned, nodeId, universalFilters } = attributesconst playerKey = `notebook-${nodeId}`@@ -106,6 +123,45 @@ const Component = ({return <SessionRecordingsPlaylist {...recordingPlaylistLogicProps} />}+function SavedPlaylistDetail(props: NotebookNodeProps<NotebookNodePlaylistAttributes>): JSX.Element {+ const { id } = props.attributes+ const logic = sessionRecordingsPlaylistSceneLogic({ shortId: id || 'new' })+ const { filters, pinnedRecordings, playlist, playlistLoading } = useValues(logic)+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(playlist?.name || playlist?.derived_name || 'Recording playlist')+ setTitleStatus(+ playlist?.type+ ? { label: playlist.type === 'collection' ? 'Collection' : 'Saved filter', type: 'default' }+ : null+ )+ }, [playlist, setTitlePlaceholder, setTitleStatus])++ if (!playlist && !playlistLoading) {+ return <NotFound object="recording playlist" />+ }+ if (!playlist || !filters) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ return (+ <PlaylistContent+ {...props}+ attributes={{+ ...props.attributes,+ id: undefined,+ universalFilters: asUniversalFilters(filters) || DEFAULT_RECORDING_FILTERS,+ pinned: pinnedRecordings?.map((recording) => String(recording.id)),+ }}+ />+ )+}+export const Settings = ({attributes,updateAttributes,@@ -124,22 +180,131 @@ export const Settings = ({}export type NotebookNodePlaylistAttributes = {+ id?: string+ view?: stringuniversalFilters: RecordingUniversalFilterspinned?: string[]}+function PlaylistSummary({ attributes }: NotebookNodeProps<NotebookNodePlaylistAttributes>): JSX.Element {+ if (!attributes.id) {+ return (+ <div className="flex items-center gap-2 p-3">+ <span className="flex-1">Ad hoc recording playlist</span>+ <LemonTag type="muted">Unsaved</LemonTag>+ </div>+ )+ }++ return <SavedPlaylistSummary id={attributes.id} />+}++function SavedPlaylistSummary({ id }: { id: string }): JSX.Element {+ const logic = sessionRecordingsPlaylistSceneLogic({ shortId: id })+ const { derivedName, playlist, playlistLoading } = useValues(logic)+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(playlist?.name || playlist?.derived_name || 'Recording playlist')+ setTitleStatus(+ playlist?.type+ ? { label: playlist.type === 'collection' ? 'Collection' : 'Saved filter', type: 'default' }+ : null+ )+ }, [playlist, setTitlePlaceholder, setTitleStatus])++ if (!playlist && !playlistLoading) {+ return <NotFound object="recording playlist" />+ }+ if (!playlist) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ const recordingCount =+ playlist.type === 'collection'+ ? playlist.recordings_counts?.collection?.count || 0+ : playlist.recordings_counts?.saved_filters?.count || 0++ return (+ <div className="flex flex-wrap items-center gap-2 p-3">+ <span className="min-w-48 flex-1 truncate">{playlist.description || derivedName}</span>+ <span className="text-xs text-secondary">+ {recordingCount} {recordingCount === 1 ? 'recording' : 'recordings'}+ </span>+ </div>+ )+}++function PlaylistConditions({ attributes }: NotebookNodeProps<NotebookNodePlaylistAttributes>): JSX.Element {+ if (!attributes.id) {+ return <Settings attributes={attributes} updateAttributes={() => {}} />+ }++ return <SavedPlaylistConditions id={attributes.id} />+}++function SavedPlaylistConditions({ id }: { id: string }): JSX.Element {+ const { playlist, playlistLoading } = useValues(sessionRecordingsPlaylistSceneLogic({ shortId: id }))+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(playlist?.name || playlist?.derived_name || 'Recording playlist')+ setTitleStatus(+ playlist?.type+ ? { label: playlist.type === 'collection' ? 'Collection' : 'Saved filter', type: 'default' }+ : null+ )+ }, [playlist, setTitlePlaceholder, setTitleStatus])++ if (!playlist && !playlistLoading) {+ return <NotFound object="recording playlist" />+ }++ if (!playlist || playlistLoading) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ return (+ <Settings+ attributes={{+ nodeId: `playlist-${id}-conditions`,+ universalFilters: asUniversalFilters(playlist.filters) || DEFAULT_RECORDING_FILTERS,+ }}+ updateAttributes={() => {}}+ />+ )+}++const PLAYLIST_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodePlaylistAttributes, 'RecordingPlaylist'>(+ 'RecordingPlaylist',+ {+ summary: PlaylistSummary,+ conditions: PlaylistConditions,+ }+)+export const NotebookNodePlaylist = createPostHogWidgetNode<NotebookNodePlaylistAttributes>({nodeType: NotebookNodeType.RecordingPlaylist,titlePlaceholder: 'Session replays',+ editableTitle: false,Component,heightEstimate: 'calc(100vh - 20rem)',href: (attrs) => {- // TODO: Fix parsing of attrs- return urls.replay(undefined, attrs.universalFilters)+ return attrs.id ? urls.replayPlaylist(attrs.id) : urls.replay(undefined, attrs.universalFilters)},resizeable: true,expandable: false,attributes: {+ id: {},+ view: {},universalFilters: {default: DEFAULT_RECORDING_FILTERS,},@@ -148,6 +313,9 @@ export const NotebookNodePlaylist = createPostHogWidgetNode<NotebookNodePlaylist},},Settings,+ defaultView: getNotebookWidgetDefaultView('RecordingPlaylist'),+ views: PLAYLIST_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Recording playlist',})export function buildPlaylistContent(filters: Partial<FilterType>): JSONContent {diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsxindex 6ddce28f7782..92ac2e75161f 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx@@ -1,15 +1,18 @@import { BindLogic, useActions, useValues } from 'kea'import { useEffect, useMemo } from 'react'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'import { useComponentPanelState } from 'lib/components/MarkdownNotebook/componentPanelContext'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { urls } from 'scenes/urls'import { Query } from '~/queries/Query/Query'@@ -24,7 +27,7 @@ import {isSavedInsightNode,isActorsQuery,} from '~/queries/utils'-import { InsightLogicProps } from '~/types'+import { InsightLogicProps, InsightShortId } from '~/types'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import {@@ -43,6 +46,10 @@ type NotebookSqlOutputToolbarVisibilityProps = {isEditing: boolean}+function getResolvedNotebookQuery(attributes: NotebookNodeQueryAttributes): QuerySchema {+ return attributes.id ? { kind: NodeKind.SavedInsightNode, shortId: attributes.id } : attributes.query+}+export function getNotebookSqlOutputToolbarVisibility({componentPanelState,expanded,@@ -69,7 +76,8 @@ const Component = ({attributes,updateAttributes,}: NotebookNodeProps<NotebookNodeQueryAttributes>): JSX.Element | null => {- const { query, nodeId } = attributes+ const { nodeId } = attributes+ const query = getResolvedNotebookQuery(attributes)const nodeLogic = useRequiredNotebookNode()const { expanded, nodeId: resolvedNodeId, notebookLogic } = useValues(nodeLogic)const {@@ -256,6 +264,8 @@ const Component = ({type NotebookNodeQueryAttributes = {query: QuerySchema+ id?: InsightShortId+ view?: string/* Whether canvasFiltersOverride is applied, as we should apply it only once */isDefaultFilterApplied: booleanshowSettings?: boolean@@ -266,7 +276,8 @@ export const Settings = ({attributes,updateAttributes,}: NotebookNodeAttributeProperties<NotebookNodeQueryAttributes>): JSX.Element => {- const { query, isDefaultFilterApplied } = attributes+ const { isDefaultFilterApplied } = attributes+ const query = getResolvedNotebookQuery(attributes)const nodeLogic = useRequiredNotebookNode()const { notebookLogic } = useValues(nodeLogic)const { canvasFiltersOverride } = useValues(notebookLogic)@@ -320,19 +331,19 @@ export const Settings = ({}, [query, canvasFiltersOverride, isDefaultFilterApplied, attributes, updateAttributes])const detachSavedInsight = (): void => {- if (isSavedInsightNode(attributes.query)) {- const insightProps: InsightLogicProps = { dashboardItemId: attributes.query.shortId }+ if (isSavedInsightNode(query)) {+ const insightProps: InsightLogicProps = { dashboardItemId: query.shortId }const dataLogic = insightDataLogic.findMounted(insightProps)if (dataLogic) {- updateAttributes({ query: dataLogic.values.query as QuerySchema })+ updateAttributes({ id: undefined, query: dataLogic.values.query as QuerySchema })}}}const isSqlEditorQuery = !!getSqlEditorSourceQuery(query)- return isSavedInsightNode(attributes.query) ? (+ return isSavedInsightNode(query) ? (<div className="p-3 deprecated-space-y-2"><div className="text-lg font-semibold">Insight created outside of this notebook</div><div>@@ -346,7 +357,7 @@ export const Settings = ({type="secondary"fullWidthclassName="flex flex-1"- to={urls.insightEdit(attributes.query.shortId)}+ to={urls.insightEdit(query.shortId)}>Edit the insight</LemonButton>@@ -373,7 +384,7 @@ export const Settings = ({setQuery={(t) => {updateAttributes({query: {- ...attributes.query,+ ...query,source: (t as DataTableNode | InsightVizNode).source,} as QuerySchema,})@@ -383,6 +394,64 @@ export const Settings = ({)}+function InsightSummary({ attributes }: NotebookNodeProps<NotebookNodeQueryAttributes>): JSX.Element {+ const query = getResolvedNotebookQuery(attributes)++ if (!isSavedInsightNode(query)) {+ return <Component attributes={attributes} updateAttributes={() => {}} />+ }++ return <SavedInsightSummary shortId={query.shortId} />+}++function SavedInsightSummary({ shortId }: { shortId: InsightShortId }): JSX.Element {+ const logic = insightLogic({ dashboardItemId: shortId })+ const { insight, insightLoading, insightName } = useValues(logic)+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(insightName || 'Insight')+ }, [insightName, setTitlePlaceholder])++ if (insightLoading && !insight.id) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }++ const insightType = insight.query?.kind?.replace('Node', '').replace('Query', '') || 'Insight'++ return (+ <BindLogic logic={insightLogic} props={{ dashboardItemId: shortId }}>+ <div className="flex flex-wrap items-center gap-2 p-3">+ <span className="min-w-48 flex-1 truncate">{insight.description || insightName}</span>+ <LemonTag type="muted">{insightType}</LemonTag>+ </div>+ </BindLogic>+ )+}++function InsightEditor(props: NotebookNodeProps<NotebookNodeQueryAttributes>): JSX.Element {+ const query = getResolvedNotebookQuery(props.attributes)+ const shortId = isSavedInsightNode(query) ? query.shortId : ('new' as const)+ const { insightName } = useValues(insightLogic({ dashboardItemId: shortId }))+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(insightName || 'Insight')+ }, [insightName, setTitlePlaceholder])++ return <Settings {...props} />+}++const INSIGHT_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodeQueryAttributes, 'Insight'>('Insight', {+ summary: InsightSummary,+ editor: InsightEditor,+ results: Component,+})+export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttributes>({nodeType: NotebookNodeType.Query,titlePlaceholder: 'Query',@@ -395,6 +464,8 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttribquery: {default: DEFAULT_QUERY,},+ id: {},+ view: {},isDefaultFilterApplied: {default: false,},@@ -405,17 +476,21 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttribdefault: OutputTab.Results,},},- href: ({ query }) =>- isSavedInsightNode(query)+ href: (attributes) => {+ const query = getResolvedNotebookQuery(attributes)+ return isSavedInsightNode(query)? urls.insightView(query.shortId): isInsightVizNode(query)? urls.insightNew({ query })- : undefined,+ : undefined+ },Settings,+ defaultView: getNotebookWidgetDefaultView('Insight'),+ views: INSIGHT_NOTEBOOK_WIDGET_VIEWS,settingsPlacement: 'inline',serializedText: (attrs) => {let text = ''- const q = attrs.query+ const q = getResolvedNotebookQuery(attrs)if (containsHogQLQuery(q)) {if (isHogQLQuery(q)) {text = q.querydiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsxindex ee21526f4bba..f7f6ee8fc292 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx@@ -8,6 +8,7 @@ import { NotFound } from 'lib/components/NotFound'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { colonDelimitedDuration } from 'lib/utils/durations'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { defineNotebookWidgetViews, getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { asDisplay } from 'scenes/persons/person-utils'import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'import {@@ -145,10 +146,43 @@ export const Settings = ({type NotebookNodeRecordingAttributes = {id: string+ view?: stringnoInspector: booleantimestampMs?: number}+function RecordingSummary({ attributes }: NotebookNodeProps<NotebookNodeRecordingAttributes>): JSX.Element {+ const recordingLogicProps = sessionRecordingPlayerProps(attributes.id)+ const { sessionPlayerMetaData, sessionPlayerMetaDataLoading } = useValues(+ sessionRecordingDataCoordinatorLogic(recordingLogicProps)+ )+ const { loadRecordingMeta } = useActions(sessionRecordingDataCoordinatorLogic(recordingLogicProps))+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)++ useOnMountEffect(loadRecordingMeta)++ useEffect(() => {+ setTitlePlaceholder(+ sessionPlayerMetaData?.person ? asDisplay(sessionPlayerMetaData.person) : 'Session recording'+ )+ }, [sessionPlayerMetaData?.person, setTitlePlaceholder])++ if (!sessionPlayerMetaData && !sessionPlayerMetaDataLoading) {+ return <NotFound object="replay" />+ }++ return sessionPlayerMetaData ? (+ <SessionRecordingPreview recording={sessionPlayerMetaData} />+ ) : (+ <SessionRecordingPreviewSkeleton />+ )+}++const RECORDING_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<NotebookNodeRecordingAttributes, 'Recording'>(+ 'Recording',+ { summary: RecordingSummary }+)+export const NotebookNodeRecording = createPostHogWidgetNode<NotebookNodeRecordingAttributes>({nodeType: NotebookNodeType.Recording,titlePlaceholder: 'Session recording',@@ -165,6 +199,7 @@ export const NotebookNodeRecording = createPostHogWidgetNode<NotebookNodeRecordiid: {default: null,},+ view: {},noInspector: {default: false,},@@ -173,9 +208,9 @@ export const NotebookNodeRecording = createPostHogWidgetNode<NotebookNodeRecordi},},Settings,- serializedText: (attrs) => {- return attrs.id- },+ defaultView: getNotebookWidgetDefaultView('Recording'),+ views: RECORDING_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Session recording',})export function sessionRecordingPlayerProps(id: SessionRecordingId): SessionRecordingPlayerProps {diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeWorkflow.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeWorkflow.tsxnew file mode 100644index 000000000000..058342928165--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeWorkflow.tsx@@ -0,0 +1,29 @@+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'+import { urls } from 'scenes/urls'++import {+ WORKFLOW_NOTEBOOK_WIDGET_VIEWS,+ WorkflowDetail,+ WorkflowNotebookWidgetAttributes,+} from 'products/workflows/frontend/workflowNotebookWidgetViews'++import { NotebookNodeType } from '../types'++export const NotebookNodeWorkflow = createPostHogWidgetNode<WorkflowNotebookWidgetAttributes>({+ nodeType: NotebookNodeType.Workflow,+ titlePlaceholder: 'Workflow',+ editableTitle: false,+ Component: WorkflowDetail,+ heightEstimate: 420,+ minHeight: 200,+ href: (attributes) => urls.workflow(attributes.id, 'workflow'),+ resizeable: true,+ attributes: {+ id: {},+ view: {},+ },+ defaultView: getNotebookWidgetDefaultView('Workflow'),+ views: WORKFLOW_NOTEBOOK_WIDGET_VIEWS,+ serializedText: () => 'Workflow',+})diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityPicker.tsxindex e32c5b1570a0..dcd0c5876cc2 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityPicker.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookEntityPicker.tsx@@ -1,7 +1,20 @@+import { useValues } from 'kea'+import { IconMessage, IconRocket } from '@posthog/icons'import api from 'lib/api'import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'+import { teamLogic } from 'scenes/teamLogic'++import { groupsModel } from '~/models/groupsModel'+import { NodeKind, TracesQuery } from '~/queries/schema/schema-general'++import * as earlyAccessFeatureApi from 'products/early_access_features/frontend/generated/api'+import * as errorTrackingApi from 'products/error_tracking/frontend/generated/api'+import * as personsApi from 'products/persons/frontend/generated/api'+import * as replayApi from 'products/replay/frontend/generated/api'+import * as surveysApi from 'products/surveys/frontend/generated/api'+import * as workflowsApi from 'products/workflows/frontend/generated/api'import { NotebookWidgetPickerKind } from '../notebookWidgetCatalog'import {@@ -33,10 +46,29 @@ const PICKER_LABELS: Record<MarkdownNotebookEntityPickerKind, string> = {survey: 'Survey','early-access-feature': 'Early access feature',cohort: 'Cohort',+ insight: 'Insight',+ recording: 'Session recording',+ 'recording-playlist': 'Recording playlist',+ person: 'Person',+ group: 'Group',+ 'error-tracking-issue': 'Error tracking issue',+ 'llm-trace': 'LLM trace',+ dashboard: 'Dashboard',+ action: 'Action',+ workflow: 'Workflow',+}++function currentProjectId(): string | null {+ const projectId = teamLogic.values.currentProjectId+ return projectId == null ? null : String(projectId)}async function loadSurveyPickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {- const response = await api.surveys.list({ limit: 100 })+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await surveysApi.surveysList(projectId, { limit: 100 })return response.results.map((survey) => ({id: survey.id,name: survey.name,@@ -45,7 +77,11 @@ async function loadSurveyPickerItems(): Promise<MarkdownNotebookEntityListPicker}async function loadEarlyAccessFeaturePickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {- const response = await api.earlyAccessFeatures.list()+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await earlyAccessFeatureApi.earlyAccessFeatureList(projectId)return response.results.map((feature) => ({id: feature.id,name: feature.name,@@ -53,12 +89,92 @@ async function loadEarlyAccessFeaturePickerItems(): Promise<MarkdownNotebookEnti}))}+async function loadRecordingPickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await replayApi.sessionRecordingsList(projectId, { limit: 100 })+ return response.results.map((recording) => ({+ id: recording.id,+ name: recording.person?.name || recording.distinct_id || recording.id,+ description: recording.start_url,+ }))+}++async function loadRecordingPlaylistPickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await replayApi.sessionRecordingPlaylistsList(projectId, { limit: 100 })+ return response.results.map((playlist) => ({+ id: playlist.short_id,+ name: playlist.name || playlist.derived_name || playlist.short_id,+ description: playlist.description,+ }))+}++async function loadPersonPickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await personsApi.personsList(projectId, { limit: 100 })+ return (response.results || []).map((person) => ({+ id: person.uuid,+ name: person.name,+ description: person.distinct_ids.join(', '),+ }))+}++async function loadErrorTrackingIssuePickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await errorTrackingApi.errorTrackingIssuesList(projectId, { limit: 100 })+ return response.results.map((issue) => ({+ id: issue.id,+ name: issue.name || issue.description || issue.id,+ description: issue.status,+ }))+}++async function loadLLMTracePickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const response = await api.query<TracesQuery>({+ kind: NodeKind.TracesQuery,+ dateRange: { date_from: '-30d' },+ limit: 100,+ })+ return response.results.map((trace) => ({+ id: trace.id,+ name: trace.traceName || trace.id,+ description: trace.distinctId,+ }))+}++async function loadWorkflowPickerItems(): Promise<MarkdownNotebookEntityListPickerItem[]> {+ const projectId = currentProjectId()+ if (!projectId) {+ return []+ }+ const response = await workflowsApi.hogFlowsList(projectId, { limit: 100 })+ return response.results.map((workflow) => ({+ id: workflow.id,+ name: workflow.name || workflow.id,+ description: workflow.description,+ }))+}+export function MarkdownNotebookEntityPicker({action,kind,onClose,onSelect,}: MarkdownNotebookEntityPickerProps): JSX.Element | null {+ const { groupTypes } = useValues(groupsModel)+if (!kind) {return null}@@ -66,18 +182,22 @@ export function MarkdownNotebookEntityPicker({const label = PICKER_LABELS[kind]const title = action === 'add' ? `Add ${label.toLowerCase()} to notebook` : `Select ${label.toLowerCase()}`- if (kind === 'saved-insight') {+ if (kind === 'saved-insight' || kind === 'insight') {return (<MarkdownNotebookSavedInsightPickerisOpen+ title={title}onClose={onClose}onSelect={(shortId, insightTitle) =>onSelect({- tagName: 'Query',- props: {- query: { kind: 'SavedInsightNode', shortId },- ...(insightTitle ? { title: insightTitle } : {}),- },+ tagName: kind === 'insight' ? 'Insight' : 'Query',+ props:+ kind === 'insight'+ ? { id: shortId }+ : {+ query: { kind: 'SavedInsightNode', shortId },+ ...(insightTitle ? { title: insightTitle } : {}),+ },})}/>@@ -118,18 +238,123 @@ export function MarkdownNotebookEntityPicker({)}- const isSurvey = kind === 'survey'+ if (kind === 'action' || kind === 'dashboard') {+ const isAction = kind === 'action'+ return (+ <MarkdownNotebookTaxonomicPicker+ isOpen+ title={title}+ groupType={isAction ? TaxonomicFilterGroupType.Actions : TaxonomicFilterGroupType.Dashboards}+ onClose={onClose}+ onSelect={(value) => {+ const id = Number(value)+ if (Number.isInteger(id) && id > 0) {+ onSelect({ tagName: isAction ? 'Action' : 'Dashboard', props: { id } })+ } else {+ onClose()+ }+ }}+ />+ )+ }++ if (kind === 'group') {+ const groupPickerTypes = Array.from(groupTypes.values()).map(+ (groupType) =>+ `${TaxonomicFilterGroupType.GroupNamesPrefix}_${groupType.group_type_index}` as TaxonomicFilterGroupType+ )++ if (groupPickerTypes.length === 0) {+ return null+ }++ return (+ <MarkdownNotebookTaxonomicPicker+ isOpen+ title={title}+ groupType={groupPickerTypes[0]}+ groupTypes={groupPickerTypes}+ onClose={onClose}+ onSelect={(value, group) => {+ if (group.groupTypeIndex !== undefined) {+ onSelect({+ tagName: 'Group',+ props: { id: String(value), groupTypeIndex: group.groupTypeIndex },+ })+ } else {+ onClose()+ }+ }}+ />+ )+ }++ const listPicker = {+ survey: {+ searchPlaceholder: 'Search surveys',+ entityIcon: <IconMessage />,+ loadItems: loadSurveyPickerItems,+ tagName: 'Survey',+ },+ 'early-access-feature': {+ searchPlaceholder: 'Search early access features',+ entityIcon: <IconRocket />,+ loadItems: loadEarlyAccessFeaturePickerItems,+ tagName: 'EarlyAccessFeature',+ },+ recording: {+ searchPlaceholder: 'Search session recordings',+ entityIcon: undefined,+ loadItems: loadRecordingPickerItems,+ tagName: 'Recording',+ },+ 'recording-playlist': {+ searchPlaceholder: 'Search recording playlists',+ entityIcon: undefined,+ loadItems: loadRecordingPlaylistPickerItems,+ tagName: 'RecordingPlaylist',+ },+ person: {+ searchPlaceholder: 'Search people',+ entityIcon: undefined,+ loadItems: loadPersonPickerItems,+ tagName: 'Person',+ },+ 'error-tracking-issue': {+ searchPlaceholder: 'Search error tracking issues',+ entityIcon: undefined,+ loadItems: loadErrorTrackingIssuePickerItems,+ tagName: 'ErrorTrackingIssue',+ },+ 'llm-trace': {+ searchPlaceholder: 'Search LLM traces',+ entityIcon: undefined,+ loadItems: loadLLMTracePickerItems,+ tagName: 'LLMTrace',+ },+ workflow: {+ searchPlaceholder: 'Search workflows',+ entityIcon: undefined,+ loadItems: loadWorkflowPickerItems,+ tagName: 'Workflow',+ },+ }[kind]++ if (!listPicker) {+ return null+ }+return (<MarkdownNotebookEntityListPickerisOpentitle={title}- searchPlaceholder={isSurvey ? 'Search surveys' : 'Search early access features'}- entityIcon={isSurvey ? <IconMessage /> : <IconRocket />}- loadItems={isSurvey ? loadSurveyPickerItems : loadEarlyAccessFeaturePickerItems}+ searchPlaceholder={listPicker.searchPlaceholder}+ entityIcon={listPicker.entityIcon}+ loadItems={listPicker.loadItems}onClose={onClose}onSelect={(item) =>onSelect({- tagName: isSurvey ? 'Survey' : 'EarlyAccessFeature',+ tagName: listPicker.tagName,props: { id: String(item.id) },})}diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsxindex abebf65b2c9e..aa30cc45a2c6 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookSavedInsightPicker.tsx@@ -6,12 +6,14 @@ import { SavedInsightsTable } from 'scenes/saved-insights/SavedInsightsTable'export type MarkdownNotebookSavedInsightPickerProps = {isOpen: boolean+ title?: stringonClose: () => voidonSelect: (shortId: string, title: string) => void}export function MarkdownNotebookSavedInsightPicker({isOpen,+ title = 'Add insight to notebook',onClose,onSelect,}: MarkdownNotebookSavedInsightPickerProps): JSX.Element {@@ -19,7 +21,7 @@ export function MarkdownNotebookSavedInsightPicker({return (<LemonModal- title="Add insight to notebook"+ title={title}onClose={onClose}isOpen={isOpen}footer={diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsxindex 1908987d6fa8..2d5199fabb7b 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookTaxonomicPicker.tsx@@ -1,15 +1,20 @@import { LemonButton } from '@posthog/lemon-ui'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'-import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'+import {+ TaxonomicFilterGroup,+ TaxonomicFilterGroupType,+ TaxonomicFilterValue,+} from 'lib/components/TaxonomicFilter/types'import { LemonModal } from 'lib/lemon-ui/LemonModal'export type MarkdownNotebookTaxonomicPickerProps = {isOpen: booleantitle: stringgroupType: TaxonomicFilterGroupType+ groupTypes?: TaxonomicFilterGroupType[]onClose: () => void- onSelect: (value: TaxonomicFilterValue) => void+ onSelect: (value: TaxonomicFilterValue, group: TaxonomicFilterGroup) => void}/** Entity picker for insert-menu commands whose entity has a taxonomic group (feature flags,@@ -18,6 +23,7 @@ export function MarkdownNotebookTaxonomicPicker({isOpen,title,groupType,+ groupTypes,onClose,onSelect,}: MarkdownNotebookTaxonomicPickerProps): JSX.Element {@@ -36,10 +42,10 @@ export function MarkdownNotebookTaxonomicPicker({{isOpen ? (<TaxonomicFiltergroupType={groupType}- taxonomicGroupTypes={[groupType]}- onChange={(_, value) => {+ taxonomicGroupTypes={groupTypes || [groupType]}+ onChange={(group, value) => {if (value !== null && value !== undefined && value !== '') {- onSelect(value)+ onSelect(value, group)}}}/>diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex ab35f0cd14d9..4d58ca2ae9ee 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -2,12 +2,13 @@ import { useActions, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { IconFlask, IconGraph, IconMessage, IconPeople, IconRocket, IconToggle } from '@posthog/icons'+import { IconGraph } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'import {MarkdownNotebook,NotebookComponentRunStatusContext,+ PRODUCTS_INSERT_COMMAND_CATEGORY,parseMarkdownNotebook,} from 'lib/components/MarkdownNotebook'import type {@@ -31,6 +32,9 @@ import { uuid } from 'lib/utils/dom'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'+import { NODE_ICONS } from '../nodeIcons'+import { notebookWidgetCatalog, NotebookWidgetPickerKind } from '../notebookWidgetCatalog'+import { NotebookNodeType } from '../types'import {MarkdownNotebookEntityPicker,MarkdownNotebookEntityPickerKind,@@ -445,7 +449,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot): InsertCommand => ({key,label,- category: 'Products',+ category: PRODUCTS_INSERT_COMMAND_CATEGORY,icon,aliases,run: (targetNodeId) => {@@ -454,19 +458,14 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot},})- return [- pickerCommand('query-saved-insight', 'Saved insight', <IconGraph />, 'saved-insight', ['insight']),- pickerCommand('experiment', 'Experiment', <IconFlask />, 'experiment', ['ab test']),- pickerCommand('product-feature-flag', 'Feature flag', <IconToggle />, 'feature-flag', ['flag']),- pickerCommand('product-survey', 'Survey', <IconMessage />, 'survey'),+ return Object.entries(notebookWidgetCatalog.widgets).map(([tagName, widget]) =>pickerCommand(- 'product-early-access-feature',- 'Early access feature',- <IconRocket />,- 'early-access-feature'- ),- pickerCommand('product-cohort', 'Cohort', <IconPeople />, 'cohort'),- ]+ `product-${tagName.replaceAll(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()}`,+ widget.label,+ NODE_ICONS[widget.nodeType as NotebookNodeType] || <IconGraph />,+ widget.picker as NotebookWidgetPickerKind+ )+ )}, [])const closeEntityPicker = useCallback((): void => {diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsxindex 35f1e55a4425..6ebc4437fe47 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx@@ -1,13 +1,22 @@+import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'+import { Meta, StoryObj } from '@storybook/react'+import { HttpResponse } from 'msw'-import { JSONContent } from 'lib/components/RichContentEditor/types'import { App } from 'scenes/App'+import dashboardFixture from 'scenes/dashboard/__mocks__/dashboard.json'+import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'+import { recordingPlaylists } from 'scenes/session-recordings/__mocks__/recording_playlists'+import { snapshotsAsJSONLines } from 'scenes/session-recordings/__mocks__/recording_snapshots'+import { recordings } from 'scenes/session-recordings/__mocks__/recordings'import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import EXPERIMENT_DRAFT from '~/mocks/fixtures/api/experiments/_experiment_draft.json'+import { NodeKind } from '~/queries/schema/schema-general'import {AccessControlLevel,+ ActionType,CohortType,EarlyAccessFeatureStage,EarlyAccessFeatureType,@@ -17,16 +26,36 @@ import {SurveyType,} from '~/types'+import traceWithoutContent from 'products/ai_observability/frontend/__mocks__/traceWithoutContent.json'+import {+ errorTrackingEventsQueryResponse,+ errorTrackingQueryResponse,+ errorTrackingTypeIssue,+} from 'products/error_tracking/frontend/__mocks__/error_tracking_query'+import { NEW_WORKFLOW } from 'products/workflows/frontend/Workflows/workflowLogic'++import { expect, waitFor } from 'storybook/test'+import featureFlags from '../../feature-flags/__mocks__/feature_flags.json'import { notebookWidgetCatalog, NotebookWidgetTagName } from '../notebookWidgetCatalog'-import { NotebookNodeType } from '../types'import { notebookTestTemplate } from './__mocks__/notebook-template-for-snapshot'+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from './markdownNotebookV2'const FEATURE_FLAG_ID = 1779const SURVEY_ID = '0187c279-bcae-0000-34f5-4f121921f005'const EXPERIMENT_ID = EXPERIMENT_DRAFT.idconst EARLY_ACCESS_FEATURE_ID = '0187c22c-06d9-0000-34fe-daa2e2afb503'const COHORT_ID = 1+const INSIGHT_ID = 'widget-insight'+const RECORDING_ID = String(recordings[0].id)+const PLAYLIST_ID = 'widget-playlist'+const PERSON_ID = '0198a76b-7d8b-7000-8fb2-a6f4d27b0811'+const GROUP_KEY = 'example-company'+const ERROR_TRACKING_ISSUE_ID = 'widget-issue'+const LLM_TRACE_ID = traceWithoutContent.id+const DASHBOARD_ID = 5+const ACTION_ID = 123+const WORKFLOW_ID = 'widget-workflow'const featureFlag = {...featureFlags.results.find((flag) => flag.id === FEATURE_FLAG_ID),@@ -90,55 +119,195 @@ const cohort = {groups: [],} as CohortType-function createWidgetViewNodes(+const insight = {+ ...dashboardFixture.tiles[0].insight,+ id: 901,+ short_id: INSIGHT_ID,+ name: 'Activation by day',+ description: 'Daily activation events for the current release.',+}++const recording = {+ ...recordingMetaJson,+ id: RECORDING_ID,+ person: {+ ...recordingMetaJson.person,+ properties: { ...recordingMetaJson.person?.properties, email: '[email protected]' },+ },+}++const playlist = {+ ...recordingPlaylists.results[0],+ short_id: PLAYLIST_ID,+ name: 'New user sessions',+ description: 'Sessions from people completing their first setup.',+}++const personHogQLRow = [+ PERSON_ID,+ ['[email protected]'],+ JSON.stringify({+ email: '[email protected]',+ name: 'Taylor Example',+ $browser: 'Chrome',+ $device_type: 'Desktop',+ $geoip_country_code: 'BE',+ $geoip_country_name: 'Belgium',+ }),+ true,+ '2023-06-15T10:00:00Z',+ '2023-07-03T10:00:00Z',+]++const group = {+ group_type_index: 0,+ group_key: GROUP_KEY,+ group_properties: { name: 'Example Company', industry: 'Software', mrr: 1200 },+ created_at: '2023-06-15T10:00:00Z',+}++const errorTrackingIssue = {+ ...errorTrackingTypeIssue,+ id: ERROR_TRACKING_ISSUE_ID,+ name: 'Checkout request failed',+ description: 'The checkout request returned an unexpected response.',+}++const errorTrackingSummary = {+ ...errorTrackingQueryResponse,+ results: [+ {+ ...errorTrackingQueryResponse.results[0],+ ...errorTrackingIssue,+ aggregations: {+ ...errorTrackingQueryResponse.results[0].aggregations,+ occurrences: 38,+ users: 8,+ },+ },+ ],+}++const errorTrackingActivityResponse = {+ columns: ['*', 'timestamp', 'person'],+ hasMore: false,+ results: errorTrackingEventsQueryResponse.results.map((row) => [+ {+ uuid: row[0] as string,+ properties: {+ ...JSON.parse(row[1] as string),+ $exception_types: ['TypeError'],+ $exception_values: ['The checkout request returned an unexpected response.'],+ },+ },+ row[2],+ row[3],+ ]),+}++const dashboard = {+ ...dashboardFixture,+ id: DASHBOARD_ID,+ name: 'Growth overview',+ description: 'The metrics used in the weekly growth review.',+ is_shared: true,+ tiles: dashboardFixture.tiles.map((tile, index) => ({ ...tile, id: index + 1 })),+}++const action = {+ id: ACTION_ID,+ name: 'Completed onboarding',+ description: 'People who completed the onboarding flow.',+ tags: ['onboarding'],+ post_to_slack: false,+ slack_message_format: '',+ steps: [+ {+ event: 'onboarding completed',+ selector: null,+ text: null,+ text_matching: null,+ href: null,+ href_matching: 'contains',+ url: null,+ url_matching: 'contains',+ },+ ],+ created_at: '2023-06-15T10:00:00Z',+ created_by: MOCK_DEFAULT_BASIC_USER,+ deleted: false,+ is_calculating: false,+ last_calculated_at: '2023-07-03T10:00:00Z',+ pinned_at: null,+ user_access_level: AccessControlLevel.Editor,+ reference_count: 1,+} as ActionType++const workflow = {+ ...NEW_WORKFLOW,+ id: WORKFLOW_ID,+ name: 'Welcome new users',+ description: 'Send onboarding guidance after signup.',+ team_id: 1,+ created_at: '2023-06-15T10:00:00Z',+ updated_at: '2023-07-03T10:00:00Z',+}++function notebookWidgetViewTestTemplate(tagName: NotebookWidgetTagName,- nodeType: NotebookNodeType,- id: string | number-): JSONContent[] {+ title: string,+ id: string | number,+ attributes: Record<string, string | number> = {}+): ReturnType<typeof notebookTestTemplate> {const widget = notebookWidgetCatalog.widgets[tagName]const views = [{ key: widget.defaultView.name, label: widget.defaultView.label, isDefault: true },...Object.entries(widget.views).map(([key, view]) => ({ key, label: view.label, isDefault: false })),]-- return views.flatMap(({ key, label, isDefault }, index) => [- {- type: 'heading',- attrs: { level: 2 },- content: [{ type: 'text', text: label }],- },- {- type: nodeType,- attrs: {+ const markdown = [+ `# ${title}`,+ ...views.flatMap(({ key, label, isDefault }) => [+ `## ${label}`,+ serializeMarkdownNotebookComponent(tagName, {id,- nodeId: `${tagName}-${key}-${index}`,+ ...attributes,...(isDefault ? {} : { view: key }),- },- },- ])+ }),+ ]),+ ].join('\n\n')++ return { ...notebookTestTemplate(title, []), content: buildMarkdownNotebookContent(markdown) }}const notebooks = {- 'feature-flag-widget-views': notebookTestTemplate(- 'Feature flag views',- createWidgetViewNodes('FeatureFlag', NotebookNodeType.FeatureFlag, FEATURE_FLAG_ID)- ),- 'survey-widget-views': notebookTestTemplate(- 'Survey views',- createWidgetViewNodes('Survey', NotebookNodeType.Survey, SURVEY_ID)- ),- 'experiment-widget-views': notebookTestTemplate(- 'Experiment views',- createWidgetViewNodes('Experiment', NotebookNodeType.Experiment, EXPERIMENT_ID)- ),- 'early-access-feature-widget-views': notebookTestTemplate(+ 'feature-flag-widget-views': notebookWidgetViewTestTemplate('FeatureFlag', 'Feature flag views', FEATURE_FLAG_ID),+ 'survey-widget-views': notebookWidgetViewTestTemplate('Survey', 'Survey views', SURVEY_ID),+ 'experiment-widget-views': notebookWidgetViewTestTemplate('Experiment', 'Experiment views', EXPERIMENT_ID),+ 'early-access-feature-widget-views': notebookWidgetViewTestTemplate(+ 'EarlyAccessFeature','Early access feature views',- createWidgetViewNodes('EarlyAccessFeature', NotebookNodeType.EarlyAccessFeature, EARLY_ACCESS_FEATURE_ID)+ EARLY_ACCESS_FEATURE_ID+ ),+ 'cohort-widget-views': notebookWidgetViewTestTemplate('Cohort', 'Cohort views', COHORT_ID),+ 'insight-widget-views': notebookWidgetViewTestTemplate('Insight', 'Insight views', INSIGHT_ID),+ 'recording-widget-views': notebookWidgetViewTestTemplate('Recording', 'Session recording views', RECORDING_ID),+ 'recording-playlist-widget-views': notebookWidgetViewTestTemplate(+ 'RecordingPlaylist',+ 'Recording playlist views',+ PLAYLIST_ID,+ { height: 400 }),- 'cohort-widget-views': notebookTestTemplate(- 'Cohort views',- createWidgetViewNodes('Cohort', NotebookNodeType.Cohort, COHORT_ID)+ 'person-widget-views': notebookWidgetViewTestTemplate('Person', 'Person views', PERSON_ID),+ 'group-widget-views': notebookWidgetViewTestTemplate('Group', 'Group views', GROUP_KEY, { groupTypeIndex: 0 }),+ 'error-tracking-issue-widget-views': notebookWidgetViewTestTemplate(+ 'ErrorTrackingIssue',+ 'Error tracking issue views',+ ERROR_TRACKING_ISSUE_ID),+ 'llm-trace-widget-views': notebookWidgetViewTestTemplate('LLMTrace', 'LLM trace views', LLM_TRACE_ID),+ 'dashboard-widget-views': notebookWidgetViewTestTemplate('Dashboard', 'Dashboard views', DASHBOARD_ID),+ 'action-widget-views': notebookWidgetViewTestTemplate('Action', 'Action views', ACTION_ID),+ 'workflow-widget-views': notebookWidgetViewTestTemplate('Workflow', 'Workflow views', WORKFLOW_ID),}const meta: Meta = {@@ -172,6 +341,51 @@ const meta: Meta = {'/api/projects/:team_id/experiment_saved_metrics/': [],[`/api/projects/:team_id/early_access_feature/${EARLY_ACCESS_FEATURE_ID}/`]: earlyAccessFeature,[`/api/projects/:team_id/cohorts/${COHORT_ID}/`]: cohort,+ [`/api/environments/:team_id/insights/${INSIGHT_ID}/`]: insight,+ [`/api/projects/:team_id/insights/${INSIGHT_ID}/`]: insight,+ '/api/environments/:team_id/session_recordings/:id': recording,+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {+ return new HttpResponse(snapshotsAsJSONLines())+ }++ return {+ sources: [+ {+ source: 'blob_v2',+ start_timestamp: '2023-08-11T12:03:36.097000Z',+ end_timestamp: '2023-08-11T12:04:52.268000Z',+ blob_key: '0',+ },+ ],+ }+ },+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': playlist,+ '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': {+ has_next: false,+ results: recordings,+ version: 1,+ },+ '/api/environments/:team_id/groups/find': group,+ '/api/environments/:team_id/error_tracking/issues/:id/': errorTrackingIssue,+ '/api/environments/:team_id/error_tracking/issues/:id/fingerprints/': [],+ '/api/environments/:team_id/error_tracking/fingerprints': { next: null, results: [] },+ '/api/environments/:team_id/error_tracking/spike_events': { results: [] },+ [`/api/environments/:team_id/dashboards/${DASHBOARD_ID}/`]: dashboard,+ '/api/environments/:team_id/insights/:insight_id/': ({ params }) =>+ dashboardFixture.tiles.find((tile) => String(tile.insight?.id) === String(params.insight_id))+ ?.insight || insight,+ [`/api/projects/:team_id/actions/${ACTION_ID}/`]: action,+ [`/api/environments/:team_id/actions/${ACTION_ID}/`]: action,+ [`/api/environments/:team_id/hog_flows/${WORKFLOW_ID}/`]: workflow,+ [`/api/environments/:team_id/hog_flows/${WORKFLOW_ID}/schedules/`]: [],+ [`/api/environments/:team_id/hog_flows/${WORKFLOW_ID}/batch_jobs/`]: [],+ '/api/environments/:team_id/hog_function_templates/': {+ count: 0,+ next: null,+ previous: null,+ results: [],+ },'/api/projects/:team_id/actions/': { count: 0, next: null, previous: null, results: [] },'/api/projects/:team_id/integrations': {},'/api/environments/:team_id/default_evaluation_contexts/': {@@ -182,12 +396,49 @@ const meta: Meta = {},'/api/environments/:team_id/default_release_conditions/': [],},+ patch: {+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>+ return { ...playlist, ...body }+ },+ },post: {- '/api/environments/:team_id/query/:kind': {- columns: [],- results: [],- types: [],+ '/api/projects/:team_id/session_recording_playlists/:playlist_id/playlist_viewed': { success: true },+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const body = (await request.json()) as {+ query?: { kind?: string; query?: string; select?: string[] }+ }+ const query = body.query++ if (query?.kind === NodeKind.TraceQuery) {+ return { results: [traceWithoutContent] }+ }+ if (query?.kind === NodeKind.ErrorTrackingQuery) {+ return errorTrackingSummary+ }+ if (query?.kind === NodeKind.EventsQuery) {+ return query.select?.includes('*')+ ? errorTrackingActivityResponse+ : errorTrackingEventsQueryResponse+ }+ if (query?.kind === NodeKind.HogQLQuery) {+ if (query.query?.includes('FROM persons\n')) {+ return { results: [personHogQLRow] }+ }+ if (query.query?.includes('persons_revenue_analytics')) {+ return { results: [[1200, 50000]] }+ }+ if (query.query?.includes('groups_revenue_analytics')) {+ return { results: [[2400, 75000]] }+ }+ if (query.query?.includes('count(DISTINCT $session_id)')) {+ return { results: [[3, 42]] }+ }+ }++ return { columns: [], results: [], types: [] }},+ '/api/environments/:team_id/error_tracking/stack_frames/batch_get/': { results: [] },'/api/projects/:team_id/feature_flags/user_blast_radius/': { affected: 120, total: 2000 },},}),@@ -205,3 +456,63 @@ export const EarlyAccessFeatureViews: Story = {parameters: { pageUrl: urls.notebook('early-access-feature-widget-views') },}export const CohortViews: Story = { parameters: { pageUrl: urls.notebook('cohort-widget-views') } }+export const InsightViews: Story = {+ parameters: { pageUrl: urls.notebook('insight-widget-views') },+ play: async ({ canvasElement }) => {+ await waitFor(() => {+ expect(+ canvasElement.querySelectorAll('.MarkdownNotebook__real-node-content').length+ ).toBeGreaterThanOrEqual(4)+ expect(+ canvasElement.querySelectorAll('.MarkdownNotebook__component-toolbar-title-placeholder')+ ).toHaveLength(0)+ })+ },+}+export const RecordingViews: Story = {+ parameters: {+ pageUrl: urls.notebook('recording-widget-views'),+ testOptions: { waitForLoadersToDisappear: false },+ },+}+export const RecordingPlaylistViews: Story = {+ parameters: {+ pageUrl: urls.notebook('recording-playlist-widget-views'),+ testOptions: {+ waitForLoadersToDisappear: false,+ waitForSelector: '.MarkdownNotebook__component-toolbar-title[title="New user sessions"]',+ },+ },+}+export const PersonViews: Story = { parameters: { pageUrl: urls.notebook('person-widget-views') } }+export const GroupViews: Story = { parameters: { pageUrl: urls.notebook('group-widget-views') } }+export const ErrorTrackingIssueViews: Story = {+ parameters: { pageUrl: urls.notebook('error-tracking-issue-widget-views') },+}+export const LLMTraceViews: Story = { parameters: { pageUrl: urls.notebook('llm-trace-widget-views') } }+export const DashboardViews: Story = { parameters: { pageUrl: urls.notebook('dashboard-widget-views') } }+export const ActionViews: Story = { parameters: { pageUrl: urls.notebook('action-widget-views') } }+export const WorkflowViews: Story = {+ parameters: { pageUrl: urls.notebook('workflow-widget-views') },+ play: async ({ canvasElement }) => {+ await waitFor(+ () => {+ const editor = canvasElement.querySelector<HTMLElement>('[data-attr="workflow-editor"]')+ const canvas = editor?.querySelector<HTMLElement>('.react-flow')+ const nodes = Array.from(editor?.querySelectorAll<HTMLElement>('.react-flow__node') || [])++ expect(canvas).not.toBeNull()+ expect(nodes).toHaveLength(2)++ const canvasBounds = canvas!.getBoundingClientRect()+ expect(+ nodes.every((node) => {+ const nodeBounds = node.getBoundingClientRect()+ return nodeBounds.top >= canvasBounds.top && nodeBounds.bottom <= canvasBounds.bottom+ })+ ).toBe(true)+ },+ { timeout: 10000 }+ )+ },+}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex 8fbe6291fe78..80b65db6efdd 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -9,11 +9,14 @@ import {import { FEATURE_FLAGS } from 'lib/constants'import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import notebookWidgetCatalog from 'products/notebooks/notebook-widget-catalog.json'+import { NotebookNodeType } from '../types'import { KNOWN_NODES } from '../utils'import {NOTEBOOK_MARKDOWN_REGISTRY,RealNotebookNodeEdit,+ RealNotebookNodeIdentityAndViewEdit,getEditableNodeAttributeKeys,getHiddenInsertCommandKeysForFeatureFlags,getMarkdownNodeAttributeLabel,@@ -112,13 +115,46 @@ describe('markdownNotebookRegistry', () => {'Experiment','EarlyAccessFeature','Cohort',+ 'Insight','Person','Group','Recording',+ 'RecordingPlaylist',+ 'ErrorTrackingIssue',+ 'LLMTrace',+ 'Dashboard',+ 'Action',+ 'Workflow',])('uses the resource-derived title for %s nodes', (tagName) => {expect(NOTEBOOK_MARKDOWN_REGISTRY.components[tagName].editableTitle).toBe(false)})+ it.each([+ ['FeatureFlag', NotebookNodeType.FeatureFlag],+ ['Survey', NotebookNodeType.Survey],+ ['Experiment', NotebookNodeType.Experiment],+ ['EarlyAccessFeature', NotebookNodeType.EarlyAccessFeature],+ ['Cohort', NotebookNodeType.Cohort],+ ['Insight', NotebookNodeType.Query],+ ['Recording', NotebookNodeType.Recording],+ ['RecordingPlaylist', NotebookNodeType.RecordingPlaylist],+ ['Person', NotebookNodeType.Person],+ ['Group', NotebookNodeType.Group],+ ['ErrorTrackingIssue', NotebookNodeType.ErrorTrackingIssue],+ ['LLMTrace', NotebookNodeType.LLMTrace],+ ['Dashboard', NotebookNodeType.Dashboard],+ ['Action', NotebookNodeType.Action],+ ['Workflow', NotebookNodeType.Workflow],+ ])('registers every catalog view for %s', (tagName, nodeType) => {+ const widget = notebookWidgetCatalog.widgets[tagName as keyof typeof notebookWidgetCatalog.widgets]+ const registeredViewNames = [+ KNOWN_NODES[nodeType].defaultView?.key,+ ...Object.keys(KNOWN_NODES[nodeType].views ?? {}),+ ]++ expect(registeredViewNames).toEqual([widget.defaultView.name, ...Object.keys(widget.views)])+ })+it.each([{tagName: 'FeatureFlag',@@ -206,6 +242,28 @@ describe('markdownNotebookRegistry', () => {})+ it('keeps the resource ID before the view for nodes with product settings', () => {+ const { container } = render(+ <RealNotebookNodeIdentityAndViewEdit+ node={{+ id: 'recording-node',+ type: 'component',+ tagName: 'Recording',+ props: { id: 'recording-id' },+ }}+ mode="edit"+ updateProps={jest.fn()}+ deleteNode={jest.fn()}+ notebookNodeType={NotebookNodeType.Recording}+ options={KNOWN_NODES[NotebookNodeType.Recording]}+ />+ )+ const fields = Array.from(container.querySelectorAll('.MarkdownNotebook__component-form > label'))++ expect(fields[0].textContent).toContain('Session recording ID')+ expect(fields[1].textContent).toContain('View')+ })+it('selects a referenced object from the same picker used by notebook insertion', () => {const updateProps = jest.fn()const { container } = render(diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 420a6f71bc23..1b94186eaea5 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -1,10 +1,12 @@import '../Nodes/NotebookNodeCohort'+import '../Nodes/NotebookNodeDashboard'import '../Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney'import '../Nodes/NotebookNodeSQLV2'import '../Nodes/NotebookNodeDuckSQL'import '../Nodes/NotebookNodeEarlyAccessFeature'import '../Nodes/NotebookNodeEmbed'import '../Nodes/NotebookNodeExperiment'+import '../Nodes/NotebookNodeErrorTrackingIssue'import '../Nodes/NotebookNodeFlag'import '../Nodes/NotebookNodeFlagCodeExample'import '../Nodes/NotebookNodeGroup'@@ -26,9 +28,11 @@ import '../Nodes/NotebookNodeRecording'import '../Nodes/NotebookNodeRelatedGroups'import '../Nodes/NotebookNodeSupportTickets'import '../Nodes/NotebookNodeSurvey'+import '../Nodes/NotebookNodeAction'import '../Nodes/NotebookNodeTaskCreate'import '../Nodes/NotebookNodeUsageMetrics'import '../Nodes/NotebookNodeZendeskTickets'+import '../Nodes/NotebookNodeWorkflow'import clsx from 'clsx'import { BindLogic, useMountedLogic, useValues } from 'kea'@@ -95,6 +99,8 @@ const INTERNAL_MARKDOWN_NODE_ATTRIBUTE_KEYS = new Set([const NUMERIC_MARKDOWN_NODE_ATTRIBUTE_KEYS: Partial<Record<NotebookNodeType, string[]>> = {[NotebookNodeType.Cohort]: ['id'],[NotebookNodeType.Experiment]: ['id'],+ [NotebookNodeType.Dashboard]: ['id'],+ [NotebookNodeType.Action]: ['id'],[NotebookNodeType.Group]: ['groupTypeIndex'],}@@ -102,6 +108,12 @@ const MARKDOWN_NODE_ATTRIBUTE_LABELS: Partial<Record<NotebookNodeType, Record<st[NotebookNodeType.Cohort]: {id: 'Cohort ID',},+ [NotebookNodeType.Dashboard]: {+ id: 'Dashboard ID',+ },+ [NotebookNodeType.Action]: {+ id: 'Action ID',+ },[NotebookNodeType.EarlyAccessFeature]: {id: 'Early access feature ID',},@@ -118,6 +130,21 @@ const MARKDOWN_NODE_ATTRIBUTE_LABELS: Partial<Record<NotebookNodeType, Record<stgroupTypeIndex: 'Group type index',id: 'Group key',},+ [NotebookNodeType.Recording]: {+ id: 'Session recording ID',+ },+ [NotebookNodeType.RecordingPlaylist]: {+ id: 'Recording playlist ID',+ },+ [NotebookNodeType.ErrorTrackingIssue]: {+ id: 'Error tracking issue ID',+ },+ [NotebookNodeType.LLMTrace]: {+ id: 'LLM trace ID',+ },+ [NotebookNodeType.Workflow]: {+ id: 'Workflow ID',+ },[NotebookNodeType.Person]: {distinctId: 'Distinct ID',id: 'Person UUID',@@ -133,6 +160,10 @@ const MARKDOWN_NODE_ATTRIBUTE_LABELS: Partial<Record<NotebookNodeType, Record<stexport const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookNodeType>> = {Query: NotebookNodeType.Query,+ Insight: NotebookNodeType.Query,+ Dashboard: NotebookNodeType.Dashboard,+ Action: NotebookNodeType.Action,+ Workflow: NotebookNodeType.Workflow,Python: NotebookNodeType.Python,PythonV2: NotebookNodeType.PythonV2,DuckSQL: NotebookNodeType.DuckSQL,@@ -160,6 +191,7 @@ export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookTaskCreate: NotebookNodeType.TaskCreate,LLMTrace: NotebookNodeType.LLMTrace,Issues: NotebookNodeType.Issues,+ ErrorTrackingIssue: NotebookNodeType.ErrorTrackingIssue,UsageMetrics: NotebookNodeType.UsageMetrics,ZendeskTickets: NotebookNodeType.ZendeskTickets,RelatedGroups: NotebookNodeType.RelatedGroups,@@ -167,6 +199,34 @@ export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookSupportTickets: NotebookNodeType.SupportTickets,}+const INSIGHT_NOTEBOOK_NODE_OPTIONS: CreatePostHogWidgetNodeOptions<any> = {+ ...KNOWN_NODES[NotebookNodeType.Query],+ editableTitle: false,+}+const INLINE_QUERY_NOTEBOOK_NODE_OPTIONS: CreatePostHogWidgetNodeOptions<any> = {+ ...KNOWN_NODES[NotebookNodeType.Query],+ attributes: {+ query: KNOWN_NODES[NotebookNodeType.Query].attributes.query,+ isDefaultFilterApplied: KNOWN_NODES[NotebookNodeType.Query].attributes.isDefaultFilterApplied,+ showSettings: KNOWN_NODES[NotebookNodeType.Query].attributes.showSettings,+ outputTab: KNOWN_NODES[NotebookNodeType.Query].attributes.outputTab,+ },+ defaultView: undefined,+ views: undefined,+}++function getMarkdownNodeOptions(tagName: string): CreatePostHogWidgetNodeOptions<any> | null {+ const nodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[tagName]++ if (tagName === 'Insight') {+ return INSIGHT_NOTEBOOK_NODE_OPTIONS+ }+ if (tagName === 'Query') {+ return INLINE_QUERY_NOTEBOOK_NODE_OPTIONS+ }+ return nodeType ? KNOWN_NODES[nodeType] : null+}+export const MARKDOWN_NODE_DEFINITIONS: {tagName: stringcategory: string@@ -176,6 +236,10 @@ export const MARKDOWN_NODE_DEFINITIONS: {insertCommand?: NotebookComponentDefinition['insertCommand']}[] = [{ tagName: 'Query', category: 'Insight' },+ { tagName: 'Insight', category: 'Insight', label: 'Insight' },+ { tagName: 'Dashboard', category: 'Insight' },+ { tagName: 'Action', category: 'Data' },+ { tagName: 'Workflow', category: 'PostHog' },// Legacy in-browser-kernel Python cell: still renders where it exists, but new cells// are always the revamped PythonV2 below, so it has no insertCommand.{ tagName: 'Python', category: 'Code' },@@ -232,6 +296,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {{ tagName: 'TaskCreate', category: 'PostHog' },{ tagName: 'LLMTrace', category: 'PostHog' },{ tagName: 'Issues', category: 'PostHog' },+ { tagName: 'ErrorTrackingIssue', category: 'PostHog', label: 'Error tracking issue' },{ tagName: 'UsageMetrics', category: 'PostHog' },{ tagName: 'ZendeskTickets', category: 'PostHog' },{ tagName: 'RelatedGroups', category: 'PostHog' },@@ -248,7 +313,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkdownNotebookRegistry([...MARKDOWN_NODE_DEFINITIONS.map((definition) => {const nodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[definition.tagName]- const options = nodeType ? KNOWN_NODES[nodeType] : null+ const options = getMarkdownNodeOptions(definition.tagName)const label = definition.label ?? options?.titlePlaceholder ?? splitTagName(definition.tagName)return {@@ -341,6 +406,9 @@ export function getMarkdownNotebookNodeTitle(}if (nodeType === NotebookNodeType.Query) {+ if (attributes.id) {+ return fallback+ }// No fallback label: an unnamed/SQL query stays empty so the title field reads as "Add a title"return getQueryTitle(attributes.query)}@@ -465,7 +533,7 @@ export function RealNotebookNodeView(props: NotebookComponentRenderProps): JSX.Eexport function RealNotebookNodeEdit(props: NotebookComponentRenderProps): JSX.Element {const notebookNodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[props.node.tagName]- const options = notebookNodeType ? KNOWN_NODES[notebookNodeType] : null+ const options = getMarkdownNodeOptions(props.node.tagName)if (!options || !notebookNodeType) {return <div className="MarkdownNotebook__component-preview">Unsupported notebook node.</div>@@ -477,16 +545,47 @@ export function RealNotebookNodeEdit(props: NotebookComponentRenderProps): JSX.Ereturn (<>- {options.views ? (- <div className="MarkdownNotebook__component-form">- <RealNotebookNodeViewSelect {...props} options={options} />- </div>- ) : null}+ <RealNotebookNodeIdentityAndViewEdit {...props} notebookNodeType={notebookNodeType} options={options} /><RealNotebookNodeComponent {...props} forceEditing editOnly /></>)}+export function RealNotebookNodeIdentityAndViewEdit({+ node,+ updateProps,+ notebookNodeType,+ options,+}: NotebookComponentRenderProps & {+ notebookNodeType: NotebookNodeType+ options: CreatePostHogWidgetNodeOptions<any>+}): JSX.Element | null {+ const hasId = 'id' in options.attributes+ if (!hasId && !options.views) {+ return null+ }++ const attributes = getNodeAttributes(node.props, node.id, options, notebookNodeType, true)++ return (+ <div className="MarkdownNotebook__component-form">+ {hasId ? (+ <RealNotebookNodeAttributeField+ node={node}+ updateProps={updateProps}+ notebookNodeType={notebookNodeType}+ attributeKey="id"+ value={attributes.id}+ autoFocus={wasNotebookNodeJustInserted(node.id)}+ />+ ) : null}+ {options.views ? (+ <RealNotebookNodeViewSelect node={node} updateProps={updateProps} options={options} />+ ) : null}+ </div>+ )+}+function RealNotebookNodeViewSelect({node,updateProps,@@ -623,7 +722,7 @@ export function RealNotebookNodeComponent({editOnly = false,}: NotebookComponentRenderProps & { forceEditing?: boolean; editOnly?: boolean }): JSX.Element {const notebookNodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[node.tagName]- const options = notebookNodeType ? KNOWN_NODES[notebookNodeType] : null+ const options = getMarkdownNodeOptions(node.tagName)if (!options || !notebookNodeType) {return <div className="MarkdownNotebook__component-preview">Unsupported notebook node.</div>diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.tsindex aed5b450dd32..46a0fc52a7c8 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts@@ -254,6 +254,29 @@ Dashboard 123<Query query={{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"select event from events limit 1"}}} />`)})+ it.each([+ [NotebookNodeType.Dashboard, 'Dashboard'],+ [NotebookNodeType.Action, 'Action'],+ [NotebookNodeType.Workflow, 'Workflow'],+ [NotebookNodeType.ErrorTrackingIssue, 'ErrorTrackingIssue'],+ ])('converts the %s widget node to its markdown component', (nodeType, tagName) => {+ expect(+ convertNotebookContentToMarkdown({+ type: 'doc',+ content: [{ type: nodeType, attrs: { id: 'resource-id' } }],+ })+ ).toEqual(`<${tagName} id="resource-id" />`)+ })++ it('converts query nodes with an insight ID to the Insight component', () => {+ expect(+ convertNotebookContentToMarkdown({+ type: 'doc',+ content: [{ type: NotebookNodeType.Query, attrs: { id: 'insight-id', view: 'summary' } }],+ })+ ).toEqual('<Insight id="insight-id" view="summary" />')+ })+it('keeps the stable id vector for markdown query blocks without nodeId props', () => {const markdown ='<Query query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"],"after":"-24h","limit":1}}} />'diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex 1addb9a6f315..0f4cb3e193b9 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -47,6 +47,9 @@ const MARKDOWN_NOTEBOOK_NODE_ID = 'markdown-notebook-v2'export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType, string>> = {[NotebookNodeType.Query]: 'Query',+ [NotebookNodeType.Dashboard]: 'Dashboard',+ [NotebookNodeType.Action]: 'Action',+ [NotebookNodeType.Workflow]: 'Workflow',[NotebookNodeType.Python]: 'Python',[NotebookNodeType.PythonV2]: 'PythonV2',[NotebookNodeType.DuckSQL]: 'DuckSQL',@@ -74,6 +77,7 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType[NotebookNodeType.TaskCreate]: 'TaskCreate',[NotebookNodeType.LLMTrace]: 'LLMTrace',[NotebookNodeType.Issues]: 'Issues',+ [NotebookNodeType.ErrorTrackingIssue]: 'ErrorTrackingIssue',[NotebookNodeType.UsageMetrics]: 'UsageMetrics',[NotebookNodeType.ZendeskTickets]: 'ZendeskTickets',[NotebookNodeType.RelatedGroups]: 'RelatedGroups',@@ -666,6 +670,15 @@ function serializeRichContentNode(return serializeLegacyQueryNode(node)}+ if (nodeType === NotebookNodeType.Query && typeof node.attrs?.id === 'string' && node.attrs.id) {+ return serializeNode({+ id: '',+ type: 'component',+ tagName: 'Insight',+ props: getSerializableAttrs(node.attrs),+ })+ }+if (nodeType === 'ph-link') {return serializeLegacyLinkNode(node, options)}diff --git a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsxindex de1940b08997..d1ebef58cfc1 100644--- a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx+++ b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx@@ -25,6 +25,9 @@ export const fromNodeTypeToLabel: Omit<[NotebookNodeType.Image]: 'Images',[NotebookNodeType.Person]: 'Persons',[NotebookNodeType.Query]: 'Queries',+ [NotebookNodeType.Dashboard]: 'Dashboards',+ [NotebookNodeType.Action]: 'Actions',+ [NotebookNodeType.Workflow]: 'Workflows',[NotebookNodeType.Python]: 'Python',[NotebookNodeType.PythonV2]: 'Python (v2)',[NotebookNodeType.DuckSQL]: 'SQL (DuckDB)',@@ -38,6 +41,7 @@ export const fromNodeTypeToLabel: Omit<[NotebookNodeType.TaskCreate]: 'Task suggestions',[NotebookNodeType.LLMTrace]: 'LLM traces',[NotebookNodeType.Issues]: 'Issues',+ [NotebookNodeType.ErrorTrackingIssue]: 'Error tracking issues',[NotebookNodeType.UsageMetrics]: 'Usage metrics',[NotebookNodeType.ZendeskTickets]: 'Zendesk tickets',[NotebookNodeType.RelatedGroups]: 'Related groups',diff --git a/frontend/src/scenes/notebooks/nodeIcons.tsx b/frontend/src/scenes/notebooks/nodeIcons.tsxindex a70b849d4da9..1434ec6fb4df 100644--- a/frontend/src/scenes/notebooks/nodeIcons.tsx+++ b/frontend/src/scenes/notebooks/nodeIcons.tsx@@ -30,6 +30,9 @@ import { NotebookNodeType } from './types'// back to the generic notebook icon at the consumer site.export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {[NotebookNodeType.Query]: <IconGraph />,+ [NotebookNodeType.Dashboard]: <IconPieChart />,+ [NotebookNodeType.Action]: <IconList />,+ [NotebookNodeType.Workflow]: <IconUserPaths />,[NotebookNodeType.HogQLSQL]: <IconBracketsChart />,[NotebookNodeType.DuckSQL]: <IconBracketsChart />,[NotebookNodeType.SQLV2]: <IconBracketsChart />,@@ -49,6 +52,7 @@ export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {[NotebookNodeType.Group]: <IconGroups />,[NotebookNodeType.GroupProperties]: <IconList />,[NotebookNodeType.Issues]: <IconWarning />,+ [NotebookNodeType.ErrorTrackingIssue]: <IconWarning />,[NotebookNodeType.LLMTrace]: <IconAI />,[NotebookNodeType.Map]: <IconMapPin />,[NotebookNodeType.RelatedGroups]: <IconGroups />,diff --git a/frontend/src/scenes/notebooks/notebookWidgetCatalog.ts b/frontend/src/scenes/notebooks/notebookWidgetCatalog.tsindex cb2a93abf80e..2be0097f2438 100644--- a/frontend/src/scenes/notebooks/notebookWidgetCatalog.ts+++ b/frontend/src/scenes/notebooks/notebookWidgetCatalog.ts@@ -3,7 +3,22 @@ import notebookWidgetCatalog from 'products/notebooks/notebook-widget-catalog.jsimport { CustomNotebookNodeAttributes, NotebookNodeProps, PostHogWidgetDefaultView, PostHogWidgetViews } from './types'export type NotebookWidgetTagName = keyof typeof notebookWidgetCatalog.widgets-export type NotebookWidgetPickerKind = 'cohort' | 'early-access-feature' | 'experiment' | 'feature-flag' | 'survey'+export type NotebookWidgetPickerKind =+ | 'action'+ | 'cohort'+ | 'dashboard'+ | 'early-access-feature'+ | 'error-tracking-issue'+ | 'experiment'+ | 'feature-flag'+ | 'group'+ | 'insight'+ | 'llm-trace'+ | 'person'+ | 'recording'+ | 'recording-playlist'+ | 'survey'+ | 'workflow'type NotebookWidgetViewName<TTagName extends NotebookWidgetTagName> =keyof (typeof notebookWidgetCatalog.widgets)[TTagName]['views']diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex 0c5542aa22ae..f7ea65d558fe 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -38,6 +38,9 @@ export enum NotebookNodeType {Mention = RichContentNodeType.Mention,MarkdownNotebook = 'ph-markdown-notebook',Query = 'ph-query',+ Dashboard = 'ph-dashboard-widget',+ Action = 'ph-action',+ Workflow = 'ph-workflow',Python = 'ph-python',// The revamped Python cell: runs in the notebook's sandbox kernel via the SQLV2 run// path, unlike the legacy ph-python node's in-browser kernel.@@ -67,6 +70,7 @@ export enum NotebookNodeType {TaskCreate = 'ph-task-create',LLMTrace = 'ph-llm-trace',Issues = 'ph-issues',+ ErrorTrackingIssue = 'ph-error-tracking-issue',UsageMetrics = 'ph-usage-metrics',ZendeskTickets = 'ph-zendesk-tickets',RelatedGroups = 'ph-related-groups',diff --git a/products/actions/frontend/actionNotebookWidgetViews.tsx b/products/actions/frontend/actionNotebookWidgetViews.tsxnew file mode 100644index 000000000000..329ba3eb3337--- /dev/null+++ b/products/actions/frontend/actionNotebookWidgetViews.tsx@@ -0,0 +1,114 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { LemonTag } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { defineNotebookWidgetViews } from 'scenes/notebooks/notebookWidgetCatalog'+import { NotebookNodeProps } from 'scenes/notebooks/types'++import { actionLogic } from './logics/actionLogic'+import { ActionEdit } from './pages/ActionEdit'+import { ActionStepConditions } from './utils/actionStepDescription'++export type ActionNotebookWidgetAttributes = {+ id: number+ view?: string+}++function ActionMetadata({ attributes }: NotebookNodeProps<ActionNotebookWidgetAttributes>): null {+ const { action } = useValues(actionLogic({ id: attributes.id }))+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(action?.name || 'Action')+ }, [action?.name, setTitlePlaceholder])++ return null+}++function ActionLoading(): JSX.Element {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+}++function ActionSummary({ attributes }: NotebookNodeProps<ActionNotebookWidgetAttributes>): JSX.Element {+ const { action, actionLoading } = useValues(actionLogic({ id: attributes.id }))++ if (!action && actionLoading) {+ return <ActionLoading />+ }+ if (!action) {+ return <NotFound object="action" />+ }++ const stepCount = action.steps?.length || 0++ return (+ <>+ <ActionMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-wrap items-center gap-2 p-3">+ <span className="min-w-48 flex-1 truncate">{action.description || 'No description'}</span>+ <LemonTag type="muted">+ {stepCount} {stepCount === 1 ? 'step' : 'steps'}+ </LemonTag>+ </div>+ </>+ )+}++export function ActionDetail({ attributes }: NotebookNodeProps<ActionNotebookWidgetAttributes>): JSX.Element {+ const { action, actionLoading } = useValues(actionLogic({ id: attributes.id }))++ if (!action && actionLoading) {+ return <ActionLoading />+ }+ if (!action) {+ return <NotFound object="action" />+ }++ return (+ <BindLogic logic={actionLogic} props={{ id: attributes.id }}>+ <ActionMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-col gap-3 p-3">+ {action.description ? <p className="text-secondary">{action.description}</p> : null}+ {action.steps?.length ? (+ action.steps.map((step, index) => (+ <div className="rounded border p-3" key={index}>+ <ActionStepConditions step={step} />+ </div>+ ))+ ) : (+ <span className="text-secondary">This action has no matching steps.</span>+ )}+ </div>+ </BindLogic>+ )+}++function ActionEditor({ attributes }: NotebookNodeProps<ActionNotebookWidgetAttributes>): JSX.Element {+ const logic = actionLogic({ id: attributes.id })+ const { action, actionLoading } = useValues(logic)++ return (+ <BindLogic logic={actionLogic} props={{ id: attributes.id }}>+ <ActionMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="max-h-[48rem] overflow-auto p-3">+ <ActionEdit id={attributes.id} action={action} actionLoading={actionLoading} attachTo={logic} />+ </div>+ </BindLogic>+ )+}++export const ACTION_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<ActionNotebookWidgetAttributes, 'Action'>(+ 'Action',+ {+ summary: ActionSummary,+ editor: ActionEditor,+ }+)diff --git a/products/dashboards/frontend/dashboardNotebookWidgetViews.tsx b/products/dashboards/frontend/dashboardNotebookWidgetViews.tsxnew file mode 100644index 000000000000..8a44be6ce28e--- /dev/null+++ b/products/dashboards/frontend/dashboardNotebookWidgetViews.tsx@@ -0,0 +1,80 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { LemonTag } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { Dashboard } from 'scenes/dashboard/Dashboard'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { defineNotebookWidgetViews } from 'scenes/notebooks/notebookWidgetCatalog'+import { NotebookNodeProps } from 'scenes/notebooks/types'++import { DashboardPlacement } from '~/types'++export type DashboardNotebookWidgetAttributes = {+ id: number+ view?: string+}++function DashboardMetadata({ attributes }: NotebookNodeProps<DashboardNotebookWidgetAttributes>): null {+ const { dashboard } = useValues(dashboardLogic({ id: attributes.id, placement: DashboardPlacement.Builtin }))+ const { setTitlePlaceholder } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(dashboard?.name || 'Dashboard')+ }, [dashboard?.name, setTitlePlaceholder])++ return null+}++function DashboardSummary({ attributes }: NotebookNodeProps<DashboardNotebookWidgetAttributes>): JSX.Element {+ const { dashboard, itemsLoading, tiles } = useValues(+ dashboardLogic({ id: attributes.id, placement: DashboardPlacement.Builtin })+ )++ if (!dashboard && itemsLoading) {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+ }+ if (!dashboard) {+ return <NotFound object="dashboard" />+ }++ const insightCount = tiles?.length || 0++ return (+ <>+ <DashboardMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-wrap items-center gap-2 p-3">+ <span className="min-w-48 flex-1 truncate">{dashboard.description || 'No description'}</span>+ {dashboard.is_shared ? <LemonTag type="muted">Shared</LemonTag> : null}+ <span className="text-xs text-secondary">+ {insightCount} {insightCount === 1 ? 'insight' : 'insights'}+ </span>+ </div>+ </>+ )+}++export function DashboardDetail({ attributes }: NotebookNodeProps<DashboardNotebookWidgetAttributes>): JSX.Element {+ return (+ <>+ <DashboardMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="max-h-[48rem] overflow-auto">+ <Dashboard id={String(attributes.id)} placement={DashboardPlacement.Builtin} />+ </div>+ </>+ )+}++export const DASHBOARD_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<+ DashboardNotebookWidgetAttributes,+ 'Dashboard'+>('Dashboard', {+ summary: DashboardSummary,+})diff --git a/products/error_tracking/frontend/errorTrackingIssueNotebookWidgetViews.tsx b/products/error_tracking/frontend/errorTrackingIssueNotebookWidgetViews.tsxnew file mode 100644index 000000000000..6c5f644260a0--- /dev/null+++ b/products/error_tracking/frontend/errorTrackingIssueNotebookWidgetViews.tsx@@ -0,0 +1,154 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { NotFound } from 'lib/components/NotFound'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { compactNumber } from 'lib/utils/numbers'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { defineNotebookWidgetViews } from 'scenes/notebooks/notebookWidgetCatalog'+import { NotebookNodeProps } from 'scenes/notebooks/types'++import { eventsSourceLogic } from './components/EventsTable/eventsSourceLogic'+import { EventsTable } from './components/EventsTable/EventsTable'+import { ExceptionCard } from './components/ExceptionCard'+import { errorTrackingIssueSceneLogic } from './scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'++export type ErrorTrackingIssueNotebookWidgetAttributes = {+ id: string+ view?: string+}++function ErrorTrackingIssueMetadata({+ attributes,+}: NotebookNodeProps<ErrorTrackingIssueNotebookWidgetAttributes>): null {+ const { issue } = useValues(errorTrackingIssueSceneLogic({ id: attributes.id }))+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(issue?.name || issue?.description || 'Error tracking issue')+ setTitleStatus(+ issue?.status+ ? {+ label: capitalizeFirstLetter(issue.status.replaceAll('_', ' ')),+ type: issue.status === 'resolved' ? 'success' : issue.status === 'active' ? 'danger' : 'default',+ }+ : null+ )+ }, [issue, setTitlePlaceholder, setTitleStatus])++ return null+}++function ErrorTrackingIssueLoading(): JSX.Element {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+}++function ErrorTrackingIssueSummary({+ attributes,+}: NotebookNodeProps<ErrorTrackingIssueNotebookWidgetAttributes>): JSX.Element {+ const logic = errorTrackingIssueSceneLogic({ id: attributes.id })+ const { aggregations, firstSeen, issue, issueLoading } = useValues(logic)++ if (!issue && issueLoading) {+ return <ErrorTrackingIssueLoading />+ }+ if (!issue) {+ return <NotFound object="error tracking issue" />+ }++ return (+ <BindLogic logic={errorTrackingIssueSceneLogic} props={{ id: attributes.id }}>+ <ErrorTrackingIssueMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 p-3 text-sm">+ {firstSeen ? (+ <span>+ <span className="text-secondary">First seen: </span>+ <TZLabel time={firstSeen} />+ </span>+ ) : null}+ <span>{compactNumber(aggregations?.occurrences || 0)} occurrences</span>+ <span>{compactNumber(aggregations?.users || 0)} users</span>+ </div>+ </BindLogic>+ )+}++export function ErrorTrackingIssueDetail({+ attributes,+}: NotebookNodeProps<ErrorTrackingIssueNotebookWidgetAttributes>): JSX.Element {+ const logic = errorTrackingIssueSceneLogic({ id: attributes.id })+ const { initialEvent, initialEventLoading, issue, issueLoading, selectedEvent } = useValues(logic)++ if (!issue && !issueLoading) {+ return <NotFound object="error tracking issue" />+ }++ return (+ <BindLogic logic={errorTrackingIssueSceneLogic} props={{ id: attributes.id }}>+ <ErrorTrackingIssueMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="min-h-96 p-3">+ <ExceptionCard+ issueId={attributes.id}+ issueName={issue?.name || null}+ event={selectedEvent || initialEvent || undefined}+ loading={issueLoading || initialEventLoading}+ />+ </div>+ </BindLogic>+ )+}++function ErrorTrackingIssueActivity({+ attributes,+}: NotebookNodeProps<ErrorTrackingIssueNotebookWidgetAttributes>): JSX.Element {+ const logic = errorTrackingIssueSceneLogic({ id: attributes.id })+ const { issue, issueLoading } = useValues(logic)++ if (!issue && !issueLoading) {+ return <NotFound object="error tracking issue" />+ }++ return (+ <BindLogic logic={errorTrackingIssueSceneLogic} props={{ id: attributes.id }}>+ <ErrorTrackingIssueMetadata attributes={attributes} updateAttributes={() => {}} />+ <ErrorTrackingIssueActivityTable />+ </BindLogic>+ )+}++function ErrorTrackingIssueActivityTable(): JSX.Element {+ const { eventsQuery, eventsQueryKey, selectedEvent, summary } = useValues(errorTrackingIssueSceneLogic)+ const { selectEvent } = useActions(errorTrackingIssueSceneLogic)+ const dataSource = eventsSourceLogic({ query: eventsQuery, queryKey: eventsQueryKey })+ const { items, itemsLoading, canLoadNextData } = useValues(dataSource)+ const { loadNextData } = useActions(dataSource)++ return (+ <div className="h-96 overflow-auto p-3">+ <EventsTable+ items={items}+ loading={itemsLoading}+ hasMore={canLoadNextData}+ selectedEvent={selectedEvent}+ firstEventUuid={summary?.first_event_uuid}+ lastEventUuid={summary?.last_event_uuid}+ onEventSelect={selectEvent}+ onLoadMore={loadNextData}+ />+ </div>+ )+}++export const ERROR_TRACKING_ISSUE_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<+ ErrorTrackingIssueNotebookWidgetAttributes,+ 'ErrorTrackingIssue'+>('ErrorTrackingIssue', {+ summary: ErrorTrackingIssueSummary,+ activity: ErrorTrackingIssueActivity,+})diff --git a/products/notebooks/backend/facade/widget_catalog.py b/products/notebooks/backend/facade/widget_catalog.pyindex 660ceb1b818a..2b055b2dca22 100644--- a/products/notebooks/backend/facade/widget_catalog.py+++ b/products/notebooks/backend/facade/widget_catalog.py@@ -11,6 +11,11 @@ class NotebookWidgetViewDefinition(BaseModel):description: str+class NotebookWidgetPropDefinition(BaseModel):+ description: str+ example: str | int++class NotebookWidgetDefinition(BaseModel):model_config = ConfigDict(populate_by_name=True)@@ -21,6 +26,7 @@ class NotebookWidgetDefinition(BaseModel):id_description: str = Field(alias="idDescription")id_example: str | int = Field(alias="idExample")picker: str+ extra_props: dict[str, NotebookWidgetPropDefinition] = Field(default_factory=dict, alias="extraProps")default_view: NotebookWidgetViewDefinition = Field(alias="defaultView")views: dict[str, NotebookWidgetViewDefinition]@@ -44,14 +50,20 @@ def format_notebook_widget_catalog_for_agents() -> str:default_view_name = widget.default_view.name or "detail"view_parts = [f"{default_view_name}: {widget.default_view.description}"]view_parts.extend(f"{view_name}: {view.description}" for view_name, view in widget.views.items())- example_props = {widget.id_prop: widget.id_example, "view": "summary"}- markdown_id = (- f"{{{widget.id_example}}}" if isinstance(widget.id_example, int) else json.dumps(widget.id_example)+ example_props = {widget.id_prop: widget.id_example}+ example_props.update({name: prop.example for name, prop in widget.extra_props.items()})+ example_props["view"] = "summary"+ markdown_props = " ".join(+ f"{name}={{{value}}}" if isinstance(value, int) else f"{name}={json.dumps(value)}"+ for name, value in example_props.items())- markdown_example = f'<{tag_name} {widget.id_prop}={markdown_id} view="summary" />'+ markdown_example = f"<{tag_name} {markdown_props} />"rich_text_example = json.dumps({"type": widget.node_type, "attrs": example_props}, separators=(",", ":"))+ identity = " ".join(+ [widget.id_description, *(f"{name}: {prop.description}" for name, prop in widget.extra_props.items())]+ )widget_lines.append(- f"- {tag_name}: {widget.description} Identity: {widget.id_description} "+ f"- {tag_name}: {widget.description} Identity: {identity} "f"Markdown: {markdown_example}. Rich text: {rich_text_example}. Views: {' '.join(view_parts)}")diff --git a/products/notebooks/backend/test/test_widget_catalog.py b/products/notebooks/backend/test/test_widget_catalog.pynew file mode 100644index 000000000000..f056ca2cadf0--- /dev/null+++ b/products/notebooks/backend/test/test_widget_catalog.py@@ -0,0 +1,40 @@+from products.notebooks.backend.facade.widget_catalog import (+ format_notebook_widget_catalog_for_agents,+ get_notebook_widget_catalog,+)+++def test_widget_catalog_exports_every_supported_product_view() -> None:+ catalog = get_notebook_widget_catalog()+ expected_views = {+ "FeatureFlag": {"summary", "detail", "editor", "conditions", "implementation"},+ "Survey": {"summary", "detail", "preview", "conditions", "results"},+ "Experiment": {"summary", "detail", "results"},+ "EarlyAccessFeature": {"summary", "detail"},+ "Cohort": {"summary", "detail"},+ "Insight": {"summary", "detail", "editor", "results"},+ "Recording": {"summary", "detail"},+ "RecordingPlaylist": {"summary", "detail", "conditions"},+ "Person": {"summary", "detail", "activity"},+ "Group": {"summary", "detail", "activity"},+ "ErrorTrackingIssue": {"summary", "detail", "activity"},+ "LLMTrace": {"summary", "detail", "activity"},+ "Dashboard": {"summary", "detail"},+ "Action": {"summary", "detail", "editor"},+ "Workflow": {"summary", "detail", "editor", "results"},+ }++ actual_views = {+ tag_name: {widget.default_view.name or "detail", *widget.views.keys()}+ for tag_name, widget in catalog.widgets.items()+ }++ assert actual_views == expected_views+++def test_widget_catalog_prompt_includes_compound_identity_props() -> None:+ prompt = format_notebook_widget_catalog_for_agents()++ assert '<Group id="group-key" groupTypeIndex={0} view="summary" />' in prompt+ assert '"attrs":{"id":"group-key","groupTypeIndex":0,"view":"summary"}' in prompt+ assert "groupTypeIndex: Numeric group type index." in promptdiff --git a/products/notebooks/notebook-widget-catalog.json b/products/notebooks/notebook-widget-catalog.jsonindex 6fb581c52a0a..dbd0d851a4a8 100644--- a/products/notebooks/notebook-widget-catalog.json+++ b/products/notebooks/notebook-widget-catalog.json@@ -137,6 +137,252 @@"description": "Show the cohort name, size, and type."}}+ },+ "Insight": {+ "label": "Insight",+ "description": "Saved insight visualization, configuration, and query results.",+ "nodeType": "ph-query",+ "idProp": "id",+ "idDescription": "Insight short ID.",+ "idExample": "insight-id",+ "picker": "insight",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the saved insight visualization."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the insight name, description, and type."+ },+ "editor": {+ "label": "Editor",+ "description": "Edit the insight query and visualization settings."+ },+ "results": {+ "label": "Results",+ "description": "Show the insight visualization and query results."+ }+ }+ },+ "Recording": {+ "label": "Session recording",+ "description": "Session recording playback and session context.",+ "nodeType": "ph-recording",+ "idProp": "id",+ "idDescription": "Session recording ID.",+ "idExample": "recording-id",+ "picker": "recording",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the session recording player."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show a compact session recording preview."+ }+ }+ },+ "RecordingPlaylist": {+ "label": "Recording playlist",+ "description": "Saved recording playlist, matching recordings, and filter conditions.",+ "nodeType": "ph-recording-playlist",+ "idProp": "id",+ "idDescription": "Recording playlist short ID.",+ "idExample": "playlist-id",+ "picker": "recording-playlist",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show recordings that belong to the playlist."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the playlist name, type, and recording count."+ },+ "conditions": {+ "label": "Conditions",+ "description": "Show the filters that define the playlist."+ }+ }+ },+ "Person": {+ "label": "Person",+ "description": "Person properties, account context, and recent activity.",+ "nodeType": "ph-person",+ "idProp": "id",+ "idDescription": "Person UUID.",+ "idExample": "person-uuid",+ "picker": "person",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show person properties and account context."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the person's display name and identifying properties."+ },+ "activity": {+ "label": "Activity",+ "description": "Show the person's recent events."+ }+ }+ },+ "Group": {+ "label": "Group",+ "description": "Group properties, account context, and recent activity.",+ "nodeType": "ph-group",+ "idProp": "id",+ "idDescription": "Group key.",+ "idExample": "group-key",+ "picker": "group",+ "extraProps": {+ "groupTypeIndex": {+ "description": "Numeric group type index.",+ "example": 0+ }+ },+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show group properties and account context."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the group name, key, and type."+ },+ "activity": {+ "label": "Activity",+ "description": "Show the group's recent events."+ }+ }+ },+ "ErrorTrackingIssue": {+ "label": "Error tracking issue",+ "description": "Error tracking issue status, exception details, and occurrences.",+ "nodeType": "ph-error-tracking-issue",+ "idProp": "id",+ "idDescription": "Error tracking issue ID.",+ "idExample": "issue-id",+ "picker": "error-tracking-issue",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the latest exception details."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the issue status, first seen time, and occurrence count."+ },+ "activity": {+ "label": "Activity",+ "description": "Show recent exceptions grouped into this issue."+ }+ }+ },+ "LLMTrace": {+ "label": "LLM trace",+ "description": "LLM trace usage, latency, cost, and chronological operations.",+ "nodeType": "ph-llm-trace",+ "idProp": "id",+ "idDescription": "LLM trace ID.",+ "idExample": "trace-id",+ "picker": "llm-trace",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show expanded trace operations and content."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show trace usage, latency, cost, and errors."+ },+ "activity": {+ "label": "Activity",+ "description": "Show the chronological trace operations."+ }+ }+ },+ "Dashboard": {+ "label": "Dashboard",+ "description": "Dashboard description, insights, and current results.",+ "nodeType": "ph-dashboard-widget",+ "idProp": "id",+ "idDescription": "Dashboard numeric ID.",+ "idExample": 123,+ "picker": "dashboard",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the dashboard and its insight results."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the dashboard description and insight count."+ }+ }+ },+ "Action": {+ "label": "Action",+ "description": "Action definition, matching steps, and editor.",+ "nodeType": "ph-action",+ "idProp": "id",+ "idDescription": "Action numeric ID.",+ "idExample": 123,+ "picker": "action",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the action definition and matching conditions."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the action name, description, and step count."+ },+ "editor": {+ "label": "Editor",+ "description": "Edit the action definition in the notebook."+ }+ }+ },+ "Workflow": {+ "label": "Workflow",+ "description": "Workflow status, steps, editor, and run results.",+ "nodeType": "ph-workflow",+ "idProp": "id",+ "idDescription": "Workflow ID.",+ "idExample": "workflow-id",+ "picker": "workflow",+ "defaultView": {+ "name": "detail",+ "label": "Detail",+ "description": "Show the workflow steps and trigger."+ },+ "views": {+ "summary": {+ "label": "Summary",+ "description": "Show the workflow status, trigger, and step count."+ },+ "editor": {+ "label": "Editor",+ "description": "Edit the workflow in the notebook."+ },+ "results": {+ "label": "Results",+ "description": "Show workflow runs and outcomes."+ }+ }}}}diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsxindex cb4ee9bc7edb..6d845067b038 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx@@ -9,6 +9,7 @@ import {Panel,ReactFlow,ReactFlowProvider,+ useNodesInitialized,useReactFlow,} from '@xyflow/react'import { BindLogic, useActions, useValues } from 'kea'@@ -43,10 +44,12 @@ function HogFlowEditorContent(): JSX.Element {setReactFlowWrapper,handlePaneClick,setIsZoomedOutFar,+ fitView,} = useActions(hogFlowEditorLogic)const reactFlowWrapper = useRef<HTMLDivElement>(null)const reactFlowInstance = useReactFlow()+ const nodesInitialized = useNodesInitialized()useEffect(() => {setReactFlowInstance(reactFlowInstance)@@ -56,6 +59,12 @@ function HogFlowEditorContent(): JSX.Element {setReactFlowWrapper(reactFlowWrapper)}, [setReactFlowWrapper])+ useEffect(() => {+ if (nodesInitialized) {+ fitView({ duration: 0 })+ }+ }, [fitView, nodesInitialized])+// ReactFlow diffs its nodes prop by reference: an inline spread would hand it a fresh array// every render, making every render look like a graph change.const nodesWithDropzones = useMemo(diff --git a/products/workflows/frontend/workflowNotebookWidgetViews.tsx b/products/workflows/frontend/workflowNotebookWidgetViews.tsxnew file mode 100644index 000000000000..cbfa31a5ea08--- /dev/null+++ b/products/workflows/frontend/workflowNotebookWidgetViews.tsx@@ -0,0 +1,137 @@+import { BindLogic, useActions, useValues } from 'kea'+import { lazy, Suspense, useEffect } from 'react'++import { LemonTag } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { defineNotebookWidgetViews } from 'scenes/notebooks/notebookWidgetCatalog'+import { NotebookNodeProps } from 'scenes/notebooks/types'++import { WorkflowInvocations } from './Workflows/WorkflowInvocations'+import { workflowLogic } from './Workflows/workflowLogic'++const Workflow = lazy(() => import('./Workflows/Workflow').then((module) => ({ default: module.Workflow })))++export type WorkflowNotebookWidgetAttributes = {+ id: string+ view?: string+}++function WorkflowMetadata({ attributes }: NotebookNodeProps<WorkflowNotebookWidgetAttributes>): null {+ const { originalWorkflow } = useValues(workflowLogic({ id: attributes.id }))+ const { setTitlePlaceholder, setTitleStatus } = useActions(notebookNodeLogic)++ useEffect(() => {+ setTitlePlaceholder(originalWorkflow?.name || 'Workflow')+ setTitleStatus(+ originalWorkflow?.status+ ? {+ label: capitalizeFirstLetter(originalWorkflow.status),+ type: originalWorkflow.status === 'active' ? 'success' : 'default',+ }+ : null+ )+ }, [originalWorkflow?.name, originalWorkflow?.status, setTitlePlaceholder, setTitleStatus])++ return null+}++function WorkflowLoading(): JSX.Element {+ return (+ <div className="p-3">+ <LemonSkeleton className="h-6 w-full" />+ </div>+ )+}++function WorkflowSummary({ attributes }: NotebookNodeProps<WorkflowNotebookWidgetAttributes>): JSX.Element {+ const { originalWorkflow, originalWorkflowLoading } = useValues(workflowLogic({ id: attributes.id }))++ if (!originalWorkflow && originalWorkflowLoading) {+ return <WorkflowLoading />+ }+ if (!originalWorkflow) {+ return <NotFound object="workflow" />+ }++ const actionCount = originalWorkflow.actions.filter(+ (action) => action.type !== 'trigger' && action.type !== 'exit'+ ).length+ const trigger = originalWorkflow.actions.find((action) => action.type === 'trigger')++ return (+ <>+ <WorkflowMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-wrap items-center gap-2 p-3">+ <span className="min-w-48 flex-1 truncate">{originalWorkflow.description || trigger?.description}</span>+ <LemonTag type="muted">+ {actionCount} {actionCount === 1 ? 'step' : 'steps'}+ </LemonTag>+ </div>+ </>+ )+}++export function WorkflowDetail({ attributes }: NotebookNodeProps<WorkflowNotebookWidgetAttributes>): JSX.Element {+ const { originalWorkflow, originalWorkflowLoading } = useValues(workflowLogic({ id: attributes.id }))++ if (!originalWorkflow && originalWorkflowLoading) {+ return <WorkflowLoading />+ }+ if (!originalWorkflow) {+ return <NotFound object="workflow" />+ }++ return (+ <BindLogic logic={workflowLogic} props={{ id: attributes.id }}>+ <WorkflowMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex flex-col gap-2 p-3">+ {originalWorkflow.actions.map((action, index) => (+ <div className="flex items-start gap-3 rounded border p-3" key={action.id}>+ <span className="text-secondary">{index + 1}</span>+ <div className="min-w-0">+ <div className="font-medium">{action.name}</div>+ <div className="text-sm text-secondary">{action.description}</div>+ </div>+ </div>+ ))}+ </div>+ </BindLogic>+ )+}++function WorkflowEditor({ attributes }: NotebookNodeProps<WorkflowNotebookWidgetAttributes>): JSX.Element {+ return (+ <BindLogic logic={workflowLogic} props={{ id: attributes.id }}>+ <WorkflowMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="flex h-[40rem] p-3">+ <Suspense fallback={<WorkflowLoading />}>+ <Workflow id={attributes.id} />+ </Suspense>+ </div>+ </BindLogic>+ )+}++function WorkflowResults({ attributes }: NotebookNodeProps<WorkflowNotebookWidgetAttributes>): JSX.Element {+ return (+ <BindLogic logic={workflowLogic} props={{ id: attributes.id }}>+ <WorkflowMetadata attributes={attributes} updateAttributes={() => {}} />+ <div className="max-h-[40rem] overflow-auto p-3">+ <WorkflowInvocations id={attributes.id} />+ </div>+ </BindLogic>+ )+}++export const WORKFLOW_NOTEBOOK_WIDGET_VIEWS = defineNotebookWidgetViews<WorkflowNotebookWidgetAttributes, 'Workflow'>(+ 'Workflow',+ {+ summary: WorkflowSummary,+ editor: WorkflowEditor,+ results: WorkflowResults,+ }+)diff --git a/services/mcp/src/tools/notebooks/widgetCatalog.ts b/services/mcp/src/tools/notebooks/widgetCatalog.tsindex 1fffe7d06215..81bc6221cdb5 100644--- a/services/mcp/src/tools/notebooks/widgetCatalog.ts+++ b/services/mcp/src/tools/notebooks/widgetCatalog.ts@@ -1,6 +1,7 @@import notebookWidgetCatalog from 'products/notebooks/notebook-widget-catalog.json'type NotebookWidgetTagName = keyof typeof notebookWidgetCatalog.widgets+type NotebookWidgetExtraProps = Record<string, { description: string; example: string | number }>export function getNotebookWidgetTagNames(): NotebookWidgetTagName[] {return Object.keys(notebookWidgetCatalog.widgets) as NotebookWidgetTagName[]@@ -32,16 +33,23 @@ export function formatNotebookWidgetCatalogForAgents(): string {const views = [widget.defaultView, ...Object.entries(widget.views).map(([name, view]) => ({ name, ...view }))].map((view) => `${view.name}: ${view.description}`).join(' ')- const exampleProps = {+ const extraProps = (widget as { extraProps?: NotebookWidgetExtraProps }).extraProps ?? {}+ const exampleProps: Record<string, string | number> = {[widget.idProp]: widget.idExample,+ ...Object.fromEntries(Object.entries(extraProps).map(([name, prop]) => [name, prop.example])),view: 'summary',}- const markdownId =- typeof widget.idExample === 'number' ? `{${widget.idExample}}` : JSON.stringify(widget.idExample)- const markdownExample = `<${tagName} ${widget.idProp}=${markdownId} view="summary" />`+ const markdownProps = Object.entries(exampleProps)+ .map(([name, value]) => `${name}=${typeof value === 'number' ? `{${value}}` : JSON.stringify(value)}`)+ .join(' ')+ const markdownExample = `<${tagName} ${markdownProps} />`const richTextExample = JSON.stringify({ type: widget.nodeType, attrs: exampleProps })+ const identity = [+ widget.idDescription,+ ...Object.entries(extraProps).map(([name, prop]) => `${name}: ${prop.description}`),+ ].join(' ')- return `- ${tagName}: ${widget.description} Identity: ${widget.idDescription} Markdown: ${markdownExample}. Rich text: ${richTextExample}. Views: ${views}`+ return `- ${tagName}: ${widget.description} Identity: ${identity} Markdown: ${markdownExample}. Rich text: ${richTextExample}. Views: ${views}`})return [diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex 29b6bb2b628d..5e66237b0d69 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -4,6 +4,7 @@ import { addCellHandler } from '@/tools/notebooks/addCell'import { createMarkdownHandler } from '@/tools/notebooks/createMarkdown'import { deleteCellHandler } from '@/tools/notebooks/deleteCell'import { updateCellHandler } from '@/tools/notebooks/updateCell'+import { formatNotebookWidgetCatalogForAgents } from '@/tools/notebooks/widgetCatalog'import { getToolDefinition } from '@/tools/toolDefinitions'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type Context } from '@/tools/types'@@ -104,6 +105,14 @@ describe('notebook cell tools', () => {}})+ it('describes compound widget identity to notebook-building agents', () => {+ const catalogPrompt = formatNotebookWidgetCatalogForAgents()++ expect(catalogPrompt).toContain('<Group id="group-key" groupTypeIndex={0} view="summary" />')+ expect(catalogPrompt).toContain('"attrs":{"id":"group-key","groupTypeIndex":0,"view":"summary"}')+ expect(catalogPrompt).toContain('groupTypeIndex: Numeric group type index.')+ })+it('add sql cell inserts the tag, runs with sibling refs, and writes the result back', async () => {const state = makeState('# Doc\n\n<SQLV2 nodeId="up" code="select 1" returnVariable="events_df" />\n')state.runStatusResponses.push(DONE_STATUS)