: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): redesign the report page around impact, proposal and evidence (#111472)
Shy Alter2009294d133a
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scssindex ddab9d0c68e3..ef831448e3a1 100644--- a/frontend/src/scenes/project-homepage/today/Today.scss+++ b/frontend/src/scenes/project-homepage/today/Today.scss@@ -1,7 +1,9 @@// The Today layout keeps its own "paper" palette. Colours that also appear on tinted surfaces stay literal,// the rest switch with the app theme. The app layout shares it so the page behind the rail matches..Today,-.TodayAppLayout {+.TodayAppLayout,+.TodayHoverMark__popup,+.TodayImplementMenu {--today-ink: #151515;--today-muted: #8d8d88;--today-faint: #a3a39e;@@ -9,24 +11,16 @@--today-line: #e5e5e0;--today-card: #fff;--today-soft: #efefeb;- --today-soft-2: #f2f2ee;- --today-drawer: #fbfbf9;- --today-secondary-text: #5f5f5a;--today-body-text: #454541;--today-input-border: #deded8;--today-focus-border: #a7a7a0;- --today-success-text: #24733a;- --today-success-fill: #e8f6eb;--today-button: #151515;- --today-button-hover: #33332f;--today-button-text: #fff;- --today-pill: #eeeeea;- --today-pill-border: #e2e2dc;--today-ease: cubic-bezier(0.23, 1, 0.32, 1);--today-ease-in-out: cubic-bezier(0.645, 0.045, 0.355, 1);- --today-ease-rise: cubic-bezier(0.22, 1, 0.36, 1);--today-ease-nudge: cubic-bezier(0.2, 0.8, 0.2, 1);--today-card-shadow: 0 1px 2px #00000008, 0 12px 32px -24px #00000059;+ --today-marker: #f54e00;[theme='dark'] & {--today-ink: #f1f1ee;@@ -36,19 +30,12 @@--today-line: #2c2c2a;--today-card: #1f1f1d;--today-soft: #262624;- --today-soft-2: #232321;- --today-drawer: #1b1b1a;- --today-secondary-text: #b5b5ae;--today-body-text: #d4d4ce;--today-input-border: #353532;--today-focus-border: #5c5c57;- --today-success-text: #7fd694;- --today-success-fill: #1d3323;--today-button: #f1f1ee;- --today-button-hover: #d9d9d4;--today-button-text: #151515;- --today-pill: #262624;- --today-pill-border: #333331;+ --today-marker: #ff8a4c;}}@@ -59,14 +46,6 @@-webkit-font-smoothing: antialiased;}-.Today__label {- font-family: var(--font-mono);- font-size: 10px;- color: var(--today-faint);- text-transform: uppercase;- letter-spacing: 0.07em;-}-.Today__page {animation: Today__page-in 0.18s ease-out both;}@@ -173,6 +152,7 @@.TodayHome,.TodayReport {width: min(840px, 100% - 144px);+ padding: 94px 0 140px;margin: 0 auto;@container main-content (max-width: 900px) {@@ -181,25 +161,10 @@@container main-content (max-width: 600px) {width: calc(100% - 40px);- }-}--.TodayHome {- padding: 94px 0 140px;-- @container main-content (max-width: 600px) {padding: 20px 0 64px;}}-.TodayReport {- padding: 56px 0 140px;-- @container main-content (max-width: 600px) {- padding: 12px 0 64px;- }-}-.TodayHome__meta {font-family: var(--font-mono);font-size: 11px;@@ -383,74 +348,212 @@margin-top: 76px;}-// Report page+.TodayHoverMark {+ cursor: default;+ outline: none;+}-.TodayReport__kicker {- display: flex;- gap: 10px;- align-items: center;- font-family: var(--font-mono);- font-size: 10.5px;- color: var(--report-color);- text-transform: uppercase;- letter-spacing: 0.04em;+.TodayHoverMark__popup {+ position: relative;++ &::after {+ position: absolute;+ top: calc(100% + 1px);+ right: -8px;+ left: -8px;+ height: 32px;+ pointer-events: none;+ content: '';+ background: linear-gradient(var(--today-paper), transparent);+ }}-.TodayTile {- display: flex;- flex: 0 0 auto;- align-items: center;- justify-content: center;- width: 28px;- height: 28px;- color: #fff;- background: var(--tile-color, var(--report-color));- border-radius: 8px;+.TodayHoverMark__card {+ background: var(--today-card);+ border-color: var(--today-line);+ box-shadow:+ 0 0 0 8px var(--today-paper),+ 0 1px 2px #00000008,+ 0 6px 16px -8px #00000024;- svg {- width: 15px;- height: 15px;+ [theme='dark'] & {+ background: #242422;+ border-color: #5c5c55;+ box-shadow:+ 0 0 0 8px var(--today-paper),+ 0 10px 28px -10px #000000b3;+ }++ blockquote {+ border-inline-start-color: color-mix(in sRGB, currentColor 22%, transparent);}}-.TodayReport__heading {- max-width: 560px;- margin: 14px 0 12px;- font-size: 18px;- font-weight: 560;- line-height: 1.3;- text-wrap: balance;- letter-spacing: -0.015em;+.TodayReportArticle {+ > *,+ [data-attr='today-report-abstract'] {+ transition: opacity 0.15s;+ }++ &:has(.TodayHoverMark[data-popup-open]) {+ > :not(:has(.TodayHoverMark[data-popup-open])),+ [data-attr='today-report-abstract']:not(:has(.TodayHoverMark[data-popup-open])) {+ filter: grayscale(1);+ opacity: 0.06;+ }+ }}-.TodayReport__body {- max-width: 600px;- margin-top: 24px;- font-size: 14px;- line-height: 1.65;- color: var(--today-muted);+.TodayFigureMark {+ position: relative;+ display: inline-block;+ margin-inline: 0.04em;+ white-space: nowrap;++ &:first-child {+ margin-inline-start: 0;+ }+}- > * + * {- margin-top: 20px;+.TodayFigureMark__circle {+ position: absolute;+ top: -0.12em;+ left: -0.26em;+ z-index: -1;+ width: calc(100% + 0.52em);+ height: calc(100% + 0.24em);+ overflow: visible;+ pointer-events: none;++ path {+ fill: none;+ stroke: var(--today-marker);+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ stroke-linecap: round;+ stroke-linejoin: round;+ stroke-width: 1.8px;+ transition: stroke-dashoffset 0.18s ease-in;+ vector-effect: non-scaling-stroke;}}-// Evidence and prompts+.TodayFigureMark:hover,+.TodayFigureMark:focus-visible,+.TodayFigureMark[data-popup-open] {+ .TodayPenMark__stroke {+ opacity: 0;+ }-.TodayEvidence,-.TodayPrompts {- display: flex;- flex-direction: column;- gap: 12px;- max-width: 600px;- margin-top: 48px;+ .TodayFigureMark__circle path {+ stroke-dashoffset: 0;+ transition: stroke-dashoffset 0.5s var(--today-ease);+ }}-.TodayEvidence__note,-.TodayPrompts__hint {- margin: 0;- font-size: 12px;- color: var(--today-muted);+.TodayPenMark__stroke {+ position: absolute;+ bottom: -0.18em;+ left: -0.04em;+ width: calc(100% + 0.16em);+ height: 0.38em;+ overflow: visible;+ pointer-events: none;+ transition: opacity 0.15s;++ path {+ fill: none;+ stroke: var(--today-marker);+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ stroke-linecap: round;+ stroke-width: 3.8;+ animation: TodayPenMark__draw 0.42s cubic-bezier(0.55, 0.1, 0.35, 1) var(--today-mark-delay, 0ms) forwards;+ }++ path + path {+ opacity: 0.5;+ stroke-width: 2.6;+ animation-duration: 0.3s;+ animation-delay: calc(var(--today-mark-delay, 0ms) + 0.36s);+ }+}++@keyframes TodayPenMark__draw {+ to {+ stroke-dashoffset: 0;+ }+}++.TodayImplementMenu.TodayImplementMenu {+ background: var(--today-card);+ border: 1px solid var(--today-line);+ box-shadow:+ 0 1px 2px #0000000f,+ 0 12px 32px -8px #00000038;++ [role='separator'] {+ background-color: var(--today-line);+ }++ [theme='dark'] & {+ background: #242422;+ border-color: #5c5c55;+ box-shadow: 0 12px 32px -8px #000000c0;++ [role='separator'] {+ background-color: #3c3c38;+ }+ }+}++.TodayEvidenceDetail {+ display: grid;+ grid-template-rows: 1fr;+ animation: TodayEvidenceDetail__open 0.22s var(--today-ease);+}++@keyframes TodayEvidenceDetail__open {+ from {+ grid-template-rows: 0fr;+ opacity: 0;+ }+}++.TodayEvidenceDetail__text {+ color: color-mix(in sRGB, var(--foreground) 72%, transparent);+}++.TodayCodeExcerpt {+ background: var(--today-card);+ border-color: var(--today-line);++ &__header {+ border-bottom: 1px solid var(--today-line);+ }++ &__body {+ color: color-mix(in sRGB, currentColor 78%, transparent);+ }++ &__line {+ padding-inline-start: 2ch;+ text-indent: -2ch;+ }+}++@media (prefers-reduced-motion: reduce) {+ .TodayPenMark__stroke path {+ stroke-dashoffset: 0;+ animation: none;+ }++ .TodayFigureMark .TodayFigureMark__circle path,+ .TodayFigureMark:hover .TodayFigureMark__circle path,+ .TodayFigureMark:focus-visible .TodayFigureMark__circle path,+ .TodayFigureMark[data-popup-open] .TodayFigureMark__circle path {+ transition: none;+ }}// Keyframesdiff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsxindex 21c0ad971ccf..7a42324d8430 100644--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx@@ -29,6 +29,7 @@ import {} from 'products/signals/frontend/inbox/__mocks__/reportMetricMocks'import { SignalReportStatus } from 'products/signals/frontend/inbox/types'import { ChannelDTOApi, TaskListItemApi } from 'products/tasks/frontend/generated/api.schemas'+import type { ReportPageApi } from 'products/today/frontend/generated/api.schemas'import type { BriefingApi, BriefingItemApi } from 'products/today/frontend/generated/api.schemas'const ADA = {@@ -537,6 +538,60 @@ function clearTodayStorage(return <Story />}+function mockReportPage(reportId: string): ReportPageApi {+ const report = REPORTS.find((candidate) => candidate.id === reportId) ?? REPORTS[0]+ const signals = mockSignals(reportId, 6).map((signal) => {+ const firstLine = signal.content.split('\n')[0]+ return {+ signal_id: signal.signal_id,+ content: signal.content,+ source_product: signal.source_product,+ source_type: signal.source_type,+ source_id: signal.source_id,+ timestamp: signal.timestamp,+ extra: { ...signal.extra },+ headline: firstLine,+ lead: firstLine,+ meta: '',+ cited: signal.source_product === 'signals_scout' ? ('code' as const) : null,+ recording: null,+ link: null,+ preview: {+ hint: 'Show the description',+ code: [],+ block: [],+ text: signal.content,+ facts: [],+ link: null,+ link_label: null,+ },+ }+ })+ return {+ lead: report.summary_lead ?? '',+ proposal: report.suggested_prompts?.[0] ?? '',+ impact_sentence: '',+ named_pull_request: null,+ solution_names_pull_request: false,+ evidence: signals.slice(0, 3),+ source_count: signals.length,+ impact_numbers:+ report.id === 'report-1'+ ? [+ {+ key: 'tickets',+ value: '4',+ sentence: 'support tickets over 3 days.',+ signal: signals[0],+ values: [],+ working: null,+ },+ ]+ : [],+ last_seen: null,+ }+}+const meta: Meta = {component: App,title: 'Scenes-App/Project Homepage/Today',@@ -553,15 +608,11 @@ const meta: Meta = {REPORTS.find((report) => report.id === req.params.id) ?? REPORTS[0],],'/api/environments/:team_id/query/:kind/': reportMetricQueryHandler,- '/api/projects/:team_id/signals/reports/:id/signals/': (req) => [- 200,- // Error tracking signals fetch their issue, which these stories do not mock.- {- signals: mockSignals(String(req.params.id), 6).filter(- (signal) => signal.source_product !== 'error_tracking'- ),- },- ],+ '/api/projects/:team_id/today/reports/:id/page/': (req) => [200, mockReportPage(String(req.params.id))],+ '/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [], count: 0, next: null },+ '/api/projects/:team_id/signals/reports/:id/checks/': { results: [], count: 0, next: null },+ '/api/users/@me/integrations/': { results: [] },+ '/api/users/@me/integrations/slack/linkable_workspaces/': { results: [] },'/api/projects/:team_id/today/briefing/': () => [404, { detail: 'Not found.' }],'/api/projects/:team_id/task_channels/': SPACES,'/api/projects/:team_id/task_channels/:id/': (req) => [@@ -745,15 +796,27 @@ export const ReportWithPullRequest: Story = {parameters: { pageUrl: urls.todayReport('report-1') },}-export const ReportWithSuggestedPrompts: Story = {+export const ReportProposingItsFirstPrompt: Story = {parameters: { pageUrl: urls.todayReport('report-2') },}-// One chart placed in the summary, one trailing it. Charts resolve without the Inbox detail logic.-export const ReportWithCharts: Story = {+export const ReportWithAnImpactMetric: Story = {parameters: { pageUrl: urls.todayReport('report-4') },}+export const ReportWithTicketsAndEvidenceDetail: Story = {+ parameters: { pageUrl: urls.todayReport('report-1') },+}++export const ReportThatFailsToLoad: Story = {+ parameters: { pageUrl: urls.todayReport('report-1') },+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/today/reports/:id/page/': () => [500, {}] } })],+}++export const ReportInANarrowWindow: Story = {+ parameters: { pageUrl: urls.todayReport('report-1'), testOptions: { viewport: { width: 800, height: 900 } } },+}+export const SpacesPane: Story = {play: async ({ canvasElement }) => {await userEvent.click(await within(canvasElement).findByLabelText('Spaces'))diff --git a/frontend/src/scenes/project-homepage/today/TodayActionButton.tsx b/frontend/src/scenes/project-homepage/today/TodayActionButton.tsxnew file mode 100644index 000000000000..18038a2507c0--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayActionButton.tsx@@ -0,0 +1,27 @@+import type { ComponentProps } from 'react'++import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++type TodayActionButtonProps = ComponentProps<typeof Button> & {+ disabledReason?: string | null+ tooltip?: string+}++export function TodayActionButton({+ disabledReason,+ tooltip,+ disabled,+ ...props+}: TodayActionButtonProps): JSX.Element {+ const label = disabledReason || tooltip+ const button = <Button {...props} disabled={disabled || !!disabledReason} />+ if (!label) {+ return button+ }+ return (+ <Tooltip>+ <TooltipTrigger render={button} delay={props.size?.startsWith('icon') ? 0 : undefined} />+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayCodeExcerpt.tsx b/frontend/src/scenes/project-homepage/today/TodayCodeExcerpt.tsxnew file mode 100644index 000000000000..28df9678e4cf--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayCodeExcerpt.tsx@@ -0,0 +1,129 @@+import { IconExternal } from '@posthog/icons'+import { Button, Skeleton, Text } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'++import type { CodeFileApi } from 'products/today/frontend/generated/api.schemas'++import { TodayPenMark } from './TodayPenMark'+import type { TodayCodeQuote, TodayCodeWindow } from './todayQuotedCode'++const PEN_DELAY_MS = 120+const PEN_STAGGER_MS = 120++function CodeLine({+ line,+ marks,+ order,+}: {+ line: string+ marks: TodayCodeWindow['marks']+ order: number+}): JSX.Element {+ const indent = line.length - line.trimStart().length+ const parts: JSX.Element[] = []+ let last = indent+ marks.forEach((mark, index) => {+ if (mark.start < last) {+ return+ }+ parts.push(<span key={`t${index}`}>{line.slice(last, mark.start)}</span>)+ parts.push(+ <TodayPenMark+ key={`m${index}`}+ seed={`${line}${mark.start}`}+ delayMs={PEN_DELAY_MS + (order + index) * PEN_STAGGER_MS}+ >+ {line.slice(mark.start, mark.end)}+ </TodayPenMark>+ )+ last = mark.end+ })+ parts.push(<span key="rest">{line.slice(last)}</span>)+ return (+ <code className="flex min-w-0 pe-3">+ <span className="shrink-0 whitespace-pre">{line.slice(0, indent)}</span>+ <span className="TodayCodeExcerpt__line min-w-0 break-words whitespace-pre-wrap">{parts}</span>+ </code>+ )+}++export function TodayCodeExcerpt({+ file,+ quote,+}: {+ file: CodeFileApi+ quote: TodayCodeQuote | 'loading'+}): JSX.Element {+ const loaded = quote === 'loading' ? null : quote+ const shown = loaded?.file ?? file+ const folderEnd = shown.path.lastIndexOf('/') + 1+ const directory = shown.path.slice(0, folderEnd)+ const name = shown.path.slice(folderEnd)+ const excerpt = loaded?.excerpt ?? null+ const lastLine = excerpt ? excerpt.startLine + excerpt.lines.length - 1 : null+ const githubUrl = loaded ? `${loaded.read.url}#L${loaded.excerpt.startLine}-L${lastLine}` : null++ return (+ <figure+ className="TodayCodeExcerpt m-0 overflow-hidden rounded-md border"+ data-attr="today-report-code-excerpt"+ >+ <figcaption className="TodayCodeExcerpt__header flex items-center justify-between gap-3 px-3 py-1.5">+ <Text+ size="xs"+ variant="muted"+ render={<span />}+ className="flex min-w-0 items-baseline font-mono"+ title={shown.path}+ >+ <span className="min-w-0 truncate">{directory}</span>+ <span className="shrink-0 text-foreground">{name}</span>+ {excerpt && (+ <span translate="no" className="shrink-0 ps-2 tabular-nums">+ {`L${excerpt.startLine}–${lastLine}`}+ </span>+ )}+ </Text>+ {githubUrl && (+ <Button+ variant="link-muted"+ size="sm"+ className="-me-2 shrink-0 px-2"+ nativeButton={false}+ render={<LinkPrimitive to={githubUrl} target="_blank" />}+ data-attr="today-report-code-github"+ >+ Open on GitHub+ <IconExternal />+ </Button>+ )}+ </figcaption>+ {excerpt ? (+ <pre className="TodayCodeExcerpt__body m-0 py-2 font-mono text-xs leading-relaxed">+ {excerpt.lines.map((line, index) => (+ <div key={index} className="flex">+ <span+ aria-hidden+ className="w-12 shrink-0 select-none pe-3 text-right text-muted-foreground tabular-nums"+ >+ {excerpt.startLine + index}+ </span>+ <CodeLine+ line={line}+ marks={excerpt.marks.filter((mark) => mark.line === index)}+ order={index}+ />+ </div>+ ))}+ </pre>+ ) : (+ <div className="flex flex-col gap-2 px-3 py-3">+ <Skeleton className="h-3 w-3/4" />+ <Skeleton className="h-3 w-1/2" />+ <Skeleton className="h-3 w-2/3" />+ </div>+ )}+ </figure>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayEvidenceDetail.tsx b/frontend/src/scenes/project-homepage/today/TodayEvidenceDetail.tsxnew file mode 100644index 000000000000..36ce4f4e916b--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayEvidenceDetail.tsx@@ -0,0 +1,123 @@+import { useValues } from 'kea'++import { IconArrowRight, IconExternal } from '@posthog/icons'+import { Button, Text, cn } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import type { SignalPreviewApi, SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { TodayCodeExcerpt } from './TodayCodeExcerpt'+import { TodayPreviewLink } from './todayEvidence'+import { TodayCodeQuoteState, todayReportLogic } from './todayReportLogic'+import { isSampleReportId } from './todaySampleReports'+import { signalSourceLabel } from './todaySignalText'++function quoteState(stored: TodayCodeQuoteState | undefined): TodayCodeQuoteState {+ return stored === undefined ? 'loading' : stored+}++function detailOpen(+ preview: SignalPreviewApi,+ open: TodayPreviewLink | null,+ quote: TodayCodeQuoteState | null+): TodayPreviewLink | null {+ return preview.code.length > 0 && quote !== null ? null : open+}++function detailLinkAttr(signal: SignalViewApi, open: TodayPreviewLink | null): string {+ if (!open) {+ return 'today-report-signal-full-report'+ }+ return signal.cited === 'slack' ? 'today-report-signal-slack' : 'today-report-signal-open'+}++function DetailLink({+ reportId,+ signal,+ open,+ showsCode,+}: {+ reportId: string+ signal: SignalViewApi+ open: TodayPreviewLink | null+ showsCode: boolean+}): JSX.Element | null {+ const fullReport = isSampleReportId(reportId)+ ? null+ : { to: urls.inboxReport('reports', reportId), external: false, label: 'Open in the full report' }+ const link = open ?? (showsCode ? null : fullReport)+ if (!link) {+ return null+ }+ return (+ <Button+ variant="link-muted"+ size="sm"+ className="-me-2 px-2"+ nativeButton={false}+ render={<LinkPrimitive to={link.to} target={link.external ? '_blank' : undefined} />}+ data-attr={detailLinkAttr(signal, open)}+ >+ {link.label}+ {link.external ? <IconExternal /> : <IconArrowRight />}+ </Button>+ )+}++export function TodayEvidenceDetail({+ id,+ reportId,+ signal,+ preview,+ open: previewLinkOpen,+}: {+ id: string+ reportId: string+ signal: SignalViewApi+ preview: SignalPreviewApi+ open: TodayPreviewLink | null+}): JSX.Element {+ const { codeQuotes } = useValues(todayReportLogic({ reportId }))+ const quote = preview.code.length ? quoteState(codeQuotes[signal.signal_id]) : null+ const open = detailOpen(preview, previewLinkOpen, quote)+ const facts = [signalSourceLabel(signal), ...preview.facts]+ const time = dayjs(signal.timestamp)++ return (+ <div id={id} className="TodayEvidenceDetail">+ <div className="flex min-h-0 flex-col gap-2 overflow-hidden px-2 pb-3">+ {quote && <TodayCodeExcerpt file={preview.code[0]} quote={quote} />}+ {preview.block.length > 0 && (+ <pre+ className="TodayCodeExcerpt TodayCodeExcerpt__body m-0 rounded-md border px-3 py-2 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap"+ data-attr="today-report-signal-block"+ >+ {preview.block.map((line, index) => (+ <div key={index} className={cn(line.quiet && 'text-muted-foreground')}>+ {line.text}+ </div>+ ))}+ </pre>+ )}+ {preview.text && (+ <Text size="sm" render={<p />} className="TodayEvidenceDetail__text leading-relaxed text-pretty">+ {preview.text}+ </Text>+ )}+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">+ <Text size="xs" variant="muted" render={<p />} className="min-w-0">+ {facts.join(' · ')}+ {' · '}+ <time dateTime={signal.timestamp}>+ {time.format(time.isSame(dayjs(), 'year') ? 'D MMM, HH:mm' : 'D MMM YYYY, HH:mm')}+ </time>+ </Text>+ <DetailLink reportId={reportId} signal={signal} open={open} showsCode={preview.code.length > 0} />+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsx b/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsxnew file mode 100644index 000000000000..321220adefdb--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsx@@ -0,0 +1,255 @@+import { useActions } from 'kea'+import type { ReactNode } from 'react'++import { IconArrowRight, IconExternal, IconPlay, IconTrends } from '@posthog/icons'+import { Button, Text } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'+import { urls } from 'scenes/urls'++import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { signalDestination } from './todayEvidence'+import { TodayQuoteSegment, quoteSegments } from './todayFigures'+import { TodayFigureCardContent, anchorToday } from './todayFigureSources'+import { TodayIcon } from './TodayIcon'+import { TodayInlineTrend } from './TodayInlineTrend'+import { TodayPenMark } from './TodayPenMark'+import { shortDate } from './todayProse'+import { isSampleReportId } from './todaySampleReports'+import { TodayReportIcon, sourceStyle } from './todaySignalReports'+import { signalSourceLabel } from './todaySignalText'++const PEN_DELAY_MS = 180+const PEN_STAGGER_MS = 140++type QuotedContent = Extract<TodayFigureCardContent, { kind: 'signal' }>+type MetricContent = Extract<TodayFigureCardContent, { kind: 'metric' }>++interface QuoteSource {+ icon: TodayReportIcon+ label: string+ date: string+ signal: SignalViewApi+}++function quoteSource(content: QuotedContent): QuoteSource {+ return {+ icon: sourceStyle(content.signal.source_product).icon,+ label: signalSourceLabel(content.signal),+ date: content.signal.timestamp,+ signal: content.signal,+ }+}++function CardHeader({ icon, children }: { icon: ReactNode; children: ReactNode }): JSX.Element {+ return (+ <Text size="xs" variant="muted" render={<div />} className="flex items-center gap-1.5">+ {icon && (+ <span aria-hidden className="flex [&_svg]:size-3.5">+ {icon}+ </span>+ )}+ {children}+ </Text>+ )+}++function CardDate({ date }: { date: string }): JSX.Element {+ const day = dayjs(date)+ return (+ <>+ <span aria-hidden>·</span>+ <time dateTime={date} title={day.format('LLL')}>+ {shortDate(day)}+ </time>+ </>+ )+}++function CardLink({+ to,+ external,+ dataAttr,+ children,+}: {+ to: string+ external: boolean+ dataAttr: string+ children: ReactNode+}): JSX.Element {+ return (+ <Button+ variant="link"+ size="sm"+ className="self-start px-0"+ nativeButton={false}+ render={<LinkPrimitive to={to} target={external ? '_blank' : undefined} />}+ data-attr={dataAttr}+ >+ {children}+ {external ? <IconExternal /> : <IconArrowRight />}+ </Button>+ )+}++function FullReportLink({ reportId, children }: { reportId: string; children: string }): JSX.Element | null {+ if (isSampleReportId(reportId)) {+ return null+ }+ return (+ <CardLink+ to={urls.inboxReport('reports', reportId)}+ external={false}+ dataAttr="today-report-figure-full-report"+ >+ {children}+ </CardLink>+ )+}++function SignalAction({ signal, reportId }: { signal: SignalViewApi; reportId: string }): JSX.Element | null {+ const { openSessionPlayer } = useActions(sessionPlayerModalLogic)+ const destination = signalDestination(signal)+ if (destination.kind === 'recording') {+ return (+ <Button+ variant="link"+ size="sm"+ className="self-start px-0"+ onClick={() => openSessionPlayer({ id: destination.sessionId }, destination.startAt)}+ data-attr="today-report-figure-play"+ >+ <IconPlay />+ {destination.offset ? `Play at ${destination.offset}` : 'Play recording'}+ </Button>+ )+ }+ if (destination.kind === 'link') {+ return (+ <CardLink to={destination.to} external={destination.external} dataAttr="today-report-figure-open">+ {destination.label}+ </CardLink>+ )+ }+ return <FullReportLink reportId={reportId}>Open the full report</FullReportLink>+}++function Quote({ segments }: { segments: TodayQuoteSegment[] }): JSX.Element {+ let order = 0+ return (+ <Text+ size="sm"+ render={<blockquote />}+ className="m-0 border-l-2 border-solid ps-3 text-pretty text-foreground"+ >+ {segments.map((segment, index) =>+ segment.marked ? (+ <TodayPenMark key={index} seed={segment.text} delayMs={PEN_DELAY_MS + order++ * PEN_STAGGER_MS}>+ {segment.text}+ </TodayPenMark>+ ) : (+ <span key={index}>{segment.text}</span>+ )+ )}+ </Text>+ )+}++function QuoteCard({+ content,+ figure,+ reportId,+}: {+ content: QuotedContent+ figure: string+ reportId: string+}): JSX.Element {+ const source = quoteSource(content)+ const { working } = content+ const segments = quoteSegments(content, figure).map((segment) =>+ source.date && !segment.marked ? { ...segment, text: anchorToday(segment.text, source.date) } : segment+ )+ return (+ <div className="flex flex-col gap-2 p-3">+ <CardHeader icon={<TodayIcon icon={source.icon} />}>+ <span>{source.label}</span>+ <CardDate date={source.date} />+ </CardHeader>+ <Quote segments={segments} />+ {working && (+ <Text size="xs" variant="muted" render={<p />} className="tabular-nums">+ {`${working.expression} = `}+ <span className="font-semibold text-foreground">{working.result}</span>+ </Text>+ )}+ <SignalAction signal={source.signal} reportId={reportId} />+ </div>+ )+}++function MetricCard({ content }: { content: MetricContent }): JSX.Element {+ return (+ <div className="flex flex-col gap-2 p-3">+ <CardHeader icon={<IconTrends />}>+ <span>Measured by an insight</span>+ {content.at && <CardDate date={content.at} />}+ </CardHeader>+ {content.caption && (+ <Text size="xs" variant="muted" render={<p />} className="text-pretty">+ {content.caption}+ </Text>+ )}+ {content.trend && content.trend.length > 1 && (+ <div className="flex items-center gap-2 pt-4 pb-1 [&>span]:h-8 [&>span]:w-full [&>svg]:h-8 [&>svg]:w-full">+ <TodayInlineTrend+ values={content.trend}+ type={content.chartType}+ detailed+ partialLast={!!content.range}+ />+ </div>+ )}+ {content.range && (+ <Text size="xxs" variant="muted" render={<div />} className="-mt-1 flex justify-between">+ <span>{content.range.from}</span>+ <span>{content.range.to}</span>+ </Text>+ )}+ <Text size="xs" variant="muted" render={<p />} className="tabular-nums">+ <span className="font-semibold text-foreground">{content.total}</span>+ {content.window ? ` ${content.window}` : ''}+ </Text>+ {content.link && (+ <CardLink to={content.link.url} external dataAttr="today-report-figure-insight">+ {content.link.label}+ </CardLink>+ )}+ </div>+ )+}++export function TodayFigureCard({+ content,+ figure,+ reportId,+}: {+ content: TodayFigureCardContent+ figure: string+ reportId: string+}): JSX.Element {+ if (content.kind === 'metric') {+ return <MetricCard content={content} />+ }+ if (content.kind === 'none') {+ return (+ <div className="flex flex-col gap-2 p-3">+ <CardHeader icon={null}>No source on this page</CardHeader>+ <FullReportLink reportId={reportId}>Read the full report</FullReportLink>+ </div>+ )+ }+ return <QuoteCard content={content} figure={figure} reportId={reportId} />+}diff --git a/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx b/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsxnew file mode 100644index 000000000000..4a074ed17324--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx@@ -0,0 +1,43 @@+import { useActions } from 'kea'+import type { ReactNode } from 'react'++import { TodayFigureCard } from './TodayFigureCard'+import { TodayFigureCardContent } from './todayFigureSources'+import { TodayHoverMark } from './TodayHoverMark'+import { TodayPenMark } from './TodayPenMark'+import { circlePath } from './todayPenPaths'+import { todayReportLogic } from './todayReportLogic'++const PEN_DELAY_MS = 250+const PEN_STAGGER_MS = 160++export function TodayFigureMark({+ children,+ figure,+ content,+ reportId,+ order,+}: {+ children: ReactNode+ figure: string+ content: TodayFigureCardContent+ reportId: string+ order: number+}): JSX.Element {+ const { markOpened } = useActions(todayReportLogic({ reportId }))+ return (+ <TodayHoverMark+ className="TodayFigureMark"+ dataAttr="today-report-figure"+ onOpen={() => markOpened('impact')}+ card={<TodayFigureCard content={content} figure={figure} reportId={reportId} />}+ >+ <TodayPenMark seed={figure} delayMs={PEN_DELAY_MS + order * PEN_STAGGER_MS}>+ {children}+ </TodayPenMark>+ <svg className="TodayFigureMark__circle" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden>+ <path d={circlePath(figure)} pathLength={1} />+ </svg>+ </TodayHoverMark>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx b/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsxindex 053e274f0dc0..4726f5c8a449 100644--- a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx@@ -89,6 +89,7 @@ export function TodayHomeSidebar(): JSX.Element {variant="outline"size="lg"className="mb-1 w-full"+ nativeButton={false}render={<LinkPrimitive to={urls.taskNewSession()} />}data-attr="today-new-chat">diff --git a/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx b/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsxnew file mode 100644index 000000000000..adb9413d4e65--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx@@ -0,0 +1,97 @@+import { Popover } from '@base-ui/react/popover'+import { type ReactNode, useCallback, useState } from 'react'++import { Card, cn } from '@posthog/quill'++const OPEN_DELAY_MS = 250+const CLOSE_DELAY_MS = 120+const CARD_GAP_PX = 10++const RECENT_MOVE_MS = 1000+let lastPointerMove = Number.NEGATIVE_INFINITY+let tracksPointer = false++function trackPointerMoves(): void {+ if (tracksPointer) {+ return+ }+ tracksPointer = true+ window.addEventListener('pointermove', () => (lastPointerMove = performance.now()), { passive: true })+}++function pointerMovedRecently(): boolean {+ return performance.now() - lastPointerMove < RECENT_MOVE_MS+}++function cardAnchor(trigger: HTMLElement | null): Element | undefined {+ return trigger?.closest('li, p') ?? undefined+}++export function TodayHoverMark({+ className,+ dataAttr,+ children,+ card,+ onOpen,+}: {+ className: string+ dataAttr: string+ children: ReactNode+ card: ReactNode+ onOpen: () => void+}): JSX.Element {+ const [trigger, setTrigger] = useState<HTMLElement | null>(null)+ const [open, setOpen] = useState(false)+ const triggerRef = useCallback((node: HTMLElement | null): void => {+ trackPointerMoves()+ setTrigger(node)+ }, [])+ return (+ <Popover.Root+ open={open}+ onOpenChange={(next, details) => {+ const hoverWithoutMove = details.reason === 'trigger-hover' && !pointerMovedRecently()+ if (next && hoverWithoutMove) {+ return+ }+ setOpen(next)+ if (next) {+ onOpen()+ }+ }}+ >+ <Popover.Trigger+ openOnHover+ delay={OPEN_DELAY_MS}+ closeDelay={CLOSE_DELAY_MS}+ nativeButton={false}+ ref={triggerRef}+ render={<span />}+ className={cn('TodayHoverMark', className)}+ data-attr={dataAttr}+ >+ {children}+ </Popover.Trigger>+ <Popover.Portal>+ <Popover.Positioner+ data-quill+ data-quill-portal="popover"+ className="[--quill-z-popover:var(--z-popover-with-chart)]"+ anchor={cardAnchor(trigger)}+ side="bottom"+ align="start"+ sideOffset={CARD_GAP_PX}+ >+ <Popover.Popup className="TodayHoverMark__popup outline-none">+ <Card+ size="sm"+ className="TodayHoverMark__card w-[var(--anchor-width)] gap-0 border border-border py-0"+ >+ {card}+ </Card>+ </Popover.Popup>+ </Popover.Positioner>+ </Popover.Portal>+ </Popover.Root>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayIcon.tsx b/frontend/src/scenes/project-homepage/today/TodayIcon.tsxindex 07c5036d2b62..8160111e702b 100644--- a/frontend/src/scenes/project-homepage/today/TodayIcon.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayIcon.tsx@@ -1,25 +1,46 @@import {IconBell,+ IconCode,+ IconDatabase,+ IconGitLab,+ IconGithub,+ IconLinear,+ IconListCheck,+ IconLlmAnalytics,IconMessage,IconPullRequest,IconPulse,IconRewindPlay,- IconSparkles,+ IconSignal,+ IconSupport,+ IconTelescope,IconTrends,IconWarning,} from '@posthog/icons'+import { IconSlack } from 'lib/lemon-ui/icons'+import { TodayReportIcon } from './todaySignalReports'const REPORT_ICONS: Record<TodayReportIcon, JSX.Element> = {pr: <IconPullRequest />,replay: <IconRewindPlay />,error: <IconWarning />,- llm: <IconSparkles />,+ llm: <IconLlmAnalytics />,+ support: <IconSupport />,survey: <IconMessage />,analytics: <IconTrends />,- trace: <IconPulse />,- inbox: <IconBell />,+ logs: <IconPulse />,+ alert: <IconBell />,+ scout: <IconTelescope />,+ github: <IconGithub />,+ gitlab: <IconGitLab />,+ linear: <IconLinear />,+ jira: <IconListCheck />,+ database: <IconDatabase />,+ signal: <IconSignal />,+ code: <IconCode />,+ slack: <IconSlack />,}export function TodayIcon({ icon }: { icon: TodayReportIcon }): JSX.Element {diff --git a/frontend/src/scenes/project-homepage/today/TodayImplementMenu.tsx b/frontend/src/scenes/project-homepage/today/TodayImplementMenu.tsxnew file mode 100644index 000000000000..adafa60ed078--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayImplementMenu.tsx@@ -0,0 +1,127 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconCode, IconCopy, IconLogomark, IconSearch } from '@posthog/icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Text,+} from '@posthog/quill'++import { copyToClipboard } from 'lib/utils/copyToClipboard'++import { IMPLEMENTATION_AGENTS } from 'products/signals/frontend/inbox/components/detail/implementationAgents'+import { captureInboxReportAction } from 'products/signals/frontend/inbox/inboxAnalytics'+import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayActionButton } from './TodayActionButton'+import { reportWorkKind, reportWorkPrompt } from './todayNextStep'+import { todayReportLogic } from './todayReportLogic'++const AGENTS = IMPLEMENTATION_AGENTS.filter((agent) => agent.key !== 'posthog-code')++export function TodayImplementMenu({+ report,+ reportUrl,+ disabledReason,+ postHogDisabledReason,+}: {+ report: SignalReport+ reportUrl: string+ disabledReason: string | null+ postHogDisabledReason: string | null+}): JSX.Element {+ const { isCreatingPr, isDiscussing } = useValues(inboxTaskKickoffLogic)+ const { startWithPostHog } = useActions(todayReportLogic({ reportId: report.id }))+ const starting = isCreatingPr || isDiscussing+ const implement = reportWorkKind(report) === 'implement'++ const sendPrompt = (agentKey: string, send: (prompt: string) => void): void => {+ captureInboxReportAction({+ report,+ actionType: 'copy_implementation_prompt',+ surface: 'today',+ extra: { agent: agentKey, work: reportWorkKind(report) },+ })+ send(reportWorkPrompt(report, reportUrl))+ }++ const label = (+ <>+ {implement ? <IconCode /> : <IconSearch />}+ <span>{implement ? 'Implement with' : 'Investigate with'}</span>+ <IconChevronDown />+ </>+ )++ if (disabledReason) {+ return (+ <TodayActionButton+ variant="primary"+ className="me-1 gap-1.5"+ disabledReason={disabledReason}+ data-attr="today-report-implement-with"+ >+ {label}+ </TodayActionButton>+ )+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="primary"+ loading={starting}+ className="me-1 gap-1.5"+ data-attr="today-report-implement-with"+ >+ {label}+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="TodayImplementMenu w-52">+ <DropdownMenuItem+ onClick={() => startWithPostHog()}+ disabled={!!postHogDisabledReason || starting}+ data-attr="today-report-start-task"+ >+ <IconLogomark className="size-4 self-start" />+ <span className="flex flex-col">+ <span>PostHog</span>+ {postHogDisabledReason && (+ <Text size="xs" variant="muted" render={<span />}>+ {postHogDisabledReason}+ </Text>+ )}+ </span>+ </DropdownMenuItem>+ {AGENTS.map((agent) => (+ <DropdownMenuItem+ key={agent.key}+ onClick={() => sendPrompt(agent.key, agent.open)}+ data-attr={`today-report-open-${agent.key}`}+ >+ {agent.icon}+ {agent.name}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() =>+ sendPrompt('clipboard', (prompt) => void copyToClipboard(prompt, 'prompt for your agent'))+ }+ data-attr="today-report-copy-prompt"+ >+ <IconCopy className="size-4" />+ Copy prompt+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsx b/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsxnew file mode 100644index 000000000000..81dc360ca984--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsx@@ -0,0 +1,33 @@+import { LinkPrimitive } from 'lib/lemon-ui/Link'++import { inlineSegments } from './todayProse'++export function TodayInlineMarkdown({ markdown }: { markdown: string }): JSX.Element {+ return (+ <>+ {inlineSegments(markdown).map((segment, index) => {+ switch (segment.kind) {+ case 'code':+ return (+ <code key={index} className="text-[0.9em]">+ {segment.text}+ </code>+ )+ case 'link':+ return (+ <LinkPrimitive+ key={index}+ to={segment.href}+ target="_blank"+ className="underline underline-offset-2"+ >+ {segment.text}+ </LinkPrimitive>+ )+ default:+ return <span key={index}>{segment.text}</span>+ }+ })}+ </>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayInlineTrend.tsx b/frontend/src/scenes/project-homepage/today/TodayInlineTrend.tsxnew file mode 100644index 000000000000..f11f3ff3b9c7--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayInlineTrend.tsx@@ -0,0 +1,119 @@+import { cn } from '@posthog/quill'++const MIN_BAR_PERCENT = 22+const MIN_PARTIAL_PERCENT = 30+const WIDTH = 56+const HEIGHT = 14++function linePoints(values: number[]): string {+ const min = Math.min(...values)+ const range = Math.max(...values) - min+ const step = WIDTH / Math.max(values.length - 1, 1)+ return values+ .map(+ (value, index) => `${index * step},${range === 0 ? HEIGHT / 2 : HEIGHT - ((value - min) / range) * HEIGHT}`+ )+ .join(' ')+}++function barHeight(value: number, max: number, minPercent: number): { height: string } {+ return { height: `${Math.max(minPercent, (value / max) * 100)}%` }+}++function TrendBar({+ value,+ max,+ partial,+ detailed,+}: {+ value: number+ max: number+ partial: boolean+ detailed: boolean+}): JSX.Element {+ const peak = value === max && value > 0+ if (value <= 0) {+ return <span className={cn('flex-1 rounded-t-[1px]', detailed && 'h-px bg-current opacity-30')} />+ }+ if (partial) {+ return (+ <span+ className={cn(+ 'flex-1 rounded-t-[1px]',+ detailed+ ? 'border border-b-0 border-dashed border-current bg-current/15 opacity-60'+ : 'bg-current opacity-25'+ )}+ style={barHeight(value, max, MIN_PARTIAL_PERCENT)}+ />+ )+ }+ if (detailed && peak) {+ return (+ <span+ className="relative flex-1 rounded-t-[1px] bg-[var(--today-marker)]"+ style={barHeight(value, max, MIN_BAR_PERCENT)}+ >+ <span className="absolute -top-4 left-1/2 -translate-x-1/2 text-xxs font-semibold text-foreground tabular-nums">+ {value.toLocaleString('en-US')}+ </span>+ </span>+ )+ }+ return (+ <span+ className={cn(+ 'flex-1 rounded-t-[1px] bg-current opacity-60',+ peak && 'bg-[var(--today-marker)] opacity-100'+ )}+ style={barHeight(value, max, MIN_BAR_PERCENT)}+ />+ )+}++export function TodayInlineTrend({+ values,+ type,+ detailed = false,+ partialLast = false,+}: {+ values: number[]+ type: 'bar' | 'line'+ detailed?: boolean+ partialLast?: boolean+}): JSX.Element {+ if (type === 'line' || values.some((value) => value < 0)) {+ return (+ <svg+ className="h-4 w-16 overflow-visible text-muted-foreground opacity-60"+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ preserveAspectRatio="none"+ aria-hidden+ >+ <polyline+ points={linePoints(values)}+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ strokeLinejoin="round"+ strokeLinecap="round"+ vectorEffect="non-scaling-stroke"+ />+ </svg>+ )+ }+ const max = Math.max(...values, 1)+ return (+ <span className="inline-flex h-4 w-16 items-end gap-px text-muted-foreground" aria-hidden>+ {values.map((value, index) => (+ <TrendBar+ key={index}+ value={value}+ max={max}+ partial={partialLast && index === values.length - 1}+ detailed={detailed}+ />+ ))}+ </span>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayPenMark.tsx b/frontend/src/scenes/project-homepage/today/TodayPenMark.tsxnew file mode 100644index 000000000000..538325fde09b--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayPenMark.tsx@@ -0,0 +1,30 @@+import type { ReactNode } from 'react'++import { underlinePaths } from './todayPenPaths'++export function TodayPenMark({+ seed,+ delayMs,+ children,+}: {+ seed: string+ delayMs: number+ children: ReactNode+}): JSX.Element {+ return (+ <span className="relative inline-block indent-0 whitespace-nowrap text-foreground">+ {children}+ <svg+ className="TodayPenMark__stroke"+ viewBox="0 0 100 10"+ preserveAspectRatio="none"+ style={{ ['--today-mark-delay' as string]: `${delayMs}ms` }}+ aria-hidden+ >+ {underlinePaths(seed).map((path) => (+ <path key={path} d={path} pathLength={1} />+ ))}+ </svg>+ </span>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsxnew file mode 100644index 000000000000..4e29eed57a0b--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx@@ -0,0 +1,71 @@+import { useValues } from 'kea'++import { Text } from '@posthog/quill'++import { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayFigureMark } from './TodayFigureMark'+import { TodayInlineMarkdown } from './TodayInlineMarkdown'+import { TodayInlineTrend } from './TodayInlineTrend'+import { todayReportLogic } from './todayReportLogic'++export function TodayReportAbstract({ report }: { report: SignalReport }): JSX.Element | null {+ const {+ impactNumbers: numbers,+ impactText,+ leadStatesNumber,+ } = useValues(todayReportLogic({ reportId: report.id }))++ if (numbers.length === 0 && !impactText) {+ if (leadStatesNumber) {+ return null+ }+ return (+ <Text size="sm" variant="muted" render={<p />} data-attr="today-report-abstract">+ The report doesn’t say how big this is yet.+ </Text>+ )+ }++ if (numbers.length === 0) {+ return (+ <Text size="sm" render={<p />} className="leading-relaxed text-pretty" data-attr="today-report-abstract">+ <TodayInlineMarkdown markdown={impactText} />+ </Text>+ )+ }++ return (+ <ul className="m-0 flex list-none flex-col gap-3 p-0" aria-label="Impact" data-attr="today-report-abstract">+ {numbers.map((number, index) => (+ <li key={number.key} className="flex flex-col gap-0.5">+ <Text size="sm" render={<span />} className="text-pretty">+ <TodayFigureMark+ figure={number.value}+ content={number.content}+ reportId={report.id}+ order={index}+ >+ <span translate="no" className="tabular-nums">+ {number.value}+ </span>+ </TodayFigureMark>+ <span>{` ${number.label}`}</span>+ </Text>+ {number.window && (+ <Text size="xs" variant="muted" render={<span />} className="flex items-center gap-2">+ <span>{number.window}</span>+ {number.chart && (+ <TodayInlineTrend+ values={number.chart.data}+ type={number.chart.type}+ partialLast={number.chart.partialLast}+ />+ )}+ </Text>+ )}+ </li>+ ))}+ </ul>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx b/frontend/src/scenes/project-homepage/today/TodayReportBody.tsxnew file mode 100644index 000000000000..04f8fc499fbf--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx@@ -0,0 +1,48 @@+import type {+ ImplementationSlotClaim,+ ReportTaskEntry,+} from 'products/signals/frontend/inbox/logics/inboxReportDetailLogic'+import { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayReportAbstract } from './TodayReportAbstract'+import { TodayReportEvidence } from './TodayReportEvidence'+import { TodayReportFeedback } from './TodayReportFeedback'+import { TodayReportHeader } from './TodayReportHeader'+import { TodayReportNextStep } from './TodayReportNextStep'+import { TodayReportProposal } from './TodayReportProposal'++interface TodayReportLiveState {+ reportTaskToOpen: ReportTaskEntry | null+ implementationSlotClaim: ImplementationSlotClaim | null+}++export function TodayReportBody({+ report,+ live,+}: {+ report: SignalReport+ live: TodayReportLiveState | null+}): JSX.Element {+ return (+ <article className="TodayReportArticle flex max-w-150 flex-col gap-10">+ <div className="flex flex-col gap-5">+ <TodayReportHeader report={report} />+ <TodayReportAbstract report={report} />+ </div>+ <section className="flex flex-col gap-4" aria-label="Proposal">+ <TodayReportProposal reportId={report.id} />+ <TodayReportNextStep+ report={report}+ reportTaskToOpen={live?.reportTaskToOpen ?? null}+ slotClaim={live?.implementationSlotClaim ?? null}+ />+ </section>+ <TodayReportEvidence report={report} />+ {live && (+ <footer>+ <TodayReportFeedback report={report} />+ </footer>+ )}+ </article>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportEvidence.tsx b/frontend/src/scenes/project-homepage/today/TodayReportEvidence.tsxindex 2e8607bec348..4de699f54c65 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportEvidence.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportEvidence.tsx@@ -1,56 +1,58 @@import { useValues } from 'kea'-import { LemonSkeleton } from '@posthog/lemon-ui'+import { Button, Text } from '@posthog/quill'-import { Link } from 'lib/lemon-ui/Link'+import { LinkPrimitive } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'-import { SignalCard } from 'products/signals/frontend/inbox/SignalCard'+import { SignalReport } from 'products/signals/frontend/inbox/types'import { todayReportLogic } from './todayReportLogic'+import { TodayReportSectionTitle } from './TodayReportSectionTitle'+import { TodayReportSignalRow } from './TodayReportSignalRow'import { isSampleReportId } from './todaySampleReports'-const SHOWN_SIGNAL_COUNT = 3+function EvidenceRows({ reportId }: { reportId: string }): JSX.Element {+ const { shownEvidence } = useValues(todayReportLogic({ reportId }))+ if (shownEvidence.length === 0) {+ return (+ <Text size="sm" variant="muted" render={<p />}>+ No signals are attached to this report yet.+ </Text>+ )+ }+ return (+ <div className="-mx-2 flex flex-col">+ {shownEvidence.map((signal) => (+ <TodayReportSignalRow key={signal.signal_id} reportId={reportId} signal={signal} />+ ))}+ </div>+ )+}-/** The newest signals behind the report. The full list stays in the Inbox. */-export function TodayReportEvidence({ reportId }: { reportId: string }): JSX.Element {- const { signals, reportSignals, reportSignalsLoading } = useValues(todayReportLogic({ reportId }))- const inboxUrl = urls.inboxReport('reports', reportId)+export function TodayReportEvidence({ report }: { report: SignalReport }): JSX.Element {+ const { shownEvidence, evidenceCount } = useValues(todayReportLogic({ reportId: report.id }))+ const fullReport = urls.inboxReport('reports', report.id)+ const showsSeeAll = evidenceCount > shownEvidence.length && !isSampleReportId(report.id)return (- <section className="TodayEvidence" aria-label="Evidence">- <div className="Today__label">- {reportSignals === null- ? 'Evidence'- : `Evidence · ${signals.length} ${signals.length === 1 ? 'signal' : 'signals'}`}+ <section className="flex flex-col gap-0.5" aria-label="Evidence" data-attr="today-report-evidence">+ <div className="flex items-baseline justify-between gap-3">+ <TodayReportSectionTitle>Evidence</TodayReportSectionTitle>+ {showsSeeAll && (+ <Button+ variant="link-muted"+ size="sm"+ className="-me-2"+ nativeButton={false}+ render={<LinkPrimitive to={fullReport} />}+ data-attr="today-report-evidence-all"+ >+ {`See all ${evidenceCount}`}+ </Button>+ )}</div>- {reportSignals === null && reportSignalsLoading ? (- <div className="flex flex-col gap-3">- <LemonSkeleton className="h-20" />- <LemonSkeleton className="h-20" />- </div>- ) : reportSignals === null ? (- <p className="TodayEvidence__note">- <span>Couldn’t load the evidence. </span>- <Link to={inboxUrl} data-attr="today-evidence-inbox">- Open the report in the Inbox- </Link>- <span> to see it there.</span>- </p>- ) : signals.length === 0 ? (- <p className="TodayEvidence__note">No signals are attached to this report yet.</p>- ) : (- <div className="flex flex-col gap-3">- {signals.slice(0, SHOWN_SIGNAL_COUNT).map((signal) => (- <SignalCard key={signal.signal_id} signal={signal} />- ))}- {signals.length > SHOWN_SIGNAL_COUNT && !isSampleReportId(reportId) && (- <Link to={inboxUrl} className="text-sm" data-attr="today-evidence-inbox">- {`See all ${signals.length} signals in the Inbox`}- </Link>- )}- </div>- )}+ <EvidenceRows reportId={report.id} /></section>)}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsx b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsxnew file mode 100644index 000000000000..df570dfae143--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportFeedback.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'+import { type ChangeEvent } from 'react'++import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled } from '@posthog/icons'+import { Button, Text, Textarea } from '@posthog/quill'++import { inboxReportDetailLogic } from 'products/signals/frontend/inbox/logics/inboxReportDetailLogic'+import { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayActionButton } from './TodayActionButton'+import { todayReportLogic } from './todayReportLogic'++const NOTE_MAX_LENGTH = 4000++export function TodayReportFeedback({ report }: { report: SignalReport }): JSX.Element {+ const logic = inboxReportDetailLogic({ reportId: report.id, report })+ const { feedbackSentiment, feedbackNoteOpen, feedbackNoteDraft, feedbackNoteSent, feedbackNoteSubmitting } =+ useValues(logic)+ const { rateReport, openFeedbackNote, setFeedbackNoteDraft, submitFeedbackNote } = useActions(logic)+ const { feedbackNoteFocused } = useValues(todayReportLogic({ reportId: report.id }))+ const { focusFeedbackNote } = useActions(todayReportLogic({ reportId: report.id }))+ const isPositive = feedbackSentiment === 'positive'+ const isNegative = feedbackSentiment === 'negative'+ const canAddNote = !!feedbackSentiment && !feedbackNoteOpen && !feedbackNoteSent++ return (+ <div className="flex flex-col gap-2" data-attr="today-report-feedback">+ <div className="flex flex-wrap items-center gap-1">+ <Text size="xs" variant="muted" render={<span />} className="me-1">+ {feedbackSentiment ? 'Thanks for the feedback' : 'Was this report useful?'}+ </Text>+ <TodayActionButton+ size="icon-sm"+ aria-label="This report was useful"+ aria-pressed={isPositive}+ tooltip="Yes, this was useful"+ onClick={() => !isPositive && rateReport('positive', 'today')}+ data-attr="today-report-feedback-up"+ >+ {isPositive ? <IconThumbsUpFilled /> : <IconThumbsUp />}+ </TodayActionButton>+ <TodayActionButton+ size="icon-sm"+ aria-label="This report was not useful"+ aria-pressed={isNegative}+ tooltip="No, this wasn't useful"+ onClick={() => !isNegative && rateReport('negative', 'today')}+ data-attr="today-report-feedback-down"+ >+ {isNegative ? <IconThumbsDownFilled /> : <IconThumbsDown />}+ </TodayActionButton>+ {canAddNote && (+ <Button+ variant="link-muted"+ size="sm"+ onClick={() => {+ focusFeedbackNote()+ openFeedbackNote()+ }}+ data-attr="today-report-feedback-note-open"+ >+ Add a note+ </Button>+ )}+ {feedbackNoteSent && (+ <Text size="xs" variant="muted" render={<span />}>+ Note added+ </Text>+ )}+ </div>+ {feedbackNoteOpen && (+ <div className="flex flex-col items-start gap-2">+ <Textarea+ value={feedbackNoteDraft}+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => setFeedbackNoteDraft(event.target.value)}+ placeholder="What was useful or off?"+ aria-label="Add a note about this report"+ maxLength={NOTE_MAX_LENGTH}+ rows={4}+ autoFocus={feedbackNoteFocused}+ className="w-full"+ data-attr="today-report-feedback-note"+ />+ <TodayActionButton+ variant="primary"+ size="sm"+ loading={feedbackNoteSubmitting}+ disabledReason={feedbackNoteDraft.trim() ? null : 'Write a note first'}+ onClick={() => submitFeedbackNote(feedbackNoteDraft, 'today')}+ data-attr="today-report-feedback-note-send"+ >+ Send+ </TodayActionButton>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsxnew file mode 100644index 000000000000..44fcdf91937e--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx@@ -0,0 +1,124 @@+import { useActions, useValues } from 'kea'++import { IconCheckCircle, IconDocument, IconHide } from '@posthog/icons'+import { Badge, Heading, Text } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { SignalReport } from 'products/signals/frontend/inbox/types'+import { hasOpenImplementationPr } from 'products/signals/frontend/inbox/utils/reportActions'+import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/utils/reportPresentation'++import { TodayActionButton } from './TodayActionButton'+import { itemStateLabel } from './todayBriefingItems'+import { TodayInlineMarkdown } from './TodayInlineMarkdown'+import { TodayReportVerdict, todayLogic } from './todayLogic'+import { resolveDisabledReason } from './todayNextStep'+import { todayReportLogic } from './todayReportLogic'+import { SAMPLE_REPORT_REASON } from './todaySampleReports'+import { priorityBadgeVariant, reportSourceLine, reportTitle } from './todaySignalReports'++export function TodayReportHeader({ report }: { report: SignalReport }): JSX.Element {+ const { requestReportVerdict } = useActions(todayLogic)+ const { lead, reportState, isSample } = useValues(todayReportLogic({ reportId: report.id }))+ const sampleReason = isSample ? SAMPLE_REPORT_REASON : null+ const stateLabel = itemStateLabel({ state: reportState })+ const sources = reportSourceLine(report)+ const updated = dayjs(report.updated_at)+ const stillInvestigating = !report.summary?.trim()++ const giveVerdict = (verdict: TodayReportVerdict): void =>+ requestReportVerdict(+ { reportId: report.id, title: reportTitle(report), hasOpenPullRequest: hasOpenImplementationPr(report) },+ verdict,+ 'report_page'+ )++ return (+ <header className="flex flex-col gap-3">+ <div className="flex min-h-7 flex-wrap items-center justify-between gap-x-3 gap-y-1">+ <Text+ size="xs"+ variant="muted"+ render={<div />}+ className="flex min-w-0 flex-1 basis-0 items-center gap-2 whitespace-nowrap"+ >+ {report.priority && (+ <Badge variant={priorityBadgeVariant(report.priority)}>{report.priority}</Badge>+ )}+ <span className="min-w-0 truncate" title={sources.title || undefined}>+ {sources.line}+ </span>+ <span aria-hidden className="-mx-0.5">+ ·+ </span>+ <time dateTime={report.updated_at} title={updated.format('LLL')}>+ <span>Updated </span>+ <span translate="no">{updated.fromNow()}</span>+ </time>+ </Text>+ <div className="-me-2 flex shrink-0 items-center gap-0.5">+ {!isSample && (+ <TodayActionButton+ size="sm"+ variant="link-muted"+ nativeButton={false}+ render={<LinkPrimitive to={urls.inboxReport('reports', report.id)} />}+ tooltip="Open the full report in the Inbox"+ data-attr="today-report-open-inbox"+ >+ <IconDocument />+ Full report+ </TodayActionButton>+ )}+ {stateLabel ? (+ <Badge variant={reportState === 'done' ? 'completed' : 'default'}>{stateLabel}</Badge>+ ) : (+ <>+ <TodayActionButton+ size="sm"+ variant="link-muted"+ onClick={() => giveVerdict('resolve')}+ disabledReason={resolveDisabledReason(report, sampleReason)}+ tooltip="Mark this report as done"+ data-attr="today-report-resolve"+ >+ <IconCheckCircle />+ Resolve+ </TodayActionButton>+ <TodayActionButton+ size="sm"+ variant="link-muted"+ onClick={() => giveVerdict('dismiss')}+ disabledReason={sampleReason}+ tooltip="Dismiss this report from your inbox"+ data-attr="today-report-dismiss"+ >+ <IconHide />+ Dismiss+ </TodayActionButton>+ </>+ )}+ </div>+ </div>+ <div className="flex flex-col gap-2">+ <Heading size="xl" render={<h1 />} className="leading-snug text-balance">+ {capitalizeFirstLetter(displayConventionalCommitTitle(report.title, 'Untitled report'))}+ </Heading>+ {lead && (+ <Text size="sm" render={<p />} className="leading-relaxed text-pretty">+ <TodayInlineMarkdown markdown={lead} />+ </Text>+ )}+ {stillInvestigating && (+ <Text variant="muted" render={<p />}>+ No summary yet. An agent is still investigating.+ </Text>+ )}+ </div>+ </header>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportLiveBody.tsx b/frontend/src/scenes/project-homepage/today/TodayReportLiveBody.tsxnew file mode 100644index 000000000000..0a0f680caa86--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportLiveBody.tsx@@ -0,0 +1,13 @@+import { useValues } from 'kea'++import { inboxReportDetailLogic } from 'products/signals/frontend/inbox/logics/inboxReportDetailLogic'+import type { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayReportBody } from './TodayReportBody'++export function TodayReportLiveBody({ report }: { report: SignalReport }): JSX.Element {+ const { implementationSlotClaim, reportTaskToOpen } = useValues(+ inboxReportDetailLogic({ reportId: report.id, report })+ )+ return <TodayReportBody report={report} live={{ reportTaskToOpen, implementationSlotClaim }} />+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportNextStep.tsx b/frontend/src/scenes/project-homepage/today/TodayReportNextStep.tsxnew file mode 100644index 000000000000..04eca38482be--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportNextStep.tsx@@ -0,0 +1,167 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import { IconClock, IconPullRequest, IconSparkles } from '@posthog/icons'+import { Text } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'++import { Composer } from 'products/posthog_ai/frontend/api/composer'+import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import type {+ ImplementationSlotClaim,+ ReportTaskEntry,+} from 'products/signals/frontend/inbox/logics/inboxReportDetailLogic'+import { SignalReport } from 'products/signals/frontend/inbox/types'++import { TodayActionButton } from './TodayActionButton'+import { TodayImplementMenu } from './TodayImplementMenu'+import { TodayPrimaryAction, startDisabledReason, todayNextStep } from './todayNextStep'+import { todayReportLogic } from './todayReportLogic'+import { SAMPLE_REPORT_REASON } from './todaySampleReports'++function PrimaryAction({+ primary,+ report,+ reportUrl,+ isSample,+ startReason,+}: {+ primary: TodayPrimaryAction+ report: SignalReport+ reportUrl: string+ isSample: boolean+ startReason: string | null+}): JSX.Element {+ const { openReportTask } = useActions(inboxTaskKickoffLogic)+ if (primary.kind === 'review') {+ return (+ <TodayActionButton+ variant="primary"+ className="me-1"+ nativeButton={false}+ render={<LinkPrimitive to={primary.url} target="_blank" />}+ disabledReason={isSample ? SAMPLE_REPORT_REASON : null}+ data-attr="today-report-review-pr"+ >+ <IconPullRequest />+ <span>{primary.label}</span>+ </TodayActionButton>+ )+ }+ if (primary.kind === 'open_task') {+ return (+ <TodayActionButton+ variant="primary"+ className="me-1"+ onClick={() => openReportTask(report, primary.taskId, primary.runId)}+ data-attr="today-report-open-task"+ >+ <IconClock />+ <span>{primary.label}</span>+ </TodayActionButton>+ )+ }+ return (+ <TodayImplementMenu+ report={report}+ reportUrl={reportUrl}+ disabledReason={isSample ? SAMPLE_REPORT_REASON : null}+ postHogDisabledReason={startReason}+ />+ )+}++export function TodayReportNextStep({+ report,+ reportTaskToOpen,+ slotClaim,+}: {+ report: SignalReport+ reportTaskToOpen: ReportTaskEntry | null+ slotClaim: ImplementationSlotClaim | null+}): JSX.Element | null {+ const { createPrDisabledReason, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)+ const logic = todayReportLogic({ reportId: report.id })+ const { reportState, reportUrl, isSample, page, askingAi, composerOpen, draft } = useValues(logic)+ const { askAboutReport, openComposer, setDraft } = useActions(logic)+ const textAreaRef = useRef<HTMLTextAreaElement>(null)+ const task = reportTaskToOpen?.task+ const { primary, note, taskPickedUp } = todayNextStep(report, {+ namedPullRequest: page?.named_pull_request ?? null,+ solutionNamesPullRequest: page?.solution_names_pull_request ?? false,+ slotClaimed: slotClaim !== null,+ runningTask: task?.latest_run ? { taskId: task.id, runId: task.latest_run.id } : null,+ })++ if (reportState !== 'open') {+ return null+ }++ const askDisabledReason = isSample ? SAMPLE_REPORT_REASON : null++ const focusComposer = (): void => {+ openComposer()+ requestAnimationFrame(() => {+ const textArea = textAreaRef.current+ textArea?.focus({ preventScroll: true })+ textArea?.setSelectionRange(textArea.value.length, textArea.value.length)+ })+ }++ return (+ <div className="flex flex-col gap-2" data-attr="today-report-continue">+ <div className="flex flex-wrap items-center gap-1">+ {primary && (+ <PrimaryAction+ primary={primary}+ report={report}+ reportUrl={reportUrl}+ isSample={isSample}+ startReason={startDisabledReason(report, taskPickedUp, {+ createPrDisabledReason,+ aiConsentDisabledReason,+ })}+ />+ )}+ <TodayActionButton+ className={primary ? undefined : '-ms-2'}+ onClick={focusComposer}+ disabledReason={askDisabledReason}+ data-attr="today-report-ask"+ >+ <IconSparkles />+ Ask about it+ </TodayActionButton>+ </div>+ {note && (+ <Text size="xs" render={<p />} className="flex items-center gap-1.5">+ <IconClock className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span>{note}</span>+ </Text>+ )}+ {composerOpen && (+ <Composer.Root+ value={draft}+ onChange={setDraft}+ onSubmit={() => askAboutReport(draft.trim())}+ textAreaRef={textAreaRef}+ loading={askingAi}+ disabled={askingAi}+ >+ <Composer.Frame>+ <Composer.Field>+ <Composer.Placeholder>Ask PostHog AI about this report</Composer.Placeholder>+ <Composer.Textarea+ maxRows={6}+ className="[mask-image:linear-gradient(to_bottom,black_calc(100%-1rem),transparent)]"+ data-attr="today-report-prompt-input"+ />+ </Composer.Field>+ </Composer.Frame>+ <Composer.Submit data-attr="today-report-prompt-submit" />+ </Composer.Root>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx b/frontend/src/scenes/project-homepage/today/TodayReportPage.tsxindex 05f87c55a6da..870c493b627d 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx@@ -1,163 +1,110 @@import { useActions, useValues } from 'kea'-import { IconCheckCircle, IconExternal, IconHide } from '@posthog/icons'-import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'+import { Button, Heading, Skeleton, Text } from '@posthog/quill'+import { LinkPrimitive } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'-import { ReportChart } from 'products/signals/frontend/inbox/components/detail/ReportChart'-import { ReportChartsContext } from 'products/signals/frontend/inbox/components/detail/reportChartsContext'-import { ReportSummaryBody } from 'products/signals/frontend/inbox/components/detail/ReportSummaryBody'-import { canResolveReport, hasOpenImplementationPr } from 'products/signals/frontend/inbox/utils/reportActions'--import { itemStateLabel } from './todayBriefingItems'-import { TodayIcon } from './TodayIcon'-import { TodayReportVerdict, todayLogic } from './todayLogic'-import { TodayReportEvidence } from './TodayReportEvidence'+import { TodayReportBody } from './TodayReportBody'+import { TodayReportLiveBody } from './TodayReportLiveBody'import { todayReportLogic } from './todayReportLogic'-import { TodayReportPrompts } from './TodayReportPrompts'import { TodaySampleBanner } from './TodaySampleBanner'-import { isSampleReportId } from './todaySampleReports'-import { reportIcon, reportMeta, reportSource, reportTitle } from './todaySignalReports'-export function TodayReportPage({ reportId }: { reportId: string }): JSX.Element {+function ReportFailed({ reportId }: { reportId: string }): JSX.Element {const logic = todayReportLogic({ reportId })- const { currentReport, reportFailed, fullReportLoading, chartPlacements, chartsById, trailingCharts, reportState } =- useValues(logic)- const { loadFullReport } = useActions(logic)- const { requestReportVerdict } = useActions(todayLogic)- const sampleDisabledReason = isSampleReportId(reportId) ? 'This is a sample report.' : undefined+ const { fullReportLoading, pageLoading } = useValues(logic)+ const { loadFullReport, loadPage } = useActions(logic)+ return (+ <div className="flex max-w-150 flex-col gap-3">+ <Heading size="lg" render={<h1 />}>+ Couldn’t open this report.+ </Heading>+ <Text variant="muted" render={<p />}>+ It may have been deleted, or the request failed. Try again, or go back to today’s briefing.+ </Text>+ <div className="mt-3 flex flex-wrap gap-2">+ <Button+ variant="primary"+ onClick={() => {+ loadFullReport()+ loadPage()+ }}+ loading={fullReportLoading || pageLoading}+ data-attr="today-report-retry"+ >+ Try again+ </Button>+ <Button+ variant="outline"+ nativeButton={false}+ render={<LinkPrimitive to={urls.projectHomepage()} />}+ data-attr="today-report-missing-home"+ >+ Back to Home+ </Button>+ </div>+ </div>+ )+}- if (!currentReport) {- return reportFailed ? (- <div className="TodayReport Today__page">- <TodaySampleBanner />- <h1 className="TodayReport__heading">Couldn’t open this report.</h1>- <div className="TodayReport__body">- <p>It may have been deleted, or the request failed. Try again, or go back to today’s briefing.</p>+function ReportSkeleton(): JSX.Element {+ return (+ <div className="flex max-w-150 flex-col gap-10" aria-busy>+ <div className="flex flex-col gap-3">+ <div className="flex h-7 items-center justify-between">+ <Skeleton className="h-3 w-48" />+ <Skeleton className="h-3 w-40" /></div>- <div className="flex flex-wrap gap-2 mt-6">- <LemonButton- type="primary"- onClick={() => loadFullReport()}- loading={fullReportLoading}- data-attr="today-report-retry"- >- Try again- </LemonButton>- <LemonButton type="secondary" to={urls.projectHomepage()} data-attr="today-report-missing-home">- Back to Home- </LemonButton>+ <Skeleton className="h-6 w-4/5" />+ <div className="flex flex-col gap-2 pt-1">+ <Skeleton className="h-3.5 w-full" />+ <Skeleton className="h-3.5 w-2/3" /></div>+ <Skeleton className="mt-3 h-3.5 w-3/5" /></div>- ) : (- <div className="TodayReport Today__page flex flex-col gap-4">- <LemonSkeleton className="h-4 w-48" />- <LemonSkeleton className="h-10 w-3/4" />- <LemonSkeleton className="h-24" />+ <div className="flex flex-col gap-2">+ <Skeleton className="h-4 w-20" />+ <Skeleton className="h-3.5 w-full" />+ <Skeleton className="h-3.5 w-1/2" />+ <div className="mt-2 flex items-center gap-4">+ <Skeleton className="h-8 w-32" />+ <Skeleton className="h-3.5 w-16" />+ <Skeleton className="h-3.5 w-24" />+ </div></div>- )- }+ <div className="flex flex-col gap-5">+ <Skeleton className="h-4 w-20" />+ {['w-11/12', 'w-3/4', 'w-5/6'].map((width) => (+ <div key={width} className="flex items-start justify-between gap-6">+ <div className="flex flex-1 flex-col gap-2">+ <Skeleton className="h-3.5 w-full" />+ <Skeleton className={`h-3.5 ${width}`} />+ </div>+ <Skeleton className="h-3 w-12" />+ </div>+ ))}+ </div>+ </div>+ )+}++export function TodayReportPage({ reportId }: { reportId: string }): JSX.Element {+ const { currentReport, page, reportFailed, isSample } = useValues(todayReportLogic({ reportId }))- const stateLabel = itemStateLabel({ state: reportState })- const giveVerdict = (verdict: TodayReportVerdict): void =>- requestReportVerdict(- {- reportId: currentReport.id,- title: reportTitle(currentReport),- hasOpenPullRequest: hasOpenImplementationPr(currentReport),- },- verdict,- 'report_page'+ if ((!currentReport || !page) && !reportFailed) {+ return (+ <div className="TodayReport Today__page" data-quill>+ <ReportSkeleton />+ </div>)+ }return (- <div- className="TodayReport Today__page"- // eslint-disable-next-line react/forbid-dom-props- style={{ '--report-color': reportSource(currentReport).color } as React.CSSProperties}- >+ <div className="TodayReport Today__page" data-quill><TodaySampleBanner />- <article>- <div className="TodayReport__kicker">- <span className="TodayTile">- <TodayIcon icon={reportIcon(currentReport)} />- </span>- <span>{reportMeta(currentReport)}</span>- {currentReport.priority && <LemonTag type="muted">{currentReport.priority}</LemonTag>}- {stateLabel && (- <LemonTag type={reportState === 'done' ? 'success' : 'muted'}>{stateLabel}</LemonTag>- )}- </div>- <h1 className="TodayReport__heading">{reportTitle(currentReport)}</h1>- <div className="flex flex-wrap gap-2 mt-4">- {currentReport.implementation_pr_url && (- <LemonButton- type="primary"- size="small"- to={currentReport.implementation_pr_url}- targetBlank- sideIcon={<IconExternal />}- disabledReason={sampleDisabledReason}- data-attr="today-report-pull-request"- >- Review the pull request- </LemonButton>- )}- <LemonButton- type="secondary"- size="small"- to={urls.inboxReport('reports', currentReport.id)}- disabledReason={sampleDisabledReason}- data-attr="today-report-open-inbox"- >- Open in Inbox- </LemonButton>- {!stateLabel && (- <>- <LemonButton- type="secondary"- size="small"- icon={<IconCheckCircle />}- onClick={() => giveVerdict('resolve')}- disabledReason={- sampleDisabledReason ??- (canResolveReport(currentReport)- ? undefined- : 'You can resolve a report only after the agent finishes its research.')- }- data-attr="today-report-resolve"- >- Resolve- </LemonButton>- <LemonButton- type="secondary"- size="small"- icon={<IconHide />}- onClick={() => giveVerdict('dismiss')}- disabledReason={sampleDisabledReason}- data-attr="today-report-dismiss"- >- Dismiss- </LemonButton>- </>- )}- </div>- <ReportChartsContext.Provider value={chartsById}>- <div className="TodayReport__body">- {currentReport.summary ? (- <ReportSummaryBody summary={currentReport.summary} chartPlacements={chartPlacements} />- ) : (- <p>No summary yet. An agent is still investigating.</p>- )}- {trailingCharts.map((chart) => (- <ReportChart key={chart.chart_id} chartId={chart.chart_id} />- ))}- </div>- </ReportChartsContext.Provider>- </article>- <TodayReportEvidence reportId={currentReport.id} />- <TodayReportPrompts report={currentReport} />+ {reportFailed && <ReportFailed reportId={reportId} />}+ {currentReport && isSample && <TodayReportBody report={currentReport} live={null} />}+ {currentReport && !isSample && <TodayReportLiveBody report={currentReport} />}</div>)}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportPrompts.tsx b/frontend/src/scenes/project-homepage/today/TodayReportPrompts.tsxdeleted file mode 100644index d6bfe66620c3..000000000000--- a/frontend/src/scenes/project-homepage/today/TodayReportPrompts.tsx+++ /dev/null@@ -1,82 +0,0 @@-import { useActions, useValues } from 'kea'-import { useState } from 'react'--import { IconSparkles } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { Composer } from 'products/posthog_ai/frontend/api/composer'-import {- InboxQuestionSource,- captureInboxReportAction,- discussQuestionProperties,-} from 'products/signals/frontend/inbox/inboxAnalytics'-import { SignalReport } from 'products/signals/frontend/inbox/types'--import { todayLogic } from './todayLogic'-import { isSampleReportId } from './todaySampleReports'-import { reportPrompts } from './todaySignalReports'--/** Prompts and a composer that open PostHog AI with the report as context. A prompt sends at once. */-export function TodayReportPrompts({ report }: { report: SignalReport }): JSX.Element {- const { askingAi } = useValues(todayLogic)- const { askAi } = useActions(todayLogic)- const [draft, setDraft] = useState('')- const prompts = reportPrompts(report)- const disabledReason = isSampleReportId(report.id)- ? 'Sample reports can’t start a chat. Turn off sample reports to ask about a real one.'- : undefined-- const ask = (question: string, source: InboxQuestionSource): void => {- if (!question || disabledReason || askingAi) {- return- }- captureInboxReportAction({- report,- actionType: 'discuss',- surface: 'today',- extra: discussQuestionProperties({ source, suggestionCount: prompts.length }),- })- askAi(question, 'report_page', report)- }-- return (- <section className="TodayPrompts" aria-label="Ask about this report">- <div className="Today__label">Ask about this report</div>- <div className="flex flex-wrap gap-2">- {prompts.map((prompt) => (- <LemonButton- key={prompt}- type="secondary"- size="small"- icon={<IconSparkles />}- onClick={() => ask(prompt, 'suggested')}- disabledReason={disabledReason ?? (askingAi ? 'Opening PostHog AI…' : undefined)}- data-attr="today-report-prompt"- >- {prompt}- </LemonButton>- ))}- </div>- <Composer.Root- value={draft}- onChange={setDraft}- onSubmit={() => {- ask(draft.trim(), 'typed')- setDraft('')- }}- disabledReason={disabledReason}- loading={askingAi}- disabled={askingAi}- >- <Composer.Frame>- <Composer.Field>- <Composer.Placeholder>Or ask your own question</Composer.Placeholder>- <Composer.Textarea data-attr="today-report-prompt-input" />- </Composer.Field>- </Composer.Frame>- <Composer.Submit data-attr="today-report-prompt-submit" />- </Composer.Root>- <p className="TodayPrompts__hint">Opens PostHog AI with this report as context.</p>- </section>- )-}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsxnew file mode 100644index 000000000000..5dc9135a4cc3--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx@@ -0,0 +1,25 @@+import { useValues } from 'kea'++import { Text } from '@posthog/quill'++import { TodayInlineMarkdown } from './TodayInlineMarkdown'+import { todayReportLogic } from './todayReportLogic'+import { TodayReportSectionTitle } from './TodayReportSectionTitle'++export function TodayReportProposal({ reportId }: { reportId: string }): JSX.Element {+ const { proposal } = useValues(todayReportLogic({ reportId }))+ return (+ <div className="flex flex-col gap-2">+ <TodayReportSectionTitle>Proposal</TodayReportSectionTitle>+ {proposal ? (+ <Text size="sm" render={<p />} className="leading-relaxed text-pretty">+ <TodayInlineMarkdown markdown={proposal} />+ </Text>+ ) : (+ <Text size="sm" variant="muted" render={<p />}>+ No fix proposed yet.+ </Text>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportSectionTitle.tsx b/frontend/src/scenes/project-homepage/today/TodayReportSectionTitle.tsxnew file mode 100644index 000000000000..40faa64683f1--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportSectionTitle.tsx@@ -0,0 +1,9 @@+import { Text } from '@posthog/quill'++export function TodayReportSectionTitle({ children }: { children: string }): JSX.Element {+ return (+ <Text size="base" weight="semibold" render={<h2 />}>+ {children}+ </Text>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx b/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsxnew file mode 100644index 000000000000..4537c524842f--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx@@ -0,0 +1,137 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { IconChevronDown, IconExternal, IconPlay } from '@posthog/icons'+import { Item, ItemActions, ItemContent, ItemTitle, Text, cn } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'+import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'++import type { SignalPreviewApi, SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { TodaySignalDestination, previewOpen, shownPreview, signalDestination } from './todayEvidence'+import { TodayEvidenceDetail } from './TodayEvidenceDetail'+import { TodayIcon } from './TodayIcon'+import { shortDate } from './todayProse'+import { todayReportLogic } from './todayReportLogic'+import { sourceStyle } from './todaySignalReports'+import { signalSourceLabel } from './todaySignalText'++const EXPAND: TodaySignalDestination = { kind: 'read' }++interface RowHint {+ label: string+ icon: JSX.Element+}++function rowHint(action: TodaySignalDestination, preview: SignalPreviewApi | null, expanded: boolean): RowHint | null {+ if (action.kind === 'recording') {+ return { label: 'Play', icon: <IconPlay /> }+ }+ if (action.kind === 'link') {+ return { label: action.label, icon: <IconExternal /> }+ }+ if (!preview) {+ return null+ }+ return {+ label: expanded ? 'Close' : preview.hint,+ icon: <IconChevronDown className={cn('transition-transform duration-200', expanded && 'rotate-180')} />,+ }+}++function rowElement(action: TodaySignalDestination, hint: RowHint | null, expanded: boolean): JSX.Element {+ if (action.kind === 'link') {+ return <LinkPrimitive to={action.to} target={action.external ? '_blank' : undefined} />+ }+ if (!hint) {+ return <div />+ }+ return <button type="button" aria-expanded={action.kind === 'read' ? expanded : undefined} />+}++function RowTrailer({ signal, hint }: { signal: SignalViewApi; hint: RowHint | null }): JSX.Element {+ const time = dayjs(signal.timestamp)+ return (+ <Text size="xs" variant="muted" render={<span />} className="flex items-center gap-2 whitespace-nowrap">+ <span aria-hidden className="flex size-3.5 items-center justify-center [&_svg]:size-3.5">+ <span className={cn('flex', hint && 'group-hover/row:hidden group-focus-visible/row:hidden')}>+ <TodayIcon icon={signal.cited ?? sourceStyle(signal.source_product).icon} />+ </span>+ {hint && (+ <span className="hidden text-foreground group-hover/row:flex group-focus-visible/row:flex">+ {hint.icon}+ </span>+ )}+ </span>+ <time dateTime={signal.timestamp} title={time.format('LLL')} className="w-12 text-right tabular-nums">+ {time.isSame(dayjs(), 'day') ? 'Today' : shortDate(time)}+ </time>+ </Text>+ )+}++export function TodayReportSignalRow({ reportId, signal }: { reportId: string; signal: SignalViewApi }): JSX.Element {+ const logic = todayReportLogic({ reportId })+ const { expandedEvidence } = useValues(logic)+ const { evidenceOpened, readCode, expandEvidence, collapseEvidence } = useActions(logic)+ const { openSessionPlayer } = useActions(sessionPlayerModalLogic)+ const expanded = !!expandedEvidence[signal.signal_id]+ const destination = useMemo(() => signalDestination(signal), [signal])+ const open = previewOpen(signal, destination)+ const preview = shownPreview(signal, open)+ const action = preview ? EXPAND : destination+ const hint = rowHint(action, preview, expanded)+ const sourceLabel = signalSourceLabel(signal)+ const detailId = `today-signal-${signal.signal_id}`++ const onClick = (): void => {+ if (expanded) {+ collapseEvidence(signal.signal_id)+ return+ }+ evidenceOpened(signal, signal.cited ?? action.kind)+ if (action.kind === 'recording') {+ openSessionPlayer({ id: action.sessionId }, action.startAt)+ }+ if (action.kind !== 'read') {+ return+ }+ if (preview?.code.length) {+ readCode(signal, preview.code)+ }+ expandEvidence(signal.signal_id)+ }++ return (+ <div className={cn('rounded-md transition-colors duration-150', expanded && 'bg-[var(--today-soft)]')}>+ <Item+ variant="default"+ size="sm"+ render={rowElement(action, hint, expanded)}+ onClick={hint ? onClick : undefined}+ aria-controls={expanded ? detailId : undefined}+ className={cn(+ 'group/row w-full rounded-md border-0 px-2 py-2 text-left text-foreground no-underline',+ expanded && 'hover:bg-transparent',+ !hint && 'cursor-default'+ )}+ title={[hint?.label, sourceLabel, signal.meta].filter(Boolean).join(' · ')}+ data-attr="today-report-signal"+ >+ <ItemContent className="min-w-0">+ <ItemTitle className={cn('font-normal text-foreground', !expanded && 'line-clamp-2')}>+ {expanded ? signal.lead : signal.headline}+ </ItemTitle>+ </ItemContent>+ <ItemActions className="shrink-0 self-start pt-0.5">+ <RowTrailer signal={signal} hint={hint} />+ </ItemActions>+ </Item>+ {expanded && preview && (+ <TodayEvidenceDetail id={detailId} reportId={reportId} signal={signal} preview={preview} open={open} />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/todayEvidence.test.ts b/frontend/src/scenes/project-homepage/today/todayEvidence.test.tsnew file mode 100644index 000000000000..9907bde14c0e--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayEvidence.test.ts@@ -0,0 +1,36 @@+import { signalDestination } from './todayEvidence'+import { signal } from './todayTestFixtures'++describe('todayEvidence', () => {+ test.each([+ [+ 'a recording without a start time, to its replay at the finding',+ signal({+ source_product: 'replay_vision',+ recording: { session_id: 's1', start_at: null, offset: '01:48', seek_seconds: 103 },+ }),+ { kind: 'link', to: '/replay/s1?t=103', external: false, label: 'Play at 01:48' },+ ],+ [+ 'a recording, just before the finding',+ signal({+ source_product: 'replay_vision',+ recording: { session_id: 's1', start_at: '2026-10-02T12:17:06Z', offset: '01:48', seek_seconds: 103 },+ }),+ { kind: 'recording', sessionId: 's1', startAt: Date.parse('2026-10-02T12:17:06Z'), offset: '01:48' },+ ],+ [+ 'an alert investigation, to its notebook',+ signal({ source_product: 'analytics', extra: { notebook_short_id: 'nb1' } }),+ { kind: 'link', to: '/notebooks/nb1', external: false, label: 'Open investigation' },+ ],+ [+ 'a finding with a link, to that link',+ signal({ link: { url: 'https://example.slack.com/archives/C1/p2', text: 'Open thread' } }),+ { kind: 'link', to: 'https://example.slack.com/archives/C1/p2', external: true, label: 'Open thread' },+ ],+ ['a finding without a link, to its own text', signal({}), { kind: 'read' }],+ ])('sends %s', (_, input, expected) => {+ expect(signalDestination(input)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayEvidence.ts b/frontend/src/scenes/project-homepage/today/todayEvidence.tsnew file mode 100644index 000000000000..0c10d8e95b04--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayEvidence.ts@@ -0,0 +1,97 @@+import { urls } from 'scenes/urls'++import type { InsightShortId } from '~/types'++import { conversationsTicketUrl, genericSignalLink } from 'products/signals/frontend/inbox/utils/signalLinks'+import type { SignalPreviewApi, SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { textOf } from './todaySignalText'++export type TodaySignalDestination =+ | { kind: 'recording'; sessionId: string; startAt: number | null; offset: string | null }+ | { kind: 'link'; to: string; external: boolean; label: string }+ | { kind: 'read' }++export interface TodayPreviewLink {+ to: string+ external: boolean+ label: string+}++type AppLink = (signal: SignalViewApi) => TodaySignalDestination | null++function link(to: string | null, label: string, external: boolean): TodaySignalDestination | null {+ return to ? { kind: 'link', to, external, label } : null+}++function errorIssue(signal: SignalViewApi): TodaySignalDestination | null {+ const fingerprint = textOf(signal.extra.fingerprint)+ const to = signal.source_id ? urls.errorTrackingIssue(signal.source_id, fingerprint ? { fingerprint } : {}) : null+ return link(to, 'Open issue', false)+}++function analyticsView(signal: SignalViewApi): TodaySignalDestination | null {+ const notebook = textOf(signal.extra.notebook_short_id)+ const insight = textOf(signal.extra.insight_short_id)+ return (+ link(notebook && urls.notebook(notebook), 'Open investigation', false) ??+ link(insight && urls.insightView(insight as InsightShortId), 'Open insight', false)+ )+}++const APP_LINKS: Record<string, AppLink> = {+ error_tracking: errorIssue,+ conversations: (signal) =>+ link(conversationsTicketUrl({ source_id: signal.source_id, extra: signal.extra }), 'Open ticket', false),+ analytics: analyticsView,+}++function recordingDestination(recording: NonNullable<SignalViewApi['recording']>): TodaySignalDestination {+ if (!recording.start_at && recording.seek_seconds !== null) {+ return {+ kind: 'link',+ to: urls.replaySingle(recording.session_id, { secondsOffsetFromStart: recording.seek_seconds }),+ external: false,+ label: `Play at ${recording.offset}`,+ }+ }+ const startAt = recording.start_at ? Date.parse(recording.start_at) : null+ return { kind: 'recording', sessionId: recording.session_id, startAt, offset: recording.offset }+}++export function signalDestination(signal: SignalViewApi): TodaySignalDestination {+ if (signal.recording) {+ return recordingDestination(signal.recording)+ }+ const own =+ link(signal.link?.url ?? null, signal.link?.text ?? '', true) ?? APP_LINKS[signal.source_product]?.(signal)+ if (own) {+ return own+ }+ const generic = genericSignalLink({+ source_product: signal.source_product,+ source_id: signal.source_id,+ extra: signal.extra,+ })+ return link(generic?.to ?? null, 'Open', generic?.external ?? false) ?? { kind: 'read' }+}++export function previewOpen(signal: SignalViewApi, destination: TodaySignalDestination): TodayPreviewLink | null {+ const preview = signal.preview+ if (preview?.link) {+ return { to: preview.link.url, external: true, label: preview.link.text }+ }+ if (destination.kind !== 'link') {+ return null+ }+ return { to: destination.to, external: destination.external, label: preview?.link_label ?? destination.label }+}++export function shownPreview(signal: SignalViewApi, open: TodayPreviewLink | null): SignalPreviewApi | null {+ const preview = signal.preview+ if (!preview) {+ return null+ }+ const hasContent = preview.code.length > 0 || preview.block.length > 0 || !!preview.text+ return hasContent || !open ? preview : null+}diff --git a/frontend/src/scenes/project-homepage/today/todayFigureSources.test.ts b/frontend/src/scenes/project-homepage/today/todayFigureSources.test.tsnew file mode 100644index 000000000000..711a99b6a126--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayFigureSources.test.ts@@ -0,0 +1,17 @@+import { dayjs } from 'lib/dayjs'++import { anchorToday } from './todayFigureSources'++describe('todayFigureSources', () => {+ test.each([+ [+ 'an older quote',+ '2026-09-04T10:00:00Z',+ 'A session from today hit it.',+ 'A session from today [4 Sep] hit it.',+ ],+ ['a quote from today', '2026-10-03T08:00:00Z', 'A session from today hit it.', 'A session from today hit it.'],+ ])('dates "today" in %s', (_, date, text, expected) => {+ expect(anchorToday(text, date, dayjs('2026-10-03T12:00:00Z'))).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayFigureSources.ts b/frontend/src/scenes/project-homepage/today/todayFigureSources.tsnew file mode 100644index 000000000000..4122bf222dba--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayFigureSources.ts@@ -0,0 +1,37 @@+import { Dayjs, dayjs } from 'lib/dayjs'++import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { shortDate } from './todayProse'++export interface TodayQuotedText {+ excerpt: string+ values?: string[]+}++export type TodayFigureCardContent =+ | ({+ kind: 'signal'+ signal: SignalViewApi+ working?: { expression: string; result: string }+ } & TodayQuotedText)+ | {+ kind: 'metric'+ total: string+ at: string | null+ range: { from: string; to: string } | null+ caption: string | null+ window: string | null+ trend: number[] | null+ chartType: 'bar' | 'line'+ link: { url: string; label: string } | null+ }+ | { kind: 'none' }++function daysAgo(date: string, now: Dayjs = dayjs()): number {+ return now.startOf('day').diff(dayjs(date).startOf('day'), 'day')+}++export function anchorToday(text: string, date: string, now: Dayjs = dayjs()): string {+ return daysAgo(date, now) > 0 ? text.replace(/\btoday\b/gi, (word) => `${word} [${shortDate(date)}]`) : text+}diff --git a/frontend/src/scenes/project-homepage/today/todayFigures.test.ts b/frontend/src/scenes/project-homepage/today/todayFigures.test.tsnew file mode 100644index 000000000000..0dbf104ab3a5--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayFigures.test.ts@@ -0,0 +1,23 @@+import { highlightSegments } from './todayFigures'++describe('todayFigures', () => {+ test.each([+ [+ 'each backing number once and never a day of the month',+ '4 failures on 2 Aug, 12 on 12 Aug, and 31 on 14 Aug.',+ ['4', '12', '31'],+ ['4', '12', '31'],+ ],+ ['an amount of money with its currency sign', 'About $4.2K in seven-day spend.', ['4.2'], ['$4.2K']],+ [+ 'numbers in the order the text states them',+ '30,000 calls at 120 ms each.',+ ['120', '30,000'],+ ['30,000', '120 ms'],+ ],+ ])('emphasizes %s', (_, text, values, expected) => {+ const segments = highlightSegments(text, values)+ expect(segments.filter((segment) => segment.marked).map((segment) => segment.text)).toEqual(expected)+ expect(segments.map((segment) => segment.text).join('')).toEqual(text)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayFigures.ts b/frontend/src/scenes/project-homepage/today/todayFigures.tsnew file mode 100644index 000000000000..871abba743d8--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayFigures.ts@@ -0,0 +1,62 @@+import type { TodayQuotedText } from './todayFigureSources'++const MONTH_AFTER = /^\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\b/++export interface TodayQuoteSegment {+ text: string+ marked: boolean+}++function withoutDigitCommas(text: string): string {+ return text.replace(/(\d),(?=\d{3}\b)/g, '$1')+}++function numberBody(value: string): string {+ const [whole, fraction] = withoutDigitCommas(value).split('.')+ return whole.split('').join(',?') + (fraction ? `\\.${fraction}` : '')+}++function numberPattern(value: string): RegExp {+ return new RegExp(`(?<![\\d.,/:-])${numberBody(value)}(?![\\d/:-]|[.,]\\d)`)+}++function firstMatch(text: string, value: string): { start: number; end: number } | null {+ const pattern = new RegExp(+ `(?:[$€£])?${numberPattern(value).source}(?:\\s?(?:ms|K|M)\\b|%|\\s(?:seconds?|minutes?|hours?)\\b)?`,+ 'g'+ )+ for (let match = pattern.exec(text); match; match = pattern.exec(text)) {+ const end = match.index + match[0].length+ if (!MONTH_AFTER.test(text.slice(end))) {+ return { start: match.index, end }+ }+ }+ return null+}++export function highlightSegments(text: string, values: string[]): TodayQuoteSegment[] {+ const matches = values+ .map((value) => firstMatch(text, value))+ .filter((match): match is { start: number; end: number } => match !== null)+ .sort((first, second) => first.start - second.start)+ const segments: TodayQuoteSegment[] = []+ let last = 0+ for (const match of matches) {+ if (match.start < last) {+ continue+ }+ if (match.start > last) {+ segments.push({ text: text.slice(last, match.start), marked: false })+ }+ segments.push({ text: text.slice(match.start, match.end), marked: true })+ last = match.end+ }+ if (last < text.length) {+ segments.push({ text: text.slice(last), marked: false })+ }+ return segments+}++export function quoteSegments(quote: TodayQuotedText, figure: string): TodayQuoteSegment[] {+ return highlightSegments(quote.excerpt, quote.values ?? [figure])+}diff --git a/frontend/src/scenes/project-homepage/today/todayImpact.test.ts b/frontend/src/scenes/project-homepage/today/todayImpact.test.tsnew file mode 100644index 000000000000..8d769bd15701--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayImpact.test.ts@@ -0,0 +1,28 @@+import { dailyTrend } from './todayImpact'++describe('todayImpact', () => {+ test.each([+ [+ 'starts at the first day with a value',+ { series: [0, 0, 3, 5], value_at: '2026-10-01T12:00:00Z', query: { source: { interval: 'day' } } },+ { data: [3, 5], since: '30 Sep', start: '2026-09-30' },+ ],+ [+ 'dates a series that has a value from its first day',+ { series: [2, 0, 3], value_at: '2026-10-01T12:00:00Z', query: { source: { interval: 'day' } } },+ { data: [2, 0, 3], since: null, start: '2026-09-29' },+ ],+ [+ 'keeps the whole window when it is not daily',+ { series: [0, 2, 3], value_at: '2026-10-01T12:00:00Z', query: { source: { interval: 'week' } } },+ { data: [0, 2, 3], since: null, start: null },+ ],+ [+ 'keeps a negative first day and reads a missing interval as daily',+ { series: [-2, 0, 3], value_at: '2026-10-01T12:00:00Z', query: { source: {} } },+ { data: [-2, 0, 3], since: null, start: '2026-09-29' },+ ],+ ])('builds a daily trend that %s', (_, metric, expected) => {+ expect(dailyTrend(metric as never)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayImpact.ts b/frontend/src/scenes/project-homepage/today/todayImpact.tsnew file mode 100644index 000000000000..7454c1291143--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayImpact.ts@@ -0,0 +1,159 @@+import { dayjs } from 'lib/dayjs'+import { isNotNil, isObject } from 'lib/utils/guards'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'+import { SignalReport } from 'products/signals/frontend/inbox/types'+import { chartOpenTarget } from 'products/signals/frontend/inbox/utils/chartOpenTarget'+import {+ asReportMetricTrendsQuery,+ reportMetricChartType,+ reportMetricRowParts,+ reportMetricWindowLabel,+ selectReportCardImpactMetric,+} from 'products/signals/frontend/inbox/utils/reportMetrics'+import type { ImpactNumberApi, ReportPageApi } from 'products/today/frontend/generated/api.schemas'++import type { TodayFigureCardContent } from './todayFigureSources'+import { shortDate } from './todayProse'+import { lowerFirst } from './todaySignalReports'++interface TodayDailyTrend {+ data: number[]+ since: string | null+ start: string | null+}++export interface TodayImpactNumber {+ key: string+ value: string+ label: string+ window: string | null+ content: TodayFigureCardContent+ chart: { data: number[]; type: 'bar' | 'line'; partialLast: boolean } | null+}++export function dailyTrend(metric: Pick<ReportMetricApi, 'series' | 'value_at' | 'query'>): TodayDailyTrend | null {+ const series = metric.series ?? []+ if (series.length < 2 || series.some((point) => !Number.isFinite(point))) {+ return null+ }+ const query = isObject(metric.query) ? (metric.query as { source?: { interval?: unknown } }) : {}+ const daily = (query.source?.interval ?? 'day') === 'day'+ const first = series.findIndex((point) => point !== 0)+ if (!daily || !metric.value_at || first < 0) {+ return { data: series, since: null, start: null }+ }+ const start = dayjs(metric.value_at).subtract(series.length - 1 - first, 'day')+ return {+ data: series.slice(first),+ since: first > 0 ? shortDate(start) : null,+ start: start.format('YYYY-MM-DD'),+ }+}++function asSentence(label: string): string {+ const text = lowerFirst(label)+ return /[.!?]$/.test(text) ? text : `${text}.`+}++function trendRange(trend: TodayDailyTrend | null): { from: string; to: string } | null {+ if (!trend?.start) {+ return null+ }+ const lastDay = dayjs(trend.start).add(trend.data.length - 1, 'day')+ return { from: shortDate(trend.start), to: `${shortDate(lastDay)} (partial)` }+}++function shownValue(metric: ReportMetricApi, value: number | null | undefined): string | null {+ const parts = reportMetricRowParts(metric, value)+ if (!parts) {+ return null+ }+ const format = metric.value_format ?? 'number'+ const formatCarriesUnit = format === 'currency' || format.startsWith('percentage')+ const titleNamesUnit = metric.title.toLowerCase().includes(parts.unit.toLowerCase())+ return parts.unit && !formatCarriesUnit && !titleNamesUnit ? `${parts.value} ${parts.unit}` : parts.value+}++function trendWindow(metric: ReportMetricApi, trend: TodayDailyTrend | null): string | null {+ if (!trend?.start) {+ return null+ }+ const additive = reportMetricChartType(metric) === 'bar'+ const peak = Math.max(...trend.data)+ const peakDay = shortDate(dayjs(trend.start).add(trend.data.indexOf(peak), 'day'))+ const peakText = peak > 0 || !additive ? `peak ${shownValue(metric, peak)} on ${peakDay}` : null+ return [additive ? 'in total' : null, peakText].filter(Boolean).join(' · ') || null+}++function metricChart(metric: ReportMetricApi, trend: TodayDailyTrend | null): TodayImpactNumber['chart'] {+ if (!trend || trend.data.length < 2) {+ return null+ }+ return { data: trend.data, type: reportMetricChartType(metric), partialLast: !!trend.start }+}++function shownWindow(trend: TodayDailyTrend | null, window: string | null): string | null {+ if (trend?.since) {+ return `First seen ${trend.since}`+ }+ return window && capitalizeFirstLetter(window)+}++function metricNumber(report: Pick<SignalReport, 'metrics'>): TodayImpactNumber | null {+ const metric = selectReportCardImpactMetric(report.metrics)+ const value = metric ? shownValue(metric, metric.value) : null+ if (!metric || !value) {+ return null+ }+ const trend = dailyTrend(metric)+ const window = reportMetricWindowLabel(metric.query)?.toLowerCase() ?? null+ const query = asReportMetricTrendsQuery(metric.query)+ return {+ key: 'metric',+ value,+ label: asSentence(metric.title.trim()),+ window: shownWindow(trend, window),+ chart: metricChart(metric, trend),+ content: {+ kind: 'metric',+ total: value,+ at: metric.value_at ?? null,+ range: trendRange(trend),+ caption: metric.caption ?? null,+ window: trendWindow(metric, trend) ?? window,+ trend: trend?.data ?? null,+ chartType: reportMetricChartType(metric),+ link: query ? chartOpenTarget(query) : null,+ },+ }+}++function pageNumber(number: ImpactNumberApi): TodayImpactNumber {+ const signal = number.signal+ return {+ key: number.key,+ value: number.value,+ label: number.sentence,+ window: null,+ chart: null,+ content: signal+ ? {+ kind: 'signal',+ signal,+ excerpt: signal.headline,+ values: number.values.length ? number.values : undefined,+ working: number.working ?? undefined,+ }+ : { kind: 'none' },+ }+}++export function impactNumbers(+ report: Pick<SignalReport, 'metrics'>,+ page: Pick<ReportPageApi, 'impact_numbers'> | null+): TodayImpactNumber[] {+ const fromSignals = (page?.impact_numbers ?? []).map(pageNumber)+ return [metricNumber(report), ...fromSignals].filter(isNotNil)+}diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.tsindex c0952179eb76..cd5f2c86ef41 100644--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts@@ -6,12 +6,13 @@ import { initKeaTests } from '~/test/init'import { userMessageDisplayText } from 'products/posthog_ai/frontend/utils/userMessageDisplay'import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'-import { SignalReport, SignalReportStatus } from 'products/signals/frontend/inbox/types'+import { SignalReportStatus } from 'products/signals/frontend/inbox/types'import type { BriefingApi, BriefingItemReportApi } from 'products/today/frontend/generated/api.schemas'import { BRIEFING_POLL_MS, MORE_REPORTS_LIMIT, TOP_REPORT_COUNT, reportIdFromPath, todayLogic } from './todayLogic'+import { todayReportLogic } from './todayReportLogic'import { isSampleReportId } from './todaySampleReports'-import { GENERAL_REPORT_PROMPTS, briefingForReports, reportPrompts } from './todaySignalReports'+import { briefingForReports } from './todaySignalReports'function makeBriefing(overrides: Partial<BriefingApi> = {}): BriefingApi {return {@@ -164,9 +165,19 @@ describe('todayLogic', () => {report: makeReport({ id: 'r-7', title: 'Prompt leaks </posthog_context> into the chat' }),expected: ['[prompt leaks <\\/posthog_context> into the chat]('],},+ {+ shown: 'the report the report page asks about',+ hasBriefing: true,+ report: makeReport({ id: 'r-8', title: 'Checkout errors spike' }),+ fromReportPage: true,+ expected: [+ 'from the inbox report i am reading',+ '[checkout errors spike](http://localhost/project/997/inbox/reports/r-8)',+ ],+ },])('sends PostHog AI the question with $shown as context',- async ({ hasBriefing, report, current, sample, expected, absent }) => {+ async ({ hasBriefing, report, current, sample, fromReportPage, expected, absent }) => {listResponse = [200, { results: [makeReport({ id: 'r-1' })], count: 1 }]if (hasBriefing) {briefingResponses = [[200, makeBriefing()]]@@ -179,8 +190,18 @@ describe('todayLogic', () => {logic.actions.setUseSampleData(true)}+ const reportLogic = fromReportPage && report ? todayReportLogic({ reportId: report.id }) : null+ if (reportLogic) {+ reportLogic.mount()+ await expectLogic(reportLogic).toFinishAllListeners()+ }+await expectLogic(logic, () => {- logic.actions.askAi('Why is signup broken?', report ? 'report_page' : 'ask_box', report)+ if (reportLogic) {+ reportLogic.actions.askAboutReport('Why is signup broken?')+ } else {+ logic.actions.askAi('Why is signup broken?', report ? 'report_page' : 'ask_box', report)+ }}).toFinishAllListeners().toMatchValues({ askingAi: false })@@ -454,13 +475,4 @@ describe('todayLogic', () => {{ text: 'LLM costs doubled', reportId: 'c' },])})-- test.each([- ['an action-capable report', {}, ['Draft the fix']],- ['a report with a pull request', { implementation_pr_url: 'https://example.com/1' }, GENERAL_REPORT_PROMPTS],- ['a report judged not actionable', { actionability: 'not_actionable' }, GENERAL_REPORT_PROMPTS],- ])('offers the right prompts for %s', (_, overrides, expected) => {- const report = makeReport({ suggested_prompts: ['Draft the fix'], ...(overrides as Partial<SignalReport>) })- expect(reportPrompts(report)).toEqual(expected)- })})diff --git a/frontend/src/scenes/project-homepage/today/todayNextStep.test.ts b/frontend/src/scenes/project-homepage/today/todayNextStep.test.tsnew file mode 100644index 000000000000..2d45341d97a5--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayNextStep.test.ts@@ -0,0 +1,132 @@+import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'+import { SignalReport } from 'products/signals/frontend/inbox/types'++import { reportWorkKind, startDisabledReason, todayNextStep } from './todayNextStep'++const RUN = { taskId: 't1', runId: 'r1' }++const CLAIMED_BY_TASK = makeReport({+ assignee: {+ kind: 'task',+ task_id: 't1',+ claimed_at: '2026-08-11T09:00:00Z',+ user: null,+ agent: null,+ claim_id: 'c1',+ },+})++describe('todayNextStep', () => {+ test.each([+ [+ 'an open pull request',+ makeReport({+ pull_requests: [+ { url: 'https://github.com/example/web/pull/1', state: 'draft', merged: false },+ ] as unknown as SignalReport['pull_requests'],+ }),+ null,+ {+ primary: { kind: 'review', url: 'https://github.com/example/web/pull/1', label: 'Review draft PR #1' },+ note: null,+ },+ ],+ [+ 'a merged pull request',+ makeReport({+ pull_requests: [+ { url: 'https://github.com/example/web/pull/1', state: 'closed', merged: true },+ ] as unknown as SignalReport['pull_requests'],+ }),+ null,+ { primary: null, note: 'The fix is merged. Resolve the report once it is live.' },+ ],+ [+ 'a task that claimed the report and has no run yet',+ CLAIMED_BY_TASK,+ null,+ { primary: { kind: 'start' }, note: 'A PostHog task picked this up on 11 Aug.' },+ ],+ [+ 'a task that claimed the report and runs',+ CLAIMED_BY_TASK,+ RUN,+ {+ primary: { kind: 'open_task', label: 'Open the running task', taskId: 't1', runId: 'r1' },+ note: null,+ },+ ],+ [+ 'a fix already in flight',+ makeReport({ already_addressed: true }),+ null,+ { primary: null, note: 'A fix is already in flight. The full report links to it.' },+ ],+ ['an untouched report', makeReport({}), null, { primary: { kind: 'start' }, note: null }],+ ])('names the next step for %s', (_, input, runningTask, expected) => {+ const { primary, note } = todayNextStep(input, {+ namedPullRequest: null,+ solutionNamesPullRequest: false,+ slotClaimed: false,+ runningTask,+ })+ expect({ primary, note }).toEqual(expected)+ })++ test.each([+ ['a task claim', CLAIMED_BY_TASK, 'A task already picked this up.'],+ [+ 'a person claim, which leaves PostHog free to start',+ makeReport({+ actionability: 'immediately_actionable',+ assignee: {+ kind: 'user',+ task_id: null,+ claimed_at: '2026-08-11T09:00:00Z',+ user: { first_name: 'Ada', last_name: '', email: '[email protected]' },+ agent: null,+ claim_id: 'c2',+ } as unknown as SignalReport['assignee'],+ }),+ null,+ ],+ ])('blocks starting with PostHog only for %s', (_, input, expected) => {+ const { taskPickedUp } = todayNextStep(input, {+ namedPullRequest: null,+ solutionNamesPullRequest: false,+ slotClaimed: false,+ runningTask: null,+ })+ expect(+ startDisabledReason(input, taskPickedUp, { createPrDisabledReason: null, aiConsentDisabledReason: null })+ ).toEqual(expected)+ })++ test.each([+ ['an implementation', 'immediately_actionable', 'Free trials can’t open pull requests.'],+ ['an investigation', 'requires_human_input', null],+ ])('keeps the free trial limit to %s', (_, actionability, expected) => {+ const report = makeReport({ actionability: actionability as SignalReport['actionability'] })+ expect(+ startDisabledReason(report, false, {+ createPrDisabledReason: 'Free trials can’t open pull requests.',+ aiConsentDisabledReason: null,+ })+ ).toEqual(expected)+ })++ test.each([+ [+ 'implement for a ready, actionable report',+ { actionability: 'immediately_actionable', status: 'ready' },+ 'implement',+ ],+ [+ 'investigate when it needs a person',+ { actionability: 'requires_human_input', status: 'pending_input' },+ 'investigate',+ ],+ ])('chooses %s', (_, input, expected) => {+ expect(reportWorkKind(input as never)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayNextStep.ts b/frontend/src/scenes/project-homepage/today/todayNextStep.tsnew file mode 100644index 000000000000..ab889dcb9049--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayNextStep.ts@@ -0,0 +1,171 @@+import { fullName } from 'lib/utils/strings'++import { buildReportImplementationPrompt } from 'products/signals/frontend/inbox/components/detail/buildReportImplementationPrompt'+import { isActionCapableReport } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import type { SignalReport } from 'products/signals/frontend/inbox/types'+import { canResolveReport } from 'products/signals/frontend/inbox/utils/reportActions'+import { parsePrUrlParts, safeHttpUrl } from 'products/signals/frontend/inbox/utils/reportPresentation'+import { primaryReportPullRequest } from 'products/signals/frontend/inbox/utils/reportPullRequests'+import type { PullRequestLinkApi } from 'products/today/frontend/generated/api.schemas'++import { shortDate } from './todayProse'++export type TodayPrimaryAction =+ | { kind: 'review'; url: string; label: string }+ | { kind: 'open_task'; label: string; taskId: string; runId: string }+ | { kind: 'start' }++interface TodayNextStep {+ primary: TodayPrimaryAction | null+ note: string | null+ taskPickedUp: boolean+}++interface TodayNextStepContext {+ namedPullRequest: PullRequestLinkApi | null+ solutionNamesPullRequest: boolean+ slotClaimed: boolean+ runningTask: { taskId: string; runId: string } | null+}++const START: TodayPrimaryAction = { kind: 'start' }+const REVIEW_NOTES: Record<string, string> = {+ approved: 'Approved and ready to merge.',+ changes_requested: 'A reviewer asked for changes.',+}++function reviewLabel(url: string, draft: boolean): string {+ const number = parsePrUrlParts(url)?.number+ const name = draft ? 'draft PR' : 'PR'+ return number ? `Review ${name} #${number}` : `Review ${name}`+}++function pickedUpOn(date: string | null | undefined): string {+ return date ? ` on ${shortDate(date)}` : ''+}++function claimant(assignee: NonNullable<SignalReport['assignee']>): string {+ const name = assignee.user ? fullName(assignee.user) || assignee.user.email : null+ return name ?? assignee.agent ?? 'An agent'+}++function namedPullRequestReview({ namedPullRequest }: TodayNextStepContext): TodayPrimaryAction | null {+ return namedPullRequest+ ? { kind: 'review', url: namedPullRequest.url, label: `View PR #${namedPullRequest.number}` }+ : null+}++function alreadyAddressed(context: TodayNextStepContext): TodayNextStep {+ const review = namedPullRequestReview(context)+ if (review) {+ return { primary: review, note: null, taskPickedUp: false }+ }+ return {+ primary: null,+ note: context.solutionNamesPullRequest ? null : 'A fix is already in flight. The full report links to it.',+ taskPickedUp: false,+ }+}++function pullRequestStep(report: SignalReport): TodayNextStep | null {+ const pullRequest = primaryReportPullRequest(report)+ const url = safeHttpUrl(pullRequest.url ?? '')+ if (!url) {+ return null+ }+ if (pullRequest.merged) {+ return { primary: null, note: 'The fix is merged. Resolve the report once it is live.', taskPickedUp: false }+ }+ if (pullRequest.state === 'closed') {+ return null+ }+ return {+ primary: { kind: 'review', url, label: reviewLabel(url, pullRequest.state === 'draft') },+ note: REVIEW_NOTES[pullRequest.review_decision ?? ''] ?? null,+ taskPickedUp: false,+ }+}++function pickedUpStep(report: SignalReport, context: TodayNextStepContext): TodayNextStep | null {+ const assignee = report.assignee ?? null+ const taskPickedUp = context.slotClaimed || assignee?.kind === 'task'+ if (taskPickedUp && context.runningTask) {+ const primary = { kind: 'open_task' as const, label: 'Open the running task', ...context.runningTask }+ return { primary, note: null, taskPickedUp: true }+ }+ if (taskPickedUp) {+ return {+ primary: namedPullRequestReview(context) ?? START,+ note: `A PostHog task picked this up${pickedUpOn(assignee?.claimed_at)}.`,+ taskPickedUp: true,+ }+ }+ if (assignee?.kind === 'user' || assignee?.kind === 'agent') {+ return {+ primary: namedPullRequestReview(context) ?? START,+ note: `${claimant(assignee)} picked this up${pickedUpOn(assignee.claimed_at)}.`,+ taskPickedUp: false,+ }+ }+ return null+}++export function todayNextStep(report: SignalReport, context: TodayNextStepContext): TodayNextStep {+ const step = pullRequestStep(report) ?? pickedUpStep(report, context)+ if (step) {+ return step+ }+ if (report.already_addressed) {+ return alreadyAddressed(context)+ }+ return { primary: START, note: null, taskPickedUp: false }+}++type TodayWorkKind = 'implement' | 'investigate'++export function reportWorkKind(report: Pick<SignalReport, 'actionability' | 'status'>): TodayWorkKind {+ return report.actionability === 'immediately_actionable' && report.status !== 'pending_input'+ ? 'implement'+ : 'investigate'+}++function buildReportInvestigationPrompt(report: Pick<SignalReport, 'id'>, reportUrl: string): string {+ return `Investigate the PostHog Inbox report at ${reportUrl} (report ID: ${report.id}).++Use the PostHog MCP tools to read the report and its full work log with inbox-report-artefacts-list. Confirm the problem it describes against the current code and data, and find the root cause.++Reply with what you found: whether the problem is real, what causes it, how many people it affects, and the smallest fix you would make. Do not change code, open a pull request, or change the report's state.`+}++export function resolveDisabledReason(report: SignalReport, sampleReason: string | null): string | null {+ if (sampleReason) {+ return sampleReason+ }+ return canResolveReport(report) ? null : 'You can resolve a report only after the agent finishes its research.'+}++export interface TodayKickoffReasons {+ createPrDisabledReason: string | null+ aiConsentDisabledReason: string | null+}++export function startDisabledReason(+ report: SignalReport,+ taskPickedUp: boolean,+ { createPrDisabledReason, aiConsentDisabledReason }: TodayKickoffReasons+): string | null {+ if (taskPickedUp) {+ return 'A task already picked this up.'+ }+ if (!isActionCapableReport(report)) {+ return 'This report can’t start work. Ask about it instead.'+ }+ return reportWorkKind(report) === 'implement' ? createPrDisabledReason : aiConsentDisabledReason+}++export function reportWorkPrompt(report: SignalReport, reportUrl: string): string {+ if (reportWorkKind(report) === 'implement') {+ return buildReportImplementationPrompt(report, reportUrl)+ }+ return buildReportInvestigationPrompt(report, reportUrl)+}diff --git a/frontend/src/scenes/project-homepage/today/todayPenPaths.ts b/frontend/src/scenes/project-homepage/today/todayPenPaths.tsnew file mode 100644index 000000000000..7b8dcce83619--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayPenPaths.ts@@ -0,0 +1,72 @@+type Point = [number, number]++function random(seed: string): () => number {+ let state = 2166136261+ for (const character of seed) {+ state = Math.imul(state ^ character.charCodeAt(0), 16777619)+ }+ return () => {+ state = Math.imul(state ^ (state >>> 15), 2246822507)+ state = Math.imul(state ^ (state >>> 13), 3266489909)+ return ((state ^= state >>> 16) >>> 0) / 4294967296+ }+}++function format([x, y]: Point): string {+ return `${x.toFixed(2)} ${y.toFixed(2)}`+}++function smooth(points: Point[]): string {+ let path = `M${format(points[0])}`+ for (let index = 1; index < points.length - 1; index++) {+ const [x, y] = points[index]+ const [nextX, nextY] = points[index + 1]+ path += ` Q${format([x, y])} ${format([(x + nextX) / 2, (y + nextY) / 2])}`+ }+ return `${path} L${format(points[points.length - 1])}`+}++function strokePass(next: () => number, from: number, to: number, height: number): string {+ const tilt = (next() - 0.6) * 2.4+ const wave = (next() - 0.5) * 2.2+ const waves = [0, wave, -wave, 0]+ const points = [0, 0.33, 0.66, 1].map(+ (progress, index): Point => [+ from + (to - from) * progress,+ height + tilt * (progress - 0.5) + waves[index] + (next() - 0.5) * 0.6,+ ]+ )+ const [start, first, second, end] = points.map(format)+ return `M${start} C${first} ${second} ${end}`+}++export function underlinePaths(seed: string): [string, string] {+ const next = random(seed)+ return [+ strokePass(next, 1 + next() * 2, 97 + next() * 2, 4.4),+ strokePass(next, 5 + next() * 6, 92 + next() * 6, 6.6),+ ]+}++const LOOP_SQUARENESS = 0.85++export function circlePath(seed: string): string {+ const next = random(`${seed}-circle`)+ const start = -2.5 + (next() - 0.5) * 0.4+ const sweep = Math.PI * 2 * (1.12 + next() * 0.05)+ const tilt = (next() - 0.5) * 0.08+ const steps = 32+ const points: Point[] = []+ for (let index = 0; index <= steps; index++) {+ const progress = index / steps+ const angle = start + sweep * progress+ const radiusX = 1 - 0.03 * progress + (next() - 0.5) * 0.02+ const radiusY = 1 - 0.12 * progress + (next() - 0.5) * 0.04+ const cos = Math.cos(angle)+ const sin = Math.sin(angle)+ const x = 49 * radiusX * Math.sign(cos) * Math.abs(cos) ** LOOP_SQUARENESS+ const y = 46 * radiusY * Math.sign(sin) * Math.abs(sin) ** LOOP_SQUARENESS+ points.push([50 + x - y * tilt, 50 + y + x * tilt])+ }+ return smooth(points)+}diff --git a/frontend/src/scenes/project-homepage/today/todayProse.test.ts b/frontend/src/scenes/project-homepage/today/todayProse.test.tsnew file mode 100644index 000000000000..35723a46a556--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayProse.test.ts@@ -0,0 +1,57 @@+import { inlineSegments, renderedText } from './todayProse'++describe('todayProse', () => {+ test.each([+ [+ 'a bare pull request URL',+ 'Fixed in https://github.com/example/web/pull/12, so P2.',+ [+ { kind: 'text', text: 'Fixed in ' },+ { kind: 'link', text: '#12', href: 'https://github.com/example/web/pull/12' },+ { kind: 'text', text: ', so P2.' },+ ],+ ],+ [+ 'a labelled link',+ 'See [the PR](https://github.com/example/web/pull/12).',+ [+ { kind: 'text', text: 'See ' },+ { kind: 'link', text: 'the PR', href: 'https://github.com/example/web/pull/12' },+ { kind: 'text', text: '.' },+ ],+ ],+ [+ 'a URL in code',+ 'Run `curl https://github.com/example/web/pull/12`.',+ [+ { kind: 'text', text: 'Run ' },+ { kind: 'code', text: 'curl https://github.com/example/web/pull/12' },+ { kind: 'text', text: '.' },+ ],+ ],+ ])('shortens GitHub links only in prose: %s', (_, markdown, expected) => {+ expect(inlineSegments(markdown)).toEqual(expected)+ })++ test.each([+ ['a valid date', 'Since 2026-08-03.', 'Since 3 Aug.'],+ ['a day its month does not have, left as written', 'Since 2026-02-30.', 'Since 2026-02-30.'],+ ['a date in code, left as written', 'Run `at 2026-08-03`.', 'Run at 2026-08-03.'],+ ['a month that does not exist, left as written', 'Since 2026-13-01.', 'Since 2026-13-01.'],+ ['a date in year zero, left as written', 'Since 0000-01-01.', 'Since 0000-01-01.'],+ ])('rewrites %s the way the backend does', (_, markdown, expected) => {+ expect(renderedText(markdown)).toEqual(expected)+ })++ test('splits inline markdown into text, code and links, dropping bold markers', () => {+ expect(+ inlineSegments('Run `retrieve` for **41 teams**, see [#12](https://github.com/example/web/pull/12).')+ ).toEqual([+ { kind: 'text', text: 'Run ' },+ { kind: 'code', text: 'retrieve' },+ { kind: 'text', text: ' for 41 teams, see ' },+ { kind: 'link', text: '#12', href: 'https://github.com/example/web/pull/12' },+ { kind: 'text', text: '.' },+ ])+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayProse.ts b/frontend/src/scenes/project-homepage/today/todayProse.tsnew file mode 100644index 000000000000..9393cd016bdb--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayProse.ts@@ -0,0 +1,109 @@+import { fromMarkdown } from 'mdast-util-from-markdown'++import { Dayjs, dayjs } from 'lib/dayjs'++const BARE_GITHUB_LINK = /(?<![(<[])https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/(?:pull|issues)\/(\d+)(?![\w/])/g++export function shortDate(date: string | number | Dayjs): string {+ return dayjs(date).format('D MMM')+}++const ISO_DATE = /\b(\d{4}-\d{2}-\d{2})\b/g++function readableDate(match: string): string {+ const [year, month, day] = match.split('-').map(Number)+ const date = new Date(Date.UTC(year, month - 1, day))+ const exists = year >= 1 && date.getUTCMonth() === month - 1 && date.getUTCDate() === day+ return exists ? shortDate(dayjs(match)) : match+}++function readableDates(text: string): string {+ return text.replace(ISO_DATE, readableDate)+}++type TodayInlineSegment = { kind: 'text' | 'code'; text: string } | { kind: 'link'; text: string; href: string }++interface MarkdownNode {+ type: string+ value?: string+ url?: string+ alt?: string | null+ children?: MarkdownNode[]+}++const INLINE_ONLY = {+ disable: {+ null: [+ 'blockQuote',+ 'codeFenced',+ 'codeIndented',+ 'definition',+ 'headingAtx',+ 'htmlFlow',+ 'list',+ 'setextUnderline',+ 'thematicBreak',+ ],+ },+}++function nodeText(node: MarkdownNode): string {+ return node.value ?? node.alt ?? (node.children ?? []).map(nodeText).join('')+}++function proseSegments(text: string): TodayInlineSegment[] {+ const segments: TodayInlineSegment[] = []+ let last = 0+ for (const match of text.matchAll(BARE_GITHUB_LINK)) {+ segments.push({ kind: 'text', text: readableDates(text.slice(last, match.index)) })+ segments.push({ kind: 'link', text: `#${match[1]}`, href: match[0] })+ last = match.index + match[0].length+ }+ segments.push({ kind: 'text', text: readableDates(text.slice(last)) })+ return segments+}++function labelText(node: MarkdownNode): string {+ if (node.type === 'text') {+ return readableDates(node.value ?? '')+ }+ return node.children ? node.children.map(labelText).join('') : nodeText(node)+}++function nodeSegments(node: MarkdownNode): TodayInlineSegment[] {+ switch (node.type) {+ case 'text':+ return proseSegments(node.value ?? '')+ case 'inlineCode':+ return [{ kind: 'code', text: node.value ?? '' }]+ case 'link':+ return [{ kind: 'link', text: labelText(node), href: node.url ?? '' }]+ case 'break':+ return [{ kind: 'text', text: ' ' }]+ default:+ return node.children ? node.children.flatMap(nodeSegments) : [{ kind: 'text', text: nodeText(node) }]+ }+}++function joinedText(segments: TodayInlineSegment[]): TodayInlineSegment[] {+ return segments.reduce<TodayInlineSegment[]>((joined, segment) => {+ const previous = joined[joined.length - 1]+ if (previous?.kind === 'text' && segment.kind === 'text') {+ joined[joined.length - 1] = { kind: 'text', text: previous.text + segment.text }+ } else {+ joined.push(segment)+ }+ return joined+ }, [])+}++export function inlineSegments(markdown: string): TodayInlineSegment[] {+ const tree: MarkdownNode = fromMarkdown(markdown.replace(/\s+/g, ' ').trim(), { extensions: [INLINE_ONLY] })+ return joinedText(nodeSegments(tree)).filter((segment) => segment.text)+}++export function renderedText(markdown: string): string {+ return inlineSegments(markdown)+ .map((segment) => segment.text)+ .join('')+}diff --git a/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.ts b/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.tsnew file mode 100644index 000000000000..54e09788e1b9--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.ts@@ -0,0 +1,100 @@+import type { RepositoryFileApi } from 'products/business_knowledge/frontend/generated/api.schemas'++import { codeExcerptCandidates, codeIdentifiers, findCodeQuote } from './todayQuotedCode'++function read(path: string, lines: string[]): RepositoryFileApi {+ return { content: lines.join('\n'), url: `https://github.com/example/shop/blob/abc/${path}` } as RepositoryFileApi+}++const OWN = { repo: 'example/shop', path: 'src/cards/Cards.tsx' }+const SIBLING = { repo: 'example/shop', path: 'src/cards/cardsLogic.ts' }+const OWN_READ = read(OWN.path, ['export function Cards(): JSX.Element {', ' return <List />', '}'])+const SIBLING_READ = read(SIBLING.path, ['const PAGE_SIZE = 50', 'export const CARDS_MAX = 120'])++describe('todayQuotedCode', () => {+ test('keeps member expressions and drops file names and blank spans', () => {+ expect(codeIdentifiers('`response.json` and `Math.max` in `Cards.tsx`, then ` `.')).toEqual([+ 'response.json',+ 'Math.max',+ ])+ })++ test('picks the lines a finding quotes and marks the quoted code', () => {+ const file = [+ "import { useValues } from 'kea'",+ '',+ 'export function CartRow({ productId }: Props): JSX.Element {',+ ' const { prices } = useValues(pricesLogic)',+ ' const price = prices[productId]',+ ' return <Price price={price} />',+ '}',+ ].join('\n')+ const identifiers = codeIdentifiers(+ '`CartRow.tsx` calls `useValues` on the store-wide logic and reads `prices[productId]` afterward.'+ )+ expect(identifiers).toEqual(['useValues', 'prices[productId]'])+ expect(codeExcerptCandidates(file, identifiers)[0]).toEqual({+ startLine: 3,+ lines: [+ 'export function CartRow({ productId }: Props): JSX.Element {',+ ' const { prices } = useValues(pricesLogic)',+ ' const price = prices[productId]',+ ' return <Price price={price} />',+ '}',+ ],+ marks: [+ { line: 1, start: 23, end: 32 },+ { line: 2, start: 18, end: 35 },+ ],+ })+ })++ test('marks every quoted name on a line in reading order, whatever order the finding names them in', () => {+ const [excerpt] = codeExcerptCandidates('total = helper(compute_total())', ['compute_total', 'helper'])+ expect(excerpt.marks).toEqual([+ { line: 0, start: 8, end: 14 },+ { line: 0, start: 15, end: 28 },+ ])+ })++ test('shows the lines that hold the most distinct pieces of the quoted code', () => {+ const gap = Array(9).fill('')+ const file = [+ 'const a = rareName',+ ...gap,+ 'one(commonName, otherName)',+ ...gap,+ 'two(commonName)',+ ...gap,+ 'three(otherName)',+ ].join('\n')+ expect(codeExcerptCandidates(file, ['rareName', 'commonName', 'otherName'])[0]?.startLine).toEqual(11)+ })++ test('offers each separate place that holds most of the quoted code', () => {+ const file = [+ 'actions({',+ ' addItem: (id: string) => ({ id }),',+ ' removeItem: (id: string) => ({ id }),',+ '}),',+ ...Array(6).fill(''),+ 'reducers({',+ ' items: [',+ ' {},',+ ' {',+ ' addItem: (state, { id }) => ({ ...state, [id]: true }),',+ ' removeItem: (state, { id }) => ({ ...state, [id]: false }),',+ ].join('\n')+ expect(+ codeExcerptCandidates(file, ['items', 'addItem', 'removeItem']).map((excerpt) => excerpt.startLine)+ ).toEqual([11, 1])+ })++ test.each([+ ['the sibling file that holds the quote', [OWN_READ, SIBLING_READ], 'cardsLogic.ts'],+ ['nothing when no file holds the quote', [OWN_READ, null], null],+ ])('chooses %s', (_, reads, expected) => {+ const chosen = findCodeQuote([OWN, SIBLING], reads, ['CARDS_MAX = 120'])+ expect(chosen?.file.path.split('/').pop() ?? null).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayQuotedCode.ts b/frontend/src/scenes/project-homepage/today/todayQuotedCode.tsnew file mode 100644index 000000000000..e073b7418e41--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayQuotedCode.ts@@ -0,0 +1,143 @@+import type { RepositoryFileApi } from 'products/business_knowledge/frontend/generated/api.schemas'+import type { CodeFileApi } from 'products/today/frontend/generated/api.schemas'++const CODE_SPAN = /`([^`\n]{3,80})`/g+const FILE_NAME = /^[\w-]+\.(?:tsx?|jsx?|mjs|py|rb|go|rs|java|kt|swift|css|scss|html|md|ya?ml|toml|sql|sh)$/i+const MAX_IDENTIFIERS = 12+const MAX_MARKS = 12++export function codeIdentifiers(content: string): string[] {+ const spans = [...content.matchAll(CODE_SPAN)].map((match) => match[1].trim())+ const identifiers = spans.filter((span) => span && !span.includes('/') && !FILE_NAME.test(span))+ return [...new Set(identifiers)].slice(0, MAX_IDENTIFIERS)+}++function occurrences(text: string, part: string): number {+ let count = 0+ for (let at = text.indexOf(part); at >= 0; at = text.indexOf(part, at + part.length)) {+ count+++ }+ return count+}++export interface TodayCodeWindow {+ startLine: number+ lines: string[]+ marks: { line: number; start: number; end: number }[]+}++const EXCERPT_CONTEXT_LINES = 2+const EXCERPT_WINDOW_LINES = 5+const MAX_EXCERPT_CANDIDATES = 5+const CANDIDATE_SLACK = 2+const IMPORT_LINE = /^\s*(import\b|from\s+\S+\s+import\b|export\s+\{.*\}\s+from\b)/++interface ScoredAnchor {+ anchor: number+ found: number+ score: number+}++function scoredAnchors(fileLines: string[], content: string, identifiers: string[]): ScoredAnchor[] {+ const weight = new Map(+ identifiers.map((identifier) => [identifier, 1 / Math.max(1, occurrences(content, identifier))])+ )+ const anchors: ScoredAnchor[] = []+ fileLines.forEach((line, index) => {+ if (IMPORT_LINE.test(line) || !identifiers.some((identifier) => line.includes(identifier))) {+ return+ }+ const window = fileLines+ .slice(Math.max(0, index - EXCERPT_CONTEXT_LINES), index + EXCERPT_WINDOW_LINES + 1)+ .join('\n')+ const found = identifiers.filter((identifier) => window.includes(identifier))+ const rarity = found.reduce((total, identifier) => total + (weight.get(identifier) ?? 0), 0)+ anchors.push({ anchor: index, found: found.length, score: found.length + rarity / (identifiers.length + 1) })+ })+ return anchors.sort((first, second) => second.score - first.score || first.anchor - second.anchor)+}++function excerptAt(fileLines: string[], identifiers: string[], anchor: number): TodayCodeWindow {+ let start = Math.max(0, anchor - EXCERPT_CONTEXT_LINES)+ let end = Math.min(fileLines.length - 1, anchor + EXCERPT_WINDOW_LINES)+ while (start < anchor && !fileLines[start].trim()) {+ start+++ }+ while (end > anchor && !fileLines[end].trim()) {+ end--+ }+ const window = fileLines.slice(start, end + 1)+ const indent = Math.min(+ ...window.filter((line) => line.trim()).map((line) => line.length - line.trimStart().length)+ )+ const lines = window.map((line) => line.slice(indent))+ const marks = lines.flatMap((line, index) =>+ identifiers.flatMap((identifier) => {+ const found: { line: number; start: number; end: number }[] = []+ let at = line.indexOf(identifier)+ while (at >= 0) {+ found.push({ line: index, start: at, end: at + identifier.length })+ at = line.indexOf(identifier, at + identifier.length)+ }+ return found+ })+ )+ marks.sort((first, second) => first.line - second.line || first.start - second.start)+ return { startLine: start + 1, lines, marks: marks.slice(0, MAX_MARKS) }+}++export function codeExcerptCandidates(+ content: string,+ identifiers: string[],+ limit: number = MAX_EXCERPT_CANDIDATES+): TodayCodeWindow[] {+ if (!identifiers.length) {+ return []+ }+ const fileLines = content.split('\n')+ const anchors = scoredAnchors(fileLines, content, identifiers)+ const mostFound = anchors[0]?.found ?? 0+ const excerpts: TodayCodeWindow[] = []+ for (const { anchor, found } of anchors) {+ if (excerpts.length >= limit || found < Math.max(1, mostFound - CANDIDATE_SLACK)) {+ break+ }+ const excerpt = excerptAt(fileLines, identifiers, anchor)+ const last = excerpt.startLine + excerpt.lines.length - 1+ const overlaps = excerpts.some(+ (taken) => excerpt.startLine <= taken.startLine + taken.lines.length - 1 && last >= taken.startLine+ )+ if (!overlaps) {+ excerpts.push(excerpt)+ }+ }+ return excerpts+}++export interface TodayCodeQuote {+ file: CodeFileApi+ read: RepositoryFileApi+ excerpt: TodayCodeWindow+}++function distinctMarked(excerpt: TodayCodeWindow): number {+ return new Set(excerpt.marks.map((mark) => excerpt.lines[mark.line].slice(mark.start, mark.end))).size+}++export function findCodeQuote(+ files: CodeFileApi[],+ reads: (RepositoryFileApi | null)[],+ identifiers: string[]+): TodayCodeQuote | null {+ let best: TodayCodeQuote | null = null+ for (const [index, file] of files.entries()) {+ const read = reads[index]+ const candidates = read ? codeExcerptCandidates(read.content, identifiers) : []+ const excerpt = candidates[0]+ const marksMore = !best || (excerpt && distinctMarked(excerpt) > distinctMarked(best.excerpt))+ if (read && excerpt && marksMore) {+ best = { file, read, excerpt }+ }+ }+ return best+}diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.tsnew file mode 100644index 000000000000..ab545ebd4772--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts@@ -0,0 +1,64 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'+import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'+import { SignalReport, SignalReportStatus } from 'products/signals/frontend/inbox/types'+import type { ReportPageApi } from 'products/today/frontend/generated/api.schemas'++import { todayReportLogic } from './todayReportLogic'++const PAGE: ReportPageApi = {+ lead: 'Checkout fails for Safari users.',+ proposal: '',+ impact_sentence: '',+ named_pull_request: null,+ solution_names_pull_request: false,+ evidence: [],+ source_count: 0,+ impact_numbers: [],+ last_seen: null,+}++describe('todayReportLogic', () => {+ test.each([+ [+ 'implements a report that is ready to act on',+ { actionability: 'immediately_actionable', status: SignalReportStatus.READY },+ ['createPrFromReport'] as const,+ 'discussReport',+ ],+ [+ 'investigates a report that needs a person',+ { actionability: 'requires_human_input', status: SignalReportStatus.PENDING_INPUT },+ ['openReportDiscussion', 'discussReport'] as const,+ 'createPrFromReport',+ ],+ ])('starting with PostHog %s through a task linked to the report', async (_, overrides, kickoffs, other) => {+ const report = makeReport(overrides as Partial<SignalReport>)+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/': () => [200, report],+ '/api/projects/:team_id/today/reports/:id/page/': () => [200, PAGE],+ },+ })+ initKeaTests()+ const kickoffLogic = inboxTaskKickoffLogic()+ kickoffLogic.mount()+ const logic = todayReportLogic({ reportId: report.id })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadFullReportSuccess', 'loadPageSuccess'])++ await expectLogic(kickoffLogic, () => logic.actions.startWithPostHog())+ .toDispatchActions(+ kickoffs.map(+ (kickoff) =>+ (action: { type: string; payload: Record<string, any> }): boolean =>+ action.type === kickoffLogic.actionTypes[kickoff] && action.payload.report.id === report.id+ )+ )+ .toNotHaveDispatchedActions([other])+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.tsindex a81e2bc9a760..eb638db2d495 100644--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.ts@@ -1,18 +1,38 @@-import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import api from 'lib/api'+import { addProjectIdIfMissing } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'-import { signalsReportsSignalsRetrieve } from 'products/signals/frontend/generated/api'-import { ReportChartApi, SignalNodeApi } from 'products/signals/frontend/generated/api.schemas'+import { businessKnowledgeRepositoriesFileRetrieve } from 'products/business_knowledge/frontend/generated/api'+import type { RepositoryFileApi } from 'products/business_knowledge/frontend/generated/api.schemas'+import { captureInboxReportAction, discussQuestionProperties } from 'products/signals/frontend/inbox/inboxAnalytics'+import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { SignalReport } from 'products/signals/frontend/inbox/types'-import { ChartPlacements, resolveChartPlacements } from 'products/signals/frontend/inbox/utils/chartPlacement'-import type { BriefingItemStateEnumApi } from 'products/today/frontend/generated/api.schemas'+import { todayReportsPageRetrieve } from 'products/today/frontend/generated/api'+import type {+ BriefingItemStateEnumApi,+ CodeFileApi,+ ReportPageApi,+ SignalViewApi,+} from 'products/today/frontend/generated/api.schemas'import { reportItemState } from './todayBriefingItems'-import { todayLogic } from './todayLogic'-import { findSampleReport, isSampleReportId, sampleSignals } from './todaySampleReports'+import { type TodaySignalDestination } from './todayEvidence'+import { TodayImpactNumber, impactNumbers } from './todayImpact'+import { type TodayAskSource, todayLogic } from './todayLogic'+import { reportWorkKind, reportWorkPrompt } from './todayNextStep'+import { renderedText } from './todayProse'+import { TodayCodeQuote, codeIdentifiers, findCodeQuote } from './todayQuotedCode'+import { findSampleReport, isSampleReportId } from './todaySampleReports'++export type TodayCodeQuoteState = TodayCodeQuote | null | 'loading'+export type TodayMarkKind = 'impact'++const INVESTIGATE_QUESTION = 'Investigate this report. Confirm the problem and find the root cause.'export interface TodayReportLogicProps {reportId: string@@ -20,23 +40,101 @@ export interface TodayReportLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todayReportLogicValues {+ currentProjectId: number | string // teamLogic+ currentTeamId: number | null // teamLogic+ askingAi: boolean // todayLogicreportStateOverrides: Record<string, BriefingItemStateEnumApi> // todayLogicreports: SignalReport[] // todayLogic- chartPlacements: ChartPlacements- chartsById: Map<string, ReportChartApi>+ codeQuotes: Record<string, TodayCodeQuoteState>+ composerOpen: booleancurrentReport: SignalReport | null+ draft: string+ evidenceCount: number+ expandedEvidence: Record<string, boolean>+ feedbackNoteFocused: booleanfullReport: SignalReport | nullfullReportLoading: boolean+ impactNumbers: TodayImpactNumber[]+ impactText: string+ isSample: boolean+ lead: string+ leadStatesNumber: boolean+ page: ReportPageApi | null+ pageLoading: boolean+ proposal: stringreportFailed: boolean- reportSignals: SignalNodeApi[] | null- reportSignalsLoading: booleanreportState: BriefingItemStateEnumApi- signals: SignalNodeApi[]- trailingCharts: ReportChartApi[]+ reportUrl: string+ shownEvidence: SignalViewApi[]}// 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+ ) => {+ agentQuestion: string | undefined+ intent: import('products/signals/frontend/inbox/inboxTaskKickoffLogic').ReportDiscussionIntent | 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+ askAboutReport: (question: string) => {+ question: string+ }+ codeQuoteCleared: (signalId: string) => {+ signalId: string+ }+ 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+ }+ focusFeedbackNote: () => {+ value: true+ }loadFullReport: () => anyloadFullReportFailure: (error: string,@@ -52,21 +150,40 @@ export interface todayReportLogicActions {fullReport: SignalReportpayload?: any}- loadReportSignals: () => any- loadReportSignalsFailure: (+ loadPage: () => any+ loadPageFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadReportSignalsSuccess: (- reportSignals: SignalNodeApi[],+ loadPageSuccess: (+ page: ReportPageApi,payload?: any) => {- reportSignals: SignalNodeApi[]+ page: ReportPageApipayload?: any}+ markOpened: (kind: TodayMarkKind) => {+ kind: 'impact'+ }+ openComposer: () => {+ value: true+ }+ readCode: (+ signal: SignalViewApi,+ files: CodeFileApi[]+ ) => {+ files: CodeFileApi[]+ signal: SignalViewApi+ }+ setDraft: (draft: string) => {+ draft: string+ }+ startWithPostHog: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -78,14 +195,19 @@ export interface todayReportLogicMeta {reports: SignalReport[],reportFailed: boolean) => SignalReport | null- chartPlacements: (currentReport: SignalReport | null) => ChartPlacements- chartsById: (currentReport: SignalReport | null) => Map<string, ReportChartApi>- trailingCharts: (currentReport: SignalReport | null, chartPlacements: ChartPlacements) => ReportChartApi[]- signals: (reportSignals: SignalNodeApi[] | null) => SignalNodeApi[]+ lead: (page: ReportPageApi | null) => string+ shownEvidence: (page: ReportPageApi | null) => SignalViewApi[]+ evidenceCount: (page: ReportPageApi | null) => number+ impactNumbers: (currentReport: SignalReport | null, page: ReportPageApi | null) => TodayImpactNumber[]reportState: (currentReport: SignalReport | null,reportStateOverrides: Record<string, BriefingItemStateEnumApi>) => BriefingItemStateEnumApi+ isSample: (reportId: string) => boolean+ proposal: (page: ReportPageApi | null) => string+ impactText: (page: ReportPageApi | null, impactNumbers: TodayImpactNumber[]) => string+ leadStatesNumber: (lead: string) => boolean+ reportUrl: (currentTeamId: number | null) => string}}@@ -100,13 +222,43 @@ export const todayReportLogic = kea<todayReportLogicType>([props({} as TodayReportLogicProps),key((props) => props.reportId),path((reportId) => ['scenes', 'project-homepage', 'today', 'todayReportLogic', reportId]),- connect(() => ({ values: [todayLogic, ['reports', 'reportStateOverrides']] })),- loaders(({ props }) => ({+ connect(() => ({+ values: [+ teamLogic,+ ['currentTeamId', 'currentProjectId'],+ todayLogic,+ ['reports', 'reportStateOverrides', 'askingAi'],+ ],+ actions: [+ todayLogic,+ ['askAi'],+ 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 }),+ askAboutReport: (question: string) => ({ question }),+ expandEvidence: (signalId: string) => ({ signalId }),+ collapseEvidence: (signalId: string) => ({ signalId }),+ openComposer: true,+ setDraft: (draft: string) => ({ draft }),+ focusFeedbackNote: true,+ startWithPostHog: true,+ markOpened: (kind: TodayMarkKind) => ({ kind }),+ }),+ loaders(({ props, values }) => ({fullReport: [null as SignalReport | null,{loadFullReport: async () => {- if (isSampleReportId(props.reportId)) {+ if (values.isSample) {const report = findSampleReport(props.reportId)if (!report) {throw new Error('Sample report not found')@@ -118,24 +270,50 @@ export const todayReportLogic = kea<todayReportLogicType>([},},],- reportSignals: [- null as SignalNodeApi[] | null,+ page: [+ null as ReportPageApi | null,{- loadReportSignals: async (): Promise<SignalNodeApi[]> => {- if (isSampleReportId(props.reportId)) {- return sampleSignals(props.reportId)- }- const response = await signalsReportsSignalsRetrieve(- String(teamLogic.values.currentTeamId),- props.reportId- )- return response.signals- },+ loadPage: async (): Promise<ReportPageApi> =>+ await todayReportsPageRetrieve(String(values.currentProjectId), props.reportId),},],})),reducers({- reportFailed: [false, { loadFullReport: () => false, loadFullReportFailure: () => true }],+ 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+ },+ },+ ],+ expandedEvidence: [+ {} as Record<string, boolean>,+ {+ expandEvidence: (state, { signalId }) => ({ ...state, [signalId]: true }),+ collapseEvidence: (state, { signalId }) => ({ ...state, [signalId]: false }),+ },+ ],+ composerOpen: [false, { openComposer: () => true }],+ feedbackNoteFocused: [false, { focusFeedbackNote: () => 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.@@ -145,31 +323,13 @@ export const todayReportLogic = kea<todayReportLogicType>([(fullReport: SignalReport | null, reports: SignalReport[], reportFailed: boolean): SignalReport | null =>reportFailed ? null : (fullReport ?? reports.find((report) => report.id === props.reportId) ?? null),],- chartPlacements: [- (s) => [s.currentReport],- (currentReport: SignalReport | null): ChartPlacements =>- resolveChartPlacements(- currentReport?.summary,- (currentReport?.charts ?? []).map((chart) => chart.chart_id)- ),- ],- chartsById: [- (s) => [s.currentReport],- (currentReport: SignalReport | null): Map<string, ReportChartApi> =>- new Map((currentReport?.charts ?? []).map((chart) => [chart.chart_id, chart])),- ],- trailingCharts: [- (s) => [s.currentReport, s.chartPlacements],- (currentReport: SignalReport | null, chartPlacements: ChartPlacements): ReportChartApi[] =>- (currentReport?.charts ?? []).filter((chart) => !chartPlacements.inlineIds.has(chart.chart_id)),- ],- // The API returns signals oldest first, and the newest one is the most useful to read first.- signals: [- (s) => [s.reportSignals],- (reportSignals: SignalNodeApi[] | null): SignalNodeApi[] =>- [...(reportSignals ?? [])].sort(- (first, second) => new Date(second.timestamp).getTime() - new Date(first.timestamp).getTime()- ),+ 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],+ 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: [@@ -181,9 +341,112 @@ export const todayReportLogic = kea<todayReportLogicType>([reportStateOverrides[props.reportId] ??(currentReport ? reportItemState(currentReport.status) : 'open'),],+ isSample: [(_, p) => [p.reportId], (reportId: string): boolean => isSampleReportId(reportId)],+ 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 ?? ''),+ ],+ leadStatesNumber: [(s) => [s.lead], (lead: string): boolean => /\d/.test(renderedText(lead))],+ 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)+ }+ return {+ 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+ }+ actions.codeQuoteRead(signal.signal_id, 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.loadReportSignals()+ actions.loadPage()}),])diff --git a/frontend/src/scenes/project-homepage/today/todaySampleReports.ts b/frontend/src/scenes/project-homepage/today/todaySampleReports.tsindex f1e490edfdaf..c578bfd76350 100644--- a/frontend/src/scenes/project-homepage/today/todaySampleReports.ts+++ b/frontend/src/scenes/project-homepage/today/todaySampleReports.ts@@ -1,5 +1,4 @@-import type { SignalNode } from 'scenes/debug/signals/types'-+import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'import { SignalReport, SignalReportStatus } from 'products/signals/frontend/inbox/types'import type { TodayReports } from './todayLogic'@@ -7,6 +6,7 @@ import { TodayBriefingSegment } from './todaySignalReports'// Sample ids carry this prefix, so a report page knows to read the fixture rather than the API.const SAMPLE_ID_PREFIX = 'sample-'+export const SAMPLE_REPORT_REASON = 'This is a sample report. Turn off sample reports to act on a real one.'const HOUR_MS = 60 * 60 * 1000export function isSampleReportId(reportId: string): boolean {@@ -35,13 +35,9 @@ interface SampleReportSpec {status: SignalReportStatussourceProducts: string[]pullRequestUrl?: string+ metrics?: ReportMetricApi[]suggestedPrompts?: string[]- signals: {- sourceProduct: SignalNode['source_product']- sourceType: SignalNode['source_type']- content: string- hoursAgo: number- }[]+ signalCount: number}// The Hedgebox demo scenarios from the Today mock, all invented. Signals leave `extra` empty so they render as@@ -51,39 +47,26 @@ const SAMPLE_SPECS: SampleReportSpec[] = [id: `${SAMPLE_ID_PREFIX}pr`,title: 'Review PR #9123',summary:- '**The Safari checkout fix is ready for review.**\n\nTuesday’s deploy stopped some Safari users before payment. The checkout sent an empty billing address to the payment service.\n\nPR #9123 restores the address before payment is submitted. The change is small, tested, and ready for you.',+ 'Safari users can’t finish checkout since Tuesday’s deploy, because the checkout sends an empty billing address to the payment service.\n\n## Problem\n\nThe deploy moved the address form into a step that Safari unmounts before payment. The payment request then goes out without the billing address.\n\n## Impact\n\nSafari checkout completion fell by 12 points while Chrome stayed flat.\n\n## Solution\n\nKeep the billing address in the checkout state, and send it with the payment request. PR #9123 does this and adds a Safari test.\n\n## Expected impact\n\nSafari checkout completion returns to **about 54%**, the same as Chrome.',hoursAgo: 2,priority: 'P1',actionability: 'immediately_actionable',status: SignalReportStatus.READY,sourceProducts: ['error_tracking', 'session_replay', 'analytics', 'github'],pullRequestUrl: 'https://github.com/example/hedgebox/pull/9123',- signals: [- {- sourceProduct: 'error_tracking',- sourceType: 'issue',- content: '1,284 events. The same TypeError started after deploy #4821.',- hoursAgo: 2,- },+ metrics: [{- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: '38 recordings. Safari users stop after they submit payment.',- hoursAgo: 3,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '−12 points. Safari completion fell while Chrome stayed flat.',- hoursAgo: 4,- },- {- sourceProduct: 'github',- sourceType: 'issue',- content: 'PR #9123. The fix restores the missing billing address.',- hoursAgo: 5,+ metric_id: 'safari-checkout-failures',+ title: 'Users who could not finish checkout in Safari',+ kind: 'affected_users',+ role: 'primary',+ value: 212,+ series: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 58, 64, 59],+ value_format: 'count',+ unit: 'users',},],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}exp`,@@ -95,32 +78,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [actionability: 'immediately_actionable',status: SignalReportStatus.READY,sourceProducts: ['analytics', 'session_replay'],- signals: [- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Experiments · 95% likely. The one-page version is the likely winner.',- hoursAgo: 3,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '+6.4%. Checkout completion rose from 54.1% to 57.6%.',- hoursAgo: 4,- },- {- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: 'Fewer exits. People no longer pause between address and payment.',- hoursAgo: 5,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Feature flags · Ready. The winning variant can reach everyone now.',- hoursAgo: 6,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}safari`,@@ -132,32 +90,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [actionability: 'requires_human_input',status: SignalReportStatus.PENDING_INPUT,sourceProducts: ['session_replay', 'analytics', 'error_tracking'],- signals: [- {- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: '38 sessions. Every sampled session stalls after payment.',- hoursAgo: 5,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '49% complete. Safari trails Chrome by 13 points.',- hoursAgo: 6,- },- {- sourceProduct: 'error_tracking',- sourceType: 'issue',- content: 'address.ts:42. The billing address is empty at submission.',- hoursAgo: 7,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Data warehouse · Safari 17. Older Safari versions stay near their baseline.',- hoursAgo: 8,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}error`,@@ -170,32 +103,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [status: SignalReportStatus.READY,sourceProducts: ['error_tracking', 'analytics', 'session_replay'],pullRequestUrl: 'https://github.com/example/hedgebox/pull/9131',- signals: [- {- sourceProduct: 'error_tracking',- sourceType: 'issue',- content: '1,284 events. TypeError in formatAddress at address.ts:42.',- hoursAgo: 7,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '412 users. Most affected users arrived from Safari.',- hoursAgo: 8,- },- {- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: '19 sampled. The submit button stops after one click.',- hoursAgo: 9,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Data warehouse · Deploy #4821. The first event arrived six minutes after release.',- hoursAgo: 10,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}llm`,@@ -208,32 +116,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [status: SignalReportStatus.READY,sourceProducts: ['llm_analytics', 'analytics'],pullRequestUrl: 'https://github.com/example/hedgebox/pull/9140',- signals: [- {- sourceProduct: 'llm_analytics',- sourceType: 'evaluation',- content: '+31% cost. Cost rose while the number of summaries stayed flat.',- hoursAgo: 9,- },- {- sourceProduct: 'llm_analytics',- sourceType: 'evaluation',- content: 'Tracing · 2.4× tokens. The new prompt repeats the source document.',- hoursAgo: 10,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Usage flat. The same number of people used summaries.',- hoursAgo: 11,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Data warehouse · summarize-doc. One workflow accounts for 84% of the increase.',- hoursAgo: 12,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}nps`,@@ -245,32 +128,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [actionability: 'requires_human_input',status: SignalReportStatus.PENDING_INPUT,sourceProducts: ['conversations', 'analytics', 'session_replay'],- signals: [- {- sourceProduct: 'conversations',- sourceType: 'feedback',- content: 'Surveys · NPS 32. Twenty-three of 61 detractors mention pricing.',- hoursAgo: 20,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Customer analytics · Small teams. Growing teams express the most uncertainty.',- hoursAgo: 21,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '71% visited. Most detractors saw the new pricing page.',- hoursAgo: 22,- },- {- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: '3 comparisons. People revisit the usage table before leaving.',- hoursAgo: 23,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}browser`,@@ -283,32 +141,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [status: SignalReportStatus.PENDING_INPUT,sourceProducts: ['analytics', 'session_replay', 'error_tracking'],pullRequestUrl: 'https://github.com/example/hedgebox/pull/9123',- signals: [- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '−13 points. Safari trails the other browsers at checkout.',- hoursAgo: 26,- },- {- sourceProduct: 'session_replay',- sourceType: 'session_problem',- content: '38 sessions. The same payment stall appears across sampled sessions.',- hoursAgo: 27,- },- {- sourceProduct: 'error_tracking',- sourceType: 'issue',- content: '1,284 events. The error appears mainly in Safari 17.',- hoursAgo: 28,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Data warehouse · 3 browsers. Chrome and Firefox stay near their baseline.',- hoursAgo: 29,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}guardrails`,@@ -320,32 +153,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [actionability: 'immediately_actionable',status: SignalReportStatus.READY,sourceProducts: ['analytics', 'error_tracking', 'conversations'],- signals: [- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Experiments · 4 passed. Every release guardrail stayed within range.',- hoursAgo: 30,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: '+6.4%. Checkout completion improved for the winning variant.',- hoursAgo: 31,- },- {- sourceProduct: 'error_tracking',- sourceType: 'issue',- content: 'No increase. Payment and checkout errors stayed flat.',- hoursAgo: 32,- },- {- sourceProduct: 'conversations',- sourceType: 'feedback',- content: 'Surveys · Support flat. The new flow did not increase support requests.',- hoursAgo: 33,- },- ],+ signalCount: 4,},{id: `${SAMPLE_ID_PREFIX}traces`,@@ -358,32 +166,7 @@ const SAMPLE_SPECS: SampleReportSpec[] = [status: SignalReportStatus.READY,sourceProducts: ['llm_analytics', 'analytics'],pullRequestUrl: 'https://github.com/example/hedgebox/pull/9147',- signals: [- {- sourceProduct: 'llm_analytics',- sourceType: 'evaluation',- content: 'Tracing · 24 traces. Each sampled trace contains the source text twice.',- hoursAgo: 40,- },- {- sourceProduct: 'llm_analytics',- sourceType: 'evaluation',- content: '2.4× tokens. Input tokens rose after the model change.',- hoursAgo: 41,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Usage flat. Traffic did not cause the higher cost.',- hoursAgo: 42,- },- {- sourceProduct: 'analytics',- sourceType: 'anomaly_investigation',- content: 'Data warehouse · Quality flat. The quality score did not improve.',- hoursAgo: 43,- },- ],+ signalCount: 4,},]@@ -420,8 +203,8 @@ function buildSampleReport(spec: SampleReportSpec, now: number): SignalReport {title: spec.title,summary: spec.summary,status: spec.status,- total_weight: spec.signals.length,- signal_count: spec.signals.length,+ total_weight: spec.signalCount,+ signal_count: spec.signalCount,created_at: updatedAt,updated_at: updatedAt,artefact_count: 0,@@ -433,6 +216,7 @@ function buildSampleReport(spec: SampleReportSpec, now: number): SignalReport {implementation_pr_url: spec.pullRequestUrl ?? null,suggested_prompts: spec.suggestedPrompts,charts: [],+ metrics: spec.metrics ?? [],}}@@ -447,17 +231,3 @@ export function findSampleReport(reportId: string, now: number = Date.now()): Siconst spec = SAMPLE_SPECS.find((candidate) => candidate.id === reportId)return spec ? buildSampleReport(spec, now) : null}--export function sampleSignals(reportId: string, now: number = Date.now()): SignalNode[] {- const spec = SAMPLE_SPECS.find((candidate) => candidate.id === reportId)- return (spec?.signals ?? []).map((signal, index) => ({- signal_id: `${reportId}-signal-${index}`,- content: signal.content,- source_product: signal.sourceProduct,- source_type: signal.sourceType,- source_id: `${reportId}-source-${index}`,- weight: 1,- timestamp: new Date(now - signal.hoursAgo * HOUR_MS).toISOString(),- extra: {} as SignalNode['extra'],- }))-}diff --git a/frontend/src/scenes/project-homepage/today/todaySignalReports.test.ts b/frontend/src/scenes/project-homepage/today/todaySignalReports.test.tsnew file mode 100644index 000000000000..e76f348251a2--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todaySignalReports.test.ts@@ -0,0 +1,28 @@+import { reportSourceLine, scoutLabel } from './todaySignalReports'++describe('todaySignalReports', () => {+ test.each([+ ['signals-scout-checkout-github-issues', 'Checkout GitHub issues scout'],+ ['signals-scout-react-render', 'React render scout'],+ ['signals-scout-self-driving-ui', 'Self-driving UI scout'],+ ])('names the scout for skill %s', (skill, expected) => {+ expect(scoutLabel(skill)).toEqual(expected)+ })++ test.each([+ ['one source', { source_products: ['error_tracking'] }, { line: 'Error tracking', title: 'Error tracking' }],+ [+ 'a scout by its skill',+ { source_products: ['signals_scout'], scout_name: 'signals-scout-react-render' },+ { line: 'React render scout', title: 'React render scout' },+ ],+ [+ 'more sources than fit',+ { source_products: ['error_tracking', 'session_replay', 'conversations'] },+ { line: 'Error tracking, Session replay +1', title: 'Error tracking, Session replay, Support' },+ ],+ ['no sources', { source_products: [], scout_name: null }, { line: 'Signals', title: '' }],+ ])('names the sources of %s', (_, report, expected) => {+ expect(reportSourceLine(report)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todaySignalReports.ts b/frontend/src/scenes/project-homepage/today/todaySignalReports.tsindex 7fb4391a9e4f..6bf76f18273d 100644--- a/frontend/src/scenes/project-homepage/today/todaySignalReports.ts+++ b/frontend/src/scenes/project-homepage/today/todaySignalReports.ts@@ -1,11 +1,29 @@import { dayjs } from 'lib/dayjs'+import { scoutDisplayName } from 'lib/signals/signalCardSourceLine'import type { TodayReportCard } from '~/layout/today/todayPreviewCards'-import { isActionCapableReport } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { SignalReport } from 'products/signals/frontend/inbox/types'-export type TodayReportIcon = 'pr' | 'replay' | 'error' | 'llm' | 'survey' | 'analytics' | 'trace' | 'inbox'+export type TodayReportIcon =+ | 'pr'+ | 'replay'+ | 'error'+ | 'llm'+ | 'support'+ | 'survey'+ | 'analytics'+ | 'logs'+ | 'alert'+ | 'scout'+ | 'github'+ | 'gitlab'+ | 'linear'+ | 'jira'+ | 'database'+ | 'signal'+ | 'code'+ | 'slack'/** One run of text in the briefing. A run with `reportId` links to that report. */export interface TodayBriefingSegment {@@ -28,37 +46,32 @@ const SOURCES: Record<string, TodayReportSource> = {replay_vision: { label: 'Replay vision', color: 'var(--color-product-session-replay-light)', icon: 'replay' },llm_analytics: { label: 'LLM analytics', color: 'var(--color-product-llm-analytics-light)', icon: 'llm' },analytics: { label: 'Product analytics', color: 'var(--color-product-product-analytics-light)', icon: 'analytics' },- conversations: { label: 'Support', color: 'var(--color-product-support-light)', icon: 'survey' },- zendesk: { label: 'Zendesk', color: 'var(--color-product-support-light)', icon: 'survey' },+ conversations: { label: 'Support', color: 'var(--color-product-support-light)', icon: 'support' },+ zendesk: { label: 'Zendesk', color: 'var(--color-product-support-light)', icon: 'support' },surveys: { label: 'Surveys', color: 'var(--color-product-surveys-light)', icon: 'survey' },- logs: { label: 'Logs', color: 'var(--color-product-logs-light)', icon: 'trace' },- github: { label: 'GitHub', color: 'var(--color-text-secondary)', icon: 'pr' },- gitlab: { label: 'GitLab', color: 'var(--color-text-secondary)', icon: 'pr' },- linear: { label: 'Linear', color: 'var(--color-text-secondary)', icon: 'inbox' },- jira: { label: 'Jira', color: 'var(--color-text-secondary)', icon: 'inbox' },+ logs: { label: 'Logs', color: 'var(--color-product-logs-light)', icon: 'logs' },+ github: { label: 'GitHub', color: 'var(--color-text-secondary)', icon: 'github' },+ gitlab: { label: 'GitLab', color: 'var(--color-text-secondary)', icon: 'gitlab' },+ linear: { label: 'Linear', color: 'var(--color-text-secondary)', icon: 'linear' },+ jira: { label: 'Jira', color: 'var(--color-text-secondary)', icon: 'jira' },+ signals_scout: { label: 'Scout', color: 'var(--color-text-secondary)', icon: 'scout' },+ pganalyze: { label: 'pganalyze', color: 'var(--color-text-secondary)', icon: 'database' },// Today item sources that are not signal products.product_analytics: {label: 'Product analytics',color: 'var(--color-product-product-analytics-light)',icon: 'analytics',},- alerts: { label: 'Alerts', color: 'var(--color-product-product-analytics-light)', icon: 'trace' },- support: { label: 'Support', color: 'var(--color-product-support-light)', icon: 'survey' },+ alerts: { label: 'Alerts', color: 'var(--color-product-product-analytics-light)', icon: 'alert' },+ support: { label: 'Support', color: 'var(--color-product-support-light)', icon: 'support' },}const FALLBACK_SOURCE: TodayReportSource = {- label: 'Self-driving',+ label: 'Signals',color: 'var(--color-text-secondary)',- icon: 'inbox',+ icon: 'signal',}-/** Questions that only ask for an answer, so they are safe to offer on any report. */-export const GENERAL_REPORT_PROMPTS = [- 'Why is this happening?',- 'Who is affected, and how badly?',- 'What would you look at first?',-]-export function reportTitle(report: Pick<SignalReport, 'title'>): string {return report.title?.trim() || 'Untitled report'}@@ -108,17 +121,7 @@ export function reportMeta(report: Pick<SignalReport, 'source_products' | 'updatreturn `${reportSource(report).label} · ${dayjs(report.updated_at).fromNow()}`}-/**- * The prompts offered under a report. The report's own suggestions can ask for action, so they are- * offered only where the Inbox offers them too. Every other report gets questions that only ask for- * an answer.- */-export function reportPrompts(report: SignalReport): string[] {- const suggested = isActionCapableReport(report) ? (report.suggested_prompts ?? []) : []- return suggested.length ? suggested : GENERAL_REPORT_PROMPTS-}--function lowerFirst(text: string): string {+export function lowerFirst(text: string): string {// Keep acronyms such as "API" or "LLM" as they are.return /^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text}@@ -143,3 +146,56 @@ export function briefingForReports(reports: SignalReport[]): TodayBriefingSegmen}return paragraphs}++const SHOWN_SOURCES = 2+const SOURCE_LINE_CHARS = 32++const PROPER_WORDS: Record<string, string> = {+ ai: 'AI',+ api: 'API',+ github: 'GitHub',+ llm: 'LLM',+ mcp: 'MCP',+ posthog: 'PostHog',+ pr: 'PR',+ sql: 'SQL',+ ui: 'UI',+ ux: 'UX',+}++export function scoutLabel(skillName: string | null | undefined): string | null {+ const name = scoutDisplayName(skillName)+ if (!name) {+ return null+ }+ const words = name.split(' ').map((word) => PROPER_WORDS[word.toLowerCase()] ?? word)+ return `${words.join(' ').replace(/\b(self) (driving)\b/i, '$1-$2')} scout`+}++export function priorityBadgeVariant(priority: string | null | undefined): 'destructive' | 'warning' | 'default' {+ if (priority === 'P0' || priority === 'P1') {+ return 'destructive'+ }+ return priority === 'P2' ? 'warning' : 'default'+}++export function reportSourceLine(report: Pick<SignalReport, 'source_products' | 'scout_name'>): {+ line: string+ title: string+} {+ const scout = scoutLabel(report.scout_name)+ const labels = [+ ...new Set(+ (report.source_products ?? []).map((source) =>+ source === 'signals_scout' ? (scout ?? 'Scout') : sourceStyle(source).label+ )+ ),+ ]+ if (labels.length === 0) {+ return { line: scout ?? sourceStyle(null).label, title: '' }+ }+ const count = labels.slice(0, SHOWN_SOURCES).join(', ').length > SOURCE_LINE_CHARS ? 1 : SHOWN_SOURCES+ const shown = labels.slice(0, count).join(', ')+ const rest = labels.length - count+ return { line: rest > 0 ? `${shown} +${rest}` : shown, title: labels.join(', ') }+}diff --git a/frontend/src/scenes/project-homepage/today/todaySignalText.ts b/frontend/src/scenes/project-homepage/today/todaySignalText.tsnew file mode 100644index 000000000000..3b4633139532--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todaySignalText.ts@@ -0,0 +1,15 @@+import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'++import { scoutLabel, sourceStyle } from './todaySignalReports'++export function textOf(value: unknown): string | null {+ return typeof value === 'string' && value.trim() ? value.trim() : null+}++export function signalSourceLabel(signal: Pick<SignalViewApi, 'source_product' | 'extra'>): string {+ const label = sourceStyle(signal.source_product).label+ if (signal.source_product !== 'signals_scout') {+ return label+ }+ return scoutLabel(textOf(signal.extra.skill_name)) ?? label+}diff --git a/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts b/frontend/src/scenes/project-homepage/today/todayTestFixtures.tsnew file mode 100644index 000000000000..f3bc593dbaf4--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts@@ -0,0 +1,21 @@+import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'++export function signal(overrides: Partial<SignalViewApi>): SignalViewApi {+ return {+ signal_id: 'signal-1',+ content: '',+ source_product: 'signals_scout',+ source_type: 'cross_source_issue',+ source_id: 'source-1',+ timestamp: '2026-10-01T10:00:00Z',+ extra: {},+ headline: '',+ lead: '',+ meta: '',+ cited: null,+ recording: null,+ link: null,+ preview: null,+ ...overrides,+ }+}diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 354fc982755e..696811102b59 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -129,9 +129,10 @@ export type InboxReportActionType =/*** Where the text of an "Ask AI" question came from. `suggested` is a scout-authored question sent as- * written, `edited_suggestion` one the reader changed first, and `typed` one written from scratch.+ * written, `edited_suggestion` one the reader changed first, `typed` one written from scratch, and+ * `preset` a fixed question that a button sends, such as Today's Investigate with PostHog.*/-export type InboxQuestionSource = 'suggested' | 'edited_suggestion' | 'typed'+export type InboxQuestionSource = 'suggested' | 'edited_suggestion' | 'typed' | 'preset'/*** Extra properties the `discuss` {@link captureInboxReportAction} carries. Without them the eventdiff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex acfd407217ab..5c2a9d01f9fc 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -66,6 +66,7 @@ import {captureInboxReportAction,captureInboxReportFeedback,captureInboxReportFeedbackNote,+ InboxReportActionSurface,InboxReportFeedbackSentiment,} from '../inboxAnalytics'import { inboxSceneLogic } from '../inboxSceneLogic'@@ -557,8 +558,12 @@ export interface inboxReportDetailLogicActions {postReviewCommentFinished: () => {value: true}- rateReport: (sentiment: InboxReportFeedbackSentiment) => {+ rateReport: (+ sentiment: InboxReportFeedbackSentiment,+ surface?: InboxReportActionSurface+ ) => {sentiment: InboxReportFeedbackSentiment+ surface: InboxReportActionSurface}searchAvailableReviewers: (query: string) => {query: string@@ -587,8 +592,12 @@ export interface inboxReportDetailLogicActions {setSelectedTaskId: (taskId: string | null) => {taskId: string | null}- submitFeedbackNote: (note: string) => {+ submitFeedbackNote: (+ note: string,+ surface?: InboxReportActionSurface+ ) => {note: string+ surface: InboxReportActionSurface}toggleExpandedTask: (taskId: string) => {taskId: string@@ -721,12 +730,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([toggleExpandedTask: (taskId: string) => ({ taskId }),// Thumbs feedback at the end of the report body. Recorded server-side as a report action// (consumption evidence) – nothing about the report's state changes.- rateReport: (sentiment: InboxReportFeedbackSentiment) => ({ sentiment }),+ rateReport: (sentiment: InboxReportFeedbackSentiment, surface: InboxReportActionSurface = 'detail_footer') => ({+ sentiment,+ surface,+ }),// Optional note, offered only after a rating is in. The rating is never held up waiting for it.openFeedbackNote: true,setFeedbackNoteDraft: (draft: string) => ({ draft }),// The note rides on the payload: the reducers below clear the draft, and listeners run after them.- submitFeedbackNote: (note: string) => ({ note }),+ submitFeedbackNote: (note: string, surface: InboxReportActionSurface = 'detail_footer') => ({ note, surface }),cancelReportCheck: (checkId: string) => ({ checkId }),// Fired whether the cancel succeeded or failed, so the row's button always comes back.cancelReportCheckDone: (checkId: string) => ({ checkId }),@@ -1442,11 +1454,11 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([})}},- rateReport: ({ sentiment }) => {+ rateReport: ({ sentiment, surface }) => {if (!values.report) {return}- captureInboxReportFeedback({ report: values.report, sentiment, surface: 'detail_footer' })+ captureInboxReportFeedback({ report: values.report, sentiment, surface })// Best-effort server-side record of the bare rating: consumption evidence the scout// inactivity sweep reads, so rating a report keeps its scout from being auto-paused.// The analytics event above stays the durable record of the rating itself.@@ -1455,7 +1467,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([}).catch(() => {})},// Fires on its own event so the rating stays exactly one `Inbox report feedback` per click.- submitFeedbackNote: async ({ note }) => {+ submitFeedbackNote: async ({ note, surface }) => {const trimmed = note.trim()if (!values.report || !values.feedbackSentiment || !trimmed) {return@@ -1475,7 +1487,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([report: values.report,sentiment,note: trimmed,- surface: 'detail_footer',+ surface,})// Best-effort: also carry the note into the scout steering channel so the scout that filed// the report reads it next run. The analytics event above is the durable record, so a