: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(today): send the briefing as context when asking posthog ai (#110640)
Vojta Bartošac9dc5da8a4d
diff --git a/frontend/src/scenes/project-homepage/today/TodayAskBox.tsx b/frontend/src/scenes/project-homepage/today/TodayAskBox.tsxindex 3d4069347997..b23d814cc0a6 100644--- a/frontend/src/scenes/project-homepage/today/TodayAskBox.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayAskBox.tsx@@ -5,7 +5,7 @@ import { IconArrowRight } from '@posthog/icons'import { todayLogic } from './todayLogic'-/** Sends the question to PostHog AI, which answers in a new chat under Spaces. */+/** Sends the question to PostHog AI with the briefing as context. PostHog AI answers in a new chat under Spaces. */export function TodayAskBox(): JSX.Element {const { askAi } = useActions(todayLogic)const [question, setQuestion] = useState('')@@ -17,7 +17,7 @@ export function TodayAskBox(): JSX.Element {event.preventDefault()const trimmed = question.trim()if (trimmed) {- askAi(trimmed)+ askAi(trimmed, 'ask_box')setQuestion('')}}}diff --git a/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx b/frontend/src/scenes/project-homepage/today/TodayBriefing.tsxindex 432f7242399f..75e2b834c8d5 100644--- a/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'import { TodayAskBox } from './TodayAskBox'+import { WALK_THROUGH_QUESTION } from './todayAskPrompt'import { TodayChipStack } from './TodayChipStack'import { TodayIcon } from './TodayIcon'import { todayLogic } from './todayLogic'@@ -106,7 +107,7 @@ function TodayBriefingReports(): JSX.Element {<buttontype="button"data-attr="today-ask-about-edition"- onClick={() => askAi('Walk me through what changed in my product today.')}+ onClick={() => askAi(WALK_THROUGH_QUESTION, 'walk_through')}>ask PostHog AI to walk you through it</button>diff --git a/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx b/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsxindex f7a11fb4bb9c..f5367df18e65 100644--- a/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx@@ -8,6 +8,7 @@ import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'import type { BriefingSegmentApi } from 'products/today/frontend/generated/api.schemas'+import { WALK_THROUGH_QUESTION } from './todayAskPrompt'import { isExternalHref, itemHref, itemSource } from './todayBriefingItems'import { TodayChipStack } from './TodayChipStack'import { TodayIcon } from './TodayIcon'@@ -127,7 +128,7 @@ export function TodayPersonalBriefing(): JSX.Element | null {<buttontype="button"data-attr="today-ask-about-edition"- onClick={() => askAi('Walk me through what changed in my product today.')}+ onClick={() => askAi(WALK_THROUGH_QUESTION, 'walk_through')}>ask PostHog AI to walk you through it</button>diff --git a/frontend/src/scenes/project-homepage/today/todayAskPrompt.ts b/frontend/src/scenes/project-homepage/today/todayAskPrompt.tsnew file mode 100644index 000000000000..eae62e84c062--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayAskPrompt.ts@@ -0,0 +1,79 @@+import { urls } from 'scenes/urls'++import { SignalReport } from 'products/signals/frontend/inbox/types'+import type { BriefingApi } from 'products/today/frontend/generated/api.schemas'++import { isExternalHref, itemHref } from './todayBriefingItems'++export const WALK_THROUGH_QUESTION = 'Walk me through my Today briefing and tell me what to do first.'++/** What the Today page showed when the person asked, so PostHog AI can read the same briefing and reports. */+export type TodayAskContext =+ | { kind: 'briefing'; briefing: BriefingApi }+ | { kind: 'reports'; reports: SignalReport[] }+ | { kind: 'none' }++// Briefing item URLs from the API already start with `/project/<id>`, but Today's own report pages do not.+function absoluteHref(href: string): string {+ if (isExternalHref(href)) {+ return href+ }+ return urls.absolute(href.startsWith('/project/') ? href : urls.currentProject(href))+}++function markdownLink(text: string, href: string): string {+ return `[${text.replace(/[[\]]/g, '\\$&')}](${absoluteHref(href)})`+}++function briefingContext(briefing: BriefingApi): string[] {+ const items = briefing.items.map(+ (item) => `${item.rank}. ${markdownLink(item.label, itemHref(item))} (${item.signal}; state: ${item.state})`+ )+ return [+ `- Briefing id: \`${briefing.id}\`, for ${briefing.local_day}`,+ ...(items.length ? ['- Items, most urgent first:', ...items.map((line) => ` ${line}`)] : []),+ ...(briefing.more_reports_count > 0+ ? [+ `- ${briefing.more_reports_count} more open reports for me are in the ${markdownLink('Inbox', urls.inbox())}.`,+ ]+ : []),+ '',+ `Use the \`today-briefing-get\` tool to read this briefing and check that its id is \`${briefing.id}\`. ` ++ 'If the id is different, a newer briefing replaced it: tell me, and use the newer one. ' ++ 'Use `today-candidates-list` for the facts behind each item. A report link ends with the report id: use it ' ++ 'with `inbox-reports-retrieve` to read the report in full before you follow up on it.',+ ]+}++function reportsContext(reports: SignalReport[]): string[] {+ return [+ '- My briefing is not written yet. The page shows these reports, most urgent first:',+ ...reports.map(+ (report, index) =>+ ` ${index + 1}. ${markdownLink(report.title ?? 'Untitled report', urls.todayReport(report.id))}` ++ (report.priority ? ` (${report.priority})` : '')+ ),+ '',+ 'Each link ends with the report id. Use it with `inbox-reports-retrieve` to read the report in full before you ' ++ 'follow up on it.',+ ]+}++/**+ * The question with the Today page's context under it, as Markdown. PostHog AI reads the briefing and reports+ * through the MCP tools the context names, so the context holds ids rather than the full report text.+ */+export function todayAskPrompt(question: string, context: TodayAskContext): string {+ if (context.kind === 'none' || (context.kind === 'reports' && context.reports.length === 0)) {+ return question+ }+ return [+ question,+ '',+ '---',+ '',+ `#### Context from my ${markdownLink('Today home page', urls.projectHomepage())}`,+ '',+ ...(context.kind === 'briefing' ? briefingContext(context.briefing) : reportsContext(context.reports)),+ ].join('\n')+}diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.tsindex e1294c24dea6..08ea7d925a50 100644--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts@@ -95,6 +95,35 @@ describe('todayLogic', () => {})})+ it.each([+ {+ shown: 'the briefing',+ hasBriefing: true,+ expected: ['briefing id: `briefing-1`', '](http://localhost/project/997/home/reports/a)'],+ },+ {+ shown: 'the report list',+ hasBriefing: false,+ expected: ['briefing is not written yet', '](http://localhost/project/997/home/reports/r-1)'],+ },+ ])('sends PostHog AI the question with $shown as context', async ({ hasBriefing, expected }) => {+ listResponse = [200, { results: [makeReport({ id: 'r-1' })], count: 1 }]+ if (hasBriefing) {+ briefingResponses = [[200, makeBriefing()]]+ }+ const logic = todayLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.askAi('Why is signup broken?', 'ask_box')++ const prompt = router.values.searchParams.ask as string+ expect(prompt.startsWith('Why is signup broken?\n')).toBe(true)+ for (const text of expected) {+ expect(prompt.toLowerCase()).toContain(text.toLowerCase())+ }+ })+it('keeps the last briefing on screen, polls while the next is written, and stops when it is ready', async () => {jest.useFakeTimers()const previous = makeBriefing({ id: 'b-previous', status: 'writing' })diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.tsindex 576291b76259..e1932ae59bd9 100644--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts@@ -22,6 +22,7 @@ import { todayBriefingRefreshCreate, todayBriefingRetrieve } from 'products/todaimport type { BriefingApi, BriefingItemApi } from 'products/today/frontend/generated/api.schemas'import type { TeamPublicType } from '../../../types'+import { TodayAskContext, todayAskPrompt } from './todayAskPrompt'import {TodayItemOpenSurface,briefingDayKey,@@ -43,6 +44,9 @@ const MAX_BRIEFING_POLLS = 132/** Where a report was opened from, sent with the `today report opened` event. */export type TodayReportOpenSource = 'briefing' | 'chip' | 'sidebar'+/** Where a question to PostHog AI came from, sent with the `today ai asked` event. */+export type TodayAskSource = 'ask_box' | 'walk_through'+/** The count behind the Inbox link: reports for the person beyond the shown ones, or open in the project. */export interface TodayInboxMore {count: number@@ -164,8 +168,12 @@ export interface todayLogicActions {searchParams: Record<string, any>url: string} // router- askAi: (prompt: string) => {+ askAi: (+ prompt: string,+ source: TodayAskSource+ ) => {prompt: string+ source: TodayAskSource}itemOpened: (item: BriefingItemApi,@@ -314,7 +322,7 @@ export const todayLogic = kea<todayLogicType>([actions: [router, ['locationChanged']],})),actions({- askAi: (prompt: string) => ({ prompt }),+ askAi: (prompt: string, source: TodayAskSource) => ({ prompt, source }),setHoveredReportId: (reportId: string | null) => ({ reportId }),openReport: (report: SignalReport, source: TodayReportOpenSource) => ({ report, source }),reportOpened: (report: SignalReport, source: TodayReportOpenSource) => ({ report, source }),@@ -541,8 +549,20 @@ export const todayLogic = kea<todayLogicType>([}, 'briefingPoll')}return {- askAi: ({ prompt }) => {- router.actions.push(urls.ai(undefined, prompt))+ askAi: ({ prompt, source }) => {+ // Sample reports have ids that do not exist, so PostHog AI gets no context to look up.+ const context: TodayAskContext = values.useSampleData+ ? { kind: 'none' }+ : values.showPersonalBriefing && values.personalBriefing+ ? { kind: 'briefing', briefing: values.personalBriefing }+ : { kind: 'reports', reports: values.reports }+ router.actions.push(urls.ai(undefined, todayAskPrompt(prompt, context)))+ // pinned: analytics event name and properties. Renaming them breaks dashboards.+ posthog.capture('today ai asked', {+ source,+ context: context.kind,+ briefing_id: context.kind === 'briefing' ? context.briefing.id : null,+ })},tick: () => {// An open tab moves to the new day's briefing at 8:00 without a reload, including a laptop