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(notebooks): capture inline ai request and finish events (#100913)

Sinan Kucukkoseler4fc73c9d868d
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 0a6ef65db56d..f49b6e177d7e 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -62,6 +62,7 @@ import {
getMarkdownNotebookMarkdown,
notebookArtifactContentToMarkdown,
} from './markdownNotebookV2'
+import { buildNotebookInlineAIFinishedEvent, buildNotebookInlineAIRequestedEvent } from './notebookAnalytics'
import { notebookLogic } from './notebookLogic'
import {
NOTEBOOK_AI_PRESENCE_COLOR,
@@ -118,6 +119,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
const inlineAIResponseNodeCountsRef = useRef<Record<string, number>>({})
const inlineAIResponseNodeIndicesRef = useRef<Record<string, number>>({})
const activeInlineAIRequestIdsRef = useRef<Set<string>>(new Set())
+ const inlineAIRequestStartedAtRef = useRef<Record<string, number>>({})
const aiPresenceRetainedByPromptRef = useRef(false)
const aiPresenceActivityVersionRef = useRef(0)
const aiPresenceDepartureTimeoutRef = useRef<number | null>(null)
@@ -386,6 +388,12 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
])
inlineAIResponseNodeCountsRef.current[conversationId] = 1
inlineAIResponseNodeIndicesRef.current[conversationId] = responseNodeIndex
+ inlineAIRequestStartedAtRef.current[conversationId] = Date.now()
+ // pinned: analytics event name and property names; renaming breaks dashboards
+ posthog.capture(
+ 'notebook inline ai requested',
+ buildNotebookInlineAIRequestedEvent(inlineAIRequest, notebook?.short_id ?? shortId)
+ )
},
[markAIPresenceActive, notebook?.short_id, notebook?.title, shortId]
)
@@ -614,8 +622,27 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
[updateMarkdownEditorValue]
)
+ const captureInlineAIFinished = useCallback(
+ (request: InlineNotebookAIRequest, completion: InlineAICompletion): void => {
+ // pinned: analytics event name and property names; renaming breaks dashboards
+ posthog.capture(
+ 'notebook inline ai finished',
+ buildNotebookInlineAIFinishedEvent(
+ request,
+ completion,
+ notebook?.short_id ?? shortId,
+ inlineAIRequestStartedAtRef.current[request.conversationId],
+ Date.now()
+ )
+ )
+ delete inlineAIRequestStartedAtRef.current[request.conversationId]
+ },
+ [notebook?.short_id, shortId]
+ )
+
const handleInlineAIComplete = useCallback(
(request: InlineNotebookAIRequest, completion: InlineAICompletion): void => {
+ captureInlineAIFinished(request, completion)
if (completion.kind !== 'assistant' && completion.kind !== 'artifact' && !completion.hasArtifact) {
const replacedNodeCount = inlineAIResponseNodeCountsRef.current[request.conversationId] ?? 1
updateMarkdownEditorValue((currentMarkdown) => {
@@ -652,11 +679,12 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
)
}, 0)
},
- [markAIPresenceInactive, retainAIPresenceForPrompt, updateMarkdownEditorValue]
+ [captureInlineAIFinished, markAIPresenceInactive, retainAIPresenceForPrompt, updateMarkdownEditorValue]
)
const handleInlineAIError = useCallback(
(request: InlineNotebookAIRequest, completion: InlineAICompletion): void => {
+ captureInlineAIFinished(request, completion)
const replacedNodeCount = inlineAIResponseNodeCountsRef.current[request.conversationId] ?? 1
updateMarkdownEditorValue((currentMarkdown) => {
const result = replaceNotebookAIResponseMarkdown(
@@ -677,7 +705,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
currentRequests.filter((currentRequest) => currentRequest.conversationId !== request.conversationId)
)
},
- [markAIPresenceInactive, updateMarkdownEditorValue]
+ [captureInlineAIFinished, markAIPresenceInactive, updateMarkdownEditorValue]
)
const aiWritingNodeIndexes = useMemo(
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.test.ts
index 6d5d34643225..2098d24ca248 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.test.ts
@@ -1,58 +1,132 @@
+import type { MarkdownNotebookAskAIRequest } from 'lib/components/MarkdownNotebook'
+
import { AccessControlLevel, UserType } from '~/types'
import { NotebookType } from '../types'
-import { NotebookOpenedProperties, buildNotebookOpenedEvent } from './notebookAnalytics'
+import type { InlineAICompletion } from './MarkdownNotebookInlineAI'
+import {
+ NotebookInlineAIFinishedProperties,
+ NotebookOpenedProperties,
+ buildNotebookInlineAIFinishedEvent,
+ buildNotebookInlineAIRequestedEvent,
+ buildNotebookOpenedEvent,
+} from './notebookAnalytics'
-describe('buildNotebookOpenedEvent', () => {
- const user = { uuid: 'user-1' } as UserType
+describe('notebookAnalytics', () => {
+ describe('buildNotebookOpenedEvent', () => {
+ const user = { uuid: 'user-1' } as UserType
- const notebook = (overrides: Partial<NotebookType> = {}): NotebookType =>
- ({
- short_id: 'abc123',
- created_by: { uuid: 'user-1' },
- user_access_level: AccessControlLevel.Editor,
- content: { type: 'doc', content: [{}, {}, {}] },
- ...overrides,
- }) as NotebookType
-
- it.each([
- [
- 'the creator opening directly (counts top-level nodes)',
- {},
- false,
- {
+ const notebook = (overrides: Partial<NotebookType> = {}): NotebookType =>
+ ({
short_id: 'abc123',
- is_creator: true,
+ created_by: { uuid: 'user-1' },
user_access_level: AccessControlLevel.Editor,
- access_source: 'direct',
- node_count: 3,
- },
- ],
- [
- 'a viewer of another user’s notebook via shared link',
- { created_by: { uuid: 'other' } as UserType },
- true,
- { is_creator: false, access_source: 'shared_link' },
- ],
- [
- 'a notebook with no content and no creator',
- { content: null, created_by: null },
- false,
- { is_creator: false, node_count: 0 },
- ],
- ] as [string, Partial<NotebookType>, boolean, Partial<NotebookOpenedProperties>][])(
- 'builds the event for %s',
- (_label, overrides, isShared, expected) => {
- expect(buildNotebookOpenedEvent(notebook(overrides), user, isShared)).toMatchObject(expected)
- }
- )
-
- it.each([
- ['scratchpad', 'scratchpad'],
- ['template', 'template-onboarding'],
- ['no notebook loaded', undefined],
- ])('does not emit for %s', (_label, shortId) => {
- const nb = shortId === undefined ? null : notebook({ short_id: shortId })
- expect(buildNotebookOpenedEvent(nb, user, false)).toBeNull()
+ content: { type: 'doc', content: [{}, {}, {}] },
+ ...overrides,
+ }) as NotebookType
+
+ it.each([
+ [
+ 'the creator opening directly (counts top-level nodes)',
+ {},
+ false,
+ {
+ short_id: 'abc123',
+ is_creator: true,
+ user_access_level: AccessControlLevel.Editor,
+ access_source: 'direct',
+ node_count: 3,
+ },
+ ],
+ [
+ 'a viewer of another user’s notebook via shared link',
+ { created_by: { uuid: 'other' } as UserType },
+ true,
+ { is_creator: false, access_source: 'shared_link' },
+ ],
+ [
+ 'a notebook with no content and no creator',
+ { content: null, created_by: null },
+ false,
+ { is_creator: false, node_count: 0 },
+ ],
+ ] as [string, Partial<NotebookType>, boolean, Partial<NotebookOpenedProperties>][])(
+ 'builds the event for %s',
+ (_label, overrides, isShared, expected) => {
+ expect(buildNotebookOpenedEvent(notebook(overrides), user, isShared)).toMatchObject(expected)
+ }
+ )
+
+ it.each([
+ ['scratchpad', 'scratchpad'],
+ ['template', 'template-onboarding'],
+ ['no notebook loaded', undefined],
+ ])('does not emit for %s', (_label, shortId) => {
+ const nb = shortId === undefined ? null : notebook({ short_id: shortId })
+ expect(buildNotebookOpenedEvent(nb, user, false)).toBeNull()
+ })
+ })
+
+ describe('inline AI events', () => {
+ const request = (overrides: Partial<MarkdownNotebookAskAIRequest> = {}): MarkdownNotebookAskAIRequest => ({
+ conversationId: 'conversation-1',
+ query: 'Summarize signups',
+ source: 'slash',
+ responseNodeId: 'node-1',
+ responseNodeIndex: 2,
+ responseMarker: 'Thinking...',
+ markdown: '# Private notebook text',
+ markdownWithResponse: '# Private notebook text\n\nThinking...',
+ ...overrides,
+ })
+
+ it.each([
+ ['a slash command', {}, { source: 'slash', has_selection: false }],
+ [
+ 'a selection',
+ { source: 'selection', selectedMarkdown: 'Private selected text', selectedRefId: 'ref-1' },
+ { source: 'selection', has_selection: true },
+ ],
+ ] as [
+ string,
+ Partial<MarkdownNotebookAskAIRequest>,
+ Partial<ReturnType<typeof buildNotebookInlineAIRequestedEvent>>,
+ ][])('builds the requested event for %s without prompt or notebook text', (_label, overrides, expected) => {
+ expect(buildNotebookInlineAIRequestedEvent(request(overrides), 'abc123')).toEqual({
+ conversation_id: 'conversation-1',
+ notebook_short_id: 'abc123',
+ prompt_length: 'Summarize signups'.length,
+ ...expected,
+ })
+ })
+
+ it.each([
+ [
+ 'an artifact that updated the notebook',
+ { status: 'done', kind: 'artifact', hasArtifact: true, message: 'Updated the notebook.' },
+ 1000,
+ { status: 'done', result_kind: 'artifact', has_artifact: true, duration_ms: 1500 },
+ ],
+ [
+ 'a failed request',
+ { status: 'error', kind: 'error', hasArtifact: false, message: 'Private error text' },
+ 1000,
+ { status: 'error', result_kind: 'error', has_artifact: false, duration_ms: 1500 },
+ ],
+ [
+ 'a request whose start time was lost',
+ { status: 'done', kind: 'assistant', hasArtifact: false, message: 'Private answer' },
+ undefined,
+ { status: 'done', result_kind: 'assistant', duration_ms: null },
+ ],
+ ] as [string, InlineAICompletion, number | undefined, Partial<NotebookInlineAIFinishedProperties>][])(
+ 'builds the finished event for %s',
+ (_label, completion, startedAtMs, expected) => {
+ const event = buildNotebookInlineAIFinishedEvent(request(), completion, 'abc123', startedAtMs, 2500)
+
+ expect(event).toMatchObject({ conversation_id: 'conversation-1', ...expected })
+ expect(JSON.stringify(event)).not.toContain('Private')
+ }
+ )
})
})
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
index eb86c606cc9a..f553a6aa9752 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
@@ -1,7 +1,58 @@
+import type { MarkdownNotebookAskAIRequest } from 'lib/components/MarkdownNotebook'
+
import { SCRATCHPAD_NOTEBOOK } from '~/models/notebooksModel'
import { AccessControlLevel, UserType } from '~/types'
import { NotebookType } from '../types'
+import type { InlineAICompletion } from './MarkdownNotebookInlineAI'
+
+export type NotebookInlineAIRequestedProperties = {
+ conversation_id: string
+ notebook_short_id: string | null
+ source: MarkdownNotebookAskAIRequest['source']
+ prompt_length: number
+ has_selection: boolean
+}
+
+export type NotebookInlineAIFinishedProperties = NotebookInlineAIRequestedProperties & {
+ status: InlineAICompletion['status']
+ result_kind: InlineAICompletion['kind']
+ has_artifact: boolean
+ duration_ms: number | null
+}
+
+/**
+ * Builds the `notebook inline ai requested` event payload. It carries lengths and flags only, because
+ * the prompt and the selected markdown can contain customer data.
+ */
+export function buildNotebookInlineAIRequestedEvent(
+ request: MarkdownNotebookAskAIRequest,
+ notebookShortId: string | null
+): NotebookInlineAIRequestedProperties {
+ return {
+ conversation_id: request.conversationId,
+ notebook_short_id: notebookShortId,
+ source: request.source,
+ prompt_length: request.query.length,
+ has_selection: !!request.selectedMarkdown,
+ }
+}
+
+export function buildNotebookInlineAIFinishedEvent(
+ request: MarkdownNotebookAskAIRequest,
+ completion: InlineAICompletion,
+ notebookShortId: string | null,
+ startedAtMs: number | undefined,
+ finishedAtMs: number
+): NotebookInlineAIFinishedProperties {
+ return {
+ ...buildNotebookInlineAIRequestedEvent(request, notebookShortId),
+ status: completion.status,
+ result_kind: completion.kind,
+ has_artifact: completion.hasArtifact,
+ duration_ms: startedAtMs === undefined ? null : Math.max(0, Math.round(finishedAtMs - startedAtMs)),
+ }
+}
export type NotebookOpenedProperties = {
short_id: string