: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
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { businessKnowledgeRepositoriesFileRetrieve } from 'products/business_knowledge/frontend/generated/api'
import type { RepositoryFileApi } from 'products/business_knowledge/frontend/generated/api.schemas'
import {
type InboxReportLinkSource,
captureInboxReportAction,
captureTodayReportOpened,
discussQuestionProperties,
parseInboxReportLinkSource,
} from 'products/signals/frontend/inbox/inboxAnalytics'
import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'
import { SignalReport } from 'products/signals/frontend/inbox/types'
import {
todayExcerptChoiceCreate,
todayReportsFigureMarksRetrieve,
todayReportsKeyClausesRetrieve,
todayReportsPageRetrieve,
} from 'products/today/frontend/generated/api'
import type {
CodeFileApi,
FigureMarkApi,
FigureTextEnumApi,
ReportKeyClausesApi,
ReportPageApi,
SignalViewApi,
} from 'products/today/frontend/generated/api.schemas'
import {
todayExcerptChoiceCreateBodyExcerptsItemMax,
todayExcerptChoiceCreateBodyExcerptsMax,
todayExcerptChoiceCreateBodyFindingMax,
} from 'products/today/frontend/generated/api.zod'
import { type TodaySignalDestination } from './todayEvidence'
import { type TodayMarkedFigure, markedFigures, staleEvidenceDate } from './todayFigureSources'
import { TodayImpactNumber, impactNumbers } from './todayImpact'
import {
type TodayAskSource,
type TodayReportOpenContext,
reportIdFromPath,
signalReportSnapshot,
todayLogic,
} from './todayLogic'
import { reportWorkKind, reportWorkPrompt } from './todayNextStep'
import { TodayCodeQuote, codeIdentifiers, findCodeQuote } from './todayQuotedCode'
import { type TodayReportState, reportState } from './todayReportState'
import { findSampleReport, isSampleReportId } from './todaySampleReports'
import { todayVerdictLogic } from './todayVerdictLogic'
export type TodayCodeQuoteState = TodayCodeQuote | null | 'loading'
export type TodayMarkKind = 'impact' | 'figure' | 'key_clause'
const INVESTIGATE_QUESTION = 'Investigate this report. Confirm the problem and find the root cause.'
function marksIn(figureMarks: FigureMarkApi[] | null, text: FigureTextEnumApi): FigureMarkApi[] {
return (figureMarks ?? []).filter((mark) => mark.text === text)
}
export interface TodayReportLogicProps {
reportId: string
}
/** A visit whose `Inbox report opened` event waits for the report to load. */
interface TodayPendingOpen {
context: TodayReportOpenContext | null
linkSource: InboxReportLinkSource | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayReportLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
currentProjectId: number | string // teamLogic
currentTeamId: number | null // teamLogic
askingAi: boolean // todayLogic
reportOpenContext: TodayReportOpenContext | null // todayLogic
reports: SignalReport[] // todayLogic
reportStateOverrides: Record<string, TodayReportState> // todayVerdictLogic
asksJev: boolean
codeQuotes: Record<string, TodayCodeQuoteState>
composerOpen: boolean
currentReport: SignalReport | null
draft: string
evidenceCount: number
expandedEvidence: Record<string, boolean>
figureMarks: FigureMarkApi[] | null
figureMarksLoading: boolean
fullReport: SignalReport | null
fullReportLoading: boolean
impactMarks: TodayMarkedFigure[]
impactNumbers: TodayImpactNumber[]
impactText: string
isSample: boolean
keyClauses: ReportKeyClausesApi | null
keyClausesLoading: boolean
lastSeen: string | null
lead: string
leadMarks: TodayMarkedFigure[]
page: ReportPageApi | null
pageLoading: boolean
proposal: string
reportFailed: boolean
reportState: TodayReportState
reportUrl: string
shownEvidence: SignalViewApi[]
shownFigureMarks: FigureMarkApi[] | null
shownKeyClauses: ReportKeyClausesApi | null
staleFiguresDate: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayReportLogicActions {
createPrFromReport: (
report: SignalReport,
feedback?: string | undefined
) => {
feedback: string | undefined
report: SignalReport
} // inboxTaskKickoffLogic
discussReport: (
report: SignalReport,
reportUrl: string,
question: string,
agentQuestion?: string | undefined,
intent?: import('products/signals/frontend/inbox/inboxTaskKickoffLogic').ReportDiscussionIntent | undefined,
pullRequestUrl?: string | undefined,
background?: boolean | undefined
) => {
agentQuestion: string | undefined
background: boolean | undefined
intent: import('products/signals/frontend/inbox/inboxTaskKickoffLogic').ReportDiscussionIntent | undefined
pullRequestUrl: string | undefined
question: string
report: SignalReport
reportUrl: string
} // inboxTaskKickoffLogic
openReportDiscussion: (
report: SignalReport,
reportUrl: string
) => {
report: SignalReport
reportUrl: string
} // inboxTaskKickoffLogic
askAi: (
prompt: string,
source: TodayAskSource,
report?: SignalReport | undefined
) => {
prompt: string
report: SignalReport | undefined
source: TodayAskSource
} // todayLogic
setReportOpenContext: (context: TodayReportOpenContext | null) => {
context: TodayReportOpenContext | null
} // todayLogic
askAboutReport: (question: string) => {
question: string
}
codeQuoteCleared: (signalId: string) => {
signalId: string
}
codeQuotePicksCleared: () => {
value: true
}
codeQuoteRead: (
signalId: string,
quote: TodayCodeQuoteState
) => {
quote: TodayCodeQuoteState
signalId: string
}
collapseEvidence: (signalId: string) => {
signalId: string
}
evidenceOpened: (
signal: SignalViewApi,
destination: TodaySignalDestination['kind'] | 'code' | 'slack'
) => {
destination: 'code' | 'link' | 'read' | 'recording' | 'slack'
signal: SignalViewApi
}
expandEvidence: (signalId: string) => {
signalId: string
}
loadFigureMarks: () => any
loadFigureMarksFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFigureMarksSuccess: (
figureMarks: FigureMarkApi[] | null,
payload?: any
) => {
figureMarks: FigureMarkApi[] | null
payload?: any
}
loadFullReport: () => any
loadFullReportFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFullReportSuccess: (
fullReport: SignalReport,
payload?: any
) => {
fullReport: SignalReport
payload?: any
}
loadKeyClauses: () => any
loadKeyClausesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadKeyClausesSuccess: (
keyClauses: ReportKeyClausesApi | null,
payload?: any
) => {
keyClauses: ReportKeyClausesApi | null
payload?: any
}
loadPage: () => any
loadPageFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPageSuccess: (
page: ReportPageApi,
payload?: any
) => {
page: ReportPageApi
payload?: any
}
markOpened: (kind: TodayMarkKind) => {
kind: TodayMarkKind
}
openComposer: () => {
value: true
}
readCode: (
signal: SignalViewApi,
files: CodeFileApi[]
) => {
files: CodeFileApi[]
signal: SignalViewApi
}
reportVisited: () => {
value: true
}
setDraft: (draft: string) => {
draft: string
}
startWithPostHog: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayReportLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
currentReport: (
fullReport: SignalReport | null,
reports: SignalReport[],
reportFailed: boolean
) => SignalReport | null
lead: (page: ReportPageApi | null) => string
shownEvidence: (page: ReportPageApi | null) => SignalViewApi[]
evidenceCount: (page: ReportPageApi | null) => number
lastSeen: (page: ReportPageApi | null) => string | null
impactNumbers: (currentReport: SignalReport | null, page: ReportPageApi | null) => TodayImpactNumber[]
reportState: (
currentReport: SignalReport | null,
reportStateOverrides: Record<string, TodayReportState>
) => TodayReportState
isSample: (reportId: string) => boolean
asksJev: (featureFlags: FeatureFlagsSet, isSample: boolean) => boolean
proposal: (page: ReportPageApi | null) => string
impactText: (page: ReportPageApi | null, impactNumbers: TodayImpactNumber[]) => string
shownFigureMarks: (asksJev: boolean, figureMarks: FigureMarkApi[] | null) => FigureMarkApi[] | null
shownKeyClauses: (asksJev: boolean, keyClauses: ReportKeyClausesApi | null) => ReportKeyClausesApi | null
leadMarks: (lead: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]
impactMarks: (impactText: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]
staleFiguresDate: (leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]) => string | null
reportUrl: (currentTeamId: number | null) => string
}
}
export type todayReportLogicType = MakeLogicType<
todayReportLogicValues,
todayReportLogicActions,
TodayReportLogicProps,
todayReportLogicMeta
>
export const todayReportLogic = kea<todayReportLogicType>([
props({} as TodayReportLogicProps),
key((props) => props.reportId),
path((reportId) => ['scenes', 'project-homepage', 'today', 'todayReportLogic', reportId]),
connect(() => ({
values: [
teamLogic,
['currentTeamId', 'currentProjectId'],
todayLogic,
['reports', 'askingAi', 'reportOpenContext'],
todayVerdictLogic,
['reportStateOverrides'],
featureFlagLogic,
['featureFlags'],
],
actions: [
todayLogic,
['askAi', 'setReportOpenContext'],
inboxTaskKickoffLogic,
['createPrFromReport', 'discussReport', 'openReportDiscussion'],
],
})),
actions({
evidenceOpened: (signal: SignalViewApi, destination: TodaySignalDestination['kind'] | 'code' | 'slack') => ({
signal,
destination,
}),
readCode: (signal: SignalViewApi, files: CodeFileApi[]) => ({ signal, files }),
codeQuoteRead: (signalId: string, quote: TodayCodeQuoteState) => ({ signalId, quote }),
codeQuoteCleared: (signalId: string) => ({ signalId }),
codeQuotePicksCleared: true,
askAboutReport: (question: string) => ({ question }),
expandEvidence: (signalId: string) => ({ signalId }),
collapseEvidence: (signalId: string) => ({ signalId }),
openComposer: true,
setDraft: (draft: string) => ({ draft }),
startWithPostHog: true,
markOpened: (kind: TodayMarkKind) => ({ kind }),
reportVisited: true,
}),
loaders(({ props, values, cache }) => ({
fullReport: [
null as SignalReport | null,
{
loadFullReport: async () => {
if (values.isSample) {
const report = findSampleReport(props.reportId)
if (!report) {
throw new Error('Sample report not found')
}
return report
}
// nosemgrep: prefer-codegen-api-namespaced-signals -- Today passes reports to the Inbox's helpers, which take the handwritten SignalReport. The generated report type is wider (string status and priority, read-only arrays), so this call moves to generated types together with the Inbox.
return await api.signalReports.get(props.reportId)
},
},
],
page: [
null as ReportPageApi | null,
{
loadPage: async (): Promise<ReportPageApi> =>
await todayReportsPageRetrieve(String(values.currentProjectId), props.reportId),
},
],
figureMarks: [
null as FigureMarkApi[] | null,
{
loadFigureMarks: async (): Promise<FigureMarkApi[] | null> => {
if (!values.asksJev) {
return values.figureMarks
}
cache.figureMarks ??= todayReportsFigureMarksRetrieve(
String(values.currentProjectId),
props.reportId
).then(
({ marks }) => marks,
(): FigureMarkApi[] => {
cache.figureMarks = null
return []
}
)
return await cache.figureMarks
},
},
],
keyClauses: [
null as ReportKeyClausesApi | null,
{
loadKeyClauses: async (): Promise<ReportKeyClausesApi | null> => {
if (!values.asksJev || !values.fullReport || !values.page) {
return values.keyClauses
}
cache.keyClauses ??= todayReportsKeyClausesRetrieve(
String(values.currentProjectId),
props.reportId,
{ include_impact: !!values.impactText }
).catch((): null => {
cache.keyClauses = null
return null
})
return await cache.keyClauses
},
},
],
})),
reducers({
reportFailed: [
false,
{
loadFullReport: () => false,
loadFullReportFailure: () => true,
loadPage: () => false,
loadPageFailure: () => true,
},
],
codeQuotes: [
{} as Record<string, TodayCodeQuoteState>,
{
codeQuoteRead: (state, { signalId, quote }) => ({ ...state, [signalId]: quote }),
codeQuoteCleared: (state, { signalId }) => {
const { [signalId]: _, ...rest } = state
return rest
},
codeQuotePicksCleared: (state) =>
Object.fromEntries(
Object.entries(state).map(([signalId, quote]) => [
signalId,
quote && quote !== 'loading' ? { ...quote, ...quote.candidates[0] } : quote,
])
),
},
],
expandedEvidence: [
{} as Record<string, boolean>,
{
expandEvidence: (state, { signalId }) => ({ ...state, [signalId]: true }),
collapseEvidence: (state, { signalId }) => ({ ...state, [signalId]: false }),
},
],
composerOpen: [false, { openComposer: () => true }],
draft: [
'',
{
setDraft: (_, { draft }) => draft,
askAboutReport: () => '',
},
],
}),
selectors(({ props }) => ({
// The list row renders at once, and the full report replaces it when it arrives with its charts.
// A failed load shows its error instead, so the page never passes off the list row as the report.
currentReport: [
(s) => [s.fullReport, s.reports, s.reportFailed],
(fullReport: SignalReport | null, reports: SignalReport[], reportFailed: boolean): SignalReport | null =>
reportFailed ? null : (fullReport ?? reports.find((report) => report.id === props.reportId) ?? null),
],
lead: [(s) => [s.page], (page: ReportPageApi | null): string => page?.lead ?? ''],
shownEvidence: [(s) => [s.page], (page: ReportPageApi | null): SignalViewApi[] => page?.evidence ?? []],
evidenceCount: [(s) => [s.page], (page: ReportPageApi | null): number => page?.source_count ?? 0],
lastSeen: [(s) => [s.page], (page: ReportPageApi | null): string | null => page?.last_seen ?? null],
impactNumbers: [
(s) => [s.currentReport, s.page],
(currentReport: SignalReport | null, page: ReportPageApi | null): TodayImpactNumber[] =>
currentReport ? impactNumbers(currentReport, page) : [],
],
// A verdict given from Today shows before the report reloads.
reportState: [
(s) => [s.currentReport, s.reportStateOverrides],
(
currentReport: SignalReport | null,
reportStateOverrides: Record<string, TodayReportState>
): TodayReportState =>
reportStateOverrides[props.reportId] ?? (currentReport ? reportState(currentReport.status) : 'open'),
],
isSample: [(_, p) => [p.reportId], (reportId: string): boolean => isSampleReportId(reportId)],
asksJev: [
(s) => [s.featureFlags, s.isSample],
(featureFlags: FeatureFlagsSet, isSample: boolean): boolean =>
!!featureFlags[FEATURE_FLAGS.TODAY_REPORT_JEV] && !isSample,
],
proposal: [(s) => [s.page], (page: ReportPageApi | null): string => page?.proposal ?? ''],
impactText: [
(s) => [s.page, s.impactNumbers],
(page: ReportPageApi | null, impactNumbers: TodayImpactNumber[]): string =>
impactNumbers.length ? '' : (page?.impact_sentence ?? ''),
],
shownFigureMarks: [
(s) => [s.asksJev, s.figureMarks],
(asksJev: boolean, figureMarks: FigureMarkApi[] | null): FigureMarkApi[] | null =>
asksJev ? figureMarks : null,
],
shownKeyClauses: [
(s) => [s.asksJev, s.keyClauses],
(asksJev: boolean, keyClauses: ReportKeyClausesApi | null): ReportKeyClausesApi | null =>
asksJev ? keyClauses : null,
],
leadMarks: [
(s) => [s.lead, s.shownFigureMarks],
(lead: string, figureMarks: FigureMarkApi[] | null): TodayMarkedFigure[] =>
markedFigures(lead, marksIn(figureMarks, 'lead')),
],
impactMarks: [
(s) => [s.impactText, s.shownFigureMarks],
(impactText: string, figureMarks: FigureMarkApi[] | null): TodayMarkedFigure[] =>
markedFigures(impactText, marksIn(figureMarks, 'impact')),
],
staleFiguresDate: [
(s) => [s.leadMarks, s.impactMarks],
(leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]): string | null =>
staleEvidenceDate([...leadMarks, ...impactMarks]),
],
reportUrl: [
(s) => [s.currentTeamId],
(currentTeamId: number | null): string =>
`${window.location.origin}${addProjectIdIfMissing(
urls.inboxReport('reports', props.reportId),
currentTeamId ?? undefined
)}`,
],
})),
listeners(({ props, values, actions, cache }) => {
const readFile = (file: CodeFileApi): Promise<RepositoryFileApi | null> => {
if (values.isSample) {
return Promise.resolve(null)
}
const key = `${file.repo}:${file.path}`
cache.fileReads ??= new Map<string, Promise<RepositoryFileApi | null>>()
if (!cache.fileReads.has(key)) {
cache.fileReads.set(
key,
businessKnowledgeRepositoriesFileRetrieve(String(values.currentProjectId), file).catch(() => {
cache.fileReads.delete(key)
return null
})
)
}
return cache.fileReads.get(key)
}
const captureOpen = ({ context, linkSource }: TodayPendingOpen, report: SignalReport): void => {
if (values.isSample) {
return
}
captureTodayReportOpened({
report: signalReportSnapshot(report),
openMethod: context ? 'click' : 'deeplink',
linkSource,
list: context?.list ?? null,
rank: context?.rank ?? null,
listSize: context?.listSize ?? null,
source: context?.source ?? null,
})
}
return {
// A verdict that failed without an answer can still have saved, so the page reloads the report.
[todayVerdictLogic.actionTypes.setReportVerdictFailure]: ({ reportId }: { reportId: string }) => {
if (reportId === props.reportId) {
actions.loadFullReport()
}
},
reportVisited: () => {
// A visit with no click on Today is a deep-link: a shared URL, a PostHog AI link, a refresh,
// or back / forward.
const context = values.reportOpenContext
const { pathname } = router.values.location
const { link_source: linkSource, ...searchParams } = router.values.searchParams
const onReportPage = reportIdFromPath(pathname) === props.reportId
const open: TodayPendingOpen = {
context: context?.reportId === props.reportId ? context : null,
linkSource: onReportPage ? parseInboxReportLinkSource(linkSource) : null,
}
if (context) {
actions.setReportOpenContext(null)
}
if (onReportPage && linkSource !== undefined) {
// A copied address bar must not pass the original `link_source` on to the next reader.
router.actions.replace(pathname, searchParams, router.values.hashParams)
}
// A prefetched neighbor already has its report, so its open goes out now.
if (values.fullReport && !values.fullReportLoading) {
captureOpen(open, values.fullReport)
} else {
// A step away and back before the fetch ends is two visits, so each one keeps its own open.
cache.pendingOpens = [...(cache.pendingOpens ?? []), open]
}
},
loadFullReportSuccess: ({ fullReport }) => {
actions.loadKeyClauses()
const opens: TodayPendingOpen[] = cache.pendingOpens ?? []
cache.pendingOpens = []
opens.forEach((open) => captureOpen(open, fullReport))
},
loadPageSuccess: () => {
actions.loadKeyClauses()
actions.loadFigureMarks()
},
[featureFlagLogic.actionTypes.setFeatureFlags]: () => {
actions.loadKeyClauses()
actions.loadFigureMarks()
if (!values.asksJev) {
actions.codeQuotePicksCleared()
}
},
readCode: async ({ signal, files }) => {
if (signal.signal_id in values.codeQuotes) {
return
}
actions.codeQuoteRead(signal.signal_id, 'loading')
const reads = await Promise.all(files.map(readFile))
const quote = findCodeQuote(files, reads, codeIdentifiers(signal.content))
if (!quote && reads.includes(null)) {
actions.codeQuoteCleared(signal.signal_id)
return
}
if (!quote || quote.candidates.length < 2 || !values.asksJev) {
actions.codeQuoteRead(signal.signal_id, quote)
return
}
const choices = quote.candidates.slice(0, todayExcerptChoiceCreateBodyExcerptsMax)
const excerpts = choices.map((candidate) =>
candidate.excerpt.lines.join('\n').slice(0, todayExcerptChoiceCreateBodyExcerptsItemMax)
)
const { index: pick } = await todayExcerptChoiceCreate(String(values.currentProjectId), {
finding: signal.content.slice(0, todayExcerptChoiceCreateBodyFindingMax),
excerpts,
}).catch(() => ({ index: null }))
const chosen = pick === null || !values.asksJev ? null : choices[pick]
actions.codeQuoteRead(signal.signal_id, chosen ? { ...quote, ...chosen } : quote)
},
askAboutReport: ({ question }) => {
const report = values.currentReport
if (!report || !question || values.askingAi) {
return
}
captureInboxReportAction({
report,
actionType: 'discuss',
surface: 'today',
extra: discussQuestionProperties({ source: 'typed', suggestionCount: 0 }),
})
actions.askAi(question, 'report_page', report)
},
startWithPostHog: () => {
const report = values.currentReport
if (!report) {
return
}
if (reportWorkKind(report) === 'implement') {
captureInboxReportAction({
report,
actionType: 'create_pr',
surface: 'today',
extra: { has_feedback: false },
})
actions.createPrFromReport(report)
return
}
captureInboxReportAction({
report,
actionType: 'discuss',
surface: 'today',
extra: discussQuestionProperties({ source: 'preset', suggestionCount: 0 }),
})
actions.openReportDiscussion(report, values.reportUrl)
actions.discussReport(
report,
values.reportUrl,
INVESTIGATE_QUESTION,
reportWorkPrompt(report, values.reportUrl)
)
},
markOpened: ({ kind }) => {
posthog.capture('today report mark opened', { report_id: props.reportId, kind })
},
evidenceOpened: ({ signal, destination }) => {
posthog.capture('today report evidence opened', {
report_id: props.reportId,
source_product: signal.source_product,
source_type: signal.source_type,
destination,
})
},
}
}),
afterMount(({ actions }) => {
actions.loadFullReport()
actions.loadPage()
}),
])