Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: add notebook sharing MVP (#57498)

Reece Jonese396c5138c4d
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.ts
index 5b6e5bcf9564..94dc05a1ef97 100644
--- a/frontend/jest.setup.ts
+++ b/frontend/jest.setup.ts
@@ -83,6 +83,14 @@ if (typeof Element.prototype.scrollIntoView !== 'function') {
Element.prototype.scrollIntoView = () => {}
}
+// maplibre-gl probes window.URL.createObjectURL at module-eval time, but jsdom
+// doesn't implement it. Provide a noop so importing modules that transitively
+// pull in maplibre-gl (e.g. NotebookNodeMap) doesn't throw.
+if (typeof window !== 'undefined' && typeof window.URL.createObjectURL !== 'function') {
+ window.URL.createObjectURL = () => ''
+ window.URL.revokeObjectURL = () => {}
+}
+
// we use CSS.escape in the toolbar, but Jest/JSDom doesn't support it
if (typeof (globalThis as any).CSS === 'undefined') {
;(globalThis as any).CSS = {}
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index 1e4f1c3aa815..efede9ef06cb 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -15,6 +15,7 @@ import { Link } from 'lib/lemon-ui/Link'
import { humanFriendlyDuration } from 'lib/utils'
import { Dashboard } from 'scenes/dashboard/Dashboard'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { Notebook } from 'scenes/notebooks/Notebook/Notebook'
import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -126,7 +127,19 @@ function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): J
export function Exporter(props: ExportedData): JSX.Element {
// NOTE: Mounting the logic is important as it is used by sub-logics
- const { type, dashboard, insight, recording, themes, accessToken, exportToken, ...exportOptions } = props
+ const {
+ type,
+ dashboard,
+ insight,
+ recording,
+ notebook,
+ insights,
+ inline_query_results: inlineQueryResults,
+ themes,
+ accessToken,
+ exportToken,
+ ...exportOptions
+ } = props
const { whitelabel, showInspector = false } = exportOptions
const forcedTheme = resolveForcedTheme(exportOptions.theme)
@@ -148,8 +161,11 @@ export function Exporter(props: ExportedData): JSX.Element {
} else if (insight && (type === ExportType.Scene || type === ExportType.Embed)) {
const baseTitle = insight.name || insight.derived_name || 'Insight'
document.title = whitelabel ? baseTitle : `${baseTitle} • PostHog`
+ } else if (notebook && (type === ExportType.Scene || type === ExportType.Embed)) {
+ const baseTitle = notebook.title || 'Notebook'
+ document.title = whitelabel ? baseTitle : `${baseTitle} • PostHog`
}
- }, [dashboard, insight, type, whitelabel])
+ }, [dashboard, insight, notebook, type, whitelabel])
useThemedHtml(false, forcedTheme)
@@ -164,6 +180,7 @@ export function Exporter(props: ExportedData): JSX.Element {
'Exporter--insight': !!insight,
'Exporter--dashboard': !!dashboard,
'Exporter--recording': !!recording,
+ 'Exporter--notebook': !!notebook,
'Exporter--heatmap': type === ExportType.Heatmap,
})}
ref={elementRef}
@@ -206,7 +223,30 @@ export function Exporter(props: ExportedData): JSX.Element {
</>
) : null
) : null}
- {insight ? (
+ {notebook ? (
+ <div className="SharedNotebook">
+ {!whitelabel && type === ExportType.Scene && (
+ <div className="SharedDashboard-header">
+ <Link
+ to="https://posthog.com?utm_medium=in-product&utm_campaign=shared-notebook"
+ target="_blank"
+ >
+ <Logo className="text-lg" />
+ </Link>
+ <div className="SharedDashboard-header-team text-right">
+ <span className="block">{currentTeam?.name}</span>
+ </div>
+ </div>
+ )}
+ <Notebook
+ shortId={notebook.short_id}
+ editable={false}
+ cachedNotebook={notebook}
+ cachedInsightsByShortId={insights}
+ cachedInlineQueryResultsByNodeId={inlineQueryResults}
+ />
+ </div>
+ ) : insight ? (
<ExportedInsight insight={insight} themes={themes!} exportOptions={exportOptions} />
) : dashboard ? (
<>
diff --git a/frontend/src/exporter/types.ts b/frontend/src/exporter/types.ts
index 5840eec4beca..6d40502f41c3 100644
--- a/frontend/src/exporter/types.ts
+++ b/frontend/src/exporter/types.ts
@@ -1,6 +1,7 @@
+import { NotebookType } from 'scenes/notebooks/types'
import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
-import { SharingConfigurationSettings } from '~/queries/schema/schema-general'
+import { AnyResponseType, SharingConfigurationSettings } from '~/queries/schema/schema-general'
import {
CohortType,
DashboardType,
@@ -26,6 +27,20 @@ export interface ExportedData extends SharingConfigurationSettings {
insight?: InsightModel
themes?: DataColorThemeModel[]
recording?: SessionRecordingType
+ notebook?: NotebookType
+ /**
+ * Pre-serialized saved insights referenced by a shared notebook, keyed by `short_id`.
+ * Each entry already includes computed `result`/`last_refresh`/etc. so the frontend can seed
+ * `cachedInsight` + `cachedResults` and avoid POSTing to `/api/projects/.../query/` (which
+ * `SharingAccessTokenAuthentication` rejects).
+ */
+ insights?: Record<string, InsightModel>
+ /**
+ * Pre-computed results for inline (non-saved-insight) ph-query nodes in a shared notebook,
+ * keyed by node `nodeId`. Same rationale as `insights` — lets the shared viewer render
+ * `<Query cachedResults={…} />` without ever hitting the query API.
+ */
+ inline_query_results?: Record<string, AnyResponseType>
autoplay?: boolean
/** Player adds border by default - we want to remove it **/
noBorder?: boolean
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 530752ca2f02..8b1eaa9e532f 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -952,6 +952,22 @@ export class ApiRequest {
return this.dashboardsDetail(dashboardId, teamId).addPathComponent('sharing')
}
+ public notebookSharing(notebookShortId: NotebookType['short_id'], teamId?: TeamType['id']): ApiRequest {
+ return this.notebook(notebookShortId, teamId).addPathComponent('sharing')
+ }
+
+ public notebookSharingPasswords(notebookShortId: NotebookType['short_id'], teamId?: TeamType['id']): ApiRequest {
+ return this.notebookSharing(notebookShortId, teamId).addPathComponent('passwords')
+ }
+
+ public notebookSharingPassword(
+ notebookShortId: NotebookType['short_id'],
+ passwordId: string,
+ teamId?: TeamType['id']
+ ): ApiRequest {
+ return this.notebookSharingPasswords(notebookShortId, teamId).addPathComponent(passwordId)
+ }
+
public dashboardSharingPasswords(dashboardId: DashboardType['id'], teamId?: TeamType['id']): ApiRequest {
return this.dashboardSharing(dashboardId, teamId).addPathComponent('passwords')
}
@@ -3587,10 +3603,12 @@ const api = {
dashboardId,
insightId,
recordingId,
+ notebookShortId,
}: {
dashboardId?: DashboardType['id']
insightId?: QueryBasedInsightModel['id']
recordingId?: SessionRecordingType['id']
+ notebookShortId?: NotebookType['short_id']
}): Promise<SharingConfigurationType | null> {
return dashboardId
? new ApiRequest().dashboardSharing(dashboardId).get()
@@ -3598,7 +3616,9 @@ const api = {
? new ApiRequest().insightSharing(insightId).get()
: recordingId
? new ApiRequest().recordingSharing(recordingId).get()
- : null
+ : notebookShortId
+ ? new ApiRequest().notebookSharing(notebookShortId).get()
+ : null
},
async update(
@@ -3606,10 +3626,12 @@ const api = {
dashboardId,
insightId,
recordingId,
+ notebookShortId,
}: {
dashboardId?: DashboardType['id']
insightId?: QueryBasedInsightModel['id']
recordingId?: SessionRecordingType['id']
+ notebookShortId?: NotebookType['short_id']
},
data: Partial<SharingConfigurationType>
): Promise<SharingConfigurationType | null> {
@@ -3619,7 +3641,9 @@ const api = {
? new ApiRequest().insightSharing(insightId).update({ data })
: recordingId
? new ApiRequest().recordingSharing(recordingId).update({ data })
- : null
+ : notebookShortId
+ ? new ApiRequest().notebookSharing(notebookShortId).update({ data })
+ : null
},
async createPassword(
@@ -3627,10 +3651,12 @@ const api = {
dashboardId,
insightId,
recordingId,
+ notebookShortId,
}: {
dashboardId?: DashboardType['id']
insightId?: QueryBasedInsightModel['id']
recordingId?: SessionRecordingType['id']
+ notebookShortId?: NotebookType['short_id']
},
data: { raw_password?: string; note?: string }
): Promise<SharingConfigurationType | null> {
@@ -3640,7 +3666,9 @@ const api = {
? new ApiRequest().insightSharingPasswords(insightId).create({ data })
: recordingId
? new ApiRequest().recordingSharingPasswords(recordingId).create({ data })
- : null
+ : notebookShortId
+ ? new ApiRequest().notebookSharingPasswords(notebookShortId).create({ data })
+ : null
},
async deletePassword(
@@ -3648,10 +3676,12 @@ const api = {
dashboardId,
insightId,
recordingId,
+ notebookShortId,
}: {
dashboardId?: DashboardType['id']
insightId?: QueryBasedInsightModel['id']
recordingId?: SessionRecordingType['id']
+ notebookShortId?: NotebookType['short_id']
},
passwordId: string
): Promise<void> {
@@ -3661,7 +3691,9 @@ const api = {
? new ApiRequest().insightSharingPassword(insightId, passwordId).delete()
: recordingId
? new ApiRequest().recordingSharingPassword(recordingId, passwordId).delete()
- : null
+ : notebookShortId
+ ? new ApiRequest().notebookSharingPassword(notebookShortId, passwordId).delete()
+ : null
},
},
diff --git a/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx b/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
index c6cf8cf177a8..28509dcf56aa 100644
--- a/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
+++ b/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
@@ -14,6 +14,7 @@ interface SharePasswordsTableProps {
dashboardId?: number
insightId?: number
recordingId?: string
+ notebookShortId?: string
}
// Export a hook to get password count for the parent component
@@ -23,8 +24,13 @@ export function useSharePasswordCount(props: SharePasswordsTableProps): number {
return sharePasswords.length
}
-export function SharePasswordsTable({ dashboardId, insightId, recordingId }: SharePasswordsTableProps): JSX.Element {
- const logicProps = { dashboardId, insightId, recordingId }
+export function SharePasswordsTable({
+ dashboardId,
+ insightId,
+ recordingId,
+ notebookShortId,
+}: SharePasswordsTableProps): JSX.Element {
+ const logicProps = { dashboardId, insightId, recordingId, notebookShortId }
const logic = sharePasswordsLogic(logicProps)
const values = useValues(logic)
diff --git a/frontend/src/lib/components/Sharing/SharingModal.tsx b/frontend/src/lib/components/Sharing/SharingModal.tsx
index 6a3a6e64a8da..bac1abed2598 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.tsx
@@ -54,7 +54,8 @@ import { sharingLogic } from './sharingLogic'
function getResourceType(
dashboardId?: number,
insightShortId?: InsightShortId,
- recordingId?: string
+ recordingId?: string,
+ notebookShortId?: string
): AccessControlResourceType {
if (dashboardId) {
return AccessControlResourceType.Dashboard
@@ -65,6 +66,9 @@ function getResourceType(
if (recordingId) {
return AccessControlResourceType.SessionRecording
}
+ if (notebookShortId) {
+ return AccessControlResourceType.Notebook
+ }
return AccessControlResourceType.Project
}
@@ -76,6 +80,7 @@ export interface SharingModalBaseProps {
insight?: Partial<QueryBasedInsightModel>
cachedResults?: AnyResponseType
recordingId?: string
+ notebookShortId?: string
title?: string
previewIframe?: boolean
@@ -100,6 +105,7 @@ export function SharingModalContent({
insight,
cachedResults,
recordingId,
+ notebookShortId,
additionalParams,
previewIframe = false,
recordingLinkTimeForm = undefined,
@@ -109,6 +115,7 @@ export function SharingModalContent({
dashboardId,
insightShortId,
recordingId,
+ notebookShortId,
additionalParams,
}
const {
@@ -163,7 +170,15 @@ export function SharingModalContent({
})
: null
- const resource = dashboardId ? 'dashboard' : insightShortId ? 'insight' : recordingId ? 'recording' : 'this'
+ const resource = dashboardId
+ ? 'dashboard'
+ : insightShortId
+ ? 'insight'
+ : recordingId
+ ? 'recording'
+ : notebookShortId
+ ? 'notebook'
+ : 'this'
const hasEditAccess = userAccessLevel
? accessLevelSatisfied(resource as AccessControlResourceType, userAccessLevel, AccessControlLevel.Editor)
: true
@@ -210,7 +225,12 @@ export function SharingModalContent({
<LemonBanner type="warning">Public sharing is disabled for this organization.</LemonBanner>
) : (
<AccessControlAction
- resourceType={getResourceType(dashboardId, insightShortId, recordingId)}
+ resourceType={getResourceType(
+ dashboardId,
+ insightShortId,
+ recordingId,
+ notebookShortId
+ )}
minAccessLevel={AccessControlLevel.Editor}
userAccessLevel={userAccessLevel}
>
@@ -263,6 +283,7 @@ export function SharingModalContent({
dashboardId={dashboardId}
insightId={insight?.id}
recordingId={recordingId}
+ notebookShortId={notebookShortId}
/>
</div>
)}
diff --git a/frontend/src/lib/components/Sharing/sharePasswordsLogic.ts b/frontend/src/lib/components/Sharing/sharePasswordsLogic.ts
index 086f8e588508..5d7a7d2030b7 100644
--- a/frontend/src/lib/components/Sharing/sharePasswordsLogic.ts
+++ b/frontend/src/lib/components/Sharing/sharePasswordsLogic.ts
@@ -12,14 +12,15 @@ export interface SharePasswordsLogicProps {
dashboardId?: number
insightId?: number
recordingId?: string
+ notebookShortId?: string
}
export const sharePasswordsLogic = kea<sharePasswordsLogicType>([
path(['lib', 'components', 'Sharing', 'sharePasswordsLogic']),
props({} as SharePasswordsLogicProps),
key(
- ({ dashboardId, insightId, recordingId }) =>
- `${dashboardId || 'no-dashboard'}-${insightId || 'no-insight'}-${recordingId || 'no-recording'}`
+ ({ dashboardId, insightId, recordingId, notebookShortId }) =>
+ `${dashboardId || 'no-dashboard'}-${insightId || 'no-insight'}-${recordingId || 'no-recording'}-${notebookShortId || 'no-notebook'}`
),
actions({
@@ -41,6 +42,7 @@ export const sharePasswordsLogic = kea<sharePasswordsLogicType>([
dashboardId: props.dashboardId,
insightId: props.insightId,
recordingId: props.recordingId,
+ notebookShortId: props.notebookShortId,
})
return (response && (response as any).share_passwords) || []
},
@@ -81,6 +83,7 @@ export const sharePasswordsLogic = kea<sharePasswordsLogicType>([
dashboardId: props.dashboardId,
insightId: props.insightId,
recordingId: props.recordingId,
+ notebookShortId: props.notebookShortId,
},
{
raw_password: password,
@@ -113,6 +116,7 @@ export const sharePasswordsLogic = kea<sharePasswordsLogicType>([
dashboardId: props.dashboardId,
insightId: props.insightId,
recordingId: props.recordingId,
+ notebookShortId: props.notebookShortId,
},
passwordId
)
diff --git a/frontend/src/lib/components/Sharing/sharingLogic.ts b/frontend/src/lib/components/Sharing/sharingLogic.ts
index e233bd5a111a..53b8f411922c 100644
--- a/frontend/src/lib/components/Sharing/sharingLogic.ts
+++ b/frontend/src/lib/components/Sharing/sharingLogic.ts
@@ -19,6 +19,7 @@ export interface SharingLogicProps {
dashboardId?: number
insightShortId?: InsightShortId
recordingId?: string
+ notebookShortId?: string
additionalParams?: Record<string, any>
}
@@ -43,12 +44,18 @@ const defaultSharingSettings = {
const propsToApiParams = async (
props: SharingLogicProps
-): Promise<{ dashboardId?: number; insightId?: number; recordingId?: string }> => {
+): Promise<{
+ dashboardId?: number
+ insightId?: number
+ recordingId?: string
+ notebookShortId?: string
+}> => {
const insightId = props.insightShortId ? await getInsightId(props.insightShortId) : undefined
return {
dashboardId: props.dashboardId,
insightId,
recordingId: props.recordingId,
+ notebookShortId: props.notebookShortId,
}
}
@@ -56,8 +63,8 @@ export const sharingLogic = kea<sharingLogicType>([
path(['lib', 'components', 'Sharing', 'sharingLogic']),
props({} as SharingLogicProps),
key(
- ({ insightShortId, dashboardId, recordingId }) =>
- `sharing-${insightShortId || dashboardId || recordingId || ''}`
+ ({ insightShortId, dashboardId, recordingId, notebookShortId }) =>
+ `sharing-${insightShortId || dashboardId || recordingId || notebookShortId || ''}`
),
connect(() => [preflightLogic, userLogic, dashboardsModel, organizationLogic]),
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8bc1e8b5aebb..d84dc1c0ee8e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -375,6 +375,7 @@ export const FEATURE_FLAGS = {
NEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-ux
NEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analytics
NOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-tools
+ NOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-features
NOTEBOOKS_COLLABORATION: 'notebooks-collaboration', // owner: #team-platform-features
NOTEBOOKS_COLLAPSIBLE_SECTIONS: 'notebooks-collapsible-sections', // owner: @benjackwhite
ONBOARDING_DATA_WAREHOUSE_VALUE_PROP: 'onboarding-data-warehouse-value-prop', // owner: @fercgomes #team-growth multivariate=control,table,query
diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
index e425730f9be3..3cd4c427ee73 100644
--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
@@ -27,6 +27,7 @@ import {
useSyncedAttributes,
} from './utils'
import { KNOWN_NODES } from '../utils'
+import { SharedNodeErrorBoundary, UnsupportedNodePlaceholder, isNodeSupportedInSharedNotebook } from './sharedNodeSupport'
import { NotebookNodeTitle } from './components/NotebookNodeTitle'
import { DuckSqlRunMenu } from './components/DuckSqlRunMenu'
import { HogqlSqlRunMenu } from './components/HogqlSqlRunMenu'
@@ -71,7 +72,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP
} = props
const mountedNotebookLogic = useMountedLogic(notebookLogic)
- const { isEditable, editingNodeIds, containerSize, notebook, mode } = useValues(mountedNotebookLogic)
+ const { isEditable, editingNodeIds, containerSize, notebook, mode, isShared } = useValues(mountedNotebookLogic)
const { unregisterNodeLogic, insertComment, selectComment } = useActions(notebookLogic)
const [slashCommandsPopoverVisible, setSlashCommandsPopoverVisible] = useState<boolean>(false)
@@ -227,7 +228,9 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP
const hogqlSqlIsStale = hogqlSqlHasExecution && !hogqlSqlIsFresh
const defaultMenuItems: LemonMenuItems = [
- !NON_COPYABLE_NODES.includes(nodeType)
+ // Copy round-trips the node attrs through HTML for paste into another notebook — doesn't
+ // make sense for an anonymous shared viewer who has no editor to paste into.
+ !NON_COPYABLE_NODES.includes(nodeType) && !isShared
? {
label: 'Copy',
onClick: () => copyToClipboard(),
@@ -303,7 +306,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP
</div>
<div className="flex deprecated-space-x-1">
- {parsedHref && (
+ {parsedHref && !isShared && (
<LemonButton
size="small"
icon={<IconLink />}
@@ -381,6 +384,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP
</div>
{Settings &&
+ !isShared &&
editingNodeIds[nodeId] &&
(containerSize === 'small' || resolvedSettingsPlacement === 'inline') ? (
<div className="NotebookNode__settings">
@@ -476,6 +480,9 @@ export function createPostHogWidgetNode<T extends CustomNotebookNodeAttributes>(
// NOTE: We use NodeViewProps here as we convert them to NotebookNodeProps
const WrappedComponent = (props: NodeViewProps): JSX.Element => {
+ // Hooks must run unconditionally on every render — keep all hook calls above any early
+ // return so the shared-notebook placeholder fast-path doesn't violate the rules of hooks.
+ const { isShared } = useValues(notebookLogic)
const [attributes, updateAttributes] = useSyncedAttributes<T>(props)
if (props.node.attrs.nodeId === null) {
@@ -494,12 +501,26 @@ export function createPostHogWidgetNode<T extends CustomNotebookNodeAttributes>(
// oxlint-disable-next-line exhaustive-deps
}, [props.node.attrs.nodeId])
+ // when in shared mode, do not render any nodes that we know are unsupported
+ if (isShared && !isNodeSupportedInSharedNotebook(wrapperProps.nodeType)) {
+ return <UnsupportedNodePlaceholder />
+ }
+
const nodeProps: NotebookNodeProps<T> & Omit<NodeViewProps, 'attributes' | 'updateAttributes'> = {
...props,
attributes,
updateAttributes,
}
+ if (isShared) {
+ // the error boundary renders the placeholder when there is an error instead of showing a bunch of random errors to the user
+ return (
+ <SharedNodeErrorBoundary>
+ <MemoizedNodeWrapper Component={Component} {...nodeProps} {...wrapperProps} />
+ </SharedNodeErrorBoundary>
+ )
+ }
+
return <MemoizedNodeWrapper Component={Component} {...nodeProps} {...wrapperProps} />
}
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx
index 18c4e261ee9c..48938916eb12 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeEmbed.tsx
@@ -3,7 +3,6 @@ import { useEffect, useMemo, useState } from 'react'
import { LemonButton, LemonInput, SpinnerOverlay } from '@posthog/lemon-ui'
-import { JSONContent } from 'lib/components/RichContentEditor/types'
import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'
@@ -149,14 +148,3 @@ export const NotebookNodeEmbed = createPostHogWidgetNode<NotebookNodeEmbedAttrib
},
},
})
-
-export function buildNodeEmbed(): JSONContent {
- return {
- type: NotebookNodeType.Embed,
- attrs: {
- __init: {
- showSettings: true,
- },
- },
- }
-}
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
index 33aefee9b040..659143166049 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx
@@ -1,4 +1,3 @@
-import { JSONContent } from '@tiptap/core'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { useEffect, useMemo } from 'react'
@@ -12,7 +11,7 @@ import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
import { urls } from 'scenes/urls'
import { Query } from '~/queries/Query/Query'
-import { DataTableNode, InsightQueryNode, InsightVizNode, NodeKind, QuerySchema } from '~/queries/schema/schema-general'
+import { DataTableNode, InsightVizNode, NodeKind, QuerySchema } from '~/queries/schema/schema-general'
import {
containsHogQLQuery,
isDataTableNode,
@@ -34,6 +33,7 @@ import {
NotebookSQLEditorSettings,
} from './components/NotebookSQLEditor'
import { notebookNodeLogic } from './notebookNodeLogic'
+import { UnsupportedNodePlaceholder } from './sharedNodeSupport'
import { SHORT_CODE_REGEX_MATCH_GROUPS } from './utils'
export const DEFAULT_QUERY: QuerySchema = {
@@ -54,14 +54,28 @@ const Component = ({
const { query, nodeId } = attributes
const nodeLogic = useMountedLogic(notebookNodeLogic)
const { expanded, nodeId: resolvedNodeId, notebookLogic } = useValues(nodeLogic)
- const { editingNodeIds } = useValues(notebookLogic)
+ const {
+ editingNodeIds,
+ isShared,
+ getSharedCachedInsight,
+ getSharedCachedInlineQueryResults,
+ canvasFiltersOverride,
+ } = useValues(notebookLogic)
const { setTitlePlaceholder } = useActions(nodeLogic)
const summarizeInsight = useSummarizeInsight()
- const { canvasFiltersOverride } = useValues(notebookLogic)
-
- const insightLogicProps = {
- dashboardItemId: query.kind === NodeKind.SavedInsightNode ? query.shortId : ('new' as const),
- }
+ const sharedCachedInsight = query.kind === NodeKind.SavedInsightNode ? getSharedCachedInsight(query.shortId) : null
+ const sharedCachedInlineResults =
+ query.kind !== NodeKind.SavedInsightNode ? getSharedCachedInlineQueryResults(resolvedNodeId) : null
+
+ const insightLogicProps: InsightLogicProps = sharedCachedInsight
+ ? {
+ dashboardItemId: sharedCachedInsight.short_id,
+ cachedInsight: sharedCachedInsight,
+ doNotLoad: true,
+ }
+ : {
+ dashboardItemId: query.kind === NodeKind.SavedInsightNode ? query.shortId : ('new' as const),
+ }
const { insightName } = useValues(insightLogic(insightLogicProps))
useEffect(() => {
@@ -121,12 +135,53 @@ const Component = ({
}
return modifiedQuery
- }, [query]) // oxlint-disable-line react-hooks/exhaustive-deps
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
+ }, [query])
if (!expanded) {
return null
}
+ // Shared notebook fast paths. The render order below is deliberate:
+ // 1. Saved insight with a pre-computed result → render via insightLogic + cachedResults.
+ // 2. Inline query with a pre-computed result → render the original query with cachedResults.
+ // 3. Otherwise (no cached result for this node, e.g. backend execution failed) → placeholder.
+ // We never fall through to the live `<Query>` path in shared mode because `dataNodeLogic`
+ // would issue a POST that the sharing token can't authenticate.
+ if (isShared) {
+ if (sharedCachedInsight) {
+ return (
+ <div className="flex flex-1 flex-col h-full" data-attr="notebook-node-query">
+ <BindLogic logic={insightLogic} props={insightLogicProps}>
+ <Query
+ uniqueKey={nodeId + '-shared'}
+ query={sharedCachedInsight.query as QuerySchema}
+ cachedResults={sharedCachedInsight}
+ embedded
+ readOnly
+ inSharedMode
+ />
+ </BindLogic>
+ </div>
+ )
+ }
+ if (sharedCachedInlineResults) {
+ return (
+ <div className="flex flex-1 flex-col h-full" data-attr="notebook-node-query">
+ <Query
+ uniqueKey={nodeId + '-shared-inline'}
+ query={query}
+ cachedResults={sharedCachedInlineResults}
+ embedded
+ readOnly
+ inSharedMode
+ />
+ </div>
+ )
+ }
+ return <UnsupportedNodePlaceholder />
+ }
+
if (getSqlEditorSourceQuery(query)) {
return (
<div className="flex flex-1 flex-col h-full" data-attr="notebook-node-query">
@@ -355,17 +410,3 @@ export const NotebookNodeQuery = createPostHogWidgetNode<NotebookNodeQueryAttrib
return text
},
})
-
-export function buildInsightVizQueryContent(source: InsightQueryNode): JSONContent {
- return buildNodeQueryContent({ kind: NodeKind.InsightVizNode, source: source })
-}
-
-export function buildNodeQueryContent(query: QuerySchema): JSONContent {
- return {
- type: NotebookNodeType.Query,
- attrs: {
- query: query,
- showSettings: true,
- },
- }
-}
diff --git a/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts b/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts
new file mode 100644
index 000000000000..2251bf18e94c
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/nodeBuilders.ts
@@ -0,0 +1,38 @@
+// Pure JSONContent factories for notebook nodes.
+//
+// Kept in a standalone module so callers (e.g. SlashCommands) can build node content without
+// pulling in the node modules themselves. The node modules import `createPostHogWidgetNode` from
+// `NodeWrapper`, and `NodeWrapper` imports `SlashCommandsPopover` from `SlashCommands` — putting
+// the builders in either node module creates a circular import that surfaces as
+// `createPostHogWidgetNode is not a function` at module-evaluation time.
+import { JSONContent } from '@tiptap/core'
+
+import { NodeKind, QuerySchema } from '~/queries/schema/schema-general'
+import { InsightQueryNode } from '~/queries/schema/schema-general'
+
+import { NotebookNodeType } from '../types'
+
+export function buildNodeEmbed(): JSONContent {
+ return {
+ type: NotebookNodeType.Embed,
+ attrs: {
+ __init: {
+ showSettings: true,
+ },
+ },
+ }
+}
+
+export function buildNodeQueryContent(query: QuerySchema): JSONContent {
+ return {
+ type: NotebookNodeType.Query,
+ attrs: {
+ query: query,
+ showSettings: true,
+ },
+ }
+}
+
+export function buildInsightVizQueryContent(source: InsightQueryNode): JSONContent {
+ return buildNodeQueryContent({ kind: NodeKind.InsightVizNode, source: source })
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx b/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx
new file mode 100644
index 000000000000..550866be7b8a
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx
@@ -0,0 +1,88 @@
+import { NodeViewWrapper } from '@tiptap/react'
+import { Component, ReactNode } from 'react'
+
+import { IconWarning } from '@posthog/icons'
+
+import { NotebookNodeType } from '../types'
+
+/**
+ * Node types that are safe to render inside a publicly shared notebook today.
+ *
+ * Anything not in this set falls back to {@link UnsupportedNodePlaceholder} so that
+ * shared notebook viewers never crash on a node we haven't audited for anonymous use yet.
+ *
+ * To add a new supported node:
+ * 1. Confirm the node only fetches data via endpoints that accept `SharingAccessTokenAuthentication`.
+ * 2. Confirm it has no editor-only side effects when `isEditable=false`.
+ * 3. Add the entry below.
+ *
+ * Built-in ProseMirror / StarterKit / Tiptap node names (paragraph, heading, bulletList, etc.) are
+ * registered separately in `Editor.tsx` and aren't gated through this list \u2014 only PostHog widget
+ * nodes (`ph-*`) flow through `createPostHogWidgetNode` where this check runs.
+ */
+export const SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES: ReadonlySet<string> = new Set([
+ NotebookNodeType.Image,
+ NotebookNodeType.Latex,
+ NotebookNodeType.Embed,
+ // `ph-query` itself is allow-listed at the node-type level, but the component does its own
+ // shared-mode check internally: only `SavedInsightNode` queries with a backend-pre-computed
+ // result render. Inline / ad-hoc queries (DataTableNode, HogQLQuery, etc.) fall back to
+ // `UnsupportedNodePlaceholder` from inside `NotebookNodeQuery` because they would otherwise
+ // POST to `/api/projects/.../query/`, which sharing tokens cannot reach.
+ NotebookNodeType.Query,
+])
+
+export function isNodeSupportedInSharedNotebook(nodeType: string): boolean {
+ return SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES.has(nodeType)
+}
+
+export function UnsupportedNodePlaceholder(): JSX.Element {
+ return (
+ <NodeViewWrapper
+ as="div"
+ className="NotebookNode--unsupported my-2 rounded border border-dashed border-warning bg-warning-highlight p-3"
+ data-attr="notebook-unsupported-node"
+ contentEditable={false}
+ >
+ <div className="flex items-start gap-2">
+ <IconWarning className="text-warning mt-0.5 shrink-0 text-lg" />
+ <div className="flex flex-col">
+ <span className="font-medium">Node cannot be rendered</span>
+ <span className="text-secondary text-sm">
+ This node type is not supported in shared notebooks. We are working on supporting it soon!
+ </span>
+ </div>
+ </div>
+ </NodeViewWrapper>
+ )
+}
+
+/**
+ * Tiny error boundary used only by the shared-notebook render path. Catches anything that throws
+ * while rendering an allow-listed node and falls back to the same placeholder so the surrounding
+ * notebook keeps rendering. The full `~/layout/ErrorBoundary` is intentionally not used here
+ * because it shows engineer-oriented support UI which we don't want anonymous viewers to see.
+ */
+interface SharedNodeErrorBoundaryProps {
+ children: ReactNode
+}
+
+export class SharedNodeErrorBoundary extends Component<SharedNodeErrorBoundaryProps, { hasError: boolean }> {
+ override state = { hasError: false }
+
+ static getDerivedStateFromError(): { hasError: boolean } {
+ return { hasError: true }
+ }
+
+ override componentDidCatch(): void {
+ // Swallow errors: a single broken node should not surface a stack trace to public viewers.
+ // The exception is still reported via the global error handler attached at app boot.
+ }
+
+ override render(): ReactNode {
+ if (this.state.hasError) {
+ return <UnsupportedNodePlaceholder />
+ }
+ return this.props.children
+ }
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
index 418a3989f71e..94b459e68e19 100644
--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
@@ -37,9 +37,18 @@ export function Notebook({
editable = true,
initialAutofocus = 'start',
initialContent,
+ cachedNotebook,
+ cachedInsightsByShortId,
+ cachedInlineQueryResultsByNodeId,
className,
}: NotebookProps): JSX.Element {
- const logicProps: NotebookLogicProps = { shortId, mode }
+ const logicProps: NotebookLogicProps = {
+ shortId,
+ mode,
+ cachedNotebook,
+ cachedInsightsByShortId,
+ cachedInlineQueryResultsByNodeId,
+ }
const logic = notebookLogic(logicProps)
const { notebook, notebookLoading, editor, conflictWarningVisible, isEditable, isTemplate, notebookMissing } =
useValues(logic)
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
index bbe2eafc93a6..9a999743ee7e 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
@@ -5,7 +5,8 @@ import { useState } from 'react'
import { IconCopy } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDivider, LemonModal } from '@posthog/lemon-ui'
-import { SHARING_MODAL_WIDTH } from 'lib/components/Sharing/SharingModal'
+import { SHARING_MODAL_WIDTH, SharingModalContent } from 'lib/components/Sharing/SharingModal'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { base64Encode } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { urls } from 'scenes/urls'
@@ -22,12 +23,12 @@ export type NotebookShareModalProps = {
export function NotebookShareModal({ shortId }: NotebookShareModalProps): JSX.Element {
const { content, isLocalOnly, isShareModalOpen } = useValues(notebookLogic({ shortId }))
const { closeShareModal } = useActions(notebookLogic({ shortId }))
+ const externalSharingEnabled = useFeatureFlag('NOTEBOOK_SHARING')
const notebookUrl = urls.absolute(urls.currentProject(urls.notebook(shortId)))
const canvasUrl = urls.absolute(urls.canvas()) + `#🦔=${base64Encode(JSON.stringify(content))}`
const [interestTracked, setInterestTracked] = useState(false)
-
const trackInterest = (): void => {
posthog.capture('pressed interested in notebook sharing', { url: notebookUrl })
}
@@ -52,11 +53,11 @@ export function NotebookShareModal({ shortId }: NotebookShareModalProps): JSX.El
}}
/>
<LemonDivider />
- <h3>Internal Link</h3>
+ <h3>Internal link</h3>
{!isLocalOnly ? (
<>
<p>
- <b>Click the button below</b> to copy a direct link to this Notebook. Make sure the person
+ <b>Click the button below</b> to copy a direct link to this notebook. Make sure the person
you share it with has access to this PostHog project.
</p>
<LemonButton
@@ -75,14 +76,14 @@ export function NotebookShareModal({ shortId }: NotebookShareModalProps): JSX.El
</>
) : (
<LemonBanner type="info">
- <p>This Notebook cannot be shared directly with others as it is only visible to you.</p>
+ <p>This notebook cannot be shared directly with others as it is only visible to you.</p>
</LemonBanner>
)}
- <h3>Template Link</h3>
+ <h3>Template link</h3>
<p>
- The link below will open a Canvas with the contents of this Notebook, allowing the receiver to view
- it, edit it or create their own Notebook without affecting this one.
+ The link below will open a Canvas with the contents of this notebook, allowing the receiver to view
+ it, edit it or create their own notebook without affecting this one.
</p>
<LemonButton
type="secondary"
@@ -96,24 +97,32 @@ export function NotebookShareModal({ shortId }: NotebookShareModalProps): JSX.El
{canvasUrl}
</LemonButton>
- <LemonDivider className="my-4" />
-
- <h3>External Sharing</h3>
-
- <LemonBanner
- type="warning"
- action={{
- children: !interestTracked ? 'I would like this!' : 'Thanks!',
- onClick: () => {
- if (!interestTracked) {
- trackInterest()
- setInterestTracked(true)
- }
- },
- }}
- >
- We don’t currently support sharing notebooks externally, but it’s on our roadmap!
- </LemonBanner>
+ {!isLocalOnly &&
+ (externalSharingEnabled ? (
+ <>
+ <LemonDivider className="my-4" />
+ <SharingModalContent notebookShortId={shortId} />
+ </>
+ ) : (
+ <>
+ <LemonDivider className="my-4" />
+ <h3>External sharing</h3>
+ <LemonBanner
+ type="warning"
+ action={{
+ children: !interestTracked ? 'I would like this!' : 'Thanks!',
+ onClick: () => {
+ if (!interestTracked) {
+ trackInterest()
+ setInterestTracked(true)
+ }
+ },
+ }}
+ >
+ We don't currently support sharing notebooks externally, but it's on our roadmap!
+ </LemonBanner>
+ </>
+ ))}
</div>
</LemonModal>
)
diff --git a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx b/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
index 2e0028c4f5d5..82918fec5133 100644
--- a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
@@ -41,8 +41,7 @@ import { NodeKind } from '~/queries/schema/schema-general'
import { BaseMathType, ChartDisplayType, FunnelVizType, PathType, RetentionPeriod } from '~/types'
import { addInsightsToNotebookModalLogic } from '../AddInsightsToNotebookModal/addInsightsToNotebookModalLogic'
-import { buildNodeEmbed } from '../Nodes/NotebookNodeEmbed'
-import { buildInsightVizQueryContent, buildNodeQueryContent } from '../Nodes/NotebookNodeQuery'
+import { buildInsightVizQueryContent, buildNodeEmbed, buildNodeQueryContent } from '../Nodes/nodeBuilders'
import { NotebookNodeType } from '../types'
import NotebookIconHeading from './NotebookIconHeading'
import { notebookLogic } from './notebookLogic'
diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
index 3a5b24ce41bf..3985b3959fd3 100644
--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
@@ -45,7 +45,15 @@ import { FunnelExclusionLegacy, LegacyRecordingFilters } from '~/types'
// is filtered through the migrate function below that ensures integrity
export const NOTEBOOKS_VERSION = '1'
-export async function migrate(notebook: NotebookType): Promise<NotebookType> {
+export interface MigrateOptions {
+ /**
+ * Skips the query migrate step which issues a POST request to the backend which will result
+ * in a 403 error for unauthenticated users viewing a shared notebook.
+ */
+ skipApiUpgrade?: boolean
+}
+
+export async function migrate(notebook: NotebookType, options: MigrateOptions = {}): Promise<NotebookType> {
let content = notebook.content?.content
if (!content) {
@@ -56,7 +64,9 @@ export async function migrate(notebook: NotebookType): Promise<NotebookType> {
content = convertInsightQueryStringsToObjects(content)
content = convertInsightQueriesToNewSchema(content)
content = convertPlaylistFiltersToUniversalFilters(content)
- content = await upgradeQueryNode(content)
+ if (!options.skipApiUpgrade) {
+ content = await upgradeQueryNode(content)
+ }
return { ...notebook, content: { type: 'doc', content: content } }
}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 5cea341d5b91..881eec6327a7 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -37,10 +37,11 @@ import {
notebooksModel,
openNotebook,
} from '~/models/notebooksModel'
-import { NodeKind } from '~/queries/schema/schema-general'
+import { AnyResponseType, NodeKind } from '~/queries/schema/schema-general'
import { isHogQLQuery, isSavedInsightNode } from '~/queries/utils'
import {
AccessControlLevel,
+ InsightModel,
AccessControlResourceType,
ActivityScope,
AnyPropertyFilter,
@@ -84,6 +85,23 @@ export type NotebookLogicProps = {
mode?: NotebookLogicMode
target?: NotebookTarget
canvasFiltersOverride?: AnyPropertyFilter[]
+ /**
+ * Pre-loaded notebook payload for shared/exported views. When set, `loadNotebook`
+ * short-circuits and uses this value instead of calling the API — anonymous shared
+ * viewers can't reach `/api/projects/.../notebooks/<short_id>/`.
+ */
+ cachedNotebook?: NotebookType
+ /**
+ * Pre-serialized saved insights referenced by a shared notebook, keyed by `short_id`.
+ * Each entry has computed results inlined so `NotebookNodeQuery` can seed `cachedInsight`
+ * and skip the `/query/` POST that sharing tokens cannot reach.
+ */
+ cachedInsightsByShortId?: Record<string, InsightModel>
+ /**
+ * Pre-computed results for inline (non-saved-insight) ph-query nodes in a shared notebook,
+ * keyed by `nodeId`. Lets `NotebookNodeQuery` seed `cachedResults` for ad-hoc queries too.
+ */
+ cachedInlineQueryResultsByNodeId?: Record<string, AnyResponseType>
}
async function runWhenEditorIsReady(waitForEditor: () => boolean, fn: () => any): Promise<any | null> {
@@ -329,7 +347,9 @@ export const notebookLogic = kea<notebookLogicType>([
return null
}
- if (props.shortId === SCRATCHPAD_NOTEBOOK.short_id) {
+ if (props.cachedNotebook) {
+ response = props.cachedNotebook
+ } else if (props.shortId === SCRATCHPAD_NOTEBOOK.short_id) {
response = {
...values.scratchpadNotebook,
content: null,
@@ -361,7 +381,7 @@ export const notebookLogic = kea<notebookLogicType>([
}
}
- const notebook = await migrate(response)
+ const notebook = await migrate(response, { skipApiUpgrade: !!values.isShared })
if (notebook.content && (!values.notebook || values.notebook.version !== notebook.version)) {
// If this is the first load we need to override the content fully
@@ -594,9 +614,16 @@ export const notebookLogic = kea<notebookLogicType>([
},
],
editingNodeLogics: [
- (s) => [s.editingNodeIds, s.nodeLogics],
- (editingNodeIds, nodeLogics) =>
- Object.values(nodeLogics).filter((nodeLogic) => editingNodeIds[nodeLogic.values.nodeId]),
+ (s) => [s.editingNodeIds, s.nodeLogics, s.isShared],
+ (editingNodeIds, nodeLogics, isShared) => {
+ // Editing UI is meaningless for anonymous shared viewers and `editingNodeIds` can
+ // arrive pre-populated from persisted local state — zero it out at the source so
+ // the Settings panel never renders for them.
+ if (isShared) {
+ return []
+ }
+ return Object.values(nodeLogics).filter((nodeLogic) => editingNodeIds[nodeLogic.values.nodeId])
+ },
],
editingNodeLogicsForLeft: [
(s) => [s.editingNodeLogics, s.containerSize],
@@ -700,6 +727,40 @@ export const notebookLogic = kea<notebookLogicType>([
))),
],
+ isShared: [() => [(_, props) => props.cachedNotebook], (cachedNotebook): boolean => !!cachedNotebook],
+
+ cachedInsightsByShortId: [
+ () => [(_, props) => props.cachedInsightsByShortId],
+ (cachedInsightsByShortId): Record<string, InsightModel> => cachedInsightsByShortId ?? {},
+ ],
+
+ cachedInlineQueryResultsByNodeId: [
+ () => [(_, props) => props.cachedInlineQueryResultsByNodeId],
+ (cachedInlineQueryResultsByNodeId): Record<string, AnyResponseType> =>
+ cachedInlineQueryResultsByNodeId ?? {},
+ ],
+
+ getSharedCachedInsight: [
+ (s) => [s.isShared, s.cachedInsightsByShortId],
+ (isShared, cachedInsightsByShortId) =>
+ (shortId: string | null | undefined): InsightModel | null => {
+ if (!isShared || !shortId) {
+ return null
+ }
+ return cachedInsightsByShortId[shortId] ?? null
+ },
+ ],
+ getSharedCachedInlineQueryResults: [
+ (s) => [s.isShared, s.cachedInlineQueryResultsByNodeId],
+ (isShared, cachedInlineQueryResultsByNodeId) =>
+ (nodeId: string | null | undefined): AnyResponseType | null => {
+ if (!isShared || !nodeId) {
+ return null
+ }
+ return cachedInlineQueryResultsByNodeId[nodeId] ?? null
+ },
+ ],
+
insightShortIdsInNotebook: [
(s) => [s.content],
(content) => {
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index c55661da5a63..a99c81498837 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -913,13 +913,20 @@ legacy_project_session_recordings_router.register(
["team_id", "recording_id"],
)
-projects_router.register(
+project_notebooks_router = projects_router.register(
r"notebooks",
NotebookViewSet,
"project_notebooks",
["project_id"],
)
+project_notebooks_router.register(
+ r"sharing",
+ sharing.SharingConfigurationViewSet,
+ "project_notebook_sharing",
+ ["project_id", "notebook_id"],
+)
+
projects_router.register(
r"session_group_summaries",
SessionGroupSummaryViewSet,
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 94b450339d4c..214eb14755a8 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -13,6 +13,7 @@ import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
from loginas.utils import is_impersonated_session
+from pydantic import BaseModel
from rest_framework import mixins, response, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
@@ -26,11 +27,13 @@ from posthog.api.exports import ExportedAssetSerializer
from posthog.api.insight import InsightSerializer
from posthog.api.insight_variable import InsightVariable
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.services.query import process_query_dict
from posthog.api.shared import TeamPublicSerializer
from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
+from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_mode
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import Cohort, InsightViewed, SessionRecording, SharePassword, SharingConfiguration, Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
@@ -47,6 +50,9 @@ from posthog.views import preflight_check
from products.dashboards.backend.api.dashboard import DashboardSerializer
from products.dashboards.backend.models.dashboard import Dashboard
+from products.notebooks.backend.api.notebook import NotebookSerializer
+from products.notebooks.backend.models import Notebook
+from products.notebooks.backend.util import extract_inline_query_nodes
logger = structlog.get_logger(__name__)
@@ -79,6 +85,11 @@ def _log_share_password_attempt(
item_id = str(resource.insight.id)
resource_type = "insight"
resource_name = resource.insight.name
+ elif resource.notebook:
+ scope = "Notebook"
+ item_id = str(resource.notebook.short_id)
+ resource_type = "notebook"
+ resource_name = resource.notebook.title or "Untitled"
else:
return
@@ -156,6 +167,11 @@ def check_can_edit_sharing_configuration(
if not access_level or not access_level_satisfied_for_resource("insight", access_level, "editor"):
raise PermissionDenied("You don't have edit permissions for this insight.")
+ if sharing.notebook:
+ access_level = user_access_control.get_user_access_level(sharing.notebook)
+ if not access_level or not access_level_satisfied_for_resource("notebook", access_level, "editor"):
+ raise PermissionDenied("You don't have edit permissions for this notebook.")
+
return True
@@ -280,7 +296,7 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
"delete_password",
]
pagination_class = None
- queryset = SharingConfiguration.objects.select_related("dashboard", "insight", "recording")
+ queryset = SharingConfiguration.objects.select_related("dashboard", "insight", "recording", "notebook")
serializer_class = SharingConfigurationSerializer
def get_serializer_context(
@@ -291,9 +307,10 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
dashboard_id = context.get("dashboard_id")
insight_id = context.get("insight_id")
recording_id = context.get("recording_id")
+ notebook_short_id = context.get("notebook_id")
- if not dashboard_id and not insight_id and not recording_id:
- raise ValidationError("Either a dashboard, insight or recording must be specified")
+ if not dashboard_id and not insight_id and not recording_id and not notebook_short_id:
+ raise ValidationError("Either a dashboard, insight, recording or notebook must be specified")
if dashboard_id:
try:
@@ -308,6 +325,11 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
if recording_id:
# NOTE: Recordings are a special case as we don't want to query CH just for this.
context["recording"] = SessionRecording.get_or_build(recording_id, team=self.team)
+ if notebook_short_id:
+ try:
+ context["notebook"] = Notebook.objects.get(short_id=notebook_short_id, team=self.team)
+ except Notebook.DoesNotExist:
+ raise NotFound("Notebook not found.")
context["insight_variables"] = InsightVariable.objects.filter(team=self.team)
@@ -321,12 +343,14 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
dashboard = context.get("dashboard")
insight = context.get("insight")
recording = context.get("recording")
+ notebook = context.get("notebook")
config_kwargs = {
"team_id": self.team_id,
"insight": insight,
"dashboard": dashboard,
"recording": recording,
+ "notebook": notebook,
"expires_at": None,
}
@@ -398,7 +422,31 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
),
)
- if not context.get("recording") and serializer.data.get("enabled"):
+ if context.get("notebook"):
+ log_activity(
+ organization_id=None,
+ team_id=self.team_id,
+ user=cast(User, self.request.user),
+ was_impersonated=is_impersonated_session(self.request),
+ item_id=instance.notebook.short_id,
+ scope="Notebook",
+ activity="sharing " + ("enabled" if serializer.data.get("enabled") else "disabled"),
+ detail=Detail(
+ name=instance.notebook.title or None,
+ changes=[
+ Change(
+ type="Notebook",
+ action="changed",
+ field="sharing",
+ after=serializer.data.get("enabled"),
+ )
+ ],
+ short_id=str(instance.notebook.short_id),
+ ),
+ )
+
+ # Open-graph image rendering is only wired up for dashboards/insights today.
+ if not context.get("recording") and not context.get("notebook") and serializer.data.get("enabled"):
export_asset_for_opengraph(instance)
return response.Response(serializer.data)
@@ -434,6 +482,21 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
),
)
+ if context.get("notebook"):
+ log_activity(
+ organization_id=None,
+ team_id=self.team_id,
+ user=cast(User, self.request.user),
+ was_impersonated=is_impersonated_session(self.request),
+ item_id=new_instance.notebook.short_id,
+ scope="Notebook",
+ activity="access token refreshed",
+ detail=Detail(
+ name=new_instance.notebook.title or None,
+ short_id=str(new_instance.notebook.short_id),
+ ),
+ )
+
serializer = self.get_serializer(new_instance)
return response.Response(serializer.data)
@@ -511,6 +574,67 @@ def custom_404_response(request):
return render(request, "shared_resource_404.html", status=404)
+def _compute_inline_query_results_for_shared_notebook(notebook: Notebook, team: Team) -> dict[str, Any]:
+ """Pre-compute results for every inline (non-saved-insight) ``ph-query`` node in a notebook.
+
+ Mirrors the shared-insight path (`InsightSerializer.insight_result`) but for queries that
+ live inline in node attrs rather than as a `SavedInsightNode`. Each query is executed under
+ `shared_insights_execution_mode`, which uses the cache aggressively and refreshes async if
+ stale — the same throttle dashboards use.
+
+ Returns a map of ``nodeId -> serialized result dict``. Nodes whose query fails to execute
+ are silently omitted; the frontend renders ``UnsupportedNodePlaceholder`` for any inline
+ node it doesn't have a cached result for.
+ """
+ results_by_node_id: dict[str, Any] = {}
+ inline_nodes = extract_inline_query_nodes(notebook.content)
+ if not inline_nodes:
+ return results_by_node_id
+
+ execution_mode = shared_insights_execution_mode(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ for node_id, query in inline_nodes:
+ serialized: dict | None = None
+ try:
+ result = process_query_dict(
+ team,
+ query,
+ execution_mode=execution_mode,
+ user=None,
+ )
+ if isinstance(result, BaseModel):
+ serialized = result.model_dump(mode="json")
+ elif isinstance(result, dict):
+ serialized = result
+ except Exception as e:
+ # One bad node must not break the whole shared notebook — the frontend will fall
+ # back to UnsupportedNodePlaceholder for any node missing from this map.
+ logger.warning(
+ "shared_notebook_inline_query_failed",
+ notebook_short_id=notebook.short_id,
+ node_id=node_id,
+ exc_info=True,
+ )
+ capture_exception(e)
+ continue
+
+ if serialized is None:
+ continue # type: ignore
+
+ # `process_query_dict` swallows pydantic validation errors and returns a `QueryResponse`
+ # with `error` populated. Don't ship those to anonymous viewers — the placeholder is a
+ # better surface than a serialized validation traceback.
+ if serialized.get("error"):
+ logger.warning(
+ "shared_notebook_inline_query_returned_error",
+ notebook_short_id=notebook.short_id,
+ node_id=node_id,
+ error=serialized.get("error"),
+ )
+ continue
+ results_by_node_id[node_id] = serialized
+ return results_by_node_id
+
+
def _collect_cohorts_for_sharing(insights: list[Insight], team: Team) -> list[dict[str, Any]]:
# Shared viewers can't hit /api/cohorts/, so inline id+name for any referenced cohort.
cohort_ids: set[int] = set()
@@ -571,7 +695,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
if access_token:
try:
sharing_configuration = (
- SharingConfiguration.objects.select_related("dashboard", "insight", "recording")
+ SharingConfiguration.objects.select_related("dashboard", "insight", "recording", "notebook")
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now()))
.get(access_token=access_token)
)
@@ -886,6 +1010,46 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
asset_title = "Session Recording"
recording_data = SessionRecordingSerializer(resource.recording, context=context).data
exported_data.update({"recording": recording_data})
+ elif isinstance(resource, SharingConfiguration) and resource.notebook and not resource.notebook.deleted:
+ asset_title = resource.notebook.title or "Notebook"
+ asset_description = ""
+ notebook_data = NotebookSerializer(resource.notebook, context=context).data
+ exported_data.update({"notebook": notebook_data})
+ exported_data.update({"themes": get_themes_for_team(resource.team)})
+
+ referenced_insight_ids = resource.get_connected_insight_ids()
+ referenced_insights = (
+ list(
+ Insight.objects.filter(
+ id__in=referenced_insight_ids, team__project_id=resource.team.project_id, deleted=False
+ )
+ )
+ if referenced_insight_ids
+ else []
+ )
+ insights_by_short_id: dict[str, Any] = {}
+ if referenced_insights:
+ insight_context = {**context, "hide_extra_details": state.get("hideExtraDetails", False)}
+ serialized_insights = InsightSerializer(referenced_insights, many=True, context=insight_context).data
+ insights_by_short_id = {item["short_id"]: item for item in serialized_insights if item.get("short_id")}
+ # Track the view exactly like the dashboard / single-insight branches do.
+ for insight in referenced_insights:
+ InsightViewed.objects.update_or_create(
+ insight=insight, team=None, user=None, defaults={"last_viewed_at": now()}
+ )
+ exported_data.update({"insights": insights_by_short_id})
+ # Pre-compute every inline (non-saved-insight) `ph-query` node so the shared viewer
+ # can seed `cachedResults` on them too — same reason as above (no `/query/` POST).
+ exported_data.update(
+ {
+ "inline_query_results": _compute_inline_query_results_for_shared_notebook(
+ resource.notebook, resource.team
+ )
+ }
+ )
+ # Inline cohorts referenced by any saved insights embedded in the notebook so the
+ # shared viewer doesn't need to hit /api/cohorts/ (which it can't authenticate against).
+ exported_data.update({"cohorts": _collect_cohorts_for_sharing(referenced_insights, resource.team)})
else:
raise NotFound("No resource found")
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index b57ee8c0592f..72ec9acf4fe7 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -1648,6 +1648,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -4575,6 +4576,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -7042,6 +7044,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -8115,6 +8118,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -9311,6 +9315,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -11142,6 +11147,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -11166,6 +11172,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -14751,6 +14758,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -16090,6 +16098,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -16114,6 +16123,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -17143,6 +17153,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -17167,6 +17178,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
@@ -18017,6 +18029,7 @@
"posthog_sharingconfiguration"."dashboard_id",
"posthog_sharingconfiguration"."insight_id",
"posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
"posthog_sharingconfiguration"."created_at",
"posthog_sharingconfiguration"."enabled",
"posthog_sharingconfiguration"."access_token",
diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
index c4f6bc672d9a..a84f2411a00e 100644
--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
@@ -881,6 +881,42 @@
'''
# ---
# name: TestNotebooks.test_updates_notebook.21
+ '''
+ SELECT "posthog_sharingconfiguration"."id",
+ "posthog_sharingconfiguration"."team_id",
+ "posthog_sharingconfiguration"."dashboard_id",
+ "posthog_sharingconfiguration"."insight_id",
+ "posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
+ "posthog_sharingconfiguration"."created_at",
+ "posthog_sharingconfiguration"."enabled",
+ "posthog_sharingconfiguration"."access_token",
+ "posthog_sharingconfiguration"."expires_at",
+ "posthog_sharingconfiguration"."settings",
+ "posthog_sharingconfiguration"."password_required"
+ FROM "posthog_sharingconfiguration"
+ WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.22
+ '''
+ SELECT "posthog_sharingconfiguration"."id",
+ "posthog_sharingconfiguration"."team_id",
+ "posthog_sharingconfiguration"."dashboard_id",
+ "posthog_sharingconfiguration"."insight_id",
+ "posthog_sharingconfiguration"."recording_id",
+ "posthog_sharingconfiguration"."notebook_id",
+ "posthog_sharingconfiguration"."created_at",
+ "posthog_sharingconfiguration"."enabled",
+ "posthog_sharingconfiguration"."access_token",
+ "posthog_sharingconfiguration"."expires_at",
+ "posthog_sharingconfiguration"."settings",
+ "posthog_sharingconfiguration"."password_required"
+ FROM "posthog_sharingconfiguration"
+ WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.23
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -889,7 +925,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.22
+# name: TestNotebooks.test_updates_notebook.24
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -898,7 +934,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.23
+# name: TestNotebooks.test_updates_notebook.25
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -942,7 +978,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.24
+# name: TestNotebooks.test_updates_notebook.26
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -985,7 +1021,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.25
+# name: TestNotebooks.test_updates_notebook.27
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -1023,7 +1059,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.26
+# name: TestNotebooks.test_updates_notebook.28
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1152,7 +1188,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.27
+# name: TestNotebooks.test_updates_notebook.29
'''
SELECT "posthog_project"."id",
"posthog_project"."organization_id",
@@ -1164,7 +1200,19 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.28
+# name: TestNotebooks.test_updates_notebook.3
+ '''
+ SELECT "posthog_project"."id",
+ "posthog_project"."organization_id",
+ "posthog_project"."name",
+ "posthog_project"."created_at",
+ "posthog_project"."product_description"
+ FROM "posthog_project"
+ WHERE "posthog_project"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.30
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1211,7 +1259,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.29
+# name: TestNotebooks.test_updates_notebook.31
'''
SELECT "ee_accesscontrol"."id",
"ee_accesscontrol"."team_id",
@@ -1257,19 +1305,7 @@
AND "ee_accesscontrol"."team_id" = 99999))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.3
- '''
- SELECT "posthog_project"."id",
- "posthog_project"."organization_id",
- "posthog_project"."name",
- "posthog_project"."created_at",
- "posthog_project"."product_description"
- FROM "posthog_project"
- WHERE "posthog_project"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestNotebooks.test_updates_notebook.30
+# name: TestNotebooks.test_updates_notebook.32
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1314,7 +1350,7 @@
WHERE "posthog_organizationmembership"."user_id" = 99999
'''
# ---
-# name: TestNotebooks.test_updates_notebook.31
+# name: TestNotebooks.test_updates_notebook.33
'''
SELECT COUNT(*) AS "__count"
FROM "posthog_activitylog"
@@ -1322,7 +1358,7 @@
AND "posthog_activitylog"."team_id" = 99999)
'''
# ---
-# name: TestNotebooks.test_updates_notebook.32
+# name: TestNotebooks.test_updates_notebook.34
'''
SELECT "posthog_activitylog"."id",
"posthog_activitylog"."team_id",
diff --git a/posthog/migrations/1143_sharingconfiguration_notebook.py b/posthog/migrations/1143_sharingconfiguration_notebook.py
new file mode 100644
index 000000000000..5e01bb17cefc
--- /dev/null
+++ b/posthog/migrations/1143_sharingconfiguration_notebook.py
@@ -0,0 +1,23 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1142_alter_batchexportdestination_type_and_more"),
+ ("notebooks", "0003_add_kernel_timeouts"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sharingconfiguration",
+ name="notebook",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="sharing_configurations",
+ to="notebooks.notebook",
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 39701f8a8036..241367268579 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1142_alter_batchexportdestination_type_and_more
+1143_sharingconfiguration_notebook
\ No newline at end of file
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index 995f4bf13be6..c6429889227c 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -34,6 +34,13 @@ class SharingConfiguration(models.Model):
null=True,
blank=True,
)
+ notebook = models.ForeignKey(
+ "notebooks.Notebook",
+ related_name="sharing_configurations",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ )
created_at = models.DateTimeField(auto_now_add=True, blank=True)
@@ -62,6 +69,7 @@ class SharingConfiguration(models.Model):
dashboard=self.dashboard,
insight=self.insight,
recording=self.recording,
+ notebook=self.notebook,
enabled=self.enabled,
settings=self.settings,
password_required=self.password_required,
@@ -115,10 +123,10 @@ class SharingConfiguration(models.Model):
if obj.team_id != self.team_id: # type: ignore
return False
- if obj._meta.object_name == "Insight" and self.dashboard:
+ if obj._meta.object_name == "Insight" and (self.dashboard or self.notebook):
return cast(Insight, obj).id in self.get_connected_insight_ids()
- for comparison in [self.insight, self.dashboard, self.recording]:
+ for comparison in [self.insight, self.dashboard, self.recording, self.notebook]:
if comparison and comparison == obj:
return True
@@ -134,4 +142,21 @@ class SharingConfiguration(models.Model):
return []
# Check whether this sharing configuration's dashboard contains this insight
return list(self.dashboard.tiles.exclude(insight__deleted=True).values_list("insight__id", flat=True))
+ elif self.notebook:
+ # Recompute on every call so that edits to the notebook automatically grant/revoke access
+ # to the insights it embeds. Mirrors dashboard semantics.
+ from products.notebooks.backend.util import extract_referenced_insight_short_ids
+
+ if self.notebook.deleted:
+ return []
+ short_ids = extract_referenced_insight_short_ids(self.notebook.content)
+ if not short_ids:
+ return []
+ return list(
+ Insight.objects.filter(
+ team=self.team,
+ short_id__in=short_ids,
+ deleted=False,
+ ).values_list("id", flat=True)
+ )
return []
diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.py
new file mode 100644
index 000000000000..dcdd056e7b6c
--- /dev/null
+++ b/products/notebooks/backend/test/test_sharing.py
@@ -0,0 +1,436 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Insight, SharingConfiguration
+
+from products.notebooks.backend.models import Notebook
+from products.notebooks.backend.util import (
+ extract_inline_query_nodes,
+ extract_referenced_insight_short_ids,
+ iter_prosemirror_nodes,
+)
+
+
+def _saved_insight_query_node(short_id: str) -> dict[str, Any]:
+ return {
+ "type": "ph-query",
+ "attrs": {"query": {"kind": "SavedInsightNode", "shortId": short_id}},
+ }
+
+
+def _ad_hoc_query_node(kind: str = "DataTableNode", node_id: str | None = "node-1") -> dict[str, Any]:
+ attrs: dict[str, Any] = {"query": {"kind": kind, "source": {"kind": "EventsQuery", "select": ["*"]}}}
+ if node_id is not None:
+ attrs["nodeId"] = node_id
+ return {
+ "type": "ph-query",
+ "attrs": attrs,
+ }
+
+
+def _doc(*nodes: dict[str, Any]) -> dict[str, Any]:
+ return {"type": "doc", "content": list(nodes)}
+
+
+class TestExtractReferencedInsightShortIds(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("none", None, set()),
+ ("not_a_dict", "not a doc", set()),
+ ("empty_doc", {"type": "doc", "content": []}, set()),
+ ("doc_without_content_array", {"type": "doc"}, set()),
+ (
+ "single_saved_insight",
+ _doc(_saved_insight_query_node("abc123")),
+ {"abc123"},
+ ),
+ (
+ "ad_hoc_query_ignored",
+ _doc(_ad_hoc_query_node()),
+ set(),
+ ),
+ (
+ "deduplicates_repeated_short_ids",
+ _doc(_saved_insight_query_node("abc"), _saved_insight_query_node("abc")),
+ {"abc"},
+ ),
+ (
+ "ignores_non_query_nodes",
+ _doc(
+ {"type": "paragraph", "content": [{"type": "text", "text": "hello"}]},
+ _saved_insight_query_node("xyz"),
+ {"type": "ph-image", "attrs": {"src": "x"}},
+ ),
+ {"xyz"},
+ ),
+ (
+ "walks_nested_content",
+ _doc(
+ {
+ "type": "blockquote",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [_saved_insight_query_node("nested1")],
+ }
+ ],
+ },
+ _saved_insight_query_node("top"),
+ ),
+ {"nested1", "top"},
+ ),
+ (
+ "missing_attrs_skipped",
+ _doc({"type": "ph-query"}),
+ set(),
+ ),
+ (
+ "empty_short_id_skipped",
+ _doc(
+ {
+ "type": "ph-query",
+ "attrs": {"query": {"kind": "SavedInsightNode", "shortId": ""}},
+ }
+ ),
+ set(),
+ ),
+ (
+ "non_string_short_id_skipped",
+ _doc(
+ {
+ "type": "ph-query",
+ "attrs": {"query": {"kind": "SavedInsightNode", "shortId": 123}},
+ }
+ ),
+ set(),
+ ),
+ ]
+ )
+ def test_extract(self, _name: str, content: Any, expected: set[str]) -> None:
+ self.assertEqual(extract_referenced_insight_short_ids(content), expected)
+
+ def test_iter_prosemirror_nodes_handles_malformed_children(self) -> None:
+ doc = {"type": "doc", "content": "this is not a list"}
+ self.assertEqual(list(iter_prosemirror_nodes(doc)), [doc])
+
+ def test_extract_handles_stringified_query_attr(self) -> None:
+ """Tiptap's jsonAttr wrapper can serialize complex attrs as JSON strings; the extractor
+ accepts either form so legacy / serialized notebooks still surface their saved insight."""
+ import json
+
+ doc = _doc(
+ {
+ "type": "ph-query",
+ "attrs": {"query": json.dumps({"kind": "SavedInsightNode", "shortId": "abc123"})},
+ }
+ )
+ self.assertEqual(extract_referenced_insight_short_ids(doc), {"abc123"})
+
+
+class TestExtractInlineQueryNodes(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("none", None, []),
+ ("empty_doc", {"type": "doc", "content": []}, []),
+ (
+ "saved_insight_excluded",
+ _doc(_saved_insight_query_node("abc123")),
+ [],
+ ),
+ (
+ "single_inline_query",
+ _doc(_ad_hoc_query_node(node_id="node-1")),
+ [("node-1", {"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["*"]}})],
+ ),
+ (
+ "missing_node_id_skipped",
+ _doc(_ad_hoc_query_node(node_id=None)),
+ [],
+ ),
+ (
+ "empty_node_id_skipped",
+ _doc(_ad_hoc_query_node(node_id="")),
+ [],
+ ),
+ (
+ "saved_insight_and_inline_mixed",
+ _doc(
+ _saved_insight_query_node("abc123"),
+ _ad_hoc_query_node(kind="HogQLQuery", node_id="node-2"),
+ ),
+ [
+ (
+ "node-2",
+ {"kind": "HogQLQuery", "source": {"kind": "EventsQuery", "select": ["*"]}},
+ ),
+ ],
+ ),
+ (
+ "deeply_nested_inline_query",
+ _doc(
+ {
+ "type": "blockquote",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [_ad_hoc_query_node(node_id="deep-node")],
+ }
+ ],
+ }
+ ),
+ [("deep-node", {"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["*"]}})],
+ ),
+ ]
+ )
+ def test_extract(self, _name: str, content: Any, expected: list[tuple[str, dict]]) -> None:
+ self.assertEqual(extract_inline_query_nodes(content), expected)
+
+ def test_extract_handles_stringified_query_attr(self) -> None:
+ import json
+
+ doc = _doc(
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "node-1",
+ "query": json.dumps({"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["*"]}}),
+ },
+ }
+ )
+ self.assertEqual(
+ extract_inline_query_nodes(doc),
+ [("node-1", {"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["*"]}})],
+ )
+
+
+class TestNotebookSharingConfiguration(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.notebook = Notebook.objects.create(team=self.team, title="My notebook", created_by=self.user)
+
+ def _sharing_url(self, short_id: str | None = None) -> str:
+ short_id = short_id or self.notebook.short_id
+ return f"/api/projects/{self.team.id}/notebooks/{short_id}/sharing/"
+
+ def test_get_sharing_returns_disabled_by_default(self) -> None:
+ response = self.client.get(self._sharing_url())
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertFalse(body["enabled"])
+ # An access token is generated even before saving so the UI can display it
+ self.assertIsNotNone(body["access_token"])
+
+ def test_enable_sharing_persists_and_grants_token(self) -> None:
+ response = self.client.patch(self._sharing_url(), {"enabled": True}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertTrue(body["enabled"])
+ access_token = body["access_token"]
+ config = SharingConfiguration.objects.get(notebook=self.notebook, team=self.team)
+ self.assertTrue(config.enabled)
+ self.assertEqual(config.access_token, access_token)
+
+ def test_refresh_rotates_access_token_and_keeps_notebook_link(self) -> None:
+ self.client.patch(self._sharing_url(), {"enabled": True}, format="json")
+ original = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)
+
+ response = self.client.post(f"{self._sharing_url()}refresh/", {}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ original.refresh_from_db()
+ self.assertIsNotNone(original.expires_at)
+
+ new_config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)
+ self.assertNotEqual(new_config.access_token, original.access_token)
+ self.assertEqual(new_config.notebook_id, self.notebook.id)
+
+ def test_unknown_notebook_returns_404(self) -> None:
+ response = self.client.get(self._sharing_url(short_id="nope"))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_shared_notebook_renders_with_inlined_content(self) -> None:
+ # Mix supported (paragraph), saved-insight, and an unsupported node type. The frontend
+ # falls back to a placeholder for the latter — the backend still inlines whatever was saved
+ # so we don't lose data round-tripping through sharing.
+ self.notebook.content = _doc(
+ {"type": "paragraph", "content": [{"type": "text", "text": "hi"}]},
+ {"type": "ph-recording", "attrs": {"id": "some-recording"}},
+ )
+ self.notebook.save()
+ self.client.patch(self._sharing_url(), {"enabled": True}, format="json")
+ config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)
+
+ # Hit the public viewer endpoint as an anonymous client
+ self.client.logout()
+ response = self.client.get(f"/shared/{config.access_token}.json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertEqual(body["type"], "scene")
+ self.assertIn("notebook", body)
+ self.assertEqual(body["notebook"]["short_id"], self.notebook.short_id)
+ self.assertEqual(body["notebook"]["title"], "My notebook")
+
+ def test_deleted_notebook_404s_on_shared_endpoint(self) -> None:
+ self.client.patch(self._sharing_url(), {"enabled": True}, format="json")
+ config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)
+ self.notebook.deleted = True
+ self.notebook.save()
+
+ self.client.logout()
+ response = self.client.get(f"/shared/{config.access_token}.json")
+ # The viewer raises NotFound which is rendered as a custom 404 HTML page for non-json paths,
+ # but the .json variant returns the standard DRF 404.
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class TestNotebookSharingGrantsInsightAccess(APIBaseTest):
+ """A notebook's sharing access token should grant read access to the saved insights it embeds."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.referenced_insight = Insight.objects.create(team=self.team, name="Referenced", short_id="ref0001")
+ self.unreferenced_insight = Insight.objects.create(team=self.team, name="Unreferenced", short_id="unr0001")
+ self.notebook = Notebook.objects.create(
+ team=self.team,
+ title="Notebook with insight",
+ content=_doc(_saved_insight_query_node("ref0001")),
+ created_by=self.user,
+ )
+ self.client.patch(
+ f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sharing/",
+ {"enabled": True},
+ format="json",
+ )
+ self.config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)
+
+ def test_get_connected_insight_ids_includes_referenced_insight(self) -> None:
+ self.assertEqual(self.config.get_connected_insight_ids(), [self.referenced_insight.id])
+
+ def test_get_connected_insight_ids_excludes_unreferenced_insight(self) -> None:
+ self.assertNotIn(self.unreferenced_insight.id, self.config.get_connected_insight_ids())
+
+ def test_can_access_object_for_referenced_insight(self) -> None:
+ self.assertTrue(self.config.can_access_object(self.referenced_insight))
+ self.assertFalse(self.config.can_access_object(self.unreferenced_insight))
+
+ def test_deleted_referenced_insight_drops_from_grant(self) -> None:
+ self.referenced_insight.deleted = True
+ self.referenced_insight.save()
+ self.assertEqual(self.config.get_connected_insight_ids(), [])
+
+ def test_editing_notebook_updates_grant(self) -> None:
+ # Initially only ref0001 is granted
+ self.assertEqual(self.config.get_connected_insight_ids(), [self.referenced_insight.id])
+
+ # Edit the notebook to also reference unr0001
+ self.notebook.content = _doc(
+ _saved_insight_query_node("ref0001"),
+ _saved_insight_query_node("unr0001"),
+ )
+ self.notebook.save()
+
+ # Re-fetch the config so the cached `self.config.notebook` doesn't mask the edit
+ config = SharingConfiguration.objects.select_related("notebook").get(pk=self.config.pk)
+ self.assertCountEqual(
+ config.get_connected_insight_ids(),
+ [self.referenced_insight.id, self.unreferenced_insight.id],
+ )
+
+ def test_anonymous_request_with_share_token_can_load_referenced_insight(self) -> None:
+ self.client.logout()
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/?short_id={self.referenced_insight.short_id}"
+ f"&sharing_access_token={self.config.access_token}"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertEqual(len(body["results"]), 1)
+ self.assertEqual(body["results"][0]["short_id"], self.referenced_insight.short_id)
+
+ def test_shared_notebook_renders_when_inline_query_execution_fails(self) -> None:
+ """If a single inline query fails server-side it must NOT 404 the whole notebook payload.
+ The node is omitted from `inline_query_results`; the frontend falls back to a placeholder.
+ Regression test: previously an inline query that needed a schema upgrade would crash
+ the entire shared render path."""
+ # Use a deliberately malformed query so process_query_dict raises during validation.
+ # The viewer endpoint must still return 200 with the rest of the payload intact.
+ self.notebook.content = _doc(
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "broken-node",
+ "query": {"kind": "DataTableNode", "source": {"kind": "NotARealQueryKind"}},
+ },
+ },
+ )
+ self.notebook.save()
+
+ self.client.logout()
+ response = self.client.get(f"/shared/{self.config.access_token}.json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertIn("notebook", body)
+ self.assertEqual(body["notebook"]["short_id"], self.notebook.short_id)
+ # The broken node is omitted from the result map but the rest of the response is intact.
+ self.assertNotIn("broken-node", body.get("inline_query_results", {}))
+
+ def test_shared_notebook_payload_inlines_inline_query_results(self) -> None:
+ """Inline (non-saved-insight) ph-query nodes get pre-computed and inlined too, keyed by
+ nodeId. Without this the shared viewer would POST `/query/` and bounce off the sharing
+ token. We don't assert specific result contents — just that the map is built and shaped."""
+ # Add an inline DataTableNode alongside the saved-insight one already on the notebook.
+ self.notebook.content = _doc(
+ _saved_insight_query_node("ref0001"),
+ {
+ "type": "ph-query",
+ "attrs": {
+ "nodeId": "inline-node-1",
+ "query": {
+ "kind": "DataTableNode",
+ "source": {"kind": "EventsQuery", "select": ["event", "timestamp"]},
+ },
+ },
+ },
+ )
+ self.notebook.save()
+
+ self.client.logout()
+ response = self.client.get(f"/shared/{self.config.access_token}.json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertIn("inline_query_results", body)
+ # Even on an empty events table the runner returns a response shape; key presence is
+ # the contract we're locking in here.
+ self.assertIn("inline-node-1", body["inline_query_results"])
+ self.assertIsInstance(body["inline_query_results"]["inline-node-1"], dict)
+
+ def test_shared_notebook_payload_inlines_referenced_insights(self) -> None:
+ """The shared notebook payload pre-serializes every referenced saved insight so the
+ viewer can render results without ever calling POST /query/ (which sharing tokens
+ cannot reach)."""
+ self.client.logout()
+ response = self.client.get(f"/shared/{self.config.access_token}.json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertIn("insights", body)
+ self.assertIn("ref0001", body["insights"])
+ self.assertNotIn("unr0001", body["insights"])
+ # The serialized payload must include `result` so the frontend can seed `cachedResults`
+ # — if it's missing, dataNodeLogic would try to POST /query/ at render time.
+ self.assertIn("result", body["insights"]["ref0001"])
+
+ def test_anonymous_request_with_share_token_cannot_load_unreferenced_insight(self) -> None:
+ self.client.logout()
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/?short_id={self.unreferenced_insight.short_id}"
+ f"&sharing_access_token={self.config.access_token}"
+ )
+ # Either filtered out (200 with empty results) or 404 — both are acceptable proof of denial
+ if response.status_code == status.HTTP_200_OK:
+ self.assertEqual(response.json()["results"], [])
+ else:
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.py
index 6c275225ed3c..6dcab8471557 100644
--- a/products/notebooks/backend/util.py
+++ b/products/notebooks/backend/util.py
@@ -1,10 +1,111 @@
+import json
import uuid
+from collections.abc import Iterator
from typing import Any
# Type aliases for TipTap editor nodes
TipTapNode = dict[str, Any]
TipTapContent = list[TipTapNode]
+# ProseMirror node type used by NotebookNodeQuery on the frontend.
+# Keep in sync with `NotebookNodeType.Query` in frontend/src/scenes/notebooks/types.ts.
+QUERY_NODE_TYPE = "ph-query"
+# QuerySchema kind that points at a saved insight by its short_id.
+SAVED_INSIGHT_NODE_KIND = "SavedInsightNode"
+
+
+def _coerce_query_attr(raw: Any) -> dict | None:
+ """Resolve a notebook ph-query node's `query` attribute to a dict.
+
+ Notebooks save attrs through tiptap, which can serialize complex attrs as JSON strings
+ (the `jsonAttr` wrapper in `NodeWrapper.tsx` round-trips through `JSON.stringify` /
+ `JSON.parse`). Older notebooks were also saved with stringified queries before the
+ `convertInsightQueryStringsToObjects` frontend migration normalized them. Accept either form.
+ """
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
+ return None
+
+
+def iter_prosemirror_nodes(doc: Any) -> Iterator[TipTapNode]:
+ """Yield every node in a ProseMirror document, depth-first.
+
+ Tolerates malformed input — anything that isn't a dict with a `content` list is skipped.
+ """
+ if not isinstance(doc, dict):
+ return
+ yield doc
+ children = doc.get("content")
+ if not isinstance(children, list):
+ return
+ for child in children:
+ yield from iter_prosemirror_nodes(child)
+
+
+def extract_referenced_insight_short_ids(content: Any) -> set[str]:
+ """Walk a notebook's ProseMirror document and collect every saved-insight short_id it embeds.
+
+ Only ``ph-query`` nodes whose query is a ``SavedInsightNode`` reference an insight by id.
+ Inline (ad-hoc) queries store the full query in node attrs — see
+ :func:`extract_inline_query_nodes` for those.
+ """
+ short_ids: set[str] = set()
+ for node in iter_prosemirror_nodes(content):
+ if node.get("type") != QUERY_NODE_TYPE:
+ continue
+ attrs = node.get("attrs")
+ if not isinstance(attrs, dict):
+ continue
+ query = _coerce_query_attr(attrs.get("query"))
+ if query is None:
+ continue
+ if query.get("kind") != SAVED_INSIGHT_NODE_KIND:
+ continue
+ short_id = query.get("shortId")
+ if isinstance(short_id, str) and short_id:
+ short_ids.add(short_id)
+ return short_ids
+
+
+def extract_inline_query_nodes(content: Any) -> list[tuple[str, dict]]:
+ """Walk a notebook's ProseMirror document and collect every inline (non-saved-insight) query.
+
+ Returns a list of ``(nodeId, query_dict)`` pairs. Used by the shared-notebook payload
+ builder to pre-compute results for ad-hoc queries (DataTableNode, HogQLQuery, InsightVizNode
+ without a saved insight reference, etc.) so the shared viewer can render them without
+ POSTing to ``/api/projects/<id>/query/`` — a path sharing tokens cannot reach.
+
+ Saved insights are deliberately excluded; they go through
+ :func:`extract_referenced_insight_short_ids` and the existing
+ ``InsightSerializer`` shared-mode path.
+
+ Nodes whose ``nodeId`` is missing are skipped; without it the frontend has no key to look
+ the cached result up by, so we'd risk attaching the wrong result to the wrong node.
+ """
+ inline_nodes: list[tuple[str, dict]] = []
+ for node in iter_prosemirror_nodes(content):
+ if node.get("type") != QUERY_NODE_TYPE:
+ continue
+ attrs = node.get("attrs")
+ if not isinstance(attrs, dict):
+ continue
+ query = _coerce_query_attr(attrs.get("query"))
+ if query is None:
+ continue
+ if query.get("kind") == SAVED_INSIGHT_NODE_KIND:
+ continue
+ node_id = attrs.get("nodeId")
+ if not isinstance(node_id, str) or not node_id:
+ continue
+ inline_nodes.append((node_id, query))
+ return inline_nodes
+
def create_bullet_list(items: list[str] | list[TipTapContent] | TipTapContent) -> TipTapNode:
"""Create a bullet list with list items. Items can be strings or content arrays."""
diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.ts
index e3b1fc8b56a1..1feda42c6150 100644
--- a/products/notebooks/frontend/generated/api.schemas.ts
+++ b/products/notebooks/frontend/generated/api.schemas.ts
@@ -137,6 +137,28 @@ export interface NotebookApi {
_create_in_folder?: string
}
+export interface SharePasswordApi {
+ readonly id: number
+ readonly created_at: string
+ /**
+ * @maxLength 100
+ * @nullable
+ */
+ note?: string | null
+ readonly created_by_email: string
+ readonly is_active: boolean
+}
+
+export interface SharingConfigurationApi {
+ readonly created_at: string
+ enabled?: boolean
+ /** @nullable */
+ readonly access_token: string | null
+ settings?: unknown | null
+ password_required?: boolean
+ readonly share_passwords: readonly SharePasswordApi[]
+}
+
export interface PatchedNotebookApi {
/** UUID of the notebook. */
readonly id?: string
diff --git a/products/notebooks/frontend/generated/api.ts b/products/notebooks/frontend/generated/api.ts
index 971fb2e0ed16..67d0948c5b82 100644
--- a/products/notebooks/frontend/generated/api.ts
+++ b/products/notebooks/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
NotebooksListParams,
PaginatedNotebookMinimalListApi,
PatchedNotebookApi,
+ SharingConfigurationApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -83,6 +84,79 @@ export const notebooksCreate = async (
})
}
+export const getNotebooksSharingListUrl = (projectId: string, notebookId: string) => {
+ return `/api/projects/${projectId}/notebooks/${notebookId}/sharing/`
+}
+
+export const notebooksSharingList = async (
+ projectId: string,
+ notebookId: string,
+ options?: RequestInit
+): Promise<SharingConfigurationApi[]> => {
+ return apiMutator<SharingConfigurationApi[]>(getNotebooksSharingListUrl(projectId, notebookId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+/**
+ * Create a new password for the sharing configuration.
+ */
+export const getNotebooksSharingPasswordsCreateUrl = (projectId: string, notebookId: string) => {
+ return `/api/projects/${projectId}/notebooks/${notebookId}/sharing/passwords/`
+}
+
+export const notebooksSharingPasswordsCreate = async (
+ projectId: string,
+ notebookId: string,
+ sharingConfigurationApi: NonReadonly<SharingConfigurationApi>,
+ options?: RequestInit
+): Promise<SharingConfigurationApi> => {
+ return apiMutator<SharingConfigurationApi>(getNotebooksSharingPasswordsCreateUrl(projectId, notebookId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sharingConfigurationApi),
+ })
+}
+
+/**
+ * Delete a password from the sharing configuration.
+ */
+export const getNotebooksSharingPasswordsDestroyUrl = (projectId: string, notebookId: string, passwordId: string) => {
+ return `/api/projects/${projectId}/notebooks/${notebookId}/sharing/passwords/${passwordId}/`
+}
+
+export const notebooksSharingPasswordsDestroy = async (
+ projectId: string,
+ notebookId: string,
+ passwordId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getNotebooksSharingPasswordsDestroyUrl(projectId, notebookId, passwordId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getNotebooksSharingRefreshCreateUrl = (projectId: string, notebookId: string) => {
+ return `/api/projects/${projectId}/notebooks/${notebookId}/sharing/refresh/`
+}
+
+export const notebooksSharingRefreshCreate = async (
+ projectId: string,
+ notebookId: string,
+ sharingConfigurationApi: NonReadonly<SharingConfigurationApi>,
+ options?: RequestInit
+): Promise<SharingConfigurationApi> => {
+ return apiMutator<SharingConfigurationApi>(getNotebooksSharingRefreshCreateUrl(projectId, notebookId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sharingConfigurationApi),
+ })
+}
+
/**
* The API for interacting with Notebooks. This feature is in early access and the API can have breaking changes without announcement.
*/
diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.ts
index b592ba999eb8..ce2befbd086a 100644
--- a/products/notebooks/frontend/generated/api.zod.ts
+++ b/products/notebooks/frontend/generated/api.zod.ts
@@ -33,6 +33,21 @@ export const NotebooksCreateBody = /* @__PURE__ */ zod.object({
_create_in_folder: zod.string().optional(),
})
+/**
+ * Create a new password for the sharing configuration.
+ */
+export const NotebooksSharingPasswordsCreateBody = /* @__PURE__ */ zod.object({
+ enabled: zod.boolean().optional(),
+ settings: zod.unknown().nullish(),
+ password_required: zod.boolean().optional(),
+})
+
+export const NotebooksSharingRefreshCreateBody = /* @__PURE__ */ zod.object({
+ enabled: zod.boolean().optional(),
+ settings: zod.unknown().nullish(),
+ password_required: zod.boolean().optional(),
+})
+
/**
* The API for interacting with Notebooks. This feature is in early access and the API can have breaking changes without announcement.
*/
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yaml
index 992ec7919bdb..ae9359d04e74 100644
--- a/products/notebooks/mcp/tools.yaml
+++ b/products/notebooks/mcp/tools.yaml
@@ -128,6 +128,18 @@ tools:
description: >
Get a specific notebook by its short_id. Returns the full notebook including title, content, version, and
creation/modification metadata.
+ notebooks-sharing-list:
+ operation: notebooks_sharing_list
+ enabled: false
+ notebooks-sharing-passwords-create:
+ operation: notebooks_sharing_passwords_create
+ enabled: false
+ notebooks-sharing-passwords-destroy:
+ operation: notebooks_sharing_passwords_destroy
+ enabled: false
+ notebooks-sharing-refresh-create:
+ operation: notebooks_sharing_refresh_create
+ enabled: false
notebooks-update:
operation: notebooks_update
enabled: false
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 0c5c19f42b27..892c49a3fda7 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -401,6 +401,18 @@ tools:
members-update:
operation: members_update
enabled: false
+ notebooks-sharing-list:
+ operation: notebooks_sharing_list
+ enabled: false
+ notebooks-sharing-passwords-create:
+ operation: notebooks_sharing_passwords_create
+ enabled: false
+ notebooks-sharing-passwords-destroy:
+ operation: notebooks_sharing_passwords_destroy
+ enabled: false
+ notebooks-sharing-refresh-create:
+ operation: notebooks_sharing_refresh_create
+ enabled: false
oauth-applications-list:
operation: oauth_applications_list
enabled: false