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): add btw side conversations (#103718)

Marius Andracc774ffb4704
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.md
index 773e7da65af8..fb45869748e0 100644
--- a/docs/internal/generated-notebook-widgets.md
+++ b/docs/internal/generated-notebook-widgets.md
@@ -126,6 +126,17 @@ New notebooks place the typing caret in the title, including when opened through
The notebook's inline **Ask AI** uses LangGraph and receives widget authoring instructions when `notebook-generated-widgets` is enabled for the user.
The bookmark toggle **Keep question with answer** is on by default, retaining the question and the submitting user's name above the answer. Turning it off saves `keepQuestion={false}` on that prompt.
**Ask AI** is disabled until the organization approves AI data processing, including submission from saved prompt blocks.
+
+**BTW** opens a separate PostHog AI conversation for side questions in a sidebar beside the notebook.
+When the notebook area is too narrow for both, the conversation opens in a modal.
+Resizing between these layouts keeps the conversation and any unsent question.
+It is the second option in the notebook's `/` menu, after **Ask AI**, and the last action in the text selection toolbar and a component block's **More actions** menu.
+The conversation receives a snapshot of the notebook and any selected content from when BTW was opened, including unsaved changes at that time.
+Later notebook edits do not update that snapshot; replies are not inserted into the notebook.
+The agent is instructed to answer without edits, but BTW does not enforce a separate read-only tool permission policy.
+Sent messages are saved in PostHog AI history separately from the notebook.
+Closing BTW or refreshing the page closes the panel; reopen the saved conversation from PostHog AI history.
+It requires the same AI data processing consent as **Ask AI**.
Inline notebook artifacts update the open notebook without saving a second copy, even when the tool requests a save.
Full-notebook replacements preserve the retained question when **Keep question with answer** is on.
Standalone AI notebook saves preserve Markdown separators and live MDX cells, including `<SQLV2 />` and `<Widget />`, while resolving visualization references.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f7756025c664..a3ce7b234a41 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1412,6 +1412,14 @@ snapshots:
hash: v1.k794b7964.ebb253a1569c71c4c5a8e8b960f46c9c7c32b29ccab555b5c646cb50a88308ed.Cec9A53K1lhmiX7cygBRREm_UGPUFhNRq3CvIttZMJ4
components-markdown-notebook--ask-ai-without-consent--light:
hash: v1.k794b7964.e97394f9850e49896ddddf9624d3b43e20200250d74e94813707d83ab7badfa3.SAe1CR7VbZrrerWJx4oCvLsskyEJ9SwjKrMjxA0Fi3U
+ components-markdown-notebook--btw-selection--dark:
+ hash: v1.k794b7964.88e49b1516512d07d5a012b8c7628cd83b38563ffd0c0af1e7cab515954907ce.1fZdFevBmrjDikYQjsDVBaGP3vXAQbYoLFxdjNKwJY4
+ components-markdown-notebook--btw-selection--light:
+ hash: v1.k794b7964.0a4b40814d56667a7ffe61f0cb45a6e24359a9dfbb374df4461e1b266badab18.sipQlAEjJ4noWFSnV3ltrP8UaZYFvl9lMVJKOfdUKBM
+ components-markdown-notebook--btw-slash-menu--dark:
+ hash: v1.k794b7964.13c5d3c2a4720a9f9eede608418272ac5267bfa73ddd55ab01172cc0a0d43f91.vnCE_FYp75-CONA3DchgqqGJ1zmRpRHOb0MUT_qMqhY
+ components-markdown-notebook--btw-slash-menu--light:
+ hash: v1.k794b7964.1b7425a34e85b58c9b9807c5fec9b3388748986eeb7ec10db9a59e7f1d4a3bc5.A6nDurYcJTVncxV_TEXjnZBiS611u_dlrXtQamC7IHk
components-markdown-notebook--canvas-header--dark:
hash: v1.k794b7964.608a0ac08314f9ca439ce83d605b5b7068699aefcdc3ec64d2ea9850b78383a5.6uhW10xIiflrvLM9jcnT-l6on-ERqLyloX1KosD6EnA
components-markdown-notebook--canvas-header--light:
@@ -9964,6 +9972,14 @@ snapshots:
hash: v1.k794b7964.370d1ecd1c43f76266ca3675ad0476bd8109db0f06b115d374626e33633c9ee3.0f7haoIw1e_CIr7pgqCBpE4VaFMma7Nccuizeb4HKro
scenes-app-notebooks--text-only-notebook--light:
hash: v1.k794b7964.b75392a9efcf1d9898116cd8ecb342011ff3a666418a9f628e9dfa870ed1a781.g2_Fv5QZy5l5xJD7Gzzxl_TRp3tY3kJ_2-862BEYPzk
+ scenes-app-notebooks-btw--default--dark:
+ hash: v1.k794b7964.ed6013135aba8a20c0ff3139a81251e01fa100021de60e33be02fcabb616db5d.g55Nmz6vHWIb6fquVcz7arqgU744j6sE5aGzOB4d4dU
+ scenes-app-notebooks-btw--default--light:
+ hash: v1.k794b7964.f098050eb19522074c201832090db049fbea2f38b39a694c0182678fbde9b75e.l3IEBuN3V47jD6a0Tf-gQxmb24iN_0iV1yUwYW124OA
+ scenes-app-notebooks-btw--narrow--dark:
+ hash: v1.k794b7964.de1c2137235f76b17892bd4cf71ac3a558ca896de7f9602653e27449792e784f.JFI6t5P9IyR3EYezlN_InBCgmZFrTqrD-9uKBdo175E
+ scenes-app-notebooks-btw--narrow--light:
+ hash: v1.k794b7964.ed7ff0a58d3e626f9e8f617b0b2d6456639d8e4ab501a38369875544e03a1cc3.rTPnEIqN-Xry6e_re_klbz3oB6hnF6fSYVee7mnUEcs
scenes-app-notebooks-components-notebook-select-button--closed-popover-state--dark:
hash: v1.k794b7964.88d1a3e9fb5510fffa7aea75e2ec02791ce7b62f8089ba839517dbccdf11d322.3ulC8gWrQJ9QnKHdNsfDxzLqV_k-9itTnB4aJNAG4BM
scenes-app-notebooks-components-notebook-select-button--closed-popover-state--light:
diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
index 097f5a2990bd..e72eee6a1fc9 100644
--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
@@ -52,6 +52,7 @@ export function FormattingToolbar({
setBlockStyle,
copySelection,
askAIAboutSelection,
+ btwAboutSelection,
askAIDisabledReason,
startInlineCommentAtSelection,
lockPosition,
@@ -71,6 +72,7 @@ export function FormattingToolbar({
setBlockStyle: (style: TextBlockStyle) => void
copySelection: () => void
askAIAboutSelection?: () => void
+ btwAboutSelection?: () => void
askAIDisabledReason?: string
startInlineCommentAtSelection?: () => void
lockPosition: () => void
@@ -353,6 +355,19 @@ export function FormattingToolbar({
onClick={askAIAboutSelection}
/>
) : null}
+ {btwAboutSelection ? (
+ <LemonButton
+ size="xsmall"
+ icon={<IconSparkles />}
+ tooltip="Ask a side question"
+ aria-label="BTW"
+ data-attr="notebook-btw-selection"
+ disabledReason={askAIDisabledReason}
+ onClick={btwAboutSelection}
+ >
+ BTW
+ </LemonButton>
+ ) : null}
{showInlineActions && isLinkEditorOpen ? (
<div className="MarkdownNotebook__format-link-editor">
<LemonInput
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
index 899b5946bb86..971e1e5b2101 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
@@ -234,7 +234,8 @@ export function buildInsertCommands(
focusInsertedCode: (nodeId: string) => void,
openAIPrompt?: (nodeId: string) => void,
isAskAIDisabled?: boolean,
- extraCommands: InsertCommand[] = []
+ extraCommands: InsertCommand[] = [],
+ openBtw?: (nodeId: string) => void
): InsertCommand[] {
const commonCategory = COMMON_INSERT_COMMAND_CATEGORY
@@ -620,6 +621,20 @@ export function buildInsertCommands(
return sortProductInsertCommandsLast([
...aiCommands,
+ ...(openBtw
+ ? [
+ {
+ key: 'ai-btw',
+ label: 'BTW',
+ category: commonCategory,
+ description: 'Ask a side question about this notebook',
+ aliases: ['btw', 'by the way', 'question'],
+ icon: <IconSparkles />,
+ disabled: isAskAIDisabled,
+ run: openBtw,
+ },
+ ]
+ : []),
...textCommands,
...sqlCommands,
...queryCommands,
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index 8eb2d40cccf6..45d647b97888 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -982,8 +982,10 @@ h3.MarkdownNotebook__text-block--heading {
left: var(--markdown-notebook-format-toolbar-left);
z-index: calc(var(--z-popover) + 2);
display: inline-flex;
+ flex-wrap: wrap;
gap: 0.125rem;
align-items: center;
+ max-width: calc(100vw - 1rem);
padding: 0.25rem;
margin: 0;
color: var(--color-text-primary);
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
index d25734ed267f..493f84dfd2fa 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx
@@ -369,6 +369,19 @@ Select part of this paragraph to format it from the inline toolbar.`,
},
}
+export const BtwSelection: Story = {
+ ...SelectionToolbarState,
+ args: { ...SelectionToolbarState.args, onBtw: fn() },
+}
+
+export const BtwSlashMenu: Story = {
+ args: {
+ value: '# BTW\n\n ',
+ initialInsertMenu: { nodeIndex: 1, query: '' },
+ onBtw: fn(),
+ },
+}
+
export const SlashMenuAndInsertion: Story = {
args: {
value: '',
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 066319a5c504..1d7670d5b544 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { createElement, useEffect, useState, type ChangeEvent, type FormEvent } from 'react'
import { mergeNotebookMarkdownChanges } from './collaboration'
@@ -4602,7 +4602,7 @@ aXbc
expect(insertMenu.style.getPropertyValue('--markdown-notebook-insert-menu-width')).toEqual('384px')
})
- it('uses the boundary gap to open the insert menu before populated rows', () => {
+ it.each([false, true])('uses the boundary gap to open the insert menu before populated rows (btw: %s)', (btw) => {
const onChange = jest.fn()
const onAskAI = jest.fn()
const queryMarkdown = `<Query query={{"kind":"DataTableNode","source":{"kind":"EventsQuery"}}} />`
@@ -4611,6 +4611,7 @@ aXbc
value: withNotebookTitle(`${queryMarkdown}\n\nIntro paragraph`),
onChange,
onAskAI,
+ onBtw: btw ? jest.fn() : undefined,
})
)
const addBeforeButton = container.querySelector(
@@ -4632,7 +4633,9 @@ aXbc
const menuItems = Array.from(container.querySelectorAll('.MarkdownNotebook__insert-item')).map((button) =>
button.textContent?.trim()
)
- expect(menuItems.slice(0, 3)).toEqual(['Ask AI', 'Text', 'SQL'])
+ expect(menuItems.slice(0, btw ? 4 : 3)).toEqual(
+ btw ? ['Ask AI', 'BTW', 'Text', 'SQL'] : ['Ask AI', 'Text', 'SQL']
+ )
const trendButton = Array.from(container.querySelectorAll('.MarkdownNotebook__insert-item')).find(
(button) => button.textContent === 'Trend'
@@ -6005,6 +6008,37 @@ First paragraph
expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n\`First\` paragraph`)
})
+ it.each([undefined, 'Approve AI data processing first'])(
+ 'opens btw from selected text without editing it (disabled: %s)',
+ (askAIDisabledReason) => {
+ const onBtw = jest.fn()
+ const onChange = jest.fn()
+ const value = withNotebookTitle('First paragraph\n\nSecond paragraph')
+ const { container } = render(
+ createElement(MarkdownNotebook, { value, onChange, onBtw, askAIDisabledReason })
+ )
+ const textBlocks = container.querySelectorAll('p.MarkdownNotebook__text-block')
+ selectTextAcrossNodes(
+ getFirstTextNode(textBlocks[0] as HTMLElement),
+ 0,
+ getFirstTextNode(textBlocks[1] as HTMLElement),
+ 6,
+ true
+ )
+ const toolbar = container.querySelector('.MarkdownNotebook__format-toolbar')!
+ const button = toolbar.querySelector('button[aria-label="BTW"]') as HTMLButtonElement
+ expect(toolbar.querySelectorAll('button')[toolbar.querySelectorAll('button').length - 1]).toBe(button)
+ fireEvent.click(button)
+ if (askAIDisabledReason) {
+ expect(onBtw).not.toHaveBeenCalled()
+ } else {
+ expect(onBtw).toHaveBeenCalledWith({ markdown: value, selectedMarkdown: 'First paragraph\n\nSecond' })
+ }
+ expect(onChange).not.toHaveBeenCalled()
+ expect(container.querySelector('.MarkdownNotebook__ai-prompt-tag')).toBeNull()
+ }
+ )
+
it('opens an inline AI prompt below highlighted text from the formatting toolbar', () => {
const onAskAI = jest.fn()
const onChange = jest.fn()
@@ -6737,6 +6771,35 @@ second line
\`\`\``)
})
+ it('opens btw from the slash menu without leaving a prompt or query in the notebook', () => {
+ const onBtw = jest.fn()
+ const onAskAI = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: withNotebookTitle(' '), onBtw, onAskAI }))
+ const textBlock = getBodyTextBlock(container)
+ updateContentEditableText(textBlock, '/btw')
+ const option = Array.from(container.querySelectorAll('.MarkdownNotebook__insert-item')).find(
+ (button) => button.textContent === 'BTW'
+ ) as HTMLButtonElement
+ fireEvent.click(option)
+ expect(onBtw).toHaveBeenCalledWith({ markdown: withNotebookTitle(' ') })
+ expect(onAskAI).not.toHaveBeenCalled()
+ expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeNull()
+ expect(container.querySelector('.MarkdownNotebook__ai-prompt-tag')).toBeNull()
+ expect(getBodyTextBlock(container).textContent).toBe('')
+ })
+
+ it('opens btw about a component block without changing it', () => {
+ const onBtw = jest.fn()
+ const onChange = jest.fn()
+ const block = '<SQLV2 code="select 1" />'
+ const value = withNotebookTitle(block)
+ const { container } = render(createElement(MarkdownNotebook, { value, onBtw, onChange }))
+ fireEvent.click(container.querySelector('button[aria-label="More actions"]') as HTMLButtonElement)
+ fireEvent.click(screen.getByText('BTW'))
+ expect(onBtw).toHaveBeenCalledWith({ markdown: value, selectedMarkdown: block })
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
it('submits an Ask AI prompt when Enter is dispatched from the root editable surface', () => {
const onAskAI = jest.fn()
const { container } = render(
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 51bc68144dd7..c899683f823c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -237,10 +237,16 @@ import {
} from './types'
import { cloneNotebookNode, getInlineText, getNodeFingerprint, normalizeInlineNodes } from './utils'
+export type NotebookBtwContext = {
+ markdown: string
+ selectedMarkdown?: string
+}
+
export type MarkdownNotebookProps = {
value: string
onChange?: (value: string) => void
onAskAI?: (request: MarkdownNotebookAskAIRequest) => void
+ onBtw?: (context: NotebookBtwContext) => void
aiPromptAuthorName?: string
isAskAIDisabled?: boolean
askAIDisabledReason?: string
@@ -604,6 +610,7 @@ function MarkdownNotebookEditor({
value,
onChange,
onAskAI,
+ onBtw,
aiPromptAuthorName = 'You',
isAskAIDisabled = false,
askAIDisabledReason,
@@ -2938,6 +2945,35 @@ function MarkdownNotebookEditor({
})
}
+ const openBtw = useCallback(
+ (selectedMarkdown?: string): void => {
+ if (!onBtw || askAIDisabledReason) {
+ return
+ }
+ onBtw({ markdown: serializeMarkdownNotebook(documentRef.current), selectedMarkdown })
+ setFloatingToolbar(null)
+ },
+ [onBtw, askAIDisabledReason]
+ )
+
+ const openBtwFromSlash = useCallback(
+ (nodeId: string): void => {
+ if (!onBtw || askAIDisabledReason) {
+ return
+ }
+ const currentDocument = documentRef.current
+ const nextDocument = {
+ ...currentDocument,
+ nodes: currentDocument.nodes.map((node) =>
+ node.id === nodeId ? { ...makeEmptyParagraph('btw'), id: nodeId } : node
+ ),
+ }
+ commitDocument(nextDocument)
+ onBtw({ markdown: serializeMarkdownNotebook(nextDocument) })
+ },
+ [onBtw, askAIDisabledReason, commitDocument]
+ )
+
const renderedNodes = getRenderedNodes()
const aiWritingPlaceholderNodeIds = useMemo(() => getAIWritingPlaceholderNodeIds(document.nodes), [document.nodes])
const focusAIPromptNodeId = useMemo(
@@ -2969,7 +3005,8 @@ function MarkdownNotebookEditor({
},
onAskAI ? openAIPrompt : undefined,
!!askAIDisabledReason,
- extraInsertCommands ? extraInsertCommands(insertMenuApi) : []
+ extraInsertCommands ? extraInsertCommands(insertMenuApi) : [],
+ onBtw ? openBtwFromSlash : undefined
),
hiddenInsertCommandKeys
),
@@ -2978,6 +3015,8 @@ function MarkdownNotebookEditor({
replaceNodeWithInsertedComponent,
replaceNode,
onAskAI,
+ onBtw,
+ openBtwFromSlash,
askAIDisabledReason,
openAIPrompt,
extraInsertCommands,
@@ -6115,6 +6154,10 @@ function MarkdownNotebookEditor({
},
updateNode,
replaceNodeWithNodes,
+ onBtw: onBtw
+ ? () => openBtw(serializeMarkdownNotebook({ ...documentRef.current, nodes: [node] }))
+ : undefined,
+ askAIDisabledReason,
deleteNode: () => deleteNodeWithRefCleanup(node.id),
deleteNodeAndFocusAdjacent: () => {
requestFocusAfterRemovingNode(node.id)
@@ -6410,6 +6453,7 @@ function MarkdownNotebookEditor({
setBlockStyle={setSelectedBlockStyle}
copySelection={copyFloatingToolbarSelection}
askAIAboutSelection={onAskAI ? askAIAboutSelection : undefined}
+ btwAboutSelection={onBtw ? () => openBtw(floatingToolbar.selectedMarkdown) : undefined}
askAIDisabledReason={askAIDisabledReason}
startInlineCommentAtSelection={
canStartInlineCommentAtSelection() ? startInlineCommentAtSelection : undefined
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
index 76307fe24652..465841648322 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx
@@ -85,6 +85,8 @@ export type NotebookComponentShellProps = {
rememberComponentPanels: (nodeId: string, panels: ComponentPanelVisibility) => void
setBlockRef: (element: HTMLElement | null) => void
updateNode: (nodeId: string, updater: (node: NotebookBlockNode) => NotebookBlockNode | null) => void
+ onBtw?: () => void
+ askAIDisabledReason?: string
deleteNode: () => void
deleteSelectedNotebookBlocks: () => boolean
insertParagraphAfterNode: () => void
@@ -106,6 +108,8 @@ export function NotebookComponentShell({
rememberComponentPanels,
setBlockRef,
updateNode,
+ onBtw,
+ askAIDisabledReason,
deleteNode,
deleteSelectedNotebookBlocks,
insertParagraphAfterNode,
@@ -187,6 +191,7 @@ export function NotebookComponentShell({
: []),
...(toolbarExtras?.menuItems ?? []),
...(mode === 'edit' ? (toolbarExtras?.editMenuItems ?? []) : []),
+ mode === 'edit' && onBtw ? { label: 'BTW', onClick: onBtw, disabledReason: askAIDisabledReason } : null,
])
const hasToolbarMenu = toolbarMenuItems.some(Boolean)
const [titleDraft, setTitleDraft] = useState<string | null>(null)
diff --git a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
index 98e8cfdccab9..36cb1bab61a8 100644
--- a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
@@ -45,6 +45,8 @@ export function renderNode({
setListItemRef,
setTableCellRef,
updateNode,
+ onBtw,
+ askAIDisabledReason,
replaceNodeWithNodes,
deleteNode,
deleteNodeAndFocusAdjacent,
@@ -95,6 +97,8 @@ export function renderNode({
setListItemRef: (itemIndex: number, itemId: string | undefined, element: HTMLElement | null) => void
setTableCellRef: (position: TableCellPosition, element: HTMLElement | null) => void
updateNode: (nodeId: string, updater: (node: NotebookBlockNode) => NotebookBlockNode | null) => void
+ onBtw?: () => void
+ askAIDisabledReason?: string
replaceNodeWithNodes: (nodeId: string, replacementNodes: NotebookBlockNode[]) => void
deleteNode: () => void
deleteNodeAndFocusAdjacent: () => void
@@ -195,6 +199,8 @@ export function renderNode({
rememberComponentPanels={rememberComponentPanels}
setBlockRef={setBlockRef}
updateNode={updateNode}
+ onBtw={onBtw}
+ askAIDisabledReason={askAIDisabledReason}
deleteNode={deleteNode}
deleteSelectedNotebookBlocks={deleteSelectedNotebookBlocks}
insertParagraphAfterNode={insertParagraphAfterNode}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 49c2d24c0b91..b69c73a7d196 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -35,6 +35,9 @@ import { userLogic } from 'scenes/userLogic'
import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'
+import { NotebookBtwLayout } from 'products/notebooks/frontend/NotebookBtwLayout'
+import { notebookBtwLogic } from 'products/notebooks/frontend/notebookBtwLogic'
+
import { NODE_ICONS } from '../nodeIcons'
import { notebookWidgetCatalog, NotebookWidgetPickerKind } from '../notebookWidgetCatalog'
import { NotebookNodeType } from '../types'
@@ -97,6 +100,8 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
const { featureFlags } = useValues(featureFlagLogic)
const { user } = useValues(userLogic)
const { dataProcessingAccepted } = useValues(aiConsentLogic)
+ const { session: btwSession } = useValues(notebookBtwLogic({ shortId }))
+ const { openBtw, closeBtw } = useActions(notebookBtwLogic({ shortId }))
const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])
const enabledAIComponentTags = useMemo(
() => [
@@ -744,45 +749,48 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
return (
<MarkdownNotebookRuntimeContext.Provider value={runtimeContext}>
- <NotebookComponentRunStatusContext.Provider value={resolveComponentRunStatus}>
- <MarkdownNotebook
- value={markdownEditorValue}
- aiPromptAuthorName={user?.first_name || 'You'}
- remoteValue={remoteMarkdown}
- remoteVersion={notebook?.version}
- mode={isEditable ? 'edit' : 'view'}
- hideResourceLinks={isShared}
- registry={markdownRegistry}
- extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}
- hiddenInsertCommandKeys={hiddenInsertCommandKeys}
- onChange={isEditable ? handleMarkdownNotebookChange : undefined}
- onSaveRequested={isEditable ? saveNotebookNow : undefined}
- onConflict={reportMarkdownMergeConflicts}
- remoteCarets={remoteCarets}
- onCaretChange={isEditable ? publishMarkdownCaret : undefined}
- onAskAI={isEditable ? handleAskAI : undefined}
- convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}
- isAskAIDisabled={inlineAIRequests.length > 0}
- askAIDisabledReason={
- dataProcessingAccepted
- ? undefined
- : 'Approve AI data processing in organization settings to use Ask AI.'
- }
- createAIConversationId={uuid}
- deferRemoteValue={markdownEditorInteractionActive}
- onInteractionStateChange={setMarkdownEditorInteractionActive}
- allowViewModeFilters={mountedNotebookLogic.props.mode === 'canvas'}
- canvasHeader={<NotebookVariablesBar />}
- className="Notebook__markdown-v2"
- data-attr="notebook-markdown-v2"
- autoFocus={isEditable}
- showDebug={isEditable}
- debugOpen={isDebugOpen}
- onDebugOpenChange={handleDebugOpenChange}
- focusAIPromptRequest={focusAIPromptRequest}
- aiWritingNodeIndexes={aiWritingNodeIndexes}
- />
- </NotebookComponentRunStatusContext.Provider>
+ <NotebookBtwLayout session={btwSession} onClose={closeBtw}>
+ <NotebookComponentRunStatusContext.Provider value={resolveComponentRunStatus}>
+ <MarkdownNotebook
+ value={markdownEditorValue}
+ aiPromptAuthorName={user?.first_name || 'You'}
+ remoteValue={remoteMarkdown}
+ remoteVersion={notebook?.version}
+ mode={isEditable ? 'edit' : 'view'}
+ hideResourceLinks={isShared}
+ registry={markdownRegistry}
+ extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}
+ hiddenInsertCommandKeys={hiddenInsertCommandKeys}
+ onChange={isEditable ? handleMarkdownNotebookChange : undefined}
+ onSaveRequested={isEditable ? saveNotebookNow : undefined}
+ onConflict={reportMarkdownMergeConflicts}
+ remoteCarets={remoteCarets}
+ onCaretChange={isEditable ? publishMarkdownCaret : undefined}
+ onAskAI={isEditable ? handleAskAI : undefined}
+ onBtw={isEditable ? openBtw : undefined}
+ convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}
+ isAskAIDisabled={inlineAIRequests.length > 0}
+ askAIDisabledReason={
+ dataProcessingAccepted
+ ? undefined
+ : 'Approve AI data processing in organization settings to use Ask AI.'
+ }
+ createAIConversationId={uuid}
+ deferRemoteValue={markdownEditorInteractionActive}
+ onInteractionStateChange={setMarkdownEditorInteractionActive}
+ allowViewModeFilters={mountedNotebookLogic.props.mode === 'canvas'}
+ canvasHeader={<NotebookVariablesBar />}
+ className="Notebook__markdown-v2"
+ data-attr="notebook-markdown-v2"
+ autoFocus={isEditable}
+ showDebug={isEditable}
+ debugOpen={isDebugOpen}
+ onDebugOpenChange={handleDebugOpenChange}
+ focusAIPromptRequest={focusAIPromptRequest}
+ aiWritingNodeIndexes={aiWritingNodeIndexes}
+ />
+ </NotebookComponentRunStatusContext.Provider>
+ </NotebookBtwLayout>
{inlineAIRequests.map((request) => (
<InlineNotebookAIRunner
key={request.conversationId}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0673540bf2d4..2d9f94cf88f8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4155,6 +4155,9 @@ importers:
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ '@types/react-dom':
+ specifier: 18.3.7
+ version: 18.3.7(@types/[email protected])
clsx:
specifier: '*'
version: 1.2.1
@@ -4176,6 +4179,9 @@ importers:
react:
specifier: 18.3.1
version: 18.3.1
+ react-dom:
+ specifier: 18.3.1
+ version: 18.3.1([email protected])
devDependencies:
'@testing-library/react':
specifier: ^14.3.1
diff --git a/products/notebooks/frontend/NotebookBtw.stories.tsx b/products/notebooks/frontend/NotebookBtw.stories.tsx
new file mode 100644
index 000000000000..1dd274e93336
--- /dev/null
+++ b/products/notebooks/frontend/NotebookBtw.stories.tsx
@@ -0,0 +1,69 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import { MarkdownNotebook } from 'lib/components/MarkdownNotebook/MarkdownNotebook'
+
+import { NotebookBtwLayout } from './NotebookBtwLayout'
+import type { NotebookBtwSession } from './notebookBtwLogic'
+
+const markdown = `# Weekly activation review
+
+Activation improved after the onboarding changes. **Signup completion** is up, while workspace setup is steady.
+
+## Questions for the team
+
+- Which onboarding step improved the most?
+- Do the results hold for new workspaces?
+- What should we investigate next?
+
+## Next steps
+
+Compare this week's signup funnel with last week's and review the sessions where setup was abandoned.`
+
+function NotebookBtwExample({ session: initialSession }: { session: NotebookBtwSession | null }): JSX.Element {
+ const [session, setSession] = useState(initialSession)
+ const [value, setValue] = useState(markdown)
+
+ return (
+ <NotebookBtwLayout session={session} onClose={() => setSession(null)}>
+ <MarkdownNotebook
+ value={value}
+ onChange={setValue}
+ onAskAI={() => {}}
+ onBtw={(context) => setSession({ panelId: 'notebook-btw-story', context })}
+ />
+ </NotebookBtwLayout>
+ )
+}
+
+const meta: Meta<typeof NotebookBtwLayout> = {
+ title: 'Scenes-App/Notebooks/BTW',
+ component: NotebookBtwLayout,
+ render: ({ session }) => <NotebookBtwExample session={session} />,
+ args: {
+ session: {
+ panelId: 'notebook-btw-story',
+ context: {
+ markdown,
+ selectedMarkdown: 'Activation improved after the onboarding changes.',
+ },
+ },
+ onClose: () => {},
+ },
+}
+
+export default meta
+type Story = StoryObj<typeof NotebookBtwLayout>
+
+export const Default: Story = {}
+
+export const Narrow: Story = {
+ parameters: { testOptions: { snapshotTargetSelector: '.LemonModal' } },
+ decorators: [
+ (Story) => (
+ <div className="max-w-2xl">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/products/notebooks/frontend/NotebookBtw.tsx b/products/notebooks/frontend/NotebookBtw.tsx
new file mode 100644
index 000000000000..6a3de2c4b22c
--- /dev/null
+++ b/products/notebooks/frontend/NotebookBtw.tsx
@@ -0,0 +1,86 @@
+import { useCallback, useMemo, useState } from 'react'
+import { createPortal } from 'react-dom'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'
+
+import { getNotebookBtwContext } from './notebookBtwContext'
+import type { NotebookBtwSession } from './notebookBtwLogic'
+
+const CONVERSATION_DESCRIPTION =
+ 'Sent messages are saved in PostHog AI history, separately from this notebook. After a refresh, reopen the conversation from history.'
+
+const COMPOSER_OVERRIDE = {
+ placeholder: 'Ask a side question...',
+ subheadline: null,
+ hideRepositorySelector: true,
+ hideSuggestions: true,
+ hideRecentTasks: true,
+ hideOnboardingReplay: true,
+}
+
+export function NotebookBtw({
+ session,
+ onClose,
+ presentation,
+}: {
+ session: NotebookBtwSession
+ onClose: () => void
+ presentation: 'sidebar' | 'modal'
+}): JSX.Element {
+ const contextItems = useMemo(() => getNotebookBtwContext(session.context), [session.context])
+
+ // Move the portal host so resizing preserves the composer draft and active conversation.
+ const [chatContainer] = useState(() => document.createElement('div'))
+ const attachChat = useCallback(
+ (host: HTMLDivElement | null) => {
+ if (host) {
+ chatContainer.className = 'flex h-full min-h-0 flex-col'
+ host.appendChild(chatContainer)
+ }
+ },
+ [chatContainer]
+ )
+
+ return (
+ <>
+ {presentation === 'modal' ? (
+ <LemonModal isOpen title="BTW" description={CONVERSATION_DESCRIPTION} onClose={onClose} width={640}>
+ <div ref={attachChat} className="h-[65vh] min-h-0 overflow-hidden" />
+ </LemonModal>
+ ) : (
+ <aside
+ aria-label="BTW"
+ className="sticky top-4 flex h-[calc(100dvh-9rem)] w-96 shrink-0 flex-col self-start overflow-hidden rounded border bg-surface-primary"
+ >
+ <header className="flex items-start justify-between gap-2 border-b p-4">
+ <div>
+ <h3 className="mb-1">BTW</h3>
+ <p className="mb-0 text-secondary">{CONVERSATION_DESCRIPTION}</p>
+ </div>
+ <LemonButton
+ icon={<IconX />}
+ size="small"
+ onClick={onClose}
+ aria-label="Close BTW"
+ data-attr="notebook-btw-close"
+ />
+ </header>
+ <div ref={attachChat} className="min-h-0 flex-1 overflow-hidden p-4" />
+ </aside>
+ )}
+ {createPortal(
+ <SidePanelRunner
+ panelId={session.panelId}
+ contextItems={contextItems}
+ composerOverride={COMPOSER_OVERRIDE}
+ welcomeHeadlines={['What would you like to know?']}
+ attachApplyBackInstructions={false}
+ />,
+ chatContainer
+ )}
+ </>
+ )
+}
diff --git a/products/notebooks/frontend/NotebookBtwLayout.tsx b/products/notebooks/frontend/NotebookBtwLayout.tsx
new file mode 100644
index 000000000000..2f5928ebf16e
--- /dev/null
+++ b/products/notebooks/frontend/NotebookBtwLayout.tsx
@@ -0,0 +1,26 @@
+import { ReactNode } from 'react'
+
+import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
+
+import { NotebookBtw } from './NotebookBtw'
+import type { NotebookBtwSession } from './notebookBtwLogic'
+
+export function NotebookBtwLayout({
+ children,
+ session,
+ onClose,
+}: {
+ children: ReactNode
+ session: NotebookBtwSession | null
+ onClose: () => void
+}): JSX.Element {
+ // Leave room for the notebook beside the conversation, including inside another side panel.
+ const { ref, size } = useResizeBreakpoints({ 0: 'modal', 900: 'sidebar' })
+
+ return (
+ <div ref={ref} className="flex min-w-0 flex-1 gap-4">
+ <div className="min-w-0 flex-1">{children}</div>
+ {session && <NotebookBtw session={session} onClose={onClose} presentation={size} />}
+ </div>
+ )
+}
diff --git a/products/notebooks/frontend/notebookBtwContext.test.ts b/products/notebooks/frontend/notebookBtwContext.test.ts
new file mode 100644
index 000000000000..02dea2b596ed
--- /dev/null
+++ b/products/notebooks/frontend/notebookBtwContext.test.ts
@@ -0,0 +1,28 @@
+import { wrapWithPosthogContext } from 'products/posthog_ai/frontend/api/logics'
+
+import { getNotebookBtwContext } from './notebookBtwContext'
+
+describe('notebook btw context', () => {
+ it.each([undefined, 'Selected paragraph'])(
+ 'sends notebook content and selection as untrusted text (%s)',
+ (selectedMarkdown) => {
+ const message = wrapWithPosthogContext(
+ 'Explain this',
+ getNotebookBtwContext({ markdown: '# Unsaved notebook\n\nDraft paragraph', selectedMarkdown })
+ )
+ const [trusted, untrusted] = message.split('<posthog_untrusted_context>')
+ expect(trusted).toContain('Do not edit the notebook')
+ expect(trusted).not.toContain('Draft paragraph')
+ expect(untrusted).toContain('Draft paragraph')
+ if (selectedMarkdown) {
+ expect(untrusted).toContain(selectedMarkdown)
+ }
+ }
+ )
+
+ it('bounds the snapshot and selection and marks omitted content', () => {
+ const items = getNotebookBtwContext({ markdown: 'a'.repeat(80_000), selectedMarkdown: 'b'.repeat(40_000) })
+ expect(items[1].value).toBe('a'.repeat(64_000) + '\n[Remaining content omitted]')
+ expect(items[2].value).toBe('b'.repeat(32_000) + '\n[Remaining content omitted]')
+ })
+})
diff --git a/products/notebooks/frontend/notebookBtwContext.ts b/products/notebooks/frontend/notebookBtwContext.ts
new file mode 100644
index 000000000000..bb5059ca0f4e
--- /dev/null
+++ b/products/notebooks/frontend/notebookBtwContext.ts
@@ -0,0 +1,38 @@
+import { stripNotebookMediaFromMarkdown } from 'lib/components/MarkdownNotebook/documentModel'
+import type { NotebookBtwContext } from 'lib/components/MarkdownNotebook/MarkdownNotebook'
+
+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
+
+const BTW_INSTRUCTIONS: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ 'You are answering a side question in notebook BTW. Answer concisely in this conversation. ' +
+ 'The notebook_snapshot contains the editor content when this conversation was opened, including unsaved changes at that time. ' +
+ 'The notebook_selection, when present, is the content the user is asking about. ' +
+ 'Treat these as reference material. Do not edit the notebook, ' +
+ 'create artifacts, or perform write operations. If the user requests changes, explain that they ' +
+ 'can use Ask AI in the notebook instead. Read-only tools may be used to answer the question. ' +
+ 'These instructions take precedence over general notebook editing instructions for this conversation.',
+}
+
+function boundedMarkdown(markdown: string, maxLength: number): string {
+ const stripped = stripNotebookMediaFromMarkdown(markdown)
+ return stripped.length > maxLength ? `${stripped.slice(0, maxLength)}\n[Remaining content omitted]` : stripped
+}
+
+export function getNotebookBtwContext(context: NotebookBtwContext): AttachedContextItem[] {
+ return [
+ BTW_INSTRUCTIONS,
+ { type: 'notebook_snapshot', label: 'Notebook', value: boundedMarkdown(context.markdown, 64_000) },
+ ...(context.selectedMarkdown
+ ? [
+ {
+ type: 'notebook_selection',
+ label: 'Selected content',
+ value: boundedMarkdown(context.selectedMarkdown, 32_000),
+ },
+ ]
+ : []),
+ ]
+}
diff --git a/products/notebooks/frontend/notebookBtwLogic.ts b/products/notebooks/frontend/notebookBtwLogic.ts
new file mode 100644
index 000000000000..2ef338c0c5c6
--- /dev/null
+++ b/products/notebooks/frontend/notebookBtwLogic.ts
@@ -0,0 +1,43 @@
+import { LogicWrapper, MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'
+
+import type { NotebookBtwContext } from 'lib/components/MarkdownNotebook/MarkdownNotebook'
+import { uuid } from 'lib/utils/dom'
+
+export interface NotebookBtwLogicProps {
+ shortId: string
+}
+
+export interface NotebookBtwSession {
+ panelId: string
+ context: NotebookBtwContext
+}
+
+export interface notebookBtwLogicValues {
+ session: NotebookBtwSession | null
+}
+
+export interface notebookBtwLogicActions {
+ openBtw: (context: NotebookBtwContext) => { context: NotebookBtwContext; panelId: string }
+ closeBtw: () => { value: true }
+}
+
+export type notebookBtwLogicType = MakeLogicType<notebookBtwLogicValues, notebookBtwLogicActions, NotebookBtwLogicProps>
+
+export const notebookBtwLogic: LogicWrapper<notebookBtwLogicType> = kea<notebookBtwLogicType>([
+ path(['products', 'notebooks', 'frontend', 'notebookBtwLogic']),
+ props({} as NotebookBtwLogicProps),
+ key(({ shortId }) => shortId),
+ actions({
+ openBtw: (context: NotebookBtwContext) => ({ context, panelId: `notebook-btw-${uuid()}` }),
+ closeBtw: true,
+ }),
+ reducers({
+ session: [
+ null as NotebookBtwSession | null,
+ {
+ openBtw: (_, { context, panelId }) => ({ context, panelId }),
+ closeBtw: () => null,
+ },
+ ],
+ }),
+])
diff --git a/products/notebooks/package.json b/products/notebooks/package.json
index 9e73b9a56fc9..f250a58656a3 100644
--- a/products/notebooks/package.json
+++ b/products/notebooks/package.json
@@ -17,8 +17,10 @@
"@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
"@types/react": "*",
+ "@types/react-dom": "*",
"clsx": "*",
"fuse.js": "*",
- "react": "*"
+ "react": "*",
+ "react-dom": "*"
}
}
diff --git a/products/posthog_ai/frontend/logics/composerOverrideLogic.ts b/products/posthog_ai/frontend/logics/composerOverrideLogic.ts
index 62195e370993..91be0d0a07c1 100644
--- a/products/posthog_ai/frontend/logics/composerOverrideLogic.ts
+++ b/products/posthog_ai/frontend/logics/composerOverrideLogic.ts
@@ -2,6 +2,8 @@ import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
/** What a host surface can change about the composer's empty state. */
export interface ComposerOverride {
+ placeholder?: string
+ subheadline?: string | null
/** Hide the repository and branch picker when the task never touches a repo. */
hideRepositorySelector?: boolean
/** Hide the generic "Try PostHog AI for…" row when the host renders its own suggestions. */
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index 704d672f6cce..42e8ecc829c2 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -1198,11 +1198,20 @@ describe('runInteractionLogic', () => {
}
)
- it('wraps outgoing content with the attached-context block while echoing the raw text, and dedupes per task', async () => {
- attachedContextLogic().actions.registerContext('scene', [
+ it.each(['global', 'runner'])('wraps and deduplicates %s context while echoing raw text', async (scope) => {
+ const contextItems = [
{ type: 'insight', key: 'sig', label: 'Signups' },
{ type: 'text', value: 'always resend me' },
- ])
+ ]
+ attachedContextLogic().actions.registerContext(
+ 'scene',
+ scope === 'global' ? contextItems : [{ type: 'text', value: 'unrelated scene context' }]
+ )
+ if (scope === 'runner') {
+ logic.unmount()
+ logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted, contextItems })
+ logic.mount()
+ }
setThinking(false)
logic.actions.setComposerFormValues({ draft: 'why the drop?' })
@@ -1216,6 +1225,7 @@ describe('runInteractionLogic', () => {
// The wire content carries the invisible context block; the echoed human message stays raw.
expect(firstSend.params.content).toContain('<posthog_untrusted_context>')
expect(firstSend.params.content).toContain('- insight sig ("Signups")')
+ expect(firstSend.params.content).not.toContain('unrelated scene context')
expect(firstSend.params.content.endsWith('why the drop?')).toBe(true)
await expectLogic(stream).toDispatchActions([
(action) =>
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 91f1f92a5512..1cc53724173d 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -76,6 +76,8 @@ export interface RunInteractionLogicProps {
initialDraft?: string
onDraftAdopted?: () => void
flushDraft?: () => void
+ /** Context exclusive to the runner that owns this interaction. */
+ contextItems?: AttachedContextItem[]
/** The run's stored model / reasoning effort / launch mode, injected by the consumer. They seed the picker's
* display and the config a terminal-run send launches the next run with (override ?? this ?? default). */
currentModel?: string | null
@@ -515,10 +517,10 @@ export interface runInteractionLogicMeta {
) => boolean
isSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean
pendingContextItems: (
- contextItems: AttachedContextItem[],
+ arg: AttachedContextItem[],
sentContextKeysByTask: Record<string, string[]>,
seenContextLinesByTask: Record<string, string[]>,
- arg: string
+ arg2: string
) => AttachedContextItem[]
}
}
@@ -1004,7 +1006,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// text is intentional, e.g. consecutive error snippets).
pendingContextItems: [
(s) => [
- s.contextItems,
+ (state, p: RunInteractionLogicProps) => p.contextItems ?? s.contextItems(state, p),
s.sentContextKeysByTask,
s.seenContextLinesByTask,
(_, p: RunInteractionLogicProps) => p.taskId,
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
index 23d8327f89bd..b99781a80c03 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
@@ -6,7 +6,8 @@ import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { useAttachedContext } from '../../../hooks/useAttachedContext'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
-import { composerOverrideLogic } from '../../../logics/composerOverrideLogic'
+import type { ComposerOverride } from '../../../logics/composerOverrideLogic'
+import type { AttachedContextItem } from '../../../types/contextTypes'
import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../../../utils/posthogContextBlock'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
import { StartupRunChat } from './StartupRunChat'
@@ -18,6 +19,11 @@ export interface SidePanelRunnerImplProps {
/** Embedded `taskTrackerSceneLogic` key — keeps this instance independent of the `/tasks` scene singleton. */
panelId: string
composer?: ReactNode
+ attachApplyBackInstructions?: boolean
+ /** Context exclusive to this runner, rather than the app-wide attached-context registry. */
+ contextItems?: AttachedContextItem[]
+ composerOverride?: ComposerOverride
+ welcomeHeadlines?: string[]
}
/**
@@ -27,17 +33,39 @@ export interface SidePanelRunnerImplProps {
* `TaskTrackerSceneLogicProps`) so `TaskComposer` — which reads the unbound `taskTrackerSceneLogic` — resolves
* this instance instead of the scene's own singleton.
*/
-export function SidePanelRunnerImpl({ panelId, composer }: SidePanelRunnerImplProps): JSX.Element {
+export function SidePanelRunnerImpl({
+ panelId,
+ composer,
+ attachApplyBackInstructions = true,
+ contextItems,
+ composerOverride,
+ welcomeHeadlines,
+}: SidePanelRunnerImplProps): JSX.Element {
return (
- <BindLogic logic={taskTrackerSceneLogic} props={{ panelId }}>
- <SidePanelRunnerContent composer={composer} />
+ <BindLogic logic={taskTrackerSceneLogic} props={{ panelId, contextItems, composerOverride, welcomeHeadlines }}>
+ <SidePanelRunnerContent
+ composer={composer}
+ attachApplyBackInstructions={attachApplyBackInstructions}
+ contextItems={contextItems}
+ />
</BindLogic>
)
}
-function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Element {
- const { activeCreation, historyExpanded } = useValues(taskTrackerSceneLogic)
- const { composerOverride } = useValues(composerOverrideLogic)
+function SidePanelRunnerContent({
+ composer,
+ attachApplyBackInstructions,
+ contextItems,
+}: {
+ composer?: ReactNode
+ attachApplyBackInstructions: boolean
+ contextItems?: AttachedContextItem[]
+}): JSX.Element {
+ const {
+ activeCreation,
+ historyExpanded,
+ effectiveComposerOverride: composerOverride,
+ } = useValues(taskTrackerSceneLogic)
const { toggleHistory, updateActiveCreationRun, setStartupDraft } = useActions(taskTrackerSceneLogic)
const startupFocusedRef = useRef(false)
@@ -47,10 +75,9 @@ function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Ele
// `TaskRunChat`; registrations are provider-keyed, so co-mounted surfaces don't clobber each other.
useForegroundStream(activeCreation?.streamKey ?? null)
- // While this side-panel surface is mounted, tell the agent its tool calls are applied back into
- // whatever the user has open (see `useMcpToolApplyBack` consumers). Attached unconditionally —
- // unlike the foreground stream above, the instruction must ride the FIRST send, before a run exists.
- useAttachedContext([AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM])
+ // Edit-capable hosts attach this before the first send, before a run exists. Question-only
+ // hosts provide their own instructions instead of advertising edits to the open page.
+ useAttachedContext(attachApplyBackInstructions ? [AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM] : null)
// `!composer`: a host that supplies its own composer offers no way into the history list, and the
// panel state is shared across hosts — so an expanded history left behind by another one must not
@@ -106,11 +133,16 @@ function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Ele
initialDraft={activeCreation.draft}
onDraftAdopted={() => setStartupDraft('')}
autoFocus={startupFocusedRef.current}
+ contextItems={contextItems}
/>
</div>
) : (
<div className="flex-1 min-h-0 px-4">
- <StartupRunChat streamKey={activeCreation.streamKey} focusedRef={startupFocusedRef} />
+ <StartupRunChat
+ streamKey={activeCreation.streamKey}
+ focusedRef={startupFocusedRef}
+ contextItems={contextItems}
+ />
</div>
)}
</div>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
index 53a8fcb3259e..f8d8314d664c 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
@@ -5,6 +5,7 @@ import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'
import { runInteractionLogic, type RunInteractionLogicProps } from '../../../logics/runInteractionLogic'
+import type { AttachedContextItem } from '../../../types/contextTypes'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
import { TaskRunComposer } from './TaskRunComposer'
@@ -12,10 +13,12 @@ export function StartupRunChat({
streamKey,
focusedRef,
escapeScope = 'composer',
+ contextItems,
}: {
streamKey: string
focusedRef?: MutableRefObject<boolean>
escapeScope?: RunEscapeBoundaryProps['scope']
+ contextItems?: AttachedContextItem[]
}): JSX.Element {
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const flushDraftRef = useRef<() => void>(() => {})
@@ -26,6 +29,7 @@ export function StartupRunChat({
streamKey,
interactionKey: streamKey,
flushDraft: () => flushDraftRef.current(),
+ contextItems,
}
const interaction = runInteractionLogic(logicProps)
const { handleEscape } = useActions(interaction)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 85a4675fed92..ce677967cd20 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -12,7 +12,6 @@ import {
Suggestions,
Welcome,
} from 'products/posthog_ai/frontend/api/primitives'
-import { composerOverrideLogic } from 'products/posthog_ai/frontend/logics/composerOverrideLogic'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
import { getRuntimeAdapterForModel, resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'
@@ -39,6 +38,7 @@ export function TaskComposer(): JSX.Element {
isSubmittingTask,
activeSuggestionGroup,
displayHeadline,
+ effectiveComposerOverride: composerOverride,
consentBlocked,
displayModel,
defaultModel,
@@ -50,7 +50,6 @@ export function TaskComposer(): JSX.Element {
} = useValues(taskTrackerSceneLogic)
const { catalogue } = useValues(modelCatalogueLogic)
const { myConfigLoading } = useValues(taskRunDefaultsLogic)
- const { composerOverride } = useValues(composerOverrideLogic)
// The bound instance's key — 'scene' on `/ai` and `/tasks`, the panel key when embedded. The onboarding
// takeover is keyed the same way, so a starter prompt chosen on replay reaches this composer.
@@ -73,7 +72,7 @@ export function TaskComposer(): JSX.Element {
return (
<div className="flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4">
<div className="w-full max-w-2xl flex flex-col items-center gap-4">
- <Welcome headline={displayHeadline}>
+ <Welcome headline={displayHeadline} subheadline={composerOverride?.subheadline}>
{/* Temporary migration affordance — delete with the rest of the onboarding takeover
once everyone is on the new PostHog AI. */}
{!composerOverride?.hideOnboardingReplay && <OnboardingReplayButton panelId={panelId} />}
@@ -112,7 +111,9 @@ export function TaskComposer(): JSX.Element {
<AttachedContextBar />
</Composer.Header>
<Composer.Field>
- <Composer.Placeholder>Describe the task in detail…</Composer.Placeholder>
+ <Composer.Placeholder>
+ {composerOverride?.placeholder ?? 'Describe the task in detail…'}
+ </Composer.Placeholder>
<Composer.Textarea autoFocus data-attr="task-composer-input" />
</Composer.Field>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 1ba03e32d419..c1537ab4489c 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -13,6 +13,7 @@ import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../compone
import { useForegroundStream } from '../../../hooks/useForegroundStream'
import { runCancellationLogic } from '../../../logics/runCancellationLogic'
import type { RunContinuationHandoff } from '../../../logics/runInteractionLogic'
+import type { AttachedContextItem } from '../../../types/contextTypes'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
import { TaskRunComposer } from './TaskRunComposer'
@@ -32,6 +33,7 @@ export interface TaskRunChatProps {
initialDraft?: string
onDraftAdopted?: () => void
autoFocus?: boolean
+ contextItems?: AttachedContextItem[]
}
/**
@@ -52,6 +54,7 @@ export function TaskRunChat({
initialDraft,
onDraftAdopted,
autoFocus,
+ contextItems,
}: TaskRunChatProps): JSX.Element {
const { setSelectedRunId, loadTaskRuns, continueWithRun } = useActions(taskDetailSceneLogic({ taskId }))
const { selectedRun, task } = useValues(taskDetailSceneLogic({ taskId }))
@@ -73,6 +76,7 @@ export function TaskRunChat({
initialDraft,
onDraftAdopted,
flushDraft: () => flushDraftRef.current(),
+ contextItems: contextItems ?? pendingInteraction?.props.contextItems,
currentModel:
runConfig?.model ??
(typeof runConfig?.state?.model === 'string'
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index df1558cec7c0..c838ada98ab0 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -19,6 +19,7 @@ import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { runInteractionLogic } from '../../logics/runInteractionLogic'
import { TaskDraftPersistence, taskDraftStorageKey } from '../../logics/taskDraftPersistence'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
+import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
@@ -606,7 +607,7 @@ describe('taskTrackerSceneLogic', () => {
})
// The side panel shares this logic, so a hidden picker can still hold a remembered repo. It must not reach the requests.
- it('keeps a hidden repository out of the warm and create requests', async () => {
+ it.each(['global', 'runner'])('keeps a repository hidden by a %s override out of requests', async (scope) => {
useMocks({
get: {
'/api/projects/:team/integrations/': {
@@ -616,7 +617,10 @@ describe('taskTrackerSceneLogic', () => {
})
const overrides = composerOverrideLogic()
overrides.mount()
- overrides.actions.registerComposerOverride('new-workflow', { hideRepositorySelector: true })
+ overrides.actions.registerComposerOverride('new-workflow', { hideRepositorySelector: scope === 'global' })
+ if (scope === 'runner') {
+ logic = taskTrackerSceneLogic({ panelId: 'btw', composerOverride: { hideRepositorySelector: true } })
+ }
logic.mount()
await expectLogic(logic).toFinishAllListeners()
logic.actions.setNewTaskData({ repositoryConfig: { integrationId: 7, repository: 'acme/widgets' } })
@@ -633,6 +637,35 @@ describe('taskTrackerSceneLogic', () => {
overrides.unmount()
})
+ it('keeps runner composer settings independent of scene overrides', () => {
+ const overrides = composerOverrideLogic()
+ const headlines = welcomeOverrideLogic()
+ overrides.mount()
+ headlines.mount()
+ overrides.actions.registerComposerOverride('scene', { placeholder: 'Edit this notebook' })
+ headlines.actions.registerHeadlines('scene', ['Make changes'])
+ logic.mount()
+ const panel = taskTrackerSceneLogic({
+ panelId: 'btw',
+ composerOverride: { placeholder: 'Ask a side question...', hideRepositorySelector: true },
+ welcomeHeadlines: ['What would you like to know?'],
+ })
+ panel.mount()
+
+ expect(panel.values.effectiveComposerOverride).toEqual({
+ placeholder: 'Ask a side question...',
+ hideRepositorySelector: true,
+ })
+ expect(panel.values.displayHeadline).toBe('What would you like to know?')
+ expect(logic.values.effectiveComposerOverride).toEqual({ placeholder: 'Edit this notebook' })
+ expect(logic.values.displayHeadline).toBe('Make changes')
+
+ panel.unmount()
+ expect(logic.values.effectiveComposerOverride).toEqual({ placeholder: 'Edit this notebook' })
+ headlines.unmount()
+ overrides.unmount()
+ })
+
// An embedded instance (e.g. Max's side panel runner) keeps the run in place instead of navigating the
// host to `/tasks/:id`, and must never have its `activeCreation` cleared by unrelated main-app
// navigation. Guards against either guard (`props.panelId` in `submitNewTask` / `urlToAction`) being
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index c0b828b3dc9f..c336eb5e0de5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -82,6 +82,10 @@ export type PersistedRepositoryConfig = Pick<RepositoryConfig, 'integrationId' |
// `urlToAction` cleanup (main-app navigation must never release a side panel's in-flight creation).
export interface TaskTrackerSceneLogicProps {
panelId?: string
+ /** Context exclusive to an embedded runner. */
+ contextItems?: AttachedContextItem[]
+ composerOverride?: ComposerOverride
+ welcomeHeadlines?: string[]
}
const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'
@@ -185,6 +189,7 @@ export interface taskTrackerSceneLogicValues {
displayEffort: ReasoningEffortEnumApi
displayHeadline: string
displayModel: string
+ effectiveComposerOverride: ComposerOverride | null
effectiveRepositoryConfig: RepositoryConfig
hasDesktopAccess: boolean
headlineSeed: number
@@ -333,7 +338,11 @@ export interface taskTrackerSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
hasDesktopAccess: (desktopAccess: LegacyDesktopAccessResponseApi | null) => boolean
- displayHeadline: (overrideHeadlines: string[] | null, headlineSeed: number) => string
+ displayHeadline: (overrideHeadlines: string[] | null, headlineSeed: number, arg: string[] | undefined) => string
+ effectiveComposerOverride: (
+ composerOverride: ComposerOverride | null,
+ arg: ComposerOverride | undefined
+ ) => ComposerOverride | null
displayModel: (newTaskData: TaskCreateForm, defaultModel: string | null) => string
displayEffort: (
newTaskData: TaskCreateForm,
@@ -349,7 +358,7 @@ export interface taskTrackerSceneLogicMeta {
) => string
effectiveRepositoryConfig: (
newTaskData: TaskCreateForm,
- composerOverride: ComposerOverride | null
+ effectiveComposerOverride: ComposerOverride | null
) => RepositoryConfig
isDefaultSelection: (newTaskData: TaskCreateForm) => boolean
}
@@ -507,9 +516,19 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Contextual headlines registered by the active scene (welcomeOverrideLogic) win over the
// generic defaults; the seed keeps the pick stable across re-renders.
displayHeadline: [
- (s) => [s.overrideHeadlines, s.headlineSeed],
- (overrideHeadlines: string[] | null, headlineSeed: number): string =>
- pickHeadline(overrideHeadlines ?? DEFAULT_HEADLINES, headlineSeed),
+ (s) => [s.overrideHeadlines, s.headlineSeed, (_, p: TaskTrackerSceneLogicProps) => p.welcomeHeadlines],
+ (
+ overrideHeadlines: string[] | null,
+ headlineSeed: number,
+ welcomeHeadlines: string[] | undefined
+ ): string => pickHeadline(welcomeHeadlines ?? overrideHeadlines ?? DEFAULT_HEADLINES, headlineSeed),
+ ],
+ effectiveComposerOverride: [
+ (s) => [s.composerOverride, (_, p: TaskTrackerSceneLogicProps) => p.composerOverride],
+ (
+ globalOverride: ComposerOverride | null,
+ localOverride: ComposerOverride | undefined
+ ): ComposerOverride | null => localOverride ?? globalOverride,
],
}),
@@ -548,7 +567,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
],
// The shared form may still hold a remembered repo while the picker is hidden. Drop it here, not from the form.
effectiveRepositoryConfig: [
- (s) => [s.newTaskData, s.composerOverride],
+ (s) => [s.newTaskData, s.effectiveComposerOverride],
(newTaskData: TaskCreateForm, composerOverride: ComposerOverride | null): RepositoryConfig =>
composerOverride?.hideRepositorySelector ? {} : newTaskData.repositoryConfig,
],
@@ -669,7 +688,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// pane renders, and survives across the React swap into the detail page (which adopts the same
// instance by binding this `streamKey`). Released by `clearActiveCreation` (failure / leaving the run).
const streamKey = `draft-${uuid()}`
- const seededContext = values.contextItems
+ const seededContext = props.contextItems ?? values.contextItems
actions.claimApplyBackTargets(streamKey)
const stream = runStreamLogic({ streamKey })
const interaction = runInteractionLogic({
@@ -682,6 +701,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
currentMode: permissionMode,
currentRuntimeAdapter:
values.isDefaultSelection && !values.defaultRuntimeAdapter ? null : values.composerAdapter,
+ contextItems: props.contextItems,
})
cache.disposables.add(
() => {