:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(growth): turn suggestion cards in posthog ai (#106435)
Rafael Audibert79503e145809
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 454b88c6c7cf..bee3059115a8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7230,6 +7230,30 @@ snapshots:hash: v1.k794b7964.01bd9095cf2448a061749878dfe6b7987084fbcbbc8fbb666ed4289e7087e332.AMVJTk5ixhgsTacK3PZ4heII47WXHCgGBohPR2DaO1sproducts-posthog-ai-threadview-quill--streaming-turn--light:hash: v1.k794b7964.caabab4d290dda51a4d3c302bfdcd4f16a6a54cc9f613da835afab3b8f2c60d3.6KgDrcJZ1u-Sm9NkUS-sUti399TsxKBCytKuU_A-EmU+ products-posthog-ai-turnsuggestioncard--alert-suggestion--dark:+ hash: v1.k794b7964.1d792984be0657f406e45722e1b4799905c474a28f8c985c8e406377a8dd97e7.gQ65VeoKFMTS04UA7UjbntfuL7nkr6Zpk-mhvoTf9X4+ products-posthog-ai-turnsuggestioncard--alert-suggestion--light:+ hash: v1.k794b7964.3c7adbcba23292f8890353b7e6788dfb5828d88388ed66d788cbf1951dd45abf.byZ29GpYD4aDnWNIvEXYy1vrSoR6au3ieBIMqNb8tMw+ products-posthog-ai-turnsuggestioncard--error-alert-suggestion--dark:+ hash: v1.k794b7964.c11acf3ed061e235f538dba634b3503de9b40201f89ddb80a4240354e4bb718f.tv5z2ob1K9r9p_i_a4gGkdSQiJqyU7KLpUMrnH3PC50+ products-posthog-ai-turnsuggestioncard--error-alert-suggestion--light:+ hash: v1.k794b7964.c6dc223c6c00ff64adca63449fff0362c816ae9aed3ddcf3c765f71ce106c440.Fk0c087zG6AoD6VRiSx9UQ7B4Z27joe_prbDsBosgcE+ products-posthog-ai-turnsuggestioncard--notebook-suggestion--dark:+ hash: v1.k794b7964.65e11b6345a9fdc5810abcce0f92950d70ce516d26b6e02fa383717e05c02a33.F-zv9h4tc-T9EGAfCACJfUG9vfRLxhRT1CMPKBiQUsA+ products-posthog-ai-turnsuggestioncard--notebook-suggestion--light:+ hash: v1.k794b7964.e192e0df3c1ebf59bcfeac230763da780f9ca42c000b045e6925fbf4da10b180.c2XzN6lvmiivKnxMijJn-QMLwsM36GWc7Q31kOxGV6w+ products-posthog-ai-turnsuggestioncard--scout-suggestion--dark:+ hash: v1.k794b7964.8ac4e973a9406f3ef5cae9d91460a2bfb174dd26d18c4ca1b95604b8d0bfe273.sRgL4LSzCJ8TLZDGTxpVOLZdA8kzZl1OoSP6C9ujXxU+ products-posthog-ai-turnsuggestioncard--scout-suggestion--light:+ hash: v1.k794b7964.52bf11d0d6830a37954b83a41d47ae883031a502e9dff4bc600735d43963cfb9.qnqqvfQz3UrtvKwfFjQNWzNVHy7jKW5icUYM-CeTxwI+ products-posthog-ai-turnsuggestioncard--scout-suggestion-narrow--dark:+ hash: v1.k794b7964.68220f8b70d659b7b4533390d0b021f7f8d039c92e231347b9cfce0d005003b9.ApVBC12Mk9WIR8U7rjcRb28iuH0oLJYt4V7exJ9VKtI+ products-posthog-ai-turnsuggestioncard--scout-suggestion-narrow--light:+ hash: v1.k794b7964.1fc7be49535f5d260ab85b717cb9d1f32187b1faadc437a7f6618d8fef1b48d2.n3uzy2p9TAPb3T5f2L2jlLUOPLfd6R0HBuCujE3T17U+ products-posthog-ai-turnsuggestioncard--subscription-suggestion--dark:+ hash: v1.k794b7964.6e6f73b3cebbeae8fd62159d4dd51f400764826e2807bb0ea0b0c890af1752f0.RKEZOvSI1RFZTb6EB5Ki_0fIzNP_qJ-4XJ-sDQyNVAY+ products-posthog-ai-turnsuggestioncard--subscription-suggestion--light:+ hash: v1.k794b7964.38410c1248a77a32176a84386f01a7811ff5542d32b8c48f947814db47a46fa7.zinqrBDUi-BxDDs94JkeU8bXN_ZRQ_0hhgcttIhlhP8products-posthog-ai-virtualizedthread--anchored-open--dark:hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OEproducts-posthog-ai-virtualizedthread--anchored-open--light:diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.tsindex 17e9c42a7606..b2caa3459e8d 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts@@ -164,13 +164,13 @@ export function decorateAlertName(baseName: string, selectedKinds: string[] | nureturn `${baseName}${formatKindsSuffix(selectedKinds)}`}-function buildAlertInputs(- template: HogFunctionTemplateType,+export function buildAlertInputs(+ inputsSchema: CyclotronJobInputSchemaType[] | null | undefined,subTemplateInputs: Record<string, CyclotronJobInputType> | null | undefined,inputValues: Record<string, CyclotronJobInputType>): Record<string, CyclotronJobInputType> {const inputs: Record<string, CyclotronJobInputType> = {}- for (const schema of template.inputs_schema ?? []) {+ for (const schema of inputsSchema ?? []) {if (schema.default !== undefined) {inputs[schema.key] = { value: schema.default }}@@ -178,6 +178,43 @@ function buildAlertInputs(return { ...inputs, ...subTemplateInputs, ...inputValues }}+export interface AlertHogFunctionConfiguration {+ type: 'internal_destination'+ template_id: string+ name: string+ description: string+ filters: CyclotronJobFiltersType | null | undefined+ enabled: true+ masking: null+ inputs: Record<string, CyclotronJobInputType>+}++/** The hog function an alert creates: an enabled internal destination with the template's merged inputs. */+export function buildAlertHogFunctionConfiguration({+ templateId,+ name,+ description,+ filters,+ inputs,+}: {+ templateId: string+ name: string+ description: string+ filters: CyclotronJobFiltersType | null | undefined+ inputs: Record<string, CyclotronJobInputType>+}): AlertHogFunctionConfiguration {+ return {+ type: 'internal_destination',+ template_id: templateId,+ name,+ description,+ filters,+ enabled: true,+ masking: null,+ inputs,+ }+}+function extractDestinationKeyFromAlert(alert: HogFunctionType, allDestinations: WizardDestination[]): string | null {const templateId = alert.template?.idif (!templateId) {@@ -685,7 +722,11 @@ export const alertWizardLogic = kea<alertWizardLogicType>([return}- const mergedInputs = buildAlertInputs(selectedTemplate, subTemplate.inputs, values.inputValues)+ const mergedInputs = buildAlertInputs(+ selectedTemplate.inputs_schema,+ subTemplate.inputs,+ values.inputValues+ )const configuration: Record<string, any> = {type: 'internal_destination',@@ -771,22 +812,23 @@ export const alertWizardLogic = kea<alertWizardLogicType>([return}- const mergedInputs = buildAlertInputs(selectedTemplate, subTemplate.inputs, values.inputValues)+ const mergedInputs = buildAlertInputs(+ selectedTemplate.inputs_schema,+ subTemplate.inputs,+ values.inputValues+ )const filters = applyKindFilter(subTemplate.filters, values.selectedKinds)const name = decorateAlertName(subTemplate.name ?? '', values.selectedKinds)const description = decorateAlertName(subTemplate.description ?? '', values.selectedKinds)- const configuration: Record<string, any> = {- type: 'internal_destination',- template_id: destination.templateId,+ const configuration = buildAlertHogFunctionConfiguration({+ templateId: destination.templateId,name,description,filters,- enabled: true,- masking: null,inputs: mergedInputs,- }+ })await api.hogFunctions.create(configuration)posthog.capture('error_tracking_alert_created', {diff --git a/frontend/src/lib/components/Comments/SlackDestinationPicker.tsx b/frontend/src/lib/components/Comments/SlackDestinationPicker.tsxindex 741d206f538f..fab923a9c1a7 100644--- a/frontend/src/lib/components/Comments/SlackDestinationPicker.tsx+++ b/frontend/src/lib/components/Comments/SlackDestinationPicker.tsx@@ -16,15 +16,20 @@ export type SlackDestinationPickerProps = {onChannelChange: (channel: string | null) => void/** Extra classes for the picker container; not applied to the loading/not-configured states. */className?: string+ /** Replaces the lead sentence of the banner shown when the project has no Slack workspace. */+ notConfiguredDescription?: string+ onConnectClick?: () => void}-/** Slack workspace + channel picker shared by the comment composer and the send-to-Slack modal. */+/** Slack workspace + channel picker shared by the comment composer, the send-to-Slack modal and PostHog AI cards. */export function SlackDestinationPicker({integrationId,channel,onIntegrationChange,onChannelChange,className,+ notConfiguredDescription,+ onConnectClick,}: SlackDestinationPickerProps): JSX.Element {const { slackIntegrations, integrationsLoading } = useValues(integrationsLogic)const selectedIntegration = slackIntegrations?.find((integration) => integration.id === integrationId)@@ -39,7 +44,13 @@ export function SlackDestinationPicker({}if (!slackIntegrations?.length) {- return <SlackNotConfiguredBanner onConnected={onIntegrationChange} />+ return (+ <SlackNotConfiguredBanner+ description={notConfiguredDescription}+ onConnected={onIntegrationChange}+ onConnectClick={onConnectClick}+ />+ )}return (diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.tsindex a4840e722530..61c40ea278fc 100644--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts@@ -2008,13 +2008,37 @@ export function escapeMarkdownLineStart(line: string): string {return `${leadingWhitespace}${orderedListMatch[1]}\\${content.slice(orderedListMatch[1].length)}`}- if (/^(#{1,6}\s|>|[-+•](\s|$)|-{3,}\s*$|<[A-Z]|<!--)/.test(content)) {+ if (/^(#{1,6}\s|>|[-+•](\s|$)|-{3,}\s*$)/.test(content) || COMPONENT_TAG_LINE_START.test(content)) {return `${leadingWhitespace}\\${content}`}return line}+const COMPONENT_TAG_LINE_START = /^(<[A-Z]|<!--)/+const COMPONENT_TAG_OPENER = /^\\?(<[A-Z][A-Za-z0-9]*|<!--)/+// The notebooks backend reads a cell after Python's `str.strip()`, which also removes `\x1c` to `\x1f`+// and `\x85`. The editor lifts a quoted tag out of its blockquote, so `>` markers count as a prefix too.+const COMPONENT_TAG_LINE_PREFIX = /^[\s\x1c-\x1f\x85>]*/++// A backslash is not enough: both parsers recover a `\<Tag` that spans lines, because the prose+// serializer writes multiline components that way. Inline code cannot be recovered into a tag.+function escapeComponentTagLineStart(line: string): string {+ const prefix = line.match(COMPONENT_TAG_LINE_PREFIX)?.[0] ?? ''+ const content = line.slice(prefix.length)+ const match = content.match(COMPONENT_TAG_OPENER)+ return match ? `${prefix}\`${match[1]}\`${content.slice(match[0].length)}` : line+}++// For markdown the author meant to render: only a line that would parse as a component tag or a+// comment is neutralized, so headings and lists stay live. Lines inside code fences are neutralized+// too, because the editor and the notebooks backend disagree on where a fence ends, and a fence can+// span the blocks a caller joins. The cost is a stray pair of backticks in a code sample.+// The notebooks backend reads `\r` as a line break, so it is one here too.+export function escapeComponentTagLines(markdown: string): string {+ return markdown.replace(/\r\n?/g, '\n').split('\n').map(escapeComponentTagLineStart).join('\n')+}+function getCodeBlockFence(text: string): string {const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), (match) => match[0].length))return '`'.repeat(Math.max(3, longestRun + 1))diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 47ad306a5804..586a456ccdcc 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7320,6 +7320,7 @@ export interface CyclotronJobFilterActions extends CyclotronJobFilterBase {export type CyclotronJobFilterPropertyFilter =| EventPropertyFilter+ | EventMetadataPropertyFilter| PersonPropertyFilter| ElementPropertyFilter| GroupPropertyFilterdiff --git a/products/posthog_ai/frontend/components/AlertSuggestionCard.tsx b/products/posthog_ai/frontend/components/AlertSuggestionCard.tsxnew file mode 100644index 000000000000..2cdaaa125874--- /dev/null+++ b/products/posthog_ai/frontend/components/AlertSuggestionCard.tsx@@ -0,0 +1,71 @@+import { useActions, useValues } from 'kea'++import { LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'+import { ALERT_DIRECTION_OPTIONS } from '../utils/turnSuggestions'+import { SlackDestinationSection } from './SlackDestinationSection'+import { SuggestionAcceptedBanner } from './SuggestionAcceptedBanner'+import { SuggestionActionRow } from './SuggestionActionRow'+import { SuggestionDraftSummary } from './SuggestionDraftSummary'++export function AlertSuggestionCard(props: TurnSuggestionLogicProps): JSX.Element | null {+ const logic = suggestionActionLogic(props)+ const { suggestion, direction, changePercent, accepted, slackChannelLabel } = useValues(logic)+ const { setDirection, setChangePercent } = useActions(logic)++ if (suggestion?.kind !== 'alert') {+ return null+ }+ if (accepted) {+ return (+ <SuggestionAcceptedBanner accepted={accepted} linkLabel="View alert">+ {accepted.slackConnected+ ? `Alert created. It checks ${suggestion.alert.insightName} once a day and posts to ${slackChannelLabel}.`+ : `Alert created, but it can't post to ${slackChannelLabel} yet. Open the alert to add Slack.`}+ </SuggestionAcceptedBanner>+ )+ }++ return (+ <>+ <SuggestionDraftSummary name={suggestion.alert.insightName} />++ <div className="flex flex-wrap items-end gap-2">+ <div className="flex flex-col gap-1">+ <LemonLabel>Fires when it</LemonLabel>+ <LemonSelect+ size="small"+ value={direction}+ options={ALERT_DIRECTION_OPTIONS}+ onChange={(value) => value && setDirection(value)}+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>More than</LemonLabel>+ <LemonInput+ size="small"+ type="number"+ min={1}+ step={1}+ suffix={<span className="text-secondary">%</span>}+ value={changePercent}+ onChange={(value) => setChangePercent(value ?? 0)}+ className="w-24"+ data-attr="posthog-ai-turn-suggestion-alert-percent"+ />+ </div>+ </div>++ <SlackDestinationSection {...props} connectHint="Connect Slack to post the alert to a channel." />++ <SuggestionActionRow+ {...props}+ label="Create alert"+ dataAttr="posthog-ai-turn-suggestion-create-alert"+ failedMessage="Couldn't create the alert. Try again."+ />+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/ErrorAlertSuggestionCard.tsx b/products/posthog_ai/frontend/components/ErrorAlertSuggestionCard.tsxnew file mode 100644index 000000000000..2bb90b29b37b--- /dev/null+++ b/products/posthog_ai/frontend/components/ErrorAlertSuggestionCard.tsx@@ -0,0 +1,38 @@+import { useValues } from 'kea'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'+import { SlackDestinationSection } from './SlackDestinationSection'+import { SuggestionAcceptedBanner } from './SuggestionAcceptedBanner'+import { SuggestionActionRow } from './SuggestionActionRow'+import { SuggestionDraftSummary } from './SuggestionDraftSummary'++export function ErrorAlertSuggestionCard(props: TurnSuggestionLogicProps): JSX.Element | null {+ const { suggestion, accepted, slackChannelLabel } = useValues(suggestionActionLogic(props))++ if (suggestion?.kind !== 'error_alert') {+ return null+ }+ if (accepted) {+ return (+ <SuggestionAcceptedBanner accepted={accepted} linkLabel="View alert">+ Alert created. {slackChannelLabel} gets a message if this issue reopens.+ </SuggestionAcceptedBanner>+ )+ }++ return (+ <>+ <SuggestionDraftSummary name={suggestion.errorAlert.issueName} />++ <SlackDestinationSection {...props} connectHint="Connect Slack to post the alert to a channel." />++ <SuggestionActionRow+ {...props}+ label="Create alert"+ dataAttr="posthog-ai-turn-suggestion-create-error-alert"+ failedMessage="Couldn't create the alert. Try again."+ />+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/NotebookSuggestionCard.tsx b/products/posthog_ai/frontend/components/NotebookSuggestionCard.tsxnew file mode 100644index 000000000000..a2a9bc10af9e--- /dev/null+++ b/products/posthog_ai/frontend/components/NotebookSuggestionCard.tsx@@ -0,0 +1,56 @@+import { useActions, useValues } from 'kea'++import { LemonInput, LemonLabel } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'+import { SuggestionAcceptedBanner } from './SuggestionAcceptedBanner'+import { SuggestionActionRow } from './SuggestionActionRow'++export function NotebookSuggestionCard(props: TurnSuggestionLogicProps): JSX.Element | null {+ const logic = suggestionActionLogic(props)+ const { suggestion, notebookTitle, conversationBlocks, accepted } = useValues(logic)+ const { setTitle } = useActions(logic)++ if (suggestion?.kind !== 'notebook') {+ return null+ }+ if (accepted) {+ return (+ <SuggestionAcceptedBanner accepted={accepted} linkLabel="Open notebook">+ Saved to a notebook.+ </SuggestionAcceptedBanner>+ )+ }++ return (+ <>+ <div className="flex flex-col gap-1">+ <LemonLabel>Notebook title</LemonLabel>+ <LemonInput+ size="small"+ value={notebookTitle}+ onChange={setTitle}+ maxLength={256}+ data-attr="posthog-ai-turn-suggestion-notebook-title"+ />+ </div>+ <span className="text-xs text-secondary">+ {suggestion.notebook.incident ? 'Saves the timeline, cause and fix, then ' : 'Saves '}+ {pluralize(conversationBlocks.messageCount, 'message')}+ {conversationBlocks.queryCount > 0+ ? ` and ${pluralize(conversationBlocks.queryCount, 'query', 'queries')}`+ : ''}+ .+ </span>+ <SuggestionActionRow+ {...props}+ label="Save to notebook"+ dataAttr="posthog-ai-turn-suggestion-save-notebook"+ failedMessage="Couldn't save the notebook. Try again."+ />+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/ScoutSuggestionCard.test.tsx b/products/posthog_ai/frontend/components/ScoutSuggestionCard.test.tsxnew file mode 100644index 000000000000..f8c55d3d40e6--- /dev/null+++ b/products/posthog_ai/frontend/components/ScoutSuggestionCard.test.tsx@@ -0,0 +1,69 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { runStreamLogic } from '../logics/runStreamLogic'+import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import { ScoutSuggestionCard } from './ScoutSuggestionCard'++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksRunsCommandCreate: jest.fn(),+ tasksRunsStreamTokenRetrieve: jest.fn(),+}))++const STREAM_KEY = 'scout-suggestion-card-test'+const CARD = { streamKey: STREAM_KEY, turnIndex: 0, sessionId: 'task', revealDelayMs: 0 }+const DRAFTED_INSTRUCTIONS = 'Count signed_up events for the last 7 days and post the total.'++describe('ScoutSuggestionCard', () => {+ beforeEach(async () => {+ useMocks({ get: { '/api/environments/:team_id/integrations': { results: [] } } })+ initKeaTests()+ const stream = runStreamLogic({ streamKey: STREAM_KEY })+ stream.mount()+ await expectLogic(stream, () => {+ stream.actions.ingestAcpFrame({+ type: 'notification',+ notification: { method: '_posthog/user_message', params: { content: 'How many signups?' } },+ })+ stream.actions.ingestAcpFrame({+ type: 'notification',+ notification: {+ method: '_posthog/turn_suggestion',+ params: {+ turnIndex: 0,+ kind: 'scout',+ intent: 'metric_state',+ confidence: 0.9,+ title: 'Get this in Slack every week',+ description: 'A scout runs this analysis again every week and posts the results to Slack.',+ scout: {+ displayName: 'Weekly signups',+ description: '',+ body: DRAFTED_INSTRUCTIONS,+ cadence: 'weekly',+ },+ },+ },+ })+ stream.actions.setTurnSuggestionLedger({ taskId: 'task', muted: false, resolvedTurns: [] })+ }).toFinishAllListeners()+ })++ afterEach(() => {+ cleanup()+ })++ it('shows the drafted instructions before the scout is created, and creates it with the edited ones', () => {+ render(<ScoutSuggestionCard {...CARD} />)++ const instructions = screen.getByDisplayValue(DRAFTED_INSTRUCTIONS)+ fireEvent.change(instructions, { target: { value: 'Count signups only.' } })++ expect(suggestionActionLogic(CARD).values.scoutBody).toBe('Count signups only.')+ })+})diff --git a/products/posthog_ai/frontend/components/ScoutSuggestionCard.tsx b/products/posthog_ai/frontend/components/ScoutSuggestionCard.tsxnew file mode 100644index 000000000000..2842fa47ca53--- /dev/null+++ b/products/posthog_ai/frontend/components/ScoutSuggestionCard.tsx@@ -0,0 +1,79 @@+import { useActions, useValues } from 'kea'++import { LemonLabel, LemonSelect, LemonTextArea, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'+import { CADENCE_OPTIONS, SCOUT_MODE_HINTS, cadenceLabel } from '../utils/turnSuggestions'+import { SlackDestinationSection } from './SlackDestinationSection'+import { SuggestionAcceptedBanner } from './SuggestionAcceptedBanner'+import { SuggestionActionRow } from './SuggestionActionRow'+import { SuggestionDraftSummary } from './SuggestionDraftSummary'++export function ScoutSuggestionCard(props: TurnSuggestionLogicProps): JSX.Element | null {+ const logic = suggestionActionLogic(props)+ const { suggestion, cadence, scoutBody, accepted, slackChannelLabel } = useValues(logic)+ const { setCadence, setScoutBody } = useActions(logic)++ if (suggestion?.kind !== 'scout') {+ return null+ }+ if (accepted) {+ return (+ <SuggestionAcceptedBanner accepted={accepted} linkLabel="View scout">+ Scout created. It runs {cadenceLabel(cadence)} and posts to {slackChannelLabel}.+ </SuggestionAcceptedBanner>+ )+ }+ const modeHint = SCOUT_MODE_HINTS[suggestion.scout.mode]++ return (+ <>+ <SuggestionDraftSummary name={suggestion.scout.displayName}>+ {suggestion.scout.description && (+ <span className="text-xs text-secondary">{suggestion.scout.description}</span>+ )}+ {modeHint && <span className="text-xs text-secondary">{modeHint}</span>}+ </SuggestionDraftSummary>++ <div className="flex flex-col gap-1">+ <LemonLabel info="The scout follows these on every run. Review them before you create it.">+ Instructions+ </LemonLabel>+ <LemonTextArea+ value={scoutBody}+ onChange={setScoutBody}+ minRows={3}+ maxRows={10}+ data-attr="posthog-ai-turn-suggestion-scout-instructions"+ />+ </div>++ <div className="flex flex-col gap-1">+ <LemonLabel>Runs</LemonLabel>+ <LemonSelect+ size="small"+ value={cadence}+ options={CADENCE_OPTIONS}+ onChange={(value) => value && setCadence(value)}+ />+ </div>++ <SlackDestinationSection {...props} connectHint="Connect Slack to post each run to a channel." />++ <SuggestionActionRow+ {...props}+ label="Create scout"+ dataAttr="posthog-ai-turn-suggestion-create-scout"+ failedMessage={+ <>+ Couldn't create the scout. Try again, or create it from the <Link to={urls.inbox()}>inbox</Link>+ .+ </>+ }+ />+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/SlackDestinationSection.tsx b/products/posthog_ai/frontend/components/SlackDestinationSection.tsxnew file mode 100644index 000000000000..79db8426ef31--- /dev/null+++ b/products/posthog_ai/frontend/components/SlackDestinationSection.tsx@@ -0,0 +1,28 @@+import { useActions, useValues } from 'kea'++import { SlackDestinationPicker } from 'lib/components/Comments/SlackDestinationPicker'++import { slackDestinationLogic } from '../logics/slackDestinationLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'++export interface SlackDestinationSectionProps extends TurnSuggestionLogicProps {+ /** What connecting Slack buys the user on this card, shown when the project has no workspace yet. */+ connectHint: string+}++export function SlackDestinationSection({ connectHint, ...logicProps }: SlackDestinationSectionProps): JSX.Element {+ const logic = slackDestinationLogic(logicProps)+ const { slackIntegrationId, slackChannel } = useValues(logic)+ const { setSlackIntegrationId, setSlackChannel, connectSlackClicked } = useActions(logic)++ return (+ <SlackDestinationPicker+ integrationId={slackIntegrationId}+ channel={slackChannel}+ onIntegrationChange={setSlackIntegrationId}+ onChannelChange={setSlackChannel}+ notConfiguredDescription={connectHint}+ onConnectClick={connectSlackClicked}+ />+ )+}diff --git a/products/posthog_ai/frontend/components/SubscriptionSuggestionCard.tsx b/products/posthog_ai/frontend/components/SubscriptionSuggestionCard.tsxnew file mode 100644index 000000000000..d5ee06823120--- /dev/null+++ b/products/posthog_ai/frontend/components/SubscriptionSuggestionCard.tsx@@ -0,0 +1,54 @@+import { useActions, useValues } from 'kea'++import { LemonLabel, LemonSelect } from '@posthog/lemon-ui'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'+import { CADENCE_OPTIONS } from '../utils/turnSuggestions'+import { SlackDestinationSection } from './SlackDestinationSection'+import { SuggestionAcceptedBanner } from './SuggestionAcceptedBanner'+import { SuggestionActionRow } from './SuggestionActionRow'+import { SuggestionDraftSummary } from './SuggestionDraftSummary'++export function SubscriptionSuggestionCard(props: TurnSuggestionLogicProps): JSX.Element | null {+ const logic = suggestionActionLogic(props)+ const { suggestion, cadence, accepted, slackChannelLabel } = useValues(logic)+ const { setCadence } = useActions(logic)++ if (suggestion?.kind !== 'subscription') {+ return null+ }+ if (accepted) {+ return (+ <SuggestionAcceptedBanner accepted={accepted} linkLabel="View subscription">+ Subscribed. {slackChannelLabel} gets {suggestion.subscription.insightName}{' '}+ {cadence === 'weekly' ? 'every Monday' : 'every day'} at 9:00.+ </SuggestionAcceptedBanner>+ )+ }++ return (+ <>+ <SuggestionDraftSummary name={suggestion.subscription.insightName} />++ <div className="flex flex-col gap-1">+ <LemonLabel>Sends</LemonLabel>+ <LemonSelect+ size="small"+ value={cadence}+ options={CADENCE_OPTIONS}+ onChange={(value) => value && setCadence(value)}+ />+ </div>++ <SlackDestinationSection {...props} connectHint="Connect Slack to post the chart to a channel." />++ <SuggestionActionRow+ {...props}+ label="Subscribe"+ dataAttr="posthog-ai-turn-suggestion-create-subscription"+ failedMessage="Couldn't create the subscription. Try again."+ />+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/SuggestionAcceptedBanner.tsx b/products/posthog_ai/frontend/components/SuggestionAcceptedBanner.tsxnew file mode 100644index 000000000000..0310dd7650f2--- /dev/null+++ b/products/posthog_ai/frontend/components/SuggestionAcceptedBanner.tsx@@ -0,0 +1,24 @@+import { LemonBanner } from '@posthog/lemon-ui'++import type { AcceptedSuggestion } from '../utils/acceptSuggestion'++export interface SuggestionAcceptedBannerProps {+ accepted: AcceptedSuggestion+ linkLabel: string+ children: React.ReactNode+}++export function SuggestionAcceptedBanner({+ accepted,+ linkLabel,+ children,+}: SuggestionAcceptedBannerProps): JSX.Element {+ return (+ <LemonBanner+ type={accepted.slackConnected ? 'success' : 'warning'}+ action={{ to: accepted.url, children: linkLabel }}+ >+ {children}+ </LemonBanner>+ )+}diff --git a/products/posthog_ai/frontend/components/SuggestionActionRow.tsx b/products/posthog_ai/frontend/components/SuggestionActionRow.tsxnew file mode 100644index 000000000000..e0716e5c4adb--- /dev/null+++ b/products/posthog_ai/frontend/components/SuggestionActionRow.tsx@@ -0,0 +1,43 @@+import { useActions, useValues } from 'kea'+import { ReactNode } from 'react'++import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { suggestionActionLogic } from '../logics/suggestionActionLogic'+import type { TurnSuggestionLogicProps } from '../logics/turnSuggestionLogic'++export interface SuggestionActionRowProps extends TurnSuggestionLogicProps {+ label: string+ failedMessage: ReactNode+ dataAttr: string+}++/** The tail every card shares: the failure banner and the one button that takes the offer. */+export function SuggestionActionRow({+ label,+ failedMessage,+ dataAttr,+ ...logicProps+}: SuggestionActionRowProps): JSX.Element {+ const logic = suggestionActionLogic(logicProps)+ const { acceptedLoading, acceptDisabledReason, acceptFailed } = useValues(logic)+ const { accept } = useActions(logic)++ return (+ <>+ {acceptFailed && <LemonBanner type="error">{failedMessage}</LemonBanner>}+ <div className="flex justify-end">+ <LemonButton+ type="primary"+ size="small"+ onClick={accept}+ loading={acceptedLoading}+ disabledReason={acceptDisabledReason ?? undefined}+ data-attr={dataAttr}+ >+ {label}+ </LemonButton>+ </div>+ </>+ )+}diff --git a/products/posthog_ai/frontend/components/SuggestionCardShell.tsx b/products/posthog_ai/frontend/components/SuggestionCardShell.tsxnew file mode 100644index 000000000000..86f937b0ba2b--- /dev/null+++ b/products/posthog_ai/frontend/components/SuggestionCardShell.tsx@@ -0,0 +1,48 @@+import { ReactNode } from 'react'++import { IconX } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++export interface SuggestionCardShellProps {+ icon: JSX.Element+ title: string+ description: string+ /** Absent once the offer was taken, so a finished card cannot be dismissed. */+ onDismiss?: () => void+ children: ReactNode+}++export function SuggestionCardShell({+ icon,+ title,+ description,+ onDismiss,+ children,+}: SuggestionCardShellProps): JSX.Element {+ return (+ <div+ className="my-2 flex flex-col gap-3 rounded border bg-surface-primary p-3"+ data-attr="posthog-ai-turn-suggestion"+ >+ <div className="flex items-start gap-2">+ <span className="mt-0.5 shrink-0 text-xl text-accent">{icon}</span>+ <div className="min-w-0 flex-1">+ <div className="font-semibold">{title}</div>+ <div className="text-sm text-secondary">{description}</div>+ </div>+ {onDismiss && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconX />}+ onClick={onDismiss}+ tooltip="Not now"+ aria-label="Not now"+ data-attr="posthog-ai-turn-suggestion-dismiss"+ />+ )}+ </div>+ {children}+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/SuggestionDraftSummary.tsx b/products/posthog_ai/frontend/components/SuggestionDraftSummary.tsxnew file mode 100644index 000000000000..267553799891--- /dev/null+++ b/products/posthog_ai/frontend/components/SuggestionDraftSummary.tsx@@ -0,0 +1,11 @@+import { ReactNode } from 'react'++/** The shaded block at the top of a card that names what will be created and how it behaves. */+export function SuggestionDraftSummary({ name, children }: { name: string; children?: ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col gap-0.5 rounded bg-surface-secondary px-2 py-1.5">+ <span className="text-sm font-medium">{name}</span>+ {children}+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/TurnSuggestionCard.stories.tsx b/products/posthog_ai/frontend/components/TurnSuggestionCard.stories.tsxnew file mode 100644index 000000000000..88c27cb8d5d2--- /dev/null+++ b/products/posthog_ai/frontend/components/TurnSuggestionCard.stories.tsx@@ -0,0 +1,334 @@+import type { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'+import { useEffect } from 'react'++import { mswDecorator } from '~/mocks/browser'+import { mockIntegration } from '~/test/mocks'++import { runStreamLogic } from '../logics/runStreamLogic'+import { ThreadView } from './ThreadView'+import { TurnFeedbackActions } from './TurnFeedbackActions'+import { TurnSuggestionCard } from './TurnSuggestionCard'++type Kind = 'scout' | 'notebook' | 'alert' | 'subscription' | 'error_alert'++interface StoryArgs {+ kind: Kind+ /** The scene width next to an open side panel on a 1280px window. */+ narrow?: boolean+}++const STREAM_KEY = 'turn-suggestion-story'+const SESSION_ID = 'turn-suggestion-story-task'++const notification = (method: string, params: Record<string, unknown>): Record<string, unknown> => ({+ type: 'notification',+ notification: { method, params },+})++const sessionUpdate = (update: Record<string, unknown>): Record<string, unknown> =>+ notification('session/update', { update })++const SCOUT_TURN_FRAMES: Record<string, unknown>[] = [+ notification('_posthog/run_started', {}),+ notification('_posthog/user_message', { content: 'How many signups did we get this week?' }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'story-query',+ title: 'Run SQL query',+ serverName: 'posthog',+ toolName: 'exec',+ status: 'completed',+ rawInput: {+ command:+ 'call execute-sql {"query":"SELECT toStartOfDay(timestamp) AS day, count() AS signups FROM events WHERE event = \'signed_up\' AND timestamp > now() - INTERVAL 7 DAY GROUP BY day ORDER BY day"}',+ },+ rawOutput: { content: [{ type: 'text', text: 'day,signups\n2026-09-15,58' }] },+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }),+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'story-answer',+ content: {+ type: 'text',+ text: 'You had **412 signups** in the last 7 days, up 8% on the week before. Tuesday was the strongest day with 74.',+ },+ }),+ notification('_posthog/turn_complete', { stopReason: 'end_turn' }),+ notification('_posthog/turn_suggestion', {+ turnIndex: 0,+ kind: 'scout',+ intent: 'metric_state',+ confidence: 0.93,+ title: 'Get this in Slack every week',+ description: 'A scout runs this analysis again every week and posts the results to Slack.',+ scout: {+ mode: 'report',+ displayName: 'Weekly signups',+ description: 'Counts signed_up events for the last 7 days and compares with the week before.',+ body: '# Weekly signups\n\nCount `signed_up` events for the last 7 days...',+ cadence: 'weekly',+ },+ }),+]++const NOTEBOOK_TURN_FRAMES: Record<string, unknown>[] = [+ notification('_posthog/run_started', {}),+ notification('_posthog/user_message', { content: 'Why did signups drop on Tuesday?' }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'story-daily',+ title: 'Run SQL query',+ serverName: 'posthog',+ toolName: 'exec',+ status: 'completed',+ rawInput: {+ command:+ 'call execute-sql {"query":"SELECT toStartOfDay(timestamp) AS day, count() AS signups FROM events WHERE event = \'signed_up\' AND timestamp > now() - INTERVAL 7 DAY GROUP BY day ORDER BY day"}',+ },+ rawOutput: {+ query: {+ kind: 'HogQLQuery',+ query: "SELECT toStartOfDay(timestamp) AS day, count() AS signups FROM events WHERE event = 'signed_up' AND timestamp > now() - INTERVAL 7 DAY GROUP BY day ORDER BY day",+ },+ results: [['2026-09-15', 58]],+ columns: ['day', 'signups'],+ },+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'story-recordings',+ title: 'Search recordings',+ serverName: 'posthog',+ toolName: 'exec',+ status: 'completed',+ rawInput: { command: 'call query-session-recordings-list {"date_from":"-7d","filter_test_accounts":true}' },+ rawOutput: { results: [], has_next: false },+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }),+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'story-diagnosis',+ content: {+ type: 'text',+ text: "Tuesday's signups fell to **41**, a third below the weekday average. Recordings from that afternoon show a checkout error on the payment step, and the drop lines up with the release at 14:10. Signups recovered on Wednesday after the fix went out.",+ },+ }),+ notification('_posthog/turn_complete', { stopReason: 'end_turn' }),+ notification('_posthog/turn_suggestion', {+ turnIndex: 0,+ kind: 'notebook',+ intent: 'diagnostic',+ confidence: 0.88,+ title: 'Save this conversation as a notebook',+ description: 'The notebook keeps the messages, and each query becomes a cell you can run again.',+ notebook: {+ title: 'Why signups dropped on Tuesday',+ summary:+ 'A checkout error on the payment step cut Tuesday signups by a third until the 14:10 release was fixed.',+ incident: null,+ },+ }),+]++const SAVED_INSIGHT_FRAMES: Record<string, unknown>[] = [+ notification('_posthog/run_started', {}),+ notification('_posthog/user_message', { content: 'Save a chart of daily signups for the last month' }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'story-insight',+ title: 'Create insight',+ serverName: 'posthog',+ toolName: 'exec',+ status: 'completed',+ rawInput: { command: 'call insight-create {"name":"Daily signups"}' },+ rawOutput: {+ id: 42,+ short_id: 'abc123',+ name: 'Daily signups',+ query: { kind: 'TrendsQuery', series: [{ event: 'signed_up', kind: 'EventsNode' }] },+ },+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }),+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'story-insight-answer',+ content: {+ type: 'text',+ text: 'Saved **Daily signups**: one line of signed_up events per day for the last 30 days.',+ },+ }),+ notification('_posthog/turn_complete', { stopReason: 'end_turn' }),+]++const INSIGHT_REF = { insightShortId: 'abc123', insightId: 42, insightName: 'Daily signups' }++const ALERT_TURN_FRAMES: Record<string, unknown>[] = [+ ...SAVED_INSIGHT_FRAMES,+ notification('_posthog/turn_suggestion', {+ turnIndex: 0,+ kind: 'alert',+ intent: 'metric_state',+ confidence: 0.9,+ title: 'Get an alert when this drops',+ description: 'The alert checks once a day, compares with the day before, and posts to Slack.',+ alert: { ...INSIGHT_REF, direction: 'decrease', changePercent: 20 },+ }),+]++const SUBSCRIPTION_TURN_FRAMES: Record<string, unknown>[] = [+ ...SAVED_INSIGHT_FRAMES,+ notification('_posthog/turn_suggestion', {+ turnIndex: 0,+ kind: 'subscription',+ intent: 'metric_state',+ confidence: 0.87,+ title: 'Send this chart to Slack every week',+ description: 'The chart posts to a Slack channel every Monday at 9:00.',+ subscription: { ...INSIGHT_REF, cadence: 'weekly' },+ }),+]++const ERROR_ALERT_TURN_FRAMES: Record<string, unknown>[] = [+ notification('_posthog/run_started', {}),+ notification('_posthog/user_message', { content: 'Why did checkout break on Tuesday?' }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'story-issues',+ title: 'List issues',+ serverName: 'posthog',+ toolName: 'exec',+ status: 'completed',+ rawInput: { command: 'call query-error-tracking-issues-list {"date_from":"-7d"}' },+ rawOutput: {+ results: [{ id: '0199c0de-1111-7000-8000-0000000000aa', name: 'TypeError: cart.total is undefined' }],+ },+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }),+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'story-issue-answer',+ content: {+ type: 'text',+ text: 'A **TypeError on the checkout page** started at 14:25 on Tuesday, right after the 14:10 release, and stopped once the fix shipped at 17:05. It is resolved now.',+ },+ }),+ notification('_posthog/turn_complete', { stopReason: 'end_turn' }),+ notification('_posthog/turn_suggestion', {+ turnIndex: 0,+ kind: 'error_alert',+ intent: 'diagnostic',+ confidence: 0.86,+ title: 'Get an alert if this error comes back',+ description: 'Slack gets a message if this issue reopens after it was resolved.',+ errorAlert: {+ issueId: '0199c0de-1111-7000-8000-0000000000aa',+ issueName: 'TypeError: cart.total is undefined',+ },+ }),+]++const FRAMES_BY_KIND: Record<Kind, Record<string, unknown>[]> = {+ scout: SCOUT_TURN_FRAMES,+ notebook: NOTEBOOK_TURN_FRAMES,+ alert: ALERT_TURN_FRAMES,+ subscription: SUBSCRIPTION_TURN_FRAMES,+ error_alert: ERROR_ALERT_TURN_FRAMES,+}++function TurnSuggestionStory({ kind, narrow }: StoryArgs): JSX.Element {+ useEffect(() => {+ const stream = runStreamLogic({ streamKey: STREAM_KEY })+ const unmountStream = stream.mount()+ for (const frame of FRAMES_BY_KIND[kind]) {+ stream.actions.ingestAcpFrame(frame as any, 'replay')+ }+ stream.actions.setTurnSuggestionLedger({ taskId: SESSION_ID, muted: false, resolvedTurns: [] })+ return unmountStream+ }, [kind])++ return (+ <div className={`${narrow ? 'w-130' : 'w-180'} max-w-full rounded border p-4`}>+ <BindLogic logic={runStreamLogic} props={{ streamKey: STREAM_KEY }}>+ <ThreadView+ virtualized={false}+ renderTurnTrailer={(trailer) => (+ <>+ {trailer.isLastTurn ? (+ <TurnSuggestionCard+ streamKey={STREAM_KEY}+ turnIndex={trailer.turnIndex}+ sessionId={SESSION_ID}+ revealDelayMs={0}+ />+ ) : null}+ <TurnFeedbackActions+ sessionId={SESSION_ID}+ turnIndex={trailer.turnIndex}+ run={{ taskId: SESSION_ID }}+ traceId={trailer.traceId}+ turnText={trailer.turnText}+ />+ </>+ )}+ />+ </BindLogic>+ </div>+ )+}++const CHANNELS = {+ channels: [+ { id: 'C0123456789', name: 'growth', is_private: false, is_ext_shared: false, is_member: true },+ { id: 'C0987654321', name: 'product', is_private: false, is_ext_shared: false, is_member: true },+ ],+ lastRefreshedAt: '2026-09-16T09:00:00Z',+}++const QUERY_RESULT = {+ results: [['2026-09-15', 58]],+ columns: ['day', 'signups'],+ types: [+ ['day', 'Date'],+ ['signups', 'UInt64'],+ ],+}++function mocks(): Parameters<typeof mswDecorator>[0] {+ const integrations = { results: [mockIntegration] }+ return {+ get: {+ '/api/environments/:team_id/integrations/': integrations,+ '/api/projects/:team_id/integrations/': integrations,+ '/api/environments/:team_id/integrations/:id/channels/': CHANNELS,+ },+ post: {+ '/api/environments/:team_id/query/': () => [200, QUERY_RESULT],+ '/api/environments/:team_id/query/:query_kind/': () => [200, QUERY_RESULT],+ },+ }+}++const meta: Meta<StoryArgs> = {+ title: 'Products/PostHog AI/TurnSuggestionCard',+ parameters: { mockDate: '2026-09-16', testOptions: { waitForLoadersToDisappear: true } },+ args: { kind: 'scout' },+ decorators: [mswDecorator(mocks())],+ render: ({ kind, narrow }) => <TurnSuggestionStory kind={kind} narrow={narrow} />,+}+export default meta++type Story = StoryObj<StoryArgs>++export const ScoutSuggestion: Story = {}++export const ScoutSuggestionNarrow: Story = { args: { kind: 'scout', narrow: true } }++export const NotebookSuggestion: Story = { args: { kind: 'notebook' } }++export const AlertSuggestion: Story = { args: { kind: 'alert' } }++export const SubscriptionSuggestion: Story = { args: { kind: 'subscription' } }++export const ErrorAlertSuggestion: Story = { args: { kind: 'error_alert' } }diff --git a/products/posthog_ai/frontend/components/TurnSuggestionCard.tsx b/products/posthog_ai/frontend/components/TurnSuggestionCard.tsxnew file mode 100644index 000000000000..3a05ef243e14--- /dev/null+++ b/products/posthog_ai/frontend/components/TurnSuggestionCard.tsx@@ -0,0 +1,54 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconBell, IconCalendar, IconNotebook, IconTelescope, IconWarning } from '@posthog/icons'++import { TurnSuggestionLogicProps, turnSuggestionLogic } from '../logics/turnSuggestionLogic'+import type { TurnSuggestion } from '../types/streamTypes'+import { AlertSuggestionCard } from './AlertSuggestionCard'+import { ErrorAlertSuggestionCard } from './ErrorAlertSuggestionCard'+import { NotebookSuggestionCard } from './NotebookSuggestionCard'+import { ScoutSuggestionCard } from './ScoutSuggestionCard'+import { SubscriptionSuggestionCard } from './SubscriptionSuggestionCard'+import { SuggestionCardShell } from './SuggestionCardShell'++const CARD_BY_KIND: Record<+ TurnSuggestion['kind'],+ { icon: JSX.Element; Body: (props: TurnSuggestionLogicProps) => JSX.Element | null }+> = {+ scout: { icon: <IconTelescope />, Body: ScoutSuggestionCard },+ notebook: { icon: <IconNotebook />, Body: NotebookSuggestionCard },+ alert: { icon: <IconBell />, Body: AlertSuggestionCard },+ subscription: { icon: <IconCalendar />, Body: SubscriptionSuggestionCard },+ error_alert: { icon: <IconWarning />, Body: ErrorAlertSuggestionCard },+}++export function TurnSuggestionCard(logicProps: TurnSuggestionLogicProps): JSX.Element | null {+ const logic = turnSuggestionLogic(logicProps)+ const { suggestion, visible, completed, shownSuggestion } = useValues(logic)+ const { dismiss, reportShown } = useActions(logic)++ useEffect(() => {+ // Server frames carry no event id, so a thread that loads the log and then the live tail gets the card frame twice.+ if (visible && suggestion && shownSuggestion?.turnIndex !== suggestion.turnIndex) {+ reportShown(suggestion)+ }+ }, [visible, suggestion, shownSuggestion, reportShown])++ if (!visible || !suggestion) {+ return null+ }+ const { icon, Body } = CARD_BY_KIND[suggestion.kind]+ return (+ <div className="animate-fade-in [animation-duration:600ms] motion-reduce:animate-none">+ <SuggestionCardShell+ icon={icon}+ title={suggestion.title}+ description={suggestion.description}+ onDismiss={completed ? undefined : dismiss}+ >+ <Body {...logicProps} />+ </SuggestionCardShell>+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/TurnTrailerActions.tsx b/products/posthog_ai/frontend/components/TurnTrailerActions.tsxindex 5f90393db27f..34d9d4bbbdf0 100644--- a/products/posthog_ai/frontend/components/TurnTrailerActions.tsx+++ b/products/posthog_ai/frontend/components/TurnTrailerActions.tsx@@ -1,8 +1,11 @@+import { useMountedLogic, useValues } from 'kea'import { memo } from 'react'+import { runStreamLogic } from '../logics/runStreamLogic'import type { RunRef } from '../utils/feedbackEvents'import type { TurnTrailer } from '../utils/turnTrailers'import { TurnFeedbackActions } from './TurnFeedbackActions'+import { TurnSuggestionCard } from './TurnSuggestionCard'export interface TurnTrailerActionsProps {trailer: TurnTrailer@@ -15,14 +18,25 @@ export const TurnTrailerActions = memo(function TurnTrailerActions({sessionId,run,}: TurnTrailerActionsProps): JSX.Element {+ const stream = useMountedLogic(runStreamLogic)+ const { turnSuggestion } = useValues(stream)return (- <TurnFeedbackActions- sessionId={sessionId}- turnIndex={trailer.turnIndex}- run={run}- traceId={trailer.traceId}- turnText={trailer.turnText}- timestamp={trailer.timestamp}- />+ <>+ {turnSuggestion?.turnIndex === trailer.turnIndex ? (+ <TurnSuggestionCard+ streamKey={stream.props.streamKey}+ turnIndex={trailer.turnIndex}+ sessionId={sessionId}+ />+ ) : null}+ <TurnFeedbackActions+ sessionId={sessionId}+ turnIndex={trailer.turnIndex}+ run={run}+ traceId={trailer.traceId}+ turnText={trailer.turnText}+ timestamp={trailer.timestamp}+ />+ </>)})diff --git a/products/posthog_ai/frontend/logics/slackDestinationLogic.ts b/products/posthog_ai/frontend/logics/slackDestinationLogic.tsnew file mode 100644index 000000000000..e3e00798db67--- /dev/null+++ b/products/posthog_ai/frontend/logics/slackDestinationLogic.ts@@ -0,0 +1,131 @@+import {+ LogicWrapper,+ MakeLogicType,+ actions,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { slackChannelDisplayName } from 'lib/integrations/slackChannel'++import { IntegrationType } from '~/types'++import type { TurnSuggestion } from '../types/streamTypes'+import { captureTurnSuggestionEvent } from '../utils/turnSuggestionEvents'+import { TurnSuggestionLogicProps, turnSuggestionLogic } from './turnSuggestionLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface slackDestinationLogicValues {+ slackIntegrations: IntegrationType[] | undefined // integrationsLogic+ suggestion: TurnSuggestion | null // turnSuggestionLogic+ hasSlackWorkspace: boolean+ slackChannel: string | null+ slackChannelLabel: string+ slackDestinationDisabledReason: string | null+ slackIntegrationId: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface slackDestinationLogicActions {+ connectSlackClicked: () => {+ value: true+ }+ setSlackChannel: (channel: string | null) => {+ channel: string | null+ }+ setSlackIntegrationId: (integrationId: number | null) => {+ integrationId: number | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface slackDestinationLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ hasSlackWorkspace: (slackIntegrations: IntegrationType[] | undefined) => boolean+ slackChannelLabel: (slackChannel: string | null) => string+ slackDestinationDisabledReason: (+ slackIntegrationId: number | null,+ slackChannel: string | null,+ hasSlackWorkspace: boolean+ ) => string | null+ }+}++export type slackDestinationLogicType = MakeLogicType<+ slackDestinationLogicValues,+ slackDestinationLogicActions,+ TurnSuggestionLogicProps,+ slackDestinationLogicMeta+>++/** The Slack workspace and channel a card posts to, shared by every kind that ends in Slack. */+export const slackDestinationLogic: LogicWrapper<slackDestinationLogicType> = kea<slackDestinationLogicType>([+ props({} as TurnSuggestionLogicProps),+ key((props) => `${props.streamKey}:${props.turnIndex}`),+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'slackDestinationLogic', key]),+ connect((props: TurnSuggestionLogicProps) => ({+ values: [turnSuggestionLogic(props), ['suggestion'], integrationsLogic, ['slackIntegrations']],+ })),+ actions({+ setSlackIntegrationId: (integrationId: number | null) => ({ integrationId }),+ setSlackChannel: (channel: string | null) => ({ channel }),+ connectSlackClicked: true,+ }),+ reducers({+ slackIntegrationId: [+ null as number | null,+ {+ setSlackIntegrationId: (_, { integrationId }) => integrationId,+ },+ ],+ slackChannel: [+ null as string | null,+ {+ setSlackChannel: (_, { channel }) => channel,+ // A channel belongs to one workspace, so switching workspace clears it.+ setSlackIntegrationId: () => null,+ },+ ],+ }),+ selectors({+ hasSlackWorkspace: [+ (s) => [s.slackIntegrations],+ (slackIntegrations: IntegrationType[] | undefined): boolean => !!slackIntegrations?.length,+ ],+ slackChannelLabel: [+ (s) => [s.slackChannel],+ (slackChannel: string | null): string => (slackChannel ? slackChannelDisplayName(slackChannel) : 'Slack'),+ ],+ slackDestinationDisabledReason: [+ (s) => [s.slackIntegrationId, s.slackChannel, s.hasSlackWorkspace],+ (+ slackIntegrationId: number | null,+ slackChannel: string | null,+ hasSlackWorkspace: boolean+ ): string | null => {+ if (slackIntegrationId === null) {+ return hasSlackWorkspace ? 'Choose a Slack workspace first' : 'Connect Slack first'+ }+ if (!slackChannel) {+ return 'Choose a Slack channel first'+ }+ return null+ },+ ],+ }),+ listeners(({ values, props }) => ({+ connectSlackClicked: () => {+ if (values.suggestion) {+ captureTurnSuggestionEvent('connect slack clicked', props, values.suggestion)+ }+ },+ })),+])diff --git a/products/posthog_ai/frontend/logics/suggestionActionLogic.ts b/products/posthog_ai/frontend/logics/suggestionActionLogic.tsnew file mode 100644index 000000000000..37da1c67183e--- /dev/null+++ b/products/posthog_ai/frontend/logics/suggestionActionLogic.ts@@ -0,0 +1,282 @@+import { LogicWrapper, MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { projectLogic } from 'scenes/projectLogic'+import { userLogic } from 'scenes/userLogic'++import type { UserType } from '~/types'++import type {+ AlertSuggestionDirection,+ ScoutSuggestionCadence,+ ThreadItem,+ ToolInvocation,+ TurnSuggestion,+} from '../types/streamTypes'+import { AcceptedSuggestion, acceptSuggestion } from '../utils/acceptSuggestion'+import { ConversationBlocks, collectConversationBlocks } from '../utils/conversationNotebook'+import { recordTurnSuggestionResolution } from '../utils/recordTurnSuggestionResolution'+import { captureTurnSuggestionEvent } from '../utils/turnSuggestionEvents'+import { runStreamLogic } from './runStreamLogic'+import { slackDestinationLogic } from './slackDestinationLogic'+import { TurnSuggestionLogicProps, turnSuggestionLogic } from './turnSuggestionLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface suggestionActionLogicValues {+ currentProjectId: number | null // projectLogic+ threadItems: ThreadItem[] // runStreamLogic+ toolInvocations: Map<string, ToolInvocation> // runStreamLogic+ slackChannel: string | null // slackDestinationLogic+ slackChannelLabel: string // slackDestinationLogic+ slackDestinationDisabledReason: string | null // slackDestinationLogic+ slackIntegrationId: number | null // slackDestinationLogic+ suggestion: TurnSuggestion | null // turnSuggestionLogic+ user: UserType | null // userLogic+ acceptDisabledReason: string | null+ acceptFailed: boolean+ accepted: AcceptedSuggestion | null+ acceptedLoading: boolean+ cadence: ScoutSuggestionCadence+ cadenceOverride: ScoutSuggestionCadence | null+ changePercent: number+ changePercentOverride: number | null+ conversationBlocks: ConversationBlocks+ direction: AlertSuggestionDirection+ directionOverride: AlertSuggestionDirection | null+ notebookTitle: string+ scoutBody: string+ scoutBodyOverride: string | null+ titleOverride: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface suggestionActionLogicActions {+ markTurnSuggestionAccepted: (turnIndex: number) => {+ turnIndex: number+ } // runStreamLogic+ accept: () => any+ acceptFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ acceptSuccess: (+ accepted: AcceptedSuggestion | null,+ payload?: any+ ) => {+ accepted: AcceptedSuggestion | null+ payload?: any+ }+ setCadence: (cadence: ScoutSuggestionCadence) => {+ cadence: 'daily' | 'weekly'+ }+ setChangePercent: (changePercent: number) => {+ changePercent: number+ }+ setDirection: (direction: AlertSuggestionDirection) => {+ direction: 'decrease' | 'increase'+ }+ setScoutBody: (scoutBody: string) => {+ scoutBody: string+ }+ setTitle: (title: string) => {+ title: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface suggestionActionLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ cadence: (+ cadenceOverride: 'daily' | 'weekly' | null,+ suggestion: TurnSuggestion | null+ ) => ScoutSuggestionCadence+ direction: (+ directionOverride: 'decrease' | 'increase' | null,+ suggestion: TurnSuggestion | null+ ) => AlertSuggestionDirection+ changePercent: (changePercentOverride: number | null, suggestion: TurnSuggestion | null) => number+ notebookTitle: (titleOverride: string | null, suggestion: TurnSuggestion | null) => string+ scoutBody: (scoutBodyOverride: string | null, suggestion: TurnSuggestion | null) => string+ conversationBlocks: (+ threadItems: ThreadItem[],+ toolInvocations: Map<string, ToolInvocation>+ ) => ConversationBlocks+ acceptDisabledReason: (+ suggestion: TurnSuggestion | null,+ currentProjectId: number | null,+ user: UserType | null,+ slackDestinationDisabledReason: string | null,+ notebookTitle: string,+ changePercent: number,+ scoutBody: string+ ) => string | null+ }+}++export type suggestionActionLogicType = MakeLogicType<+ suggestionActionLogicValues,+ suggestionActionLogicActions,+ TurnSuggestionLogicProps,+ suggestionActionLogicMeta+>++/** Taking the offer: the inputs a card can change, the one request that creates it, and the result. */+export const suggestionActionLogic: LogicWrapper<suggestionActionLogicType> = kea<suggestionActionLogicType>([+ props({} as TurnSuggestionLogicProps),+ key((props) => `${props.streamKey}:${props.turnIndex}`),+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'suggestionActionLogic', key]),+ connect((props: TurnSuggestionLogicProps) => ({+ values: [+ turnSuggestionLogic(props),+ ['suggestion'],+ slackDestinationLogic(props),+ ['slackIntegrationId', 'slackChannel', 'slackChannelLabel', 'slackDestinationDisabledReason'],+ runStreamLogic({ streamKey: props.streamKey }),+ ['threadItems', 'toolInvocations'],+ projectLogic,+ ['currentProjectId'],+ userLogic,+ ['user'],+ ],+ actions: [runStreamLogic({ streamKey: props.streamKey }), ['markTurnSuggestionAccepted']],+ })),+ actions({+ setCadence: (cadence: ScoutSuggestionCadence) => ({ cadence }),+ setDirection: (direction: AlertSuggestionDirection) => ({ direction }),+ setChangePercent: (changePercent: number) => ({ changePercent }),+ setTitle: (title: string) => ({ title }),+ setScoutBody: (scoutBody: string) => ({ scoutBody }),+ }),+ loaders(({ actions, values, props }) => ({+ accepted: [+ null as AcceptedSuggestion | null,+ {+ accept: async () => {+ const { suggestion, currentProjectId } = values+ if (!suggestion || currentProjectId === null || values.acceptDisabledReason) {+ return values.accepted+ }+ // The request can outlive the card: a message sent while it runs clears `values.suggestion`,+ // so the outcome is recorded against the suggestion this accept started from.+ let outcome: Awaited<ReturnType<typeof acceptSuggestion>>+ try {+ outcome = await acceptSuggestion({+ suggestion,+ projectId: currentProjectId,+ userId: values.user?.id,+ slackIntegrationId: values.slackIntegrationId,+ slackChannel: values.slackChannel,+ cadence: values.cadence,+ scoutBody: values.scoutBody,+ direction: values.direction,+ changePercent: values.changePercent,+ notebookTitle: values.notebookTitle,+ conversationBlocks: values.conversationBlocks,+ })+ } catch (error) {+ // posthog-js serializes an Error instance as an empty object.+ captureTurnSuggestionEvent('accept failed', props, suggestion, {+ error: error instanceof Error ? error.message : String(error),+ })+ throw error+ }+ captureTurnSuggestionEvent('accepted', props, suggestion, outcome.eventProperties)+ actions.markTurnSuggestionAccepted(suggestion.turnIndex)+ recordTurnSuggestionResolution(currentProjectId, props.sessionId, suggestion, 'accepted')+ return outcome.accepted+ },+ },+ ],+ })),+ reducers({+ cadenceOverride: [null as ScoutSuggestionCadence | null, { setCadence: (_, { cadence }) => cadence }],+ directionOverride: [null as AlertSuggestionDirection | null, { setDirection: (_, { direction }) => direction }],+ changePercentOverride: [null as number | null, { setChangePercent: (_, { changePercent }) => changePercent }],+ titleOverride: [null as string | null, { setTitle: (_, { title }) => title }],+ scoutBodyOverride: [null as string | null, { setScoutBody: (_, { scoutBody }) => scoutBody }],+ acceptFailed: [false, { accept: () => false, acceptFailure: () => true }],+ }),+ selectors({+ cadence: [+ (s) => [s.cadenceOverride, s.suggestion],+ (+ cadenceOverride: ScoutSuggestionCadence | null,+ suggestion: TurnSuggestion | null+ ): ScoutSuggestionCadence => {+ if (cadenceOverride) {+ return cadenceOverride+ }+ if (suggestion?.kind === 'scout') {+ return suggestion.scout.cadence+ }+ return suggestion?.kind === 'subscription' ? suggestion.subscription.cadence : 'weekly'+ },+ ],+ direction: [+ (s) => [s.directionOverride, s.suggestion],+ (+ directionOverride: AlertSuggestionDirection | null,+ suggestion: TurnSuggestion | null+ ): AlertSuggestionDirection =>+ directionOverride ?? (suggestion?.kind === 'alert' ? suggestion.alert.direction : 'decrease'),+ ],+ changePercent: [+ (s) => [s.changePercentOverride, s.suggestion],+ (changePercentOverride: number | null, suggestion: TurnSuggestion | null): number =>+ changePercentOverride ?? (suggestion?.kind === 'alert' ? suggestion.alert.changePercent : 20),+ ],+ notebookTitle: [+ (s) => [s.titleOverride, s.suggestion],+ (titleOverride: string | null, suggestion: TurnSuggestion | null): string =>+ titleOverride ?? (suggestion?.kind === 'notebook' ? suggestion.notebook.title : ''),+ ],+ scoutBody: [+ (s) => [s.scoutBodyOverride, s.suggestion],+ (scoutBodyOverride: string | null, suggestion: TurnSuggestion | null): string =>+ scoutBodyOverride ?? (suggestion?.kind === 'scout' ? suggestion.scout.body : ''),+ ],+ conversationBlocks: [+ (s) => [s.threadItems, s.toolInvocations],+ (threadItems: ThreadItem[], toolInvocations: Map<string, ToolInvocation>): ConversationBlocks =>+ collectConversationBlocks(threadItems, toolInvocations),+ ],+ acceptDisabledReason: [+ (s) => [+ s.suggestion,+ s.currentProjectId,+ s.user,+ s.slackDestinationDisabledReason,+ s.notebookTitle,+ s.changePercent,+ s.scoutBody,+ ],+ (+ suggestion: TurnSuggestion | null,+ currentProjectId: number | null,+ user: UserType | null,+ slackDestinationDisabledReason: string | null,+ notebookTitle: string,+ changePercent: number,+ scoutBody: string+ ): string | null => {+ if (currentProjectId === null || !user) {+ return 'Your project is still loading'+ }+ switch (suggestion?.kind) {+ case 'scout':+ return scoutBody.trim() ? slackDestinationDisabledReason : 'Add instructions for the scout'+ case 'notebook':+ return notebookTitle.trim() ? null : 'Add a notebook title'+ case 'alert':+ return changePercent > 0 ? slackDestinationDisabledReason : 'Enter a percentage above 0'+ default:+ return slackDestinationDisabledReason+ }+ },+ ],+ }),+])diff --git a/products/posthog_ai/frontend/logics/turnSuggestionLogic.test.ts b/products/posthog_ai/frontend/logics/turnSuggestionLogic.test.tsnew file mode 100644index 000000000000..964755fbc280--- /dev/null+++ b/products/posthog_ai/frontend/logics/turnSuggestionLogic.test.ts@@ -0,0 +1,148 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { turnSuggestionsResolveCreate } from '../generated/api'+import type { StoredLogEntry } from '../types/wireTypes'+import { acceptSuggestion } from '../utils/acceptSuggestion'+import { runStreamLogic } from './runStreamLogic'+import { suggestionActionLogic } from './suggestionActionLogic'+import { turnSuggestionLogic } from './turnSuggestionLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ turnSuggestionsResolveCreate: jest.fn(() => Promise.resolve({ recorded: true })),+}))++jest.mock('../utils/acceptSuggestion', () => ({+ ...jest.requireActual('../utils/acceptSuggestion'),+ acceptSuggestion: jest.fn(),+}))++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksRunsCommandCreate: jest.fn(),+ tasksRunsStreamTokenRetrieve: jest.fn(),+}))++const STREAM_KEY = 'turn-suggestion-logic-test'++function notification(method: string, params: Record<string, unknown>): StoredLogEntry {+ return { type: 'notification', notification: { method, params } }+}++// The first question got no answer, so its turn has no trailer but still counts, and the second+// question is turn 1.+const SUGGESTION = {+ turnIndex: 1,+ kind: 'scout',+ intent: 'metric_state',+ confidence: 0.9,+ title: 'Get this in Slack every week',+ description: 'A scout runs this analysis again every week and posts the results to Slack.',+ scout: { displayName: 'Weekly signups', description: '', body: '# Weekly signups', cadence: 'weekly' },+}++describe('turnSuggestionLogic', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ jest.useRealTimers()+ jest.mocked(turnSuggestionsResolveCreate).mockClear()+ })++ async function mountStreamWithSuggestion(+ suggestion: Record<string, unknown> = SUGGESTION+ ): Promise<ReturnType<typeof runStreamLogic.build>> {+ const stream = runStreamLogic({ streamKey: STREAM_KEY })+ stream.mount()+ await expectLogic(stream, () => {+ stream.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'Hello?' }))+ stream.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'How many signups?' }))+ stream.actions.ingestAcpFrame(notification('_posthog/turn_suggestion', suggestion))+ stream.actions.setTurnSuggestionLedger({ taskId: 'task', muted: false, resolvedTurns: [] })+ }).toFinishAllListeners()+ return stream+ }++ it('reveals after the delay, hides on dismiss, mutes the rest of the conversation and records the dismissal', async () => {+ const stream = await mountStreamWithSuggestion()++ // Fake timers only around the reveal: expectLogic waits on real timers.+ jest.useFakeTimers()+ const logic = turnSuggestionLogic({+ streamKey: STREAM_KEY,+ turnIndex: 1,+ sessionId: 'task',+ revealDelayMs: 1000,+ })+ logic.mount()+ expect(logic.values.suggestion).toMatchObject({ kind: 'scout' })+ expect(logic.values.visible).toBe(false)++ jest.advanceTimersByTime(1000)+ expect(logic.values.visible).toBe(true)+ jest.useRealTimers()++ logic.actions.dismiss()+ expect(logic.values.visible).toBe(false)+ expect(stream.values.turnSuggestionsMuted).toBe(true)+ expect(turnSuggestionsResolveCreate).toHaveBeenCalledWith(expect.any(String), {+ task_id: 'task',+ turn_index: 1,+ resolution: 'dismissed',+ })+ })++ it('records no accept when the accept skipped the create', async () => {+ const stream = await mountStreamWithSuggestion()+ const card = { streamKey: STREAM_KEY, turnIndex: 1, sessionId: 'task', revealDelayMs: 0 }+ const logic = suggestionActionLogic(card)+ logic.mount()+ expect(logic.values.acceptDisabledReason).not.toBeNull()++ await expectLogic(logic, () => {+ logic.actions.accept()+ }).toFinishAllListeners()++ expect(logic.values.accepted).toBeNull()+ expect(turnSuggestionLogic(card).values.completed).toBe(false)+ expect(stream.values.turnSuggestionAcceptedHere).toBeNull()+ expect(turnSuggestionsResolveCreate).not.toHaveBeenCalled()+ })++ it('records the accept when a new message clears the card while the create runs', async () => {+ const stream = await mountStreamWithSuggestion({+ ...SUGGESTION,+ kind: 'notebook',+ notebook: { title: 'Signups investigation', summary: '' },+ })+ let finishCreate: () => void = () => {}+ jest.mocked(acceptSuggestion).mockImplementation(+ () =>+ new Promise((resolve) => {+ finishCreate = () =>+ resolve({ accepted: { url: '/notebooks/abc', slackConnected: true }, eventProperties: {} })+ })+ )+ const card = { streamKey: STREAM_KEY, turnIndex: 1, sessionId: 'task', revealDelayMs: 0 }+ const logic = suggestionActionLogic(card)+ logic.mount()+ expect(logic.values.acceptDisabledReason).toBeNull()++ logic.actions.accept()+ stream.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'And last month?' }))+ expect(logic.values.suggestion).toBeNull()+ logic.unmount()+ finishCreate()+ await expectLogic(stream).toFinishAllListeners()++ expect(stream.values.turnSuggestionAcceptedHere).toBe(1)+ expect(turnSuggestionsResolveCreate).toHaveBeenCalledWith(expect.any(String), {+ task_id: 'task',+ turn_index: 1,+ resolution: 'accepted',+ })+ })+})diff --git a/products/posthog_ai/frontend/logics/turnSuggestionLogic.ts b/products/posthog_ai/frontend/logics/turnSuggestionLogic.tsnew file mode 100644index 000000000000..577c438911a0--- /dev/null+++ b/products/posthog_ai/frontend/logics/turnSuggestionLogic.ts@@ -0,0 +1,152 @@+import {+ LogicWrapper,+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'++import { projectLogic } from 'scenes/projectLogic'++import type { TurnSuggestion } from '../types/streamTypes'+import { recordTurnSuggestionResolution } from '../utils/recordTurnSuggestionResolution'+import { captureTurnSuggestionEvent } from '../utils/turnSuggestionEvents'+import { runStreamLogic } from './runStreamLogic'++/** Time between the offer arriving and the card appearing, so the reader finishes the answer first. */+const REVEAL_DELAY_MS = 2500++export interface TurnSuggestionLogicProps {+ streamKey: string+ turnIndex: number+ sessionId: string+ revealDelayMs?: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface turnSuggestionLogicValues {+ currentProjectId: number | null // projectLogic+ suggestion: TurnSuggestion | null // runStreamLogic+ turnSuggestionAcceptedHere: number | null // runStreamLogic+ completed: boolean+ dismissed: boolean+ revealReady: boolean+ shownSuggestion: TurnSuggestion | null+ visible: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface turnSuggestionLogicActions {+ recordTurnSuggestionOutcome: (+ turnIndex: number,+ outcome: string+ ) => {+ outcome: string+ turnIndex: number+ } // runStreamLogic+ dismiss: () => {+ value: true+ }+ reportShown: (suggestion: TurnSuggestion) => {+ suggestion: TurnSuggestion+ }+ reveal: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface turnSuggestionLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ completed: (turnSuggestionAcceptedHere: number | null, shownSuggestion: TurnSuggestion | null) => boolean+ visible: (suggestion: TurnSuggestion | null, revealReady: boolean, dismissed: boolean) => boolean+ }+}++export type turnSuggestionLogicType = MakeLogicType<+ turnSuggestionLogicValues,+ turnSuggestionLogicActions,+ TurnSuggestionLogicProps,+ turnSuggestionLogicMeta+>++export const turnSuggestionLogic: LogicWrapper<turnSuggestionLogicType> = kea<turnSuggestionLogicType>([+ props({} as TurnSuggestionLogicProps),+ key((props) => `${props.streamKey}:${props.turnIndex}`),+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'turnSuggestionLogic', key]),+ connect((props: TurnSuggestionLogicProps) => ({+ values: [+ runStreamLogic({ streamKey: props.streamKey }),+ ['turnSuggestion as suggestion', 'turnSuggestionAcceptedHere'],+ projectLogic,+ ['currentProjectId'],+ ],+ actions: [runStreamLogic({ streamKey: props.streamKey }), ['recordTurnSuggestionOutcome']],+ })),+ actions({+ dismiss: true,+ reveal: true,+ reportShown: (suggestion: TurnSuggestion) => ({ suggestion }),+ }),+ reducers({+ dismissed: [false, { dismiss: () => true }],+ revealReady: [false, { reveal: () => true }],+ shownSuggestion: [+ null as TurnSuggestion | null,+ {+ reportShown: (_, { suggestion }) => suggestion,+ },+ ],+ }),+ selectors({+ completed: [+ (s) => [s.turnSuggestionAcceptedHere, s.shownSuggestion],+ (turnSuggestionAcceptedHere: number | null, shownSuggestion: TurnSuggestion | null): boolean =>+ shownSuggestion !== null && turnSuggestionAcceptedHere === shownSuggestion.turnIndex,+ ],+ visible: [+ (s) => [s.suggestion, s.revealReady, s.dismissed],+ (suggestion: TurnSuggestion | null, revealReady: boolean, dismissed: boolean): boolean =>+ !!suggestion && revealReady && !dismissed,+ ],+ }),+ listeners(({ actions, values, props }) => ({+ reportShown: ({ suggestion }) => {+ captureTurnSuggestionEvent('shown', props, suggestion)+ },+ dismiss: () => {+ const { suggestion } = values+ if (suggestion) {+ actions.recordTurnSuggestionOutcome(suggestion.turnIndex, 'dismissed')+ captureTurnSuggestionEvent('dismissed', props, suggestion)+ recordTurnSuggestionResolution(values.currentProjectId, props.sessionId, suggestion, 'dismissed')+ }+ },+ })),+ afterMount(({ actions, props, cache }) => {+ const delay = props.revealDelayMs ?? REVEAL_DELAY_MS+ if (delay === 0) {+ actions.reveal()+ return+ }+ cache.disposables.add(() => {+ const timer = window.setTimeout(() => actions.reveal(), delay)+ return () => window.clearTimeout(timer)+ }, 'reveal')+ }),+ beforeUnmount(({ values, props }) => {+ // The card unmounts with its suggestion gone when a new message closed it.+ if (values.shownSuggestion && !values.suggestion && !values.dismissed && !values.completed) {+ captureTurnSuggestionEvent('superseded', props, values.shownSuggestion)+ }+ }),+])diff --git a/products/posthog_ai/frontend/utils/acceptSuggestion.ts b/products/posthog_ai/frontend/utils/acceptSuggestion.tsnew file mode 100644index 000000000000..a0917190abdc--- /dev/null+++ b/products/posthog_ai/frontend/utils/acceptSuggestion.ts@@ -0,0 +1,173 @@+import { getInsightId } from 'scenes/insights/utils'+import { urls } from 'scenes/urls'++import type { CyclotronJobInputSchemaType, InsightShortId } from '~/types'++import { alertsCreate, alertsDestinationsCreate } from 'products/alerts/frontend/generated/api'+import { hogFunctionTemplatesRetrieve, hogFunctionsCreate } from 'products/cdp/frontend/generated/api'+import { notebooksCreate } from 'products/notebooks/frontend/generated/api'+import { signalsScoutCreate } from 'products/signals/frontend/generated/api'+import { subscriptionsCreate } from 'products/subscriptions/frontend/generated/api'++import type { AlertSuggestionDirection, ScoutSuggestionCadence, TurnSuggestion } from '../types/streamTypes'+import { ConversationBlocks, buildConversationNotebook } from './conversationNotebook'+import {+ ERROR_ALERT_SLACK_TEMPLATE_ID,+ SlackDestinationInput,+ buildAlertCreatePayload,+ buildAlertDestinationPayload,+ buildErrorAlertHogFunctionPayload,+ buildScoutCreatePayload,+ buildSubscriptionCreatePayload,+} from './suggestionPayloads'++export interface AcceptedSuggestion {+ url: string+ /** False when the created thing exists but its Slack destination request failed after it. */+ slackConnected: boolean+}++export interface AcceptOutcome {+ accepted: AcceptedSuggestion+ /** What the kind created, for the accepted event. */+ eventProperties: Record<string, unknown>+}++export interface AcceptInput {+ suggestion: TurnSuggestion+ projectId: number+ userId: number | undefined+ slackIntegrationId: number | null+ slackChannel: string | null+ cadence: ScoutSuggestionCadence+ scoutBody: string+ direction: AlertSuggestionDirection+ changePercent: number+ notebookTitle: string+ conversationBlocks: ConversationBlocks+}++function slackDestination(input: AcceptInput): SlackDestinationInput {+ if (input.slackIntegrationId === null || !input.slackChannel) {+ throw new Error('Choose a Slack channel first')+ }+ return { slackIntegrationId: input.slackIntegrationId, slackChannel: input.slackChannel }+}++async function resolveInsightId(insightId: number | null, shortId: string): Promise<number> {+ const resolved = insightId ?? (await getInsightId(shortId as InsightShortId))+ if (resolved === undefined) {+ throw new Error('The saved insight could not be found')+ }+ return resolved+}++/** Creates what the card offers; the button's disabled reason keeps the inputs each kind needs in place before this runs. */+export async function acceptSuggestion(input: AcceptInput): Promise<AcceptOutcome> {+ const { suggestion, cadence } = input+ const projectId = String(input.projectId)+ switch (suggestion.kind) {+ case 'scout': {+ const created = await signalsScoutCreate(+ projectId,+ buildScoutCreatePayload({ suggestion, cadence, body: input.scoutBody, ...slackDestination(input) })+ )+ return {+ accepted: { url: urls.inboxScout(created.skill.name), slackConnected: true },+ eventProperties: { cadence, scout_mode: suggestion.scout.mode, scout_skill_name: created.skill.name },+ }+ }+ case 'notebook': {+ const blocks = input.conversationBlocks+ const notebook = buildConversationNotebook({+ title: input.notebookTitle,+ summary: suggestion.notebook.summary,+ blocks: blocks.blocks,+ incident: suggestion.notebook.incident,+ })+ const saved = await notebooksCreate(projectId, {+ title: input.notebookTitle.trim(),+ content: notebook.content,+ text_content: notebook.markdown,+ })+ return {+ accepted: { url: urls.notebook(saved.short_id), slackConnected: true },+ eventProperties: {+ notebook_short_id: saved.short_id,+ incident: suggestion.notebook.incident !== null,+ message_count: blocks.messageCount,+ query_count: blocks.queryCount,+ },+ }+ }+ case 'alert': {+ if (input.userId === undefined) {+ throw new Error('Your account is still loading')+ }+ const slack = slackDestination(input)+ const insightId = await resolveInsightId(suggestion.alert.insightId, suggestion.alert.insightShortId)+ const alert = await alertsCreate(+ projectId,+ buildAlertCreatePayload({+ suggestion,+ direction: input.direction,+ changePercent: input.changePercent,+ insightId,+ userId: input.userId,+ })+ )+ let slackConnected = true+ try {+ await alertsDestinationsCreate(projectId, alert.id, buildAlertDestinationPayload(slack))+ } catch {+ // The alert exists, so the card reports it and points at where to add the channel.+ slackConnected = false+ }+ return {+ accepted: { url: urls.alert(alert.id), slackConnected },+ eventProperties: {+ direction: input.direction,+ change_percent: input.changePercent,+ slack_connected: slackConnected,+ },+ }+ }+ case 'subscription': {+ const slack = slackDestination(input)+ const insightId = await resolveInsightId(+ suggestion.subscription.insightId,+ suggestion.subscription.insightShortId+ )+ const created = await subscriptionsCreate(+ projectId,+ buildSubscriptionCreatePayload({ suggestion, cadence, insightId, ...slack })+ )+ return {+ accepted: {+ url: urls.insightSubcription(+ suggestion.subscription.insightShortId as InsightShortId,+ String(created.id)+ ),+ slackConnected: true,+ },+ eventProperties: { cadence, subscription_id: created.id },+ }+ }+ case 'error_alert': {+ const slack = slackDestination(input)+ const template = await hogFunctionTemplatesRetrieve(projectId, ERROR_ALERT_SLACK_TEMPLATE_ID)+ const created = await hogFunctionsCreate(+ projectId,+ buildErrorAlertHogFunctionPayload({+ suggestion,+ ...slack,+ inputsSchema: template.inputs_schema as CyclotronJobInputSchemaType[] | null,+ })+ )+ return {+ accepted: { url: urls.errorTrackingAlert(created.id), slackConnected: true },+ eventProperties: { hog_function_id: created.id },+ }+ }+ }+}diff --git a/products/posthog_ai/frontend/utils/conversationNotebook.test.ts b/products/posthog_ai/frontend/utils/conversationNotebook.test.tsnew file mode 100644index 000000000000..b2d01ac5c14d--- /dev/null+++ b/products/posthog_ai/frontend/utils/conversationNotebook.test.ts@@ -0,0 +1,175 @@+import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'++import type { ThreadItem, ToolInvocation } from '../types/streamTypes'+import { buildConversationNotebook, collectConversationBlocks } from './conversationNotebook'++jest.mock('lib/utils/dom', () => ({ ...jest.requireActual('lib/utils/dom'), uuid: () => 'node-1' }))++function execInvocation(toolCallId: string, command: string, output: unknown): ToolInvocation {+ return {+ toolCallId,+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: { command },+ output,+ status: 'completed',+ contentBlocks: [],+ meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ }+}++const THREAD: ThreadItem[] = [+ { id: 'h1', type: 'human_message', text: 'Why did signups drop on Tuesday?' },+ { id: 't1', type: 'tool_invocation', toolCallId: 'sql' },+ { id: 't2', type: 'tool_invocation', toolCallId: 'insight' },+ { id: 't3', type: 'tool_invocation', toolCallId: 'recordings' },+ { id: 'a1', type: 'assistant_message', text: 'A checkout error cut signups by a third.', complete: true },+ { id: 'sep', type: 'turn_separator' },+]++const INVOCATIONS = new Map<string, ToolInvocation>([+ [+ 'sql',+ execInvocation('sql', 'call execute-sql {"query":"SELECT count() FROM events"}', {+ query: { kind: 'HogQLQuery', query: 'SELECT count() FROM events' },+ results: [[1]],+ }),+ ],+ [+ 'insight',+ execInvocation('insight', 'call insight-create {"name":"Signups"}', {+ short_id: 'abc123',+ name: 'Signups',+ query: { kind: 'TrendsQuery', series: [] },+ }),+ ],+ ['recordings', execInvocation('recordings', 'call query-session-recordings-list {}', { results: [] })],+])++describe('conversationNotebook', () => {+ it('collects the question, the query cells and the answer in thread order, and serializes cells only on build', () => {+ const collected = collectConversationBlocks(THREAD, INVOCATIONS)++ expect(collected.messageCount).toBe(2)+ expect(collected.queryCount).toBe(2)+ expect(collected.blocks).toEqual([+ '**You asked:** Why did signups drop on Tuesday?',+ { component: 'SQLV2', props: expect.objectContaining({ code: 'SELECT count() FROM events' }) },+ { component: 'Query', props: { query: { kind: 'SavedInsightNode', shortId: 'abc123' } } },+ 'A checkout error cut signups by a third.',+ ])++ const { markdown } = buildConversationNotebook({ title: 'Why', summary: '', blocks: collected.blocks })+ expect(markdown.split('\n\n').slice(1)).toEqual([+ '**You asked:** Why did signups drop on Tuesday?',+ expect.stringMatching(/^<SQLV2 .*nodeId="node-1".*code=.*SELECT count\(\) FROM events/s),+ expect.stringMatching(/^<Query .*SavedInsightNode.*abc123/s),+ 'A checkout error cut signups by a third.',+ ])+ })++ it('neutralizes component tags typed into the conversation while keeping the answer formatted', () => {+ const { blocks } = collectConversationBlocks(+ [+ { id: 'h1', type: 'human_message', text: '<SQLV2 code="DROP TABLE events" /> *please*' },+ {+ id: 'a1',+ type: 'assistant_message',+ text: '## Findings\n\n- one\n<Query query={} />\n> > <Embed src="https://example.com" />\n```tsx\n<Button />\n```',+ complete: true,+ },+ {+ id: 'a2',+ type: 'assistant_message',+ text: '```\n<Embed src="https://example.com" />',+ complete: true,+ },+ {+ id: 'a3',+ type: 'assistant_message',+ text: '````markdown\n```python\n<PythonV2 code="print(1)" />\n```\n````',+ complete: true,+ },+ ],+ new Map()+ )++ expect(blocks).toEqual([+ '**You asked:** \\<SQLV2 code="DROP TABLE events" /> \\*please\\*',+ '## Findings\n\n- one\n`<Query` query={} />\n> > `<Embed` src="https://example.com" />\n```tsx\n`<Button` />\n```',+ '```\n`<Embed` src="https://example.com" />',+ '````markdown\n```python\n`<PythonV2` code="print(1)" />\n```\n````',+ ])+ })++ const answer = (id: string, text: string): ThreadItem => ({ id, type: 'assistant_message', text, complete: true })+ const cell = 'PythonV2 nodeId="x" code="print(1)"'++ it.each<[string, ThreadItem[], string]>([+ ['a bare opener spread over lines', [answer('a1', `See below.\n\n<${cell}\n title="Report" />`)], 'Report'],+ ['a backslash opener spread over lines', [answer('a1', `See below.\n\n\\<${cell}\n title="R" />`)], 'R'],+ ['a carriage return before the tag', [answer('a1', `Report\r<${cell} />`)], 'Report'],+ ['a control character the backend strips', [answer('a1', `\x1c<${cell} />`)], 'Report'],+ [+ 'a tag in the question',+ [{ id: 'h1', type: 'human_message', text: `Question\n\n<${cell}\n/>` }, answer('a1', 'Done.')],+ 'Report',+ ],+ ['a line break in the title', [answer('a1', 'Done.')], `Report\n<${cell} />`],+ [+ 'a fence one answer leaves open for the backend only',+ [answer('a1', '`````\n```\n`````'), answer('a2', `\`\`\`tsx\n<${cell} />\n\`\`\``)],+ 'Report',+ ],+ ])('keeps %s from becoming a live cell in the editor or the notebooks backend', (_label, thread, title) => {+ const { blocks } = collectConversationBlocks(thread, new Map())+ const { markdown } = buildConversationNotebook({ title, summary: '', blocks })++ expect(parseMarkdownNotebook(markdown).nodes.some((node) => node.type === 'component')).toBe(false)+ // The backend's run-all parser takes any line that starts with a tag once Python's `strip()` runs.+ const backendLines = markdown.replace(/\r\n?/g, '\n').split('\n')+ expect(backendLines.filter((line) => /^[\s\x1c-\x1f\x85]*\\?<[A-Z]/.test(line))).toEqual([])+ })++ it('lays an incident write-up out as timeline, cause, evidence and fix around the conversation', () => {+ const { markdown } = buildConversationNotebook({+ title: 'Why signups dropped on Tuesday',+ summary: 'A checkout error was the cause.',+ blocks: ['**You asked:** Why?', 'Because.'],+ incident: { timeline: '- 14:10 release\n- 14:25 first error', cause: 'Checkout error.', fix: '' },+ })++ expect(markdown.split('\n\n')).toEqual([+ '# Why signups dropped on Tuesday',+ 'A checkout error was the cause.',+ '## Timeline',+ '- 14:10 release\n- 14:25 first error',+ '## Cause',+ 'Checkout error.',+ '## Evidence',+ '**You asked:** Why?',+ 'Because.',+ ])+ })++ it('builds the document the notebooks API stores, with the title and lead in front', () => {+ const notebook = buildConversationNotebook({+ title: 'Why signups dropped on Tuesday',+ summary: 'A checkout error was the cause.',+ blocks: ['**You asked:** Why?', 'Because.'],+ })++ expect(notebook.markdown).toEqual(+ '# Why signups dropped on Tuesday\n\nA checkout error was the cause.\n\n**You asked:** Why?\n\nBecause.'+ )+ expect(notebook.content).toEqual({+ type: 'doc',+ content: [+ {+ type: 'ph-markdown-notebook',+ attrs: { nodeId: 'markdown-notebook-v2', markdown: notebook.markdown },+ },+ ],+ })+ })+})diff --git a/products/posthog_ai/frontend/utils/conversationNotebook.ts b/products/posthog_ai/frontend/utils/conversationNotebook.tsnew file mode 100644index 000000000000..910729ce979d--- /dev/null+++ b/products/posthog_ai/frontend/utils/conversationNotebook.ts@@ -0,0 +1,148 @@+import {+ escapeComponentTagLines,+ escapeInlineMarkdownText,+ escapeMarkdownBlockLines,+} from 'lib/components/MarkdownNotebook/markdown'+import { NotebookPropValue } from 'lib/components/MarkdownNotebook/types'+import { uuid } from 'lib/utils/dom'+import {+ buildMarkdownNotebookContent,+ getSqlV2PropsFromQueryProp,+ serializeMarkdownNotebookComponent,+} from 'scenes/notebooks/Notebook/markdownNotebookV2'++import { ArtifactSource } from '~/queries/schema/schema-assistant-messages'+import { NodeKind } from '~/queries/schema/schema-general'++import { extractQueryResult, extractVisualizationArtifact } from '../components/tool/widgets/extractors'+import type { IncidentOutline, ThreadItem, ToolInvocation } from '../types/streamTypes'+import { toolInvocationToMessage } from './toolCallMessage'+import { visualizationTypeToQuery } from './visualizationQuery'++/** A component cell before serialization; the node id is minted when the notebook is built. */+export interface ConversationComponentBlock {+ component: 'Query' | 'SQLV2'+ props: Record<string, NotebookPropValue>+}++export type ConversationBlock = string | ConversationComponentBlock++export interface ConversationBlocks {+ blocks: ConversationBlock[]+ messageCount: number+ queryCount: number+}++export interface ConversationNotebook {+ markdown: string+ /** ProseMirror doc holding one markdown notebook node, the shape the notebooks API stores. */+ content: unknown+}++const INSIGHT_TOOLS = new Set(['insight-create', 'insight-update', 'insight-get', 'insight-query'])++/** Mirrors the blocks the agent's notebook tools write: a SQLV2 cell for HogQL, a Query embed otherwise. */+function toolCallToNotebookBlock(invocation: ToolInvocation): ConversationComponentBlock | null {+ const message = toolInvocationToMessage(invocation)+ if (!message || message.status !== 'completed' || !message.innerToolName) {+ return null+ }+ if (INSIGHT_TOOLS.has(message.innerToolName)) {+ const artifact = extractVisualizationArtifact(message)+ if (artifact?.envelope.source === ArtifactSource.Insight) {+ return {+ component: 'Query',+ props: { query: { kind: NodeKind.SavedInsightNode, shortId: artifact.envelope.artifact_id } },+ }+ }+ }+ const result = extractQueryResult(message)+ if (!result) {+ return null+ }+ const query = result.content.query as unknown as NotebookPropValue+ const sqlProps = getSqlV2PropsFromQueryProp({ query })+ if (sqlProps) {+ return { component: 'SQLV2', props: { ...sqlProps, returnVariable: 'sql_df' } }+ }+ const renderable = visualizationTypeToQuery(result.content)+ return renderable ? { component: 'Query', props: { query: renderable as unknown as NotebookPropValue } } : null+}++/** Recomputed on every stream frame while the card is shown, so nothing here serializes or mints ids. */+export function collectConversationBlocks(+ threadItems: ThreadItem[],+ toolInvocations: Map<string, ToolInvocation>+): ConversationBlocks {+ const blocks: ConversationBlock[] = []+ let messageCount = 0+ let queryCount = 0+ for (const item of threadItems) {+ if (item.type === 'human_message' && item.text?.trim()) {+ messageCount += 1+ // A question is plain text, so it is escaped in full; the answer is markdown by design.+ blocks.push(+ escapeComponentTagLines(+ `**You asked:** ${escapeMarkdownBlockLines(escapeInlineMarkdownText(item.text.trim()))}`+ )+ )+ } else if (item.type === 'assistant_message' && item.text?.trim()) {+ messageCount += 1+ blocks.push(escapeComponentTagLines(item.text.trim()))+ } else if (item.type === 'tool_invocation' && item.toolCallId) {+ const invocation = toolInvocations.get(item.toolCallId)+ const block = invocation ? toolCallToNotebookBlock(invocation) : null+ if (block) {+ queryCount += 1+ blocks.push(block)+ }+ }+ }+ return { blocks, messageCount, queryCount }+}++function serializeBlock(block: ConversationBlock): string {+ return typeof block === 'string'+ ? block+ : serializeMarkdownNotebookComponent(block.component, { nodeId: uuid(), ...block.props })+}++function section(heading: string, text: string): string[] {+ return text.trim() ? [`## ${heading}`, escapeComponentTagLines(text.trim())] : []+}++/** The incident write-up keeps the conversation as the evidence between the cause and the fix. */+function incidentSections(incident: IncidentOutline, blocks: string[]): string[] {+ return [+ ...section('Timeline', incident.timeline),+ ...section('Cause', incident.cause),+ '## Evidence',+ ...blocks,+ ...section('Fix', incident.fix),+ ]+}++export function buildConversationNotebook({+ title,+ summary,+ blocks,+ incident,+}: {+ title: string+ summary: string+ blocks: ConversationBlock[]+ incident?: IncidentOutline | null+}): ConversationNotebook {+ const lead = summary.trim() ? [escapeComponentTagLines(summary.trim())] : []+ const serialized = blocks.map(serializeBlock)+ const body = incident ? incidentSections(incident, serialized) : serialized+ // A line break in the title would start a line the heading marker does not cover.+ const heading = `# ${escapeInlineMarkdownText(+ title+ .split(/[\s\x1c-\x1f\x85]+/)+ .join(' ')+ .trim()+ )}`+ const markdown = [heading, ...lead, ...body].join('\n\n')+ return { markdown, content: buildMarkdownNotebookContent(markdown) }+}diff --git a/products/posthog_ai/frontend/utils/recordTurnSuggestionResolution.ts b/products/posthog_ai/frontend/utils/recordTurnSuggestionResolution.tsnew file mode 100644index 000000000000..81a3f5cd459e--- /dev/null+++ b/products/posthog_ai/frontend/utils/recordTurnSuggestionResolution.ts@@ -0,0 +1,24 @@+import { turnSuggestionsResolveCreate } from '../generated/api'+import type { TurnSuggestionResolutionEnumApi } from '../generated/api.schemas'+import type { TurnSuggestion } from '../types/streamTypes'++/**+ * Records a dismissed or accepted card in the offer ledger, so a reload keeps it hidden and a+ * dismissal mutes the conversation server-side. Best effort: the card already closed locally, and a+ * lost write only means a reload can show the card again.+ */+export function recordTurnSuggestionResolution(+ projectId: number | null,+ sessionId: string,+ suggestion: TurnSuggestion,+ resolution: TurnSuggestionResolutionEnumApi+): void {+ if (projectId === null) {+ return+ }+ void turnSuggestionsResolveCreate(String(projectId), {+ task_id: sessionId,+ turn_index: suggestion.turnIndex,+ resolution,+ }).catch(() => undefined)+}diff --git a/products/posthog_ai/frontend/utils/suggestionPayloads.test.ts b/products/posthog_ai/frontend/utils/suggestionPayloads.test.tsnew file mode 100644index 000000000000..9186b9ce9606--- /dev/null+++ b/products/posthog_ai/frontend/utils/suggestionPayloads.test.ts@@ -0,0 +1,136 @@+import { dayjs } from 'lib/dayjs'++import type { TurnSuggestion } from '../types/streamTypes'+import {+ buildAlertCreatePayload,+ buildAlertDestinationPayload,+ buildErrorAlertHogFunctionPayload,+ buildScoutCreatePayload,+ buildSubscriptionCreatePayload,+ nextSubscriptionStart,+} from './suggestionPayloads'+import { SUGGESTION_FRAMES } from './turnSuggestionFixtures'+import { parseTurnSuggestionParams } from './turnSuggestions'++function parsed<K extends TurnSuggestion['kind']>(kind: K): Extract<TurnSuggestion, { kind: K }> {+ const suggestion = parseTurnSuggestionParams(SUGGESTION_FRAMES[kind])+ if (suggestion?.kind !== kind) {+ throw new Error(`expected a ${kind} suggestion`)+ }+ return suggestion as Extract<TurnSuggestion, { kind: K }>+}++const SLACK = { slackIntegrationId: 7, slackChannel: 'C123|#growth' }++describe('suggestionPayloads', () => {+ it('buildScoutCreatePayload maps the cadence to a cron and keeps a watch scout off the inactivity sweep', () => {+ const suggestion = parsed('scout')++ expect(buildScoutCreatePayload({ suggestion, cadence: 'daily', body: 'Edited steps', ...SLACK })).toEqual({+ display_name: 'Weekly signups',+ description: 'Counts signed_up events for the last 7 days.',+ body: 'Edited steps',+ config: {+ run_cron_schedule: '0 9 * * *',+ output_destinations: { slack: { integration_id: 7, channel: 'C123|#growth' } },+ },+ })+ const watch = { ...suggestion, scout: { ...suggestion.scout, mode: 'watch' as const } }+ expect(+ buildScoutCreatePayload({ suggestion: watch, cadence: 'daily', body: '', ...SLACK }).config+ ).toMatchObject({+ auto_pause_exempt: true,+ })+ })++ it('buildAlertCreatePayload turns the percent into a relative bound on the first series', () => {+ expect(+ buildAlertCreatePayload({+ suggestion: parsed('alert'),+ direction: 'increase',+ changePercent: 35,+ insightId: 42,+ userId: 9,+ })+ ).toEqual({+ insight: 42,+ subscribed_users: [9],+ name: 'Signups: 35% increase',+ enabled: true,+ condition: { type: 'relative_increase' },+ config: { type: 'TrendsAlertConfig', series_index: 0, check_ongoing_interval: false },+ threshold: { configuration: { type: 'percentage', bounds: { upper: 0.35 } } },+ calculation_interval: 'daily',+ })+ })++ test.each([+ ['a picker value', 'C123|#growth', { slack_channel_id: 'C123', slack_channel_name: 'growth' }],+ ['a bare channel id', 'C123', { slack_channel_id: 'C123', slack_channel_name: undefined }],+ ])('buildAlertDestinationPayload splits %s', (_label, slackChannel, expected) => {+ expect(buildAlertDestinationPayload({ slackIntegrationId: 7, slackChannel })).toEqual({+ type: 'slack',+ slack_workspace_id: 7,+ ...expected,+ })+ })++ test.each([+ ['daily before 9', 'daily', '2026-09-16T07:30:00', '2026-09-16 09:00'],+ ['daily after 9', 'daily', '2026-09-16T10:00:00', '2026-09-17 09:00'],+ ['weekly on a Wednesday', 'weekly', '2026-09-16T10:00:00', '2026-09-21 09:00'],+ ['weekly on a Monday morning', 'weekly', '2026-09-21T08:00:00', '2026-09-21 09:00'],+ ] as const)('nextSubscriptionStart picks the next 9:00 for %s', (_label, cadence, now, expected) => {+ expect(nextSubscriptionStart(cadence, dayjs(now)).format('YYYY-MM-DD HH:mm')).toBe(expected)+ })++ it('buildSubscriptionCreatePayload sends the insight to the channel on Mondays without a test delivery', () => {+ const now = dayjs('2026-09-16T10:00:00')++ expect(+ buildSubscriptionCreatePayload({+ suggestion: parsed('subscription'),+ cadence: 'weekly',+ insightId: 42,+ now,+ ...SLACK,+ })+ ).toEqual({+ insight: 42,+ title: 'Weekly report: Signups',+ target_type: 'slack',+ integration_id: 7,+ target_value: 'C123|#growth',+ frequency: 'weekly',+ interval: 1,+ byweekday: ['monday'],+ start_date: nextSubscriptionStart('weekly', now).toISOString(),+ send_test_now: false,+ })+ })++ it('buildErrorAlertHogFunctionPayload scopes the Slack reopened template to the one issue', () => {+ const payload = buildErrorAlertHogFunctionPayload({+ suggestion: parsed('error_alert'),+ ...SLACK,+ inputsSchema: [+ { key: 'icon_emoji', type: 'string', label: 'Emoji icon', default: ':hedgehog:' },+ { key: 'channel', type: 'string', label: 'Channel', default: 'C-default' },+ ],+ })++ expect(payload).toMatchObject({+ type: 'internal_destination',+ template_id: 'template-slack',+ name: 'Post to Slack on issue reopened: #growth',+ enabled: true,+ filters: {+ source: 'internal-events',+ events: [{ id: '$error_tracking_issue_reopened', type: 'events' }],+ properties: [{ key: 'distinct_id', value: 'issue-1', operator: 'exact', type: 'event_metadata' }],+ },+ inputs: { icon_emoji: { value: ':hedgehog:' }, slack_workspace: { value: 7 }, channel: { value: 'C123' } },+ })+ expect(payload.inputs?.blocks).toBeTruthy()+ })+})diff --git a/products/posthog_ai/frontend/utils/suggestionPayloads.ts b/products/posthog_ai/frontend/utils/suggestionPayloads.tsnew file mode 100644index 000000000000..36a573183ad4--- /dev/null+++ b/products/posthog_ai/frontend/utils/suggestionPayloads.ts@@ -0,0 +1,212 @@+import {+ buildAlertHogFunctionConfiguration,+ buildAlertInputs,+} from 'lib/components/Alerting/AlertWizard/alertWizardLogic'+import { Dayjs, dayjs } from 'lib/dayjs'+import { slackChannelId, slackChannelName } from 'lib/integrations/slackChannel'+import {+ HOG_FUNCTION_SUB_TEMPLATES,+ HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES,+} from 'scenes/hog-functions/sub-templates/sub-templates'++import { CyclotronJobInputSchemaType, PropertyFilterType, PropertyOperator } from '~/types'++import type { alertsCreate } from 'products/alerts/frontend/generated/api'+import type { AlertCreateDestinationApi } from 'products/alerts/frontend/generated/api.schemas'+import type { hogFunctionsCreate } from 'products/cdp/frontend/generated/api'+import type { SignalScoutCreateApi } from 'products/signals/frontend/generated/api.schemas'+import {+ DEFAULT_SCOUT_DAILY_TIME,+ DEFAULT_SCOUT_WEEKLY_DAY,+ dayTimeToWeeklyCron,+ timeToDailyCron,+} from 'products/signals/frontend/inbox/utils/scoutRunsWindow'+import type { subscriptionsCreate } from 'products/subscriptions/frontend/generated/api'++import type {+ AlertSuggestionDirection,+ AlertTurnSuggestion,+ ErrorAlertTurnSuggestion,+ ScoutSuggestionCadence,+ ScoutTurnSuggestion,+ SubscriptionTurnSuggestion,+} from '../types/streamTypes'++/** The same default hour and weekday the scout settings form proposes. */+function cadenceToCron(cadence: ScoutSuggestionCadence): string {+ return cadence === 'daily'+ ? timeToDailyCron(DEFAULT_SCOUT_DAILY_TIME)+ : dayTimeToWeeklyCron(DEFAULT_SCOUT_WEEKLY_DAY, DEFAULT_SCOUT_DAILY_TIME)+}++export interface SlackDestinationInput {+ slackIntegrationId: number+ /** A `${channelId}|#${channelName}` picker value. */+ slackChannel: string+}++export interface ScoutCreateInput extends SlackDestinationInput {+ suggestion: ScoutTurnSuggestion+ cadence: ScoutSuggestionCadence+ /** The instructions the user reviewed on the card, which start as the drafted ones. */+ body: string+}++export function buildScoutCreatePayload({+ suggestion,+ cadence,+ body,+ slackIntegrationId,+ slackChannel,+}: ScoutCreateInput): SignalScoutCreateApi {+ return {+ display_name: suggestion.scout.displayName,+ description: suggestion.scout.description || suggestion.scout.displayName,+ body,+ config: {+ run_cron_schedule: cadenceToCron(cadence),+ output_destinations: {+ slack: { integration_id: slackIntegrationId, channel: slackChannel },+ },+ // A watch scout is valuable when it stays silent, which the inactivity sweep would read as dead.+ ...(suggestion.scout.mode === 'watch' ? { auto_pause_exempt: true } : {}),+ },+ }+}++export interface AlertCreateInput {+ suggestion: AlertTurnSuggestion+ direction: AlertSuggestionDirection+ changePercent: number+ insightId: number+ userId: number+}++export function buildAlertCreatePayload({+ suggestion,+ direction,+ changePercent,+ insightId,+ userId,+}: AlertCreateInput): Parameters<typeof alertsCreate>[1] {+ return {+ insight: insightId,+ subscribed_users: [userId],+ name: `${suggestion.alert.insightName}: ${changePercent}% ${direction}`,+ enabled: true,+ condition: { type: direction === 'decrease' ? 'relative_decrease' : 'relative_increase' },+ config: { type: 'TrendsAlertConfig', series_index: 0, check_ongoing_interval: false },+ // The alerts API reads a relative bound as a fraction of the previous period and fires above `upper`.+ threshold: { configuration: { type: 'percentage', bounds: { upper: changePercent / 100 } } },+ calculation_interval: 'daily',+ }+}++export function buildAlertDestinationPayload({+ slackIntegrationId,+ slackChannel,+}: SlackDestinationInput): AlertCreateDestinationApi {+ return {+ type: 'slack',+ slack_workspace_id: slackIntegrationId,+ slack_channel_id: slackChannelId(slackChannel),+ slack_channel_name: slackChannelName(slackChannel),+ }+}++const DELIVERY_HOUR = 9++/** The next 09:00 in the browser's clock, on a Monday for a weekly cadence. */+export function nextSubscriptionStart(cadence: ScoutSuggestionCadence, now: Dayjs = dayjs()): Dayjs {+ let start = now.hour(DELIVERY_HOUR).minute(0).second(0).millisecond(0)+ if (!start.isAfter(now)) {+ start = start.add(1, 'day')+ }+ while (cadence === 'weekly' && start.day() !== 1) {+ start = start.add(1, 'day')+ }+ return start+}++export interface SubscriptionCreateInput extends SlackDestinationInput {+ suggestion: SubscriptionTurnSuggestion+ cadence: ScoutSuggestionCadence+ insightId: number+ now?: Dayjs+}++export function buildSubscriptionCreatePayload({+ suggestion,+ cadence,+ insightId,+ slackIntegrationId,+ slackChannel,+ now,+}: SubscriptionCreateInput): Parameters<typeof subscriptionsCreate>[1] {+ const prefix = cadence === 'weekly' ? 'Weekly' : 'Daily'+ return {+ insight: insightId,+ title: `${prefix} report: ${suggestion.subscription.insightName}`.slice(0, 100),+ target_type: 'slack',+ integration_id: slackIntegrationId,+ target_value: slackChannel,+ frequency: cadence,+ interval: 1,+ byweekday: cadence === 'weekly' ? ['monday'] : undefined,+ start_date: nextSubscriptionStart(cadence, now).toISOString(),+ send_test_now: false,+ }+}++type HogFunctionWriteBody = NonNullable<Parameters<typeof hogFunctionsCreate>[1]>++const ERROR_ALERT_SUB_TEMPLATE = 'error-tracking-issue-reopened'+export const ERROR_ALERT_SLACK_TEMPLATE_ID = 'template-slack'++export interface ErrorAlertCreateInput extends SlackDestinationInput {+ suggestion: ErrorAlertTurnSuggestion+ /** The Slack template's input schema, whose defaults the alert wizard also fills in. */+ inputsSchema: CyclotronJobInputSchemaType[] | null | undefined+}++/**+ * The same destination the error tracking alert wizard writes for "post to Slack on issue reopened",+ * narrowed to one issue. A created-issue trigger would never fire for an issue that already exists.+ */+export function buildErrorAlertHogFunctionPayload({+ suggestion,+ slackIntegrationId,+ slackChannel,+ inputsSchema,+}: ErrorAlertCreateInput): HogFunctionWriteBody {+ const common = HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[ERROR_ALERT_SUB_TEMPLATE]+ const slackTemplate = HOG_FUNCTION_SUB_TEMPLATES[ERROR_ALERT_SUB_TEMPLATE].find(+ (template) => template.template_id === ERROR_ALERT_SLACK_TEMPLATE_ID+ )+ const channelName = slackChannelName(slackChannel)+ const configuration = buildAlertHogFunctionConfiguration({+ templateId: ERROR_ALERT_SLACK_TEMPLATE_ID,+ name: `${slackTemplate?.name ?? 'Post to Slack on issue reopened'}${channelName ? `: #${channelName}` : ''}`,+ description: `Posts to Slack when "${suggestion.errorAlert.issueName}" reopens.`,+ filters: {+ ...common.filters,+ // Issue lifecycle events carry the issue id as their distinct id, not as an event property.+ properties: [+ {+ key: 'distinct_id',+ value: suggestion.errorAlert.issueId,+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.EventMetadata,+ },+ ],+ },+ inputs: buildAlertInputs(inputsSchema, slackTemplate?.inputs, {+ slack_workspace: { value: slackIntegrationId },+ channel: { value: slackChannelId(slackChannel) },+ }),+ })+ // The wizard's configuration uses the handwritten hog function types, and the generated write body+ // marks server-set input fields (bytecode, order, transpiled) as required, so it reaches the+ // generated type only through `unknown`.+ return configuration as unknown as HogFunctionWriteBody+}diff --git a/products/posthog_ai/frontend/utils/turnSuggestionEvents.ts b/products/posthog_ai/frontend/utils/turnSuggestionEvents.tsnew file mode 100644index 000000000000..20a937480e52--- /dev/null+++ b/products/posthog_ai/frontend/utils/turnSuggestionEvents.ts@@ -0,0 +1,43 @@+import posthog from 'posthog-js'++import type { TurnSuggestion } from '../types/streamTypes'++export interface TurnSuggestionEventContext {+ sessionId: string+}++/** Shared properties of every card event, so one dashboard can split them by kind and intent. */+function turnSuggestionEventProperties(+ context: TurnSuggestionEventContext,+ suggestion: TurnSuggestion+): Record<string, unknown> {+ return {+ ai_product: 'posthog_ai',+ agent_runtime: 'sandbox',+ task_id: context.sessionId,+ turn_index: suggestion.turnIndex,+ suggestion_kind: suggestion.kind,+ intent: suggestion.intent,+ confidence: suggestion.confidence,+ }+}++export type TurnSuggestionEvent =+ | 'shown'+ | 'dismissed'+ | 'superseded'+ | 'accepted'+ | 'accept failed'+ | 'connect slack clicked'++export function captureTurnSuggestionEvent(+ event: TurnSuggestionEvent,+ context: TurnSuggestionEventContext,+ suggestion: TurnSuggestion,+ extra: Record<string, unknown> = {}+): void {+ posthog.capture(`posthog ai turn suggestion ${event}`, {+ ...turnSuggestionEventProperties(context, suggestion),+ ...extra,+ })+}