Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(today): rework today home and add the highlights framework (#116128)

Shy Alter56636bc537dc
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 2d5e03b14713..ad5296c79237 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -139,6 +139,7 @@ rules:
|CustomPropertyValue
|DAG
|DailyBriefing
+ |TodayHighlights
|Dashboard
|DashboardTemplate
|DashboardWidget
@@ -605,6 +606,7 @@ rules:
|CustomPropertyValue
|DAG
|DailyBriefing
+ |TodayHighlights
|Dashboard
|DashboardTemplate
|DashboardWidget
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 0df82334744d..fe1d17a30656 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -107,6 +107,11 @@ whose path is given here handles its own failures, so the same action elsewhere
*/
const ERROR_FILTER_ALLOW_LIST_BY_LOGIC_PATH: Record<string, string> = {
loadFeatureFlag: 'scenes.feature-flags.featureFlagLogic', // A retry banner, or a retry toast once the flag is on screen
+ loadTopReports: 'scenes.project-homepage.today.todayLogic',
+ loadHighlights: 'scenes.project-homepage.today.todayHighlightsLogic',
+ loadFullReport: 'scenes.project-homepage.today.todayReportLogic',
+ loadPage: 'scenes.project-homepage.today.todayReportLogic',
+ loadReportDiff: 'scenes.inbox.logics.inboxReportDetailLogic',
}
// A keyed logic's path ends with its key, so match the owner path as a prefix.
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index ecc625a2ad8a..49dd54b6c856 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -485,7 +485,7 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Fil
},
}
-const getIconColor = (type?: string, colorOverride?: FileSystemIconColor): FileSystemIconColor => {
+export const getIconColor = (type?: string, colorOverride?: FileSystemIconColor): FileSystemIconColor => {
// Manifest color takes precedence
const fileSystemColor = (fileSystemTypes as unknown as Record<string, { iconColor?: FileSystemIconColor }>)[
type as keyof typeof fileSystemTypes
diff --git a/frontend/src/layout/today/TodayObjectHoverCard.tsx b/frontend/src/layout/today/TodayObjectHoverCard.tsx
new file mode 100644
index 000000000000..480623836c34
--- /dev/null
+++ b/frontend/src/layout/today/TodayObjectHoverCard.tsx
@@ -0,0 +1,148 @@
+import { useActions, useValues } from 'kea'
+import { Fragment, useEffect, useMemo } from 'react'
+
+import { IconArrowRight, IconChevronRight, IconExternal } from '@posthog/icons'
+import { Badge, Item, ItemContent, ItemSeparator, ItemTitle, Skeleton } from '@posthog/quill'
+
+import { newInternalTab } from 'lib/utils/newInternalTab'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { baseObjectType } from 'scenes/library/libraryUtils'
+import { todayNumber } from 'scenes/project-homepage/today/todayNumbers'
+import { TodaySparkline } from 'scenes/project-homepage/today/TodaySparkline'
+
+import { TodayHoverCardFact } from './TodayHoverCardFact'
+import { cardMenuParts } from './todayMenuParts'
+import { todayObjectGlanceLogic } from './todayObjectGlanceLogic'
+import { GLANCE_TYPES, TodayObjectGlance } from './todayObjectGlances'
+import { TodayObjectIcon } from './TodayObjectIcon'
+import { TodayObjectPreview } from './todayPreviewCards'
+import { activityDetail } from './todayWorkItems'
+
+function Glance({ glance }: { glance: TodayObjectGlance }): JSX.Element {
+ const { headline } = glance
+ return (
+ <>
+ {headline && (
+ <div className="flex flex-col gap-1">
+ <div className="flex min-w-0 items-baseline gap-1.5">
+ <span className="text-lg leading-6 font-semibold tabular-nums">{headline.value}</span>
+ <span className="min-w-0 truncate text-xs text-muted-foreground">{headline.caption}</span>
+ </div>
+ {headline.series.length > 1 && (
+ <div className="h-10">
+ <TodaySparkline
+ values={headline.series}
+ labels={headline.labels}
+ tone="neutral"
+ emphasizeLast={1}
+ formatValue={headline.formatValue ?? todayNumber}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ {glance.description && (
+ <p className="m-0 line-clamp-2 text-xs text-muted-foreground">{glance.description}</p>
+ )}
+ {glance.facts.map(([label, value]) => (
+ <TodayHoverCardFact key={label} label={label}>
+ {value}
+ </TodayHoverCardFact>
+ ))}
+ </>
+ )
+}
+
+export function TodayObjectHoverCard({
+ preview,
+ onAction,
+}: {
+ preview: TodayObjectPreview
+ onAction: () => void
+}): JSX.Element {
+ const { href, ref, type } = preview
+ const { glanceFor } = useValues(todayObjectGlanceLogic)
+ const { showGlance } = useActions(todayObjectGlanceLogic)
+ const glanceRef = ref && GLANCE_TYPES.includes(baseObjectType(type)) ? ref : null
+ useEffect(() => {
+ if (glanceRef) {
+ showGlance(type, glanceRef)
+ }
+ }, [glanceRef, type, showGlance])
+ const glance = glanceRef ? glanceFor(type, glanceRef) : null
+ const opened = activityDetail(preview.lastViewedAt)
+ const { Item: ActionItem } = useMemo(() => cardMenuParts(onAction), [onAction])
+ return (
+ <div className="flex flex-col" data-attr="today-object-hover-card">
+ <Item size="xs" className="items-start">
+ <ItemContent className="min-w-0 gap-2">
+ <ItemTitle className="flex items-center gap-2 wrap-anywhere">
+ <TodayObjectIcon
+ type={type}
+ className="shrink-0 [--icon-stack-size:22px] [--quill-icon-stack-ring:var(--card)]"
+ />
+ <span className="min-w-0 flex-1 font-semibold">{preview.name}</span>
+ {glance?.status && (
+ <Badge variant={glance.status.tone} className="shrink-0">
+ {glance.status.label}
+ </Badge>
+ )}
+ </ItemTitle>
+ <div className="flex flex-col gap-1.5 pl-7.5">
+ <div className="flex min-w-0 items-center gap-1 text-xs text-muted-foreground">
+ {preview.typeLabel && (
+ <span className="shrink-0">{capitalizeFirstLetter(preview.typeLabel)} in</span>
+ )}
+ <span className="flex min-w-0 items-center gap-0.5" title={preview.folder.join(' / ')}>
+ {preview.folder.length === 0 ? (
+ <span>Project root</span>
+ ) : (
+ preview.folder.map((segment, index) => (
+ <Fragment key={index}>
+ {index > 0 && <IconChevronRight className="size-3 shrink-0" />}
+ <span
+ className={
+ index === preview.folder.length - 1 ? 'truncate' : 'shrink-0'
+ }
+ >
+ {segment}
+ </span>
+ </Fragment>
+ ))
+ )}
+ </span>
+ </div>
+ {glance === undefined ? (
+ <div className="flex flex-col gap-1.5" aria-busy="true">
+ <Skeleton className="h-4 w-2/3" />
+ <Skeleton className="h-4 w-1/2" />
+ </div>
+ ) : (
+ glance && <Glance glance={glance} />
+ )}
+ {opened && (
+ <TodayHoverCardFact label="Opened">
+ <span title={opened.title}>{opened.text}</span>
+ </TodayHoverCardFact>
+ )}
+ </div>
+ </ItemContent>
+ </Item>
+ {href && (
+ <>
+ <ItemSeparator className="my-0" />
+ <div className="flex flex-col p-1">
+ <ActionItem to={href} dataAttr="today-object-card-open">
+ <IconArrowRight />
+ Open
+ </ActionItem>
+ <ActionItem onClick={() => newInternalTab(href)} dataAttr="today-object-card-open-new-tab">
+ <IconExternal />
+ Open in new tab
+ </ActionItem>
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/layout/today/TodayObjectIcon.tsx b/frontend/src/layout/today/TodayObjectIcon.tsx
new file mode 100644
index 000000000000..697b6947661e
--- /dev/null
+++ b/frontend/src/layout/today/TodayObjectIcon.tsx
@@ -0,0 +1,15 @@
+import { IconStack, IconStackItem } from '@posthog/quill'
+
+import { getIconColor, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { FileSystemIconType } from '~/queries/schema/schema-general'
+
+export function TodayObjectIcon({ type, className }: { type: string | undefined; className: string }): JSX.Element {
+ const [color] = getIconColor(type)
+ return (
+ <IconStack className={className}>
+ <IconStackItem color={color === 'currentColor' ? undefined : color}>
+ {iconForType(type as FileSystemIconType | undefined)}
+ </IconStackItem>
+ </IconStack>
+ )
+}
diff --git a/frontend/src/layout/today/TodayPhoneHeader.tsx b/frontend/src/layout/today/TodayPhoneHeader.tsx
index 5a6943fa092a..85f77b8fb198 100644
--- a/frontend/src/layout/today/TodayPhoneHeader.tsx
+++ b/frontend/src/layout/today/TodayPhoneHeader.tsx
@@ -15,7 +15,7 @@ import { todayShellLogic } from './todayShellLogic'
export function TodayPhoneHeader(): JSX.Element {
const { sceneBreadcrumbs } = useValues(breadcrumbsLogic)
const { scenePanelIsPresent } = useValues(sceneLayoutLogic)
- const { onAiPage, phoneCanGoBack } = useValues(todayShellLogic)
+ const { onAiPage, phoneCanGoBack, paneHasSidebar } = useValues(todayShellLogic)
const { goBackOnPhone, setMobileSidebarOpen } = useActions(todayShellLogic)
const { openSidePanel } = useActions(sidePanelStateLogic)
const [scrolled, setScrolled] = useState(false)
@@ -38,7 +38,7 @@ export function TodayPhoneHeader(): JSX.Element {
<Button size="icon" aria-label="Back" data-attr="today-phone-back" onClick={goBackOnPhone}>
<IconChevronLeft />
</Button>
- ) : (
+ ) : paneHasSidebar ? (
<Button
size="icon"
aria-label="Open sidebar"
@@ -47,7 +47,7 @@ export function TodayPhoneHeader(): JSX.Element {
>
<IconShowSidebar />
</Button>
- )}
+ ) : null}
<h2 className="m-0 min-w-0 flex-1 truncate text-base font-bold text-foreground">{title}</h2>
{!onAiPage && (
<Button
diff --git a/frontend/src/layout/today/TodayPreviewCardProvider.tsx b/frontend/src/layout/today/TodayPreviewCardProvider.tsx
index ad99c8d2db38..f54810a9b72b 100644
--- a/frontend/src/layout/today/TodayPreviewCardProvider.tsx
+++ b/frontend/src/layout/today/TodayPreviewCardProvider.tsx
@@ -1,50 +1,33 @@
import { PreviewCard } from '@base-ui/react/preview-card'
-import { ReactNode, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { ReactNode, Suspense, useCallback, useMemo, useRef, useState } from 'react'
import { Card, Skeleton } from '@posthog/quill'
import { lazyWithRetry } from 'lib/utils/retryImport'
-import { cardSideForPointer, trackPointer } from './todayPointer'
import { TodayPreviewCard, TodayPreviewCardContext } from './todayPreviewCardContext'
import { TodayPreviewPayload } from './todayPreviewCards'
-const TodayReportHoverCard = lazyWithRetry(() =>
- import('scenes/project-homepage/today/TodayReportHoverCard').then((m) => ({ default: m.TodayReportHoverCard }))
-)
const TodayChatHoverCard = lazyWithRetry(() =>
import('./TodayChatHoverCard').then((m) => ({ default: m.TodayChatHoverCard }))
)
+const TodayObjectHoverCard = lazyWithRetry(() =>
+ import('./TodayObjectHoverCard').then((m) => ({ default: m.TodayObjectHoverCard }))
+)
const TodaySessionHoverCard = lazyWithRetry(() =>
import('./TodaySessionHoverCard').then((m) => ({ default: m.TodaySessionHoverCard }))
)
-function isInTextLink(payload: TodayPreviewPayload): boolean {
- return payload.kind === 'report' && payload.surface === 'briefing'
-}
-
-/** Beside a row, centered on it, so the path to a tall card is short from any row. On a link in the
- * home page text, above or below it on the side the pointer came from, so the card does not cover
- * the next link the pointer moves to. */
-function TodayPreviewPositioner({
- payload,
- children,
-}: {
- payload: TodayPreviewPayload
- children: ReactNode
-}): JSX.Element {
- // Fixed per link: the direction at the moment the card moves to this link, not while the pointer rests on it.
- const textSide = useMemo(() => (isInTextLink(payload) ? cardSideForPointer() : null), [payload])
- const placement: Pick<PreviewCard.Positioner.Props, 'side' | 'align' | 'sideOffset'> = textSide
- ? { side: textSide, align: 'start', sideOffset: 6 }
- : { side: 'right', align: 'center', sideOffset: 10 }
+function TodayPreviewPositioner({ below, children }: { below: boolean; children: ReactNode }): JSX.Element {
return (
<PreviewCard.Positioner
data-quill
data-quill-portal="popover"
// Quill's portal rule reads this token and wins over a z-index utility class.
className="[--quill-z-popover:var(--z-popover-with-chart)]"
- {...placement}
+ side={below ? 'bottom' : 'right'}
+ align={below ? 'start' : 'center'}
+ sideOffset={below ? 6 : 10}
>
{children}
</PreviewCard.Positioner>
@@ -79,7 +62,6 @@ export function TodayPreviewCardProvider({
}),
[handle]
)
- useEffect(trackPointer, [])
const close = useCallback(() => {
setOpen(false)
}, [])
@@ -96,9 +78,9 @@ export function TodayPreviewCardProvider({
{({ payload }) =>
payload ? (
<PreviewCard.Portal>
- <TodayPreviewPositioner payload={payload}>
+ <TodayPreviewPositioner below={payload.kind === 'object'}>
{/* Inside the popup, not its `render`: on React 18 quill's Card takes no ref. */}
- <PreviewCard.Popup className="outline-none">
+ <PreviewCard.Popup className="origin-[var(--transform-origin)] outline-none transition-[opacity,scale] duration-150 ease-out data-[ending-style]:scale-97 data-[ending-style]:opacity-0 data-[starting-style]:scale-97 data-[starting-style]:opacity-0 motion-reduce:transition-none">
<Card
size="sm"
className="w-72 gap-0 border border-border py-0 shadow-[var(--shadow-md)]"
@@ -106,8 +88,8 @@ export function TodayPreviewCardProvider({
<Suspense fallback={<Skeleton className="h-24 w-full" />}>
{payload.kind === 'chat' ? (
<TodayChatHoverCard preview={payload} onAction={close} />
- ) : payload.kind === 'report' ? (
- <TodayReportHoverCard preview={payload} />
+ ) : payload.kind === 'object' ? (
+ <TodayObjectHoverCard preview={payload} onAction={close} />
) : (
<TodaySessionHoverCard preview={payload} onAction={close} />
)}
diff --git a/frontend/src/layout/today/TodayShell.tsx b/frontend/src/layout/today/TodayShell.tsx
index 810334aebe58..4ecb6e18d7cc 100644
--- a/frontend/src/layout/today/TodayShell.tsx
+++ b/frontend/src/layout/today/TodayShell.tsx
@@ -12,12 +12,10 @@ import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { useShortcut } from 'lib/components/Shortcuts/useShortcut'
import { cn } from 'lib/utils/css-classes'
import { lazyWithRetry } from 'lib/utils/retryImport'
-import { TodayHomeSidebar } from 'scenes/project-homepage/today/TodayHomeSidebar'
import { QuillSceneHeader } from '~/layout/scenes/components/QuillSceneHeader'
import { TodayPhoneHeader } from './TodayPhoneHeader'
-import { TodayPreviewCardProvider } from './TodayPreviewCardProvider'
import { TodayRail } from './TodayRail'
import { TODAY_PANES } from './todayRailItems'
import { todayRecentsLogic } from './todayRecentsLogic'
@@ -94,11 +92,7 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {
const paneContent = (
<Suspense fallback={<Skeleton className="m-4 h-24" />}>
- {activePane === 'home' ? (
- <TodayPreviewCardProvider>
- <TodayHomeSidebar />
- </TodayPreviewCardProvider>
- ) : activePane === 'spaces' ? (
+ {activePane === 'home' ? null : activePane === 'spaces' ? (
<TodaySpacesPane />
) : activePane === 'views' ? (
<TodayViewsSidebar />
diff --git a/frontend/src/layout/today/todayObjectGlanceLogic.ts b/frontend/src/layout/today/todayObjectGlanceLogic.ts
new file mode 100644
index 000000000000..ce283792d48c
--- /dev/null
+++ b/frontend/src/layout/today/todayObjectGlanceLogic.ts
@@ -0,0 +1,107 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { baseObjectType } from 'scenes/library/libraryUtils'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { Noun, groupsModel } from '~/models/groupsModel'
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import { TodayObjectGlance, fetchGlance } from './todayObjectGlances'
+
+const glanceKey = (type: string | undefined, ref: string): string => `${baseObjectType(type)}:${ref}`
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayObjectGlanceLogicValues {
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
+ baseCurrency: CurrencyCode // teamLogic
+ currentProjectId: number | string // teamLogic
+ fetched: Record<string, TodayObjectGlance | null>
+ glanceFor: (type: string | undefined, ref: string) => TodayObjectGlance | null | undefined
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayObjectGlanceLogicActions {
+ setGlance: (
+ key: string,
+ glance: TodayObjectGlance | null
+ ) => {
+ glance: TodayObjectGlance | null
+ key: string
+ }
+ showGlance: (
+ type: string | undefined,
+ ref: string
+ ) => {
+ ref: string
+ type: string | undefined
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayObjectGlanceLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ glanceFor: (
+ fetched: Record<string, TodayObjectGlance | null>
+ ) => (type: string | undefined, ref: string) => TodayObjectGlance | null | undefined
+ }
+}
+
+export type todayObjectGlanceLogicType = MakeLogicType<
+ todayObjectGlanceLogicValues,
+ todayObjectGlanceLogicActions,
+ Record<string, any>,
+ todayObjectGlanceLogicMeta
+>
+
+export const todayObjectGlanceLogic = kea<todayObjectGlanceLogicType>([
+ path(['layout', 'today', 'todayObjectGlanceLogic']),
+ connect(() => ({
+ values: [teamLogic, ['baseCurrency', 'currentProjectId'], groupsModel, ['aggregationLabel']],
+ })),
+ actions({
+ showGlance: (type: string | undefined, ref: string) => ({ type, ref }),
+ setGlance: (key: string, glance: TodayObjectGlance | null) => ({ key, glance }),
+ }),
+ reducers({
+ fetched: [
+ {} as Record<string, TodayObjectGlance | null>,
+ { setGlance: (state, { key, glance }) => ({ ...state, [key]: glance }) },
+ ],
+ }),
+ selectors({
+ glanceFor: [
+ (s) => [s.fetched],
+ (fetched: Record<string, TodayObjectGlance | null>) =>
+ (type: string | undefined, ref: string): TodayObjectGlance | null | undefined =>
+ fetched[glanceKey(type, ref)],
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ showGlance: async ({ type, ref }) => {
+ posthog.capture('today object preview shown', { object_type: baseObjectType(type) })
+ const key = glanceKey(type, ref)
+ cache.pending ??= new Set<string>()
+ cache.failed ??= new Set<string>()
+ if ((key in values.fetched && !cache.failed.has(key)) || cache.pending.has(key)) {
+ return
+ }
+ cache.pending.add(key)
+ try {
+ actions.setGlance(
+ key,
+ await fetchGlance(String(values.currentProjectId), type, ref, {
+ currency: values.baseCurrency,
+ aggregationLabel: values.aggregationLabel,
+ })
+ )
+ cache.failed.delete(key)
+ } catch {
+ actions.setGlance(key, null)
+ cache.failed.add(key)
+ } finally {
+ cache.pending.delete(key)
+ }
+ },
+ })),
+])
diff --git a/frontend/src/layout/today/todayObjectGlances.test.ts b/frontend/src/layout/today/todayObjectGlances.test.ts
new file mode 100644
index 000000000000..942efb549333
--- /dev/null
+++ b/frontend/src/layout/today/todayObjectGlances.test.ts
@@ -0,0 +1,81 @@
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import type { InsightApi } from 'products/product_analytics/frontend/generated/api.schemas'
+
+import { flagRollout, insightGlance } from './todayObjectGlances'
+
+describe('todayObjectGlances', () => {
+ const aggregationLabel = (index: number | null | undefined): { singular: string; plural: string } =>
+ index == null ? { singular: 'user', plural: 'users' } : { singular: 'organization', plural: 'organizations' }
+
+ test.each([
+ ['variants win', { multivariate: { variants: [{}, {}] }, groups: [{ rollout_percentage: 100 }] }, '2 variants'],
+ ['one open group', { groups: [{ properties: [], rollout_percentage: 25 }] }, '25% of users'],
+ ['one group with no percentage', { groups: [{ properties: [] }] }, '100% of users'],
+ [
+ 'one open group of organizations',
+ { aggregation_group_type_index: 0, groups: [{ properties: [], rollout_percentage: 25 }] },
+ '25% of organizations',
+ ],
+ ['targeted groups', { groups: [{ properties: [{}] }, { properties: [] }] }, '2 release conditions'],
+ ['rules v2', { version: 2, return_type: 'boolean', rules: [{}, {}, {}] }, '3 rules'],
+ ['an unsupported version', { version: 9 }, null],
+ ])('rollout: %s', (_name, filters, expected) => {
+ expect(flagRollout(filters, aggregationLabel)?.replace(/\s/g, ' ') ?? null).toBe(expected)
+ })
+
+ test.each([
+ [
+ 'trend',
+ [{ label: 'Pageview', count: 1208, data: [3, 5, 1200], labels: ['a', 'b', 'c'] }],
+ null,
+ '1.2k',
+ 'Pageview',
+ ],
+ [
+ 'single-bucket trends',
+ [
+ { label: 'Signed up', count: 100, data: [100] },
+ { count: 25, data: [25] },
+ ],
+ null,
+ '100',
+ 'Signed up',
+ ],
+ [
+ 'trend in scaled percent',
+ [{ label: 'Rate', data: [0.5, 0.0123456] }],
+ {
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'TrendsQuery',
+ series: [],
+ trendsFilter: { aggregationAxisFormat: 'percentage_scaled' },
+ },
+ },
+ '1.23%',
+ 'Rate',
+ ],
+ ['funnel', [{ count: 200 }, { count: 50 }], null, '25%', 'conversion'],
+ [
+ 'compared funnel',
+ [
+ { count: 200, compare_label: 'current' },
+ { count: 100, compare_label: 'current' },
+ { count: 150, compare_label: 'previous' },
+ { count: 60, compare_label: 'previous' },
+ ],
+ null,
+ '50%',
+ 'conversion',
+ ],
+ ['breakdown funnel', [[{ count: 10 }, { count: 4 }]], null, '40%', 'conversion'],
+ ['no cached result', null, null, undefined, undefined],
+ ])('headline: %s', (_name, result, query, value, caption) => {
+ const { headline } = insightGlance(
+ { result, query, description: '' } as unknown as InsightApi,
+ CurrencyCode.USD
+ )
+ expect([headline?.value, headline?.caption]).toEqual([value, caption])
+ })
+})
diff --git a/frontend/src/layout/today/todayObjectGlances.ts b/frontend/src/layout/today/todayObjectGlances.ts
new file mode 100644
index 000000000000..f925277ff8fc
--- /dev/null
+++ b/frontend/src/layout/today/todayObjectGlances.ts
@@ -0,0 +1,275 @@
+import { dayjs } from 'lib/dayjs'
+import { pluralize } from 'lib/utils/strings'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { baseObjectType } from 'scenes/library/libraryUtils'
+import { todayNumber } from 'scenes/project-homepage/today/todayNumbers'
+
+import type { Noun } from '~/models/groupsModel'
+import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'
+import { isInsightVizNode, isTrendsQuery } from '~/queries/utils'
+import { type Experiment, ExperimentStatus, type FeatureFlagConfig } from '~/types'
+
+import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
+import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'
+import { dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'
+import type { DashboardApi } from 'products/dashboards/frontend/generated/api.schemas'
+import { getExperimentStatus } from 'products/experiments/frontend/experimentStatus'
+import { experimentsRetrieve } from 'products/experiments/frontend/generated/api'
+import type { ExperimentApi } from 'products/experiments/frontend/generated/api.schemas'
+import {
+ isRulesV2FeatureFlagConfig,
+ isV1FeatureFlagConfig,
+} from 'products/feature_flags/frontend/featureFlagConfigFormat'
+import { featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'
+import type { FeatureFlagApi } from 'products/feature_flags/frontend/generated/api.schemas'
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+import type { InsightApi } from 'products/product_analytics/frontend/generated/api.schemas'
+import { surveysRetrieve } from 'products/surveys/frontend/generated/api'
+import type { SurveyApi } from 'products/surveys/frontend/generated/api.schemas'
+
+import { activityDetail } from './todayWorkItems'
+
+export interface TodayObjectGlance {
+ status?: { label: string; tone: 'success' | 'warning' | 'info' | 'default' }
+ headline?: {
+ value: string
+ caption: string
+ series: number[]
+ labels: string[]
+ formatValue?: (value: number) => string
+ }
+ description?: string
+ facts: [string, string][]
+}
+
+export type TodayAggregationLabel = (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
+
+export interface TodayGlanceFormat {
+ currency: CurrencyCode
+ aggregationLabel: TodayAggregationLabel
+}
+
+export const GLANCE_TYPES = ['insight', 'feature_flag', 'experiment', 'survey', 'cohort', 'dashboard']
+
+const since = (timestamp: string | null | undefined): string | null => activityDetail(timestamp ?? null)?.text ?? null
+
+const day = (timestamp: string): string => dayjs(timestamp).format('D MMM YYYY')
+
+function facts(entries: [string, string | null | undefined][]): [string, string][] {
+ return entries.filter((entry): entry is [string, string] => !!entry[1])
+}
+
+function running(start: string | null | undefined): TodayObjectGlance['status'] {
+ return {
+ label: start ? `Running for ${pluralize(Math.max(1, dayjs().diff(start, 'day')), 'day')}` : 'Running',
+ tone: 'success',
+ }
+}
+
+function lifecycle(start: string | null | undefined, end: string | null | undefined): TodayObjectGlance['status'] {
+ if (!start) {
+ return { label: 'Draft', tone: 'default' }
+ }
+ if (end) {
+ return { label: 'Complete', tone: 'default' }
+ }
+ return running(start)
+}
+
+function experimentStatus(experiment: ExperimentApi): TodayObjectGlance['status'] {
+ switch (getExperimentStatus(experiment as Pick<Experiment, 'status' | 'start_date' | 'end_date'>)) {
+ case ExperimentStatus.Running:
+ return running(experiment.start_date)
+ case ExperimentStatus.Paused:
+ return { label: 'Paused', tone: 'warning' }
+ case ExperimentStatus.ExposureFrozen:
+ return { label: 'Exposure frozen', tone: 'info' }
+ case ExperimentStatus.Stopped:
+ return { label: 'Complete', tone: 'default' }
+ case ExperimentStatus.Draft:
+ return { label: 'Draft', tone: 'default' }
+ }
+}
+
+interface TrendSeries {
+ data: number[]
+ labels?: string[]
+ label?: string
+}
+
+interface FunnelStep {
+ count: number
+ compare_label?: string
+}
+
+function insightFormatter(insight: InsightApi, currency: CurrencyCode): (value: number) => string {
+ const query = insight.query as Record<string, any> | null | undefined
+ const trendsFilter: TrendsFilter | undefined =
+ isInsightVizNode(query) && isTrendsQuery(query.source) ? (query.source.trendsFilter ?? undefined) : undefined
+ const hasFormat =
+ !!trendsFilter &&
+ (!!trendsFilter.aggregationAxisFormat ||
+ !!trendsFilter.aggregationAxisPrefix ||
+ !!trendsFilter.aggregationAxisPostfix ||
+ trendsFilter.decimalPlaces != null ||
+ trendsFilter.minDecimalPlaces != null)
+ return hasFormat ? (value) => formatAggregationAxisValue(trendsFilter, value, currency) : todayNumber
+}
+
+function insightHeadline(result: unknown, formatValue: (value: number) => string): TodayObjectGlance['headline'] {
+ if (!Array.isArray(result) || result.length === 0) {
+ return undefined
+ }
+ const series = result.find((entry: TrendSeries) => Array.isArray(entry?.data) && entry.data.length > 0) as
+ | TrendSeries
+ | undefined
+ if (series) {
+ const values = series.data.slice(-30)
+ return {
+ value: formatValue(values[values.length - 1]),
+ caption: series.label ?? '',
+ series: values,
+ labels: (series.labels ?? []).slice(-30),
+ formatValue,
+ }
+ }
+ if (result.some((entry: TrendSeries) => Array.isArray(entry?.data))) {
+ return undefined
+ }
+ const steps = ((Array.isArray(result[0]) ? result[0] : result) as FunnelStep[]).filter(
+ (step) => step.compare_label !== 'previous'
+ )
+ const [top, bottom] = [steps[0]?.count, steps[steps.length - 1]?.count]
+ return top && steps.length > 1 && bottom !== undefined
+ ? { value: `${Math.round((bottom / top) * 100)}%`, caption: 'conversion', series: [], labels: [] }
+ : undefined
+}
+
+export function insightGlance(insight: InsightApi, currency: CurrencyCode): TodayObjectGlance {
+ return {
+ headline: insightHeadline(insight.result, insightFormatter(insight, currency)),
+ description: insight.description || undefined,
+ facts: facts([
+ ['Refreshed', since(insight.last_refresh)],
+ ['Edited by', insight.last_modified_by?.first_name],
+ ]),
+ }
+}
+
+export function flagRollout(
+ filters: FeatureFlagApi['filters'],
+ aggregationLabel: TodayAggregationLabel
+): string | null {
+ const config = (filters ?? {}) as unknown as FeatureFlagConfig
+ if (isRulesV2FeatureFlagConfig(config)) {
+ return pluralize(config.rules.length, 'rule')
+ }
+ if (!isV1FeatureFlagConfig(config)) {
+ return null
+ }
+ const variants = config.multivariate?.variants ?? []
+ if (variants.length > 0) {
+ return pluralize(variants.length, 'variant')
+ }
+ const groups = config.groups ?? []
+ if (groups.length === 1 && !groups[0].properties?.length) {
+ const population = aggregationLabel(config.aggregation_group_type_index, true).plural
+ return `${groups[0].rollout_percentage ?? 100}% of ${population}`
+ }
+ return pluralize(groups.length, 'release condition')
+}
+
+function flagGlance(flag: FeatureFlagApi, aggregationLabel: TodayAggregationLabel): TodayObjectGlance {
+ return {
+ status: flag.active ? { label: 'Enabled', tone: 'success' } : { label: 'Disabled', tone: 'default' },
+ description: flag.name && flag.name !== flag.key ? flag.name : undefined,
+ facts: facts([
+ ['Rollout', flagRollout(flag.filters, aggregationLabel)],
+ ['Updated', since(flag.updated_at)],
+ ]),
+ }
+}
+
+function experimentGlance(experiment: ExperimentApi): TodayObjectGlance {
+ return {
+ status: experimentStatus(experiment),
+ description: experiment.description || undefined,
+ facts: facts([
+ ['Flag', experiment.feature_flag_key],
+ ['Started', experiment.start_date ? day(experiment.start_date) : null],
+ ]),
+ }
+}
+
+function surveyGlance(survey: SurveyApi): TodayObjectGlance {
+ const questions = Array.isArray(survey.questions) ? survey.questions.length : 0
+ return {
+ status: lifecycle(survey.start_date, survey.end_date),
+ description: survey.description || undefined,
+ facts: facts([
+ ['Questions', questions ? String(questions) : null],
+ ['Started', survey.start_date ? day(survey.start_date) : null],
+ ]),
+ }
+}
+
+function cohortGlance(cohort: CohortApi): TodayObjectGlance {
+ return {
+ status: cohort.is_calculating
+ ? { label: 'Calculating', tone: 'warning' }
+ : cohort.errors_calculating
+ ? { label: 'Calculation failed', tone: 'warning' }
+ : undefined,
+ headline:
+ cohort.count !== null
+ ? {
+ value: todayNumber(cohort.count),
+ caption: cohort.count === 1 ? 'person' : 'people',
+ series: [],
+ labels: [],
+ }
+ : undefined,
+ description: cohort.description || undefined,
+ facts: facts([
+ ['Kind', cohort.is_static ? 'Static' : 'Dynamic'],
+ ['Calculated', since(cohort.last_calculation)],
+ ]),
+ }
+}
+
+function dashboardGlance(dashboard: DashboardApi): TodayObjectGlance {
+ return {
+ status: dashboard.pinned ? { label: 'Pinned', tone: 'default' } : undefined,
+ description: dashboard.description || undefined,
+ facts: facts([
+ ['Tags', dashboard.tags?.map(String).join(', ')],
+ ['Created by', dashboard.created_by?.first_name],
+ ]),
+ }
+}
+
+export async function fetchGlance(
+ projectId: string,
+ type: string | undefined,
+ ref: string,
+ format: TodayGlanceFormat
+): Promise<TodayObjectGlance | null> {
+ switch (baseObjectType(type)) {
+ case 'insight': {
+ const { results } = await insightsList(projectId, { short_id: ref, refresh: 'force_cache', limit: 1 })
+ return results[0] ? insightGlance(results[0], format.currency) : null
+ }
+ case 'feature_flag':
+ return flagGlance(await featureFlagsRetrieve(projectId, Number(ref)), format.aggregationLabel)
+ case 'experiment':
+ return experimentGlance(await experimentsRetrieve(projectId, Number(ref)))
+ case 'survey':
+ return surveyGlance(await surveysRetrieve(projectId, ref))
+ case 'dashboard':
+ return dashboardGlance(await dashboardsRetrieve(projectId, Number(ref)))
+ case 'cohort':
+ return cohortGlance(await cohortsRetrieve(projectId, Number(ref)))
+ default:
+ return null
+ }
+}
diff --git a/frontend/src/layout/today/todayPointer.ts b/frontend/src/layout/today/todayPointer.ts
index 037339ed3e9a..81852b1bd464 100644
--- a/frontend/src/layout/today/todayPointer.ts
+++ b/frontend/src/layout/today/todayPointer.ts
@@ -1,11 +1,7 @@
const RECENT_MOVE_MS = 1000
-// Small jitters while the pointer rests on a link must not flip the direction.
-const DIRECTION_THRESHOLD_PX = 6
let tracking = false
let lastMoveAt = Number.NEGATIVE_INFINITY
-let anchorY: number | null = null
-let movingUp = false
/** Starts the listener. Call it before the first card can open, so the first card already knows the pointer. */
export function trackPointer(): void {
@@ -15,13 +11,8 @@ export function trackPointer(): void {
tracking = true
window.addEventListener(
'pointermove',
- (event) => {
+ () => {
lastMoveAt = performance.now()
- const delta = event.clientY - (anchorY ?? event.clientY)
- if (anchorY === null || Math.abs(delta) >= DIRECTION_THRESHOLD_PX) {
- movingUp = delta < 0
- anchorY = event.clientY
- }
},
{ passive: true }
)
@@ -31,8 +22,3 @@ export function trackPointer(): void {
export function pointerMovedRecently(): boolean {
return performance.now() - lastMoveAt < RECENT_MOVE_MS
}
-
-/** Above a link when the pointer comes down the text, below when it goes up, so the card leaves the next link free. */
-export function cardSideForPointer(): 'top' | 'bottom' {
- return movingUp ? 'bottom' : 'top'
-}
diff --git a/frontend/src/layout/today/todayPreviewCards.ts b/frontend/src/layout/today/todayPreviewCards.ts
index efab36e65d4b..2ca34bdb7eb8 100644
--- a/frontend/src/layout/today/todayPreviewCards.ts
+++ b/frontend/src/layout/today/todayPreviewCards.ts
@@ -1,5 +1,9 @@
+import { libraryObjectHref, libraryObjectName, libraryTypeLabel } from 'scenes/library/libraryUtils'
+
+import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
import { getOriginProductMeta } from 'products/posthog_ai/frontend/api/taskSource'
-import type { ReportChartApi, ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'
import { PrStateEnumApi, TaskUserBasicInfoApi } from 'products/tasks/frontend/generated/api.schemas'
import { TaskPullRequest } from 'products/tasks/frontend/spaces/taskPullRequests'
@@ -36,41 +40,18 @@ export interface TodayChatPreview {
timestamp: string | null
}
-/** What a report's hover card says, read from a personal briefing item or from one of the team's reports. */
-export interface TodayReportCard {
- /** Stable per report and list. It keys the card's live metric queries and its analytics. */
- key: string
- /** The report the card's resolve and dismiss buttons act on, or null when the card has no report. */
- reportId: string | null
- title: string
- /** Why the briefing picked the report. Null for the team's reports, which no briefing picked. */
- reason: string | null
- /** Resolved or dismissed since the briefing, or null while open. */
- stateLabel: string | null
- resolved: boolean
- /** Whether the person is one of the report's suggested reviewers, and so can step off it. */
- canLeaveReview: boolean
- priority: string | null
- summary: string | null
- pullRequestState: PrStateEnumApi | null
- pullRequestUrl: string | null
- signalCount: number | null
- updatedAt: string | null
- metrics: ReportMetricApi[]
- /** Charts from the report body. The card draws one when no metric has a chart. */
- charts: ReportChartApi[]
- sourceLabel: string
-}
-
-/** A report's hover card. The card text comes with the page, so it opens without a request. */
-export interface TodayReportPreview {
- kind: 'report'
- card: TodayReportCard
- /** Where the card opened: a link in the briefing text, or a left-bar row. */
- surface: 'briefing' | 'sidebar'
+export interface TodayObjectPreview {
+ kind: 'object'
+ name: string
+ type: string | undefined
+ ref: string | null
+ typeLabel: string | null
+ folder: string[]
+ href: string | null
+ lastViewedAt: string | null
}
-export type TodayPreviewPayload = TodaySessionPreview | TodayChatPreview | TodayReportPreview
+export type TodayPreviewPayload = TodaySessionPreview | TodayChatPreview | TodayObjectPreview
export function sessionPreview(
item: TodayWorkItem,
@@ -112,6 +93,19 @@ export function sessionPreview(
}
}
+export function objectPreview(entry: FileSystemEntry): TodayObjectPreview {
+ return {
+ kind: 'object',
+ name: libraryObjectName(entry),
+ type: entry.type,
+ ref: entry.ref ?? null,
+ typeLabel: libraryTypeLabel(entry.type),
+ folder: splitPath(entry.path).slice(0, -1),
+ href: libraryObjectHref(entry),
+ lastViewedAt: entry.last_viewed_at ?? null,
+ }
+}
+
export function chatPreview(item: TodayWorkItem): TodayChatPreview {
return {
kind: 'chat',
diff --git a/frontend/src/layout/today/todayShellLogic.test.ts b/frontend/src/layout/today/todayShellLogic.test.ts
index acab53481d35..7eaf7c5318d5 100644
--- a/frontend/src/layout/today/todayShellLogic.test.ts
+++ b/frontend/src/layout/today/todayShellLogic.test.ts
@@ -96,7 +96,7 @@ describe('todayShellLogic', () => {
expect(logic.values.activePane).toBe(pane)
})
- test.each(['home', 'spaces', 'views', 'products'] as const)(
+ test.each(['spaces', 'views', 'products'] as const)(
'a second rail click on %s hides the sidebar it opened',
(pane) => {
const logic = todayShellLogic()
@@ -111,6 +111,21 @@ describe('todayShellLogic', () => {
}
)
+ it('never shows a sidebar on Home, so the page takes the full width', () => {
+ const logic = todayShellLogic()
+ logic.mount()
+
+ logic.actions.setSidebarOpen(true)
+ logic.actions.setSidebarWidth(300)
+ logic.actions.clickRailPane('home')
+ expect(logic.values.sidebarVisible).toBe(false)
+ expect(logic.values.sidebarBreadcrumbShown).toBe(false)
+ expect(logic.values.leftNavWidth).toBe(TODAY_RAIL_WIDTH)
+
+ logic.actions.clickRailPane('products')
+ expect(logic.values.sidebarVisible).toBe(true)
+ })
+
it('keeps the last pane open on pages that belong to no pane', () => {
const logic = todayShellLogic()
logic.mount()
@@ -127,6 +142,7 @@ describe('todayShellLogic', () => {
const logic = todayShellLogic()
logic.mount()
+ logic.actions.pickPane('products')
logic.actions.setSidebarOpen(true)
logic.actions.setSidebarWidth(10_000)
expect(logic.values.leftNavWidth).toBe(TODAY_RAIL_WIDTH + TODAY_SIDEBAR_MAX_WIDTH)
@@ -139,6 +155,7 @@ describe('todayShellLogic', () => {
const logic = todayShellLogic()
logic.mount()
+ logic.actions.pickPane('products')
logic.actions.setSidebarOpen(true)
router.actions.push('/project/1/insights')
expect(logic.values.sidebarVisible).toBe(true)
@@ -149,7 +166,7 @@ describe('todayShellLogic', () => {
router.actions.push('/project/1/cohorts')
expect(logic.values.sidebarVisible).toBe(false)
- logic.actions.pickPane('home')
+ logic.actions.pickPane('views')
expect(logic.values.sidebarVisible).toBe(true)
})
it('keeps the rail on narrow windows and opens the sidebar as a drawer that closes on navigation', () => {
diff --git a/frontend/src/layout/today/todayShellLogic.ts b/frontend/src/layout/today/todayShellLogic.ts
index 6f5f1f329430..9a9732428ea3 100644
--- a/frontend/src/layout/today/todayShellLogic.ts
+++ b/frontend/src/layout/today/todayShellLogic.ts
@@ -110,6 +110,7 @@ export interface todayShellLogicValues {
leftNavWidth: number
mobileSidebarOpen: boolean
onAiPage: boolean
+ paneHasSidebar: boolean
phoneCanGoBack: boolean
phoneHeaderHidden: boolean
phoneHeaderShown: boolean
@@ -182,13 +183,20 @@ export interface todayShellLogicMeta {
__keaTypeGenInternalSelectorTypes: {
routePane: (location: { hash: string; pathname: string; search: string }) => TodayRailPane | null
activePane: (pickedPane: TodayRailPane | null, routePane: TodayRailPane | null) => TodayRailPane
+ paneHasSidebar: (activePane: TodayRailPane) => boolean
leftNavWidth: (
sidebarOpen: boolean,
sidebarWidth: number,
mobileLayout: boolean,
- phoneLayout: boolean
+ phoneLayout: boolean,
+ paneHasSidebar: boolean
) => number
- sidebarVisible: (mobileLayout: boolean, mobileSidebarOpen: boolean, sidebarOpen: boolean) => boolean
+ sidebarVisible: (
+ mobileLayout: boolean,
+ mobileSidebarOpen: boolean,
+ sidebarOpen: boolean,
+ paneHasSidebar: boolean
+ ) => boolean
todayRailEnabled: (featureFlags: FeatureFlagsSet) => boolean
onAiPage: (location: { hash: string; pathname: string; search: string }) => boolean
phoneHeaderHidden: (
@@ -199,7 +207,12 @@ export interface todayShellLogicMeta {
) => boolean
phoneHeaderShown: (todayRailEnabled: boolean, phoneLayout: boolean, phoneHeaderHidden: boolean) => boolean
phoneCanGoBack: (phonePages: TodayPhonePage[]) => boolean
- sidebarBreadcrumbShown: (todayRailEnabled: boolean, phoneLayout: boolean, sidebarVisible: boolean) => boolean
+ sidebarBreadcrumbShown: (
+ todayRailEnabled: boolean,
+ phoneLayout: boolean,
+ sidebarVisible: boolean,
+ paneHasSidebar: boolean
+ ) => boolean
}
}
@@ -282,15 +295,28 @@ export const todayShellLogic = kea<todayShellLogicType>([
(pickedPane: TodayRailPane | null, routePane: TodayRailPane | null): TodayRailPane =>
pickedPane ?? routePane ?? 'home',
],
+ paneHasSidebar: [(s) => [s.activePane], (activePane: TodayRailPane): boolean => activePane !== 'home'],
leftNavWidth: [
- (s) => [s.sidebarOpen, s.sidebarWidth, s.mobileLayout, s.phoneLayout],
- (sidebarOpen: boolean, sidebarWidth: number, mobileLayout: boolean, phoneLayout: boolean): number =>
- phoneLayout ? 0 : TODAY_RAIL_WIDTH + (sidebarOpen && !mobileLayout ? sidebarWidth : 0),
+ (s) => [s.sidebarOpen, s.sidebarWidth, s.mobileLayout, s.phoneLayout, s.paneHasSidebar],
+ (
+ sidebarOpen: boolean,
+ sidebarWidth: number,
+ mobileLayout: boolean,
+ phoneLayout: boolean,
+ paneHasSidebar: boolean
+ ): number =>
+ phoneLayout
+ ? 0
+ : TODAY_RAIL_WIDTH + (sidebarOpen && paneHasSidebar && !mobileLayout ? sidebarWidth : 0),
],
sidebarVisible: [
- (s) => [s.mobileLayout, s.mobileSidebarOpen, s.sidebarOpen],
- (mobileLayout: boolean, mobileSidebarOpen: boolean, sidebarOpen: boolean): boolean =>
- mobileLayout ? mobileSidebarOpen : sidebarOpen,
+ (s) => [s.mobileLayout, s.mobileSidebarOpen, s.sidebarOpen, s.paneHasSidebar],
+ (
+ mobileLayout: boolean,
+ mobileSidebarOpen: boolean,
+ sidebarOpen: boolean,
+ paneHasSidebar: boolean
+ ): boolean => paneHasSidebar && (mobileLayout ? mobileSidebarOpen : sidebarOpen),
],
todayRailEnabled: [
(s) => [s.featureFlags],
@@ -323,10 +349,15 @@ export const todayShellLogic = kea<todayShellLogicType>([
// covers the button instead of replacing it, so it stays and the title never shifts. Phones open the
// sidebar from the phone header.
sidebarBreadcrumbShown: [
- (s) => [s.todayRailEnabled, s.phoneLayout, s.sidebarVisible],
- (todayRailEnabled: boolean, phoneLayout: boolean, sidebarVisible: boolean): boolean =>
+ (s) => [s.todayRailEnabled, s.phoneLayout, s.sidebarVisible, s.paneHasSidebar],
+ (
+ todayRailEnabled: boolean,
+ phoneLayout: boolean,
+ sidebarVisible: boolean,
+ paneHasSidebar: boolean
+ ): boolean =>
// A hidden sidebar needs the crumb to come back, docked or overlay. The phone header has its own.
- todayRailEnabled && !phoneLayout && !sidebarVisible,
+ todayRailEnabled && paneHasSidebar && !phoneLayout && !sidebarVisible,
],
}),
subscriptions(({ actions }) => ({
diff --git a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
index 5dbebae324da..c6c7bf9813f7 100644
--- a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
+++ b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
@@ -26,6 +26,7 @@ export interface projectHomepageLogicValues {
recentInsights: InsightModel[]
recentInsightsLoading: boolean
todayHomeEnabled: boolean
+ todayReportTitle: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -52,6 +53,9 @@ export interface projectHomepageLogicActions {
recentInsights: InsightModel<Node<Record<string, any>>>[]
payload?: any
}
+ setTodayReportTitle: (title: string | null) => {
+ title: string | null
+ }
toggleInsightExpanded: (insightShortId: string) => {
insightShortId: string
}
@@ -61,6 +65,7 @@ export interface projectHomepageLogicActions {
export interface projectHomepageLogicMeta {
__keaTypeGenInternalSelectorTypes: {
todayHomeEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ breadcrumbs: (todayReportTitle: string | null) => Breadcrumb[]
}
}
@@ -80,9 +85,11 @@ export const projectHomepageLogic = kea<projectHomepageLogicType>([
actions({
toggleInsightExpanded: (insightShortId: string) => ({ insightShortId }),
+ setTodayReportTitle: (title: string | null) => ({ title }),
}),
reducers({
+ todayReportTitle: [null as string | null, { setTodayReportTitle: (_, { title }) => title }],
expandedInsightIds: [
new Set<string>(),
{
@@ -122,13 +129,15 @@ export const projectHomepageLogic = kea<projectHomepageLogicType>([
(): MaxContextInput[] => [],
],
breadcrumbs: [
- () => [],
- (): Breadcrumb[] => [
+ (s) => [s.todayReportTitle],
+ (todayReportTitle: string | null): Breadcrumb[] => [
{
key: 'home',
name: 'Home',
iconType: 'home',
+ path: todayReportTitle ? urls.projectHomepage() : undefined,
},
+ ...(todayReportTitle ? [{ key: 'today-report', name: todayReportTitle }] : []),
],
],
}),
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scss
index 66b2b1593580..f5c0c668c667 100644
--- a/frontend/src/scenes/project-homepage/today/Today.scss
+++ b/frontend/src/scenes/project-homepage/today/Today.scss
@@ -28,6 +28,7 @@
--today-card-shadow: 0 1px 2px #00000008, 0 12px 32px -24px #00000059;
--today-marker: #f54e00;
--today-key-clause: rgb(29 74 255 / 75%);
+ --today-risk: #d6453a;
[theme='dark'] & {
--today-ink: var(--foreground, #f1f1ee);
@@ -43,6 +44,7 @@
--today-button-text: #151515;
--today-marker: #ff8a4c;
--today-key-clause: rgb(138 164 255 / 85%);
+ --today-risk: #ff7b6e;
}
}
@@ -53,8 +55,10 @@
-webkit-font-smoothing: antialiased;
}
-.Today__page {
- animation: Today__page-in 0.18s ease-out both;
+html[data-today-transition]::view-transition-old(root),
+html[data-today-transition]::view-transition-new(root) {
+ animation-duration: 200ms;
+ animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
}
// In the base layer, so layered component styles (quill) win over it; an unlayered rule beats any layer.
@@ -76,318 +80,613 @@
outline: none;
}
-// Sidebar
+.TodayHome,
+.TodayReport {
+ width: min(720px, 100% - 144px);
+ padding: 94px 0 140px;
+ margin: 0 auto;
+
+ @container main-content (max-width: 900px) {
+ width: min(100% - 72px, 700px);
+ }
+
+ @container main-content (max-width: 600px) {
+ width: calc(100% - 40px);
+ padding: 20px 0 64px;
+ }
+}
+
+.TodayHome {
+ padding-block: 40px 60px;
+}
-.TodaySidebar__list {
+.TodayHome__body {
display: flex;
flex-direction: column;
- gap: 2px;
+ gap: 44px;
+ margin-top: 28px;
}
-// Lines up with the row titles: the row padding plus the icon and its gap.
-.TodaySidebar__more {
- align-self: flex-start;
- padding-inline: 0;
- margin: 2px 0 0 65px;
- font-size: 12px;
- color: var(--today-muted);
+.TodayHome__list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
- &:hover {
- color: var(--today-ink);
- }
+.TodayHome__heading {
+ display: flex;
+ gap: 8px;
+ align-items: baseline;
+ margin: 0;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--today-muted);
+ letter-spacing: 0.01em;
}
-.TodaySidebar__more--empty {
+.TodayHome__headingCount {
color: var(--today-faint);
+}
+
+.TodayHome__headingLink {
+ display: inline-flex;
+ gap: 5px;
+ align-items: center;
+ font-size: 13px;
+ color: var(--today-muted);
&:hover {
- color: var(--today-faint);
+ color: var(--today-ink);
+ text-decoration: underline;
}
}
-.TodayNavItem {
- border-radius: 10px;
+.TodayHome__headingChevron {
+ transition: transform 200ms var(--today-ease);
+
+ [data-panel-open] > & {
+ transform: rotate(180deg);
+ }
}
-.TodayNavItem__marker {
- width: 30px;
- height: 30px;
- color: var(--report-color);
- background: color-mix(in sRGB, var(--report-color) 10%, var(--today-card));
- border: 1px solid color-mix(in sRGB, var(--report-color) 25%, var(--today-card));
- border-radius: var(--radius-sm);
+.TodayJumpList__more,
+.TodayRow__detail {
+ height: var(--collapsible-panel-height);
+ overflow: hidden;
transition:
- color 0.16s,
- background 0.16s,
- border-color 0.16s;
+ height 200ms var(--today-ease),
+ opacity 200ms var(--today-ease);
- // Center the tile; quill nudges media down when an item has a description.
- &.quill-item__media {
- align-self: center;
- translate: none;
+ &[data-starting-style],
+ &[data-ending-style] {
+ height: 0;
+ opacity: 0;
}
+}
- svg {
- width: 16px;
- height: 16px;
+.TodayJumpList__more {
+ margin: 0 -12px;
+
+ > .TodayJumpList {
+ margin: 0;
}
}
-.TodayNavItem[data-active='true'] .TodayNavItem__marker {
- color: #fff;
- background: var(--report-color);
- border-color: var(--report-color);
+.TodayPulse {
+ display: grid;
+ grid-auto-columns: minmax(0, 1fr);
+ grid-auto-flow: column;
+ gap: 16px 32px;
+ padding: 0;
+ margin: 0;
+ list-style: none;
+
+ @container main-content (max-width: 600px) {
+ grid-auto-flow: row;
+ }
}
-.TodayNavItem__title {
+.TodayPulse__metric {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
min-width: 0;
}
-.TodayNavItem[data-state='done'] .TodayNavItem__title,
-.TodayInlineLink[data-state='done'] {
- text-decoration: line-through;
+.TodayPulse__name {
+ overflow: hidden;
+ font-size: 13px;
+ color: var(--today-muted);
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-// Dismissed is not done: it stays readable, only quieter, and the left bar says why.
-.TodayNavItem[data-state='dismissed'] .quill-item__content,
-.TodayInlineLink[data-state='dismissed'] {
- opacity: 0.55;
+.TodayPulse__link:hover {
+ color: var(--today-ink);
+ text-decoration: underline;
}
-// Home
-
-.TodayHome,
-.TodayReport {
- width: min(840px, 100% - 144px);
- padding: 94px 0 140px;
- margin: 0 auto;
+.TodayPulse__row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ align-items: baseline;
+}
- @container main-content (max-width: 900px) {
- width: min(100% - 72px, 700px);
- }
+.TodayPulse__value {
+ font-size: 19px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.2;
+ color: var(--today-ink);
+ letter-spacing: -0.01em;
+}
- @container main-content (max-width: 600px) {
- width: calc(100% - 40px);
- padding: 20px 0 64px;
- }
+.TodayChange {
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: var(--today-muted);
}
-.TodayHome {
- padding-block: 60px;
+.TodayPulse__spark {
+ display: block;
+ flex: 0 1 64px;
+ align-self: center;
+ min-width: 32px;
+ height: 20px;
+ margin-left: 6px;
}
-.TodayHome__meta {
+.TodayHome__headingRow {
display: flex;
- flex-wrap: wrap;
- align-items: center;
- font-family: var(--font-mono);
- font-size: 13px;
- color: var(--today-faint);
- letter-spacing: 0.02em;
+ gap: 16px;
+ align-items: baseline;
+ justify-content: space-between;
+}
- time {
- font-variant-numeric: tabular-nums;
- color: var(--today-ink);
- white-space: nowrap;
+.TodayHome__note {
+ margin: 0;
+ font-size: 15px;
+ color: var(--today-muted);
+}
+
+.TodayHome__noteLink {
+ color: var(--today-ink);
+ text-decoration: underline;
+ text-decoration-color: var(--today-line);
+ text-underline-offset: 3px;
+
+ &:hover {
+ text-decoration-color: currentColor;
}
}
-.TodayPartyPopper {
- flex-shrink: 0;
- margin-right: 8px;
+.TodayRows {
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ margin: 0 -12px;
+ list-style: none;
}
-// The running text of the home: the brief and the recent objects.
-.TodayHome__prose {
- max-width: 680px;
- font-size: 16px;
- line-height: 1.7;
- letter-spacing: -0.005em;
+.TodayRow {
+ --quill-icon-stack-ring: var(--today-paper);
- p {
- margin: 0;
+ position: relative;
+ display: grid;
+ grid-template-columns: 26px minmax(0, 1fr) auto;
+ column-gap: 12px;
+ padding: 10px 12px;
+ border-radius: 8px;
+ transition: background-color 0.12s var(--today-ease);
+
+ &[data-interactive]:hover,
+ &[data-expanded] {
+ --quill-icon-stack-ring: var(--today-soft);
+
+ background: var(--today-soft);
+ }
+
+ &[data-interactive]:hover .TodayRow__arrow {
+ opacity: 1;
+ transform: none;
+ }
+
+ &[data-interactive]:hover .TodayRow__chevron,
+ &[data-expanded] .TodayRow__chevron {
+ opacity: 1;
+ }
+
+ &[data-expanded] .TodayRow__chevron {
+ transform: rotate(180deg);
+ }
+
+ &:hover .TodayRow__actions,
+ &:focus-within .TodayRow__actions {
+ pointer-events: auto;
+ opacity: 1;
+ }
+
+ &[data-done] .TodayRow__title {
+ color: var(--today-muted);
+ }
+
+ &[data-done] .TodayRow__icons {
+ filter: grayscale(1);
+ opacity: 0.45;
}
- p + p {
- margin-top: 7px;
+ &[data-done] .TodayRow__label {
+ color: inherit;
}
}
-.TodayHome__intro {
- margin-top: clamp(72px, 12vh, 120px);
- color: var(--today-faint);
+.TodayRow__icons {
+ margin-top: -2px;
+ margin-left: -3px;
}
-.TodayHome__greeting {
- display: flex;
- gap: 10px;
- align-items: center;
- margin-bottom: 10px;
+.TodayRow__iconSkeleton {
+ width: 26px;
+ height: 26px;
+ border-radius: 8px;
}
-.TodayHome__badge {
- display: inline-flex;
- gap: 6px;
- align-items: center;
- padding: 2px 8px;
- font-size: 12px;
+.TodayRow__title {
+ display: block;
+ font-size: 15px;
font-weight: 500;
- color: var(--today-faint);
- letter-spacing: 0;
- border: 1px solid color-mix(in sRGB, var(--today-ink) 12%, transparent);
- border-radius: 999px;
+ line-height: 22px;
+ color: var(--today-ink);
+ text-wrap: pretty;
}
-.TodayChipStack {
- --quill-icon-stack-ring: var(--today-paper);
-
- margin-left: 10px;
- vertical-align: -8px;
-}
+.TodayRow__link,
+.TodayJumpRow__link {
+ &::after {
+ position: absolute;
+ inset: 0;
+ content: '';
+ border-radius: 8px;
+ }
-// A link inside running text. A container sets `--today-link` to change its resting colour.
-.TodayInlineLink {
- color: var(--today-link, var(--today-muted));
- text-decoration: underline;
- text-decoration-thickness: 1.5px;
- text-decoration-color: color-mix(in oklab, currentColor 50%, transparent);
- text-underline-offset: 5px;
- transition:
- color 0.16s,
- text-decoration-color 0.16s;
+ &:focus-visible {
+ outline: none;
- &:hover,
- &:active,
- &[data-active='true'] {
- color: var(--today-ink);
- text-decoration-color: var(--today-ink);
+ &::after {
+ outline: 2px solid var(--today-focus-border);
+ outline-offset: -2px;
+ }
}
}
-.TodayHome__highlight {
- padding: 0.02em 0.2em 0.08em;
- margin: 0 -0.03em;
+.TodayReportHeader__icon {
+ --icon-stack-size: 22px;
+ --quill-icon-stack-ring: var(--today-paper);
+}
- // `--primary-light` is the brand orange in both themes; `--primary` turns yellow in dark mode.
- background: color-mix(in oklab, var(--primary-light) 22%, transparent);
- border-radius: 0.26em;
- box-decoration-break: clone;
+.TodayRow__label {
+ font-variant-numeric: tabular-nums;
- .TodayInlineLink,
- .TodayInlineLink:hover,
- .TodayInlineLink[data-active='true'] {
+ &[data-tone='risk'] {
font-weight: 500;
- color: var(--primary-light);
- text-decoration: none;
+ color: var(--today-risk);
}
+}
- // The strike outlives the reset above, so a resolved item reads the same here as in the rail.
- .TodayInlineLink[data-state='done'] {
- text-decoration: line-through;
- }
+.TodayRow__meta {
+ margin: 2px 0 0;
+ font-size: 14px;
+ line-height: 20px;
+ color: var(--today-muted);
+ text-wrap: pretty;
}
-.TodayHome__progress {
- font-size: 13px;
- font-variant-numeric: tabular-nums;
- color: var(--today-faint);
+.TodayRow__end {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ align-self: center;
+}
+
+.TodayRow__actions {
+ position: absolute;
+ top: 50%;
+ right: 34px;
+ z-index: 1;
+ display: flex;
+ gap: 2px;
+ align-items: center;
+ padding-left: 24px;
+ pointer-events: none;
+ background: linear-gradient(to right, transparent, var(--today-soft) 20px);
+ opacity: 0;
+ transition: opacity 0.12s var(--today-ease);
+ transform: translateY(-50%);
}
-.TodayHome__foot {
- margin-top: 48px;
+.TodayRow__toggle {
+ padding: 0;
+ margin: 0;
+ font-family: inherit;
+ text-align: left;
+ appearance: none;
+ cursor: pointer;
+ background: none;
+ border: 0;
+}
+
+.TodayRow__chevron {
+ width: 14px;
+ height: 14px;
+ color: var(--today-muted);
+ opacity: 0;
+ transition:
+ opacity 0.12s var(--today-ease),
+ transform 0.2s var(--today-ease);
}
-.TodayInboxLink {
- color: var(--primary);
+.TodayRow__detail {
+ position: relative;
+ z-index: 1;
+ grid-column: 2 / -1;
+ margin: 0 -3px -3px 0;
}
-// A button inside running text that reads as a link.
-.TodayInlineAction {
+.TodayRow__detailBody {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 8px 3px 3px 0;
+}
+
+.TodayRow__detailLead {
+ max-width: 62ch;
+ margin: 0;
+ font-size: 14px;
+ line-height: 21px;
+ color: var(--today-body-text);
+ text-wrap: pretty;
+}
+
+.TodayRow__detailFooter {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px 12px;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.TodayRow__detailFacts {
+ min-width: 0;
+ margin: 0;
+ font-size: 13px;
+ line-height: 18px;
+ color: var(--today-muted);
+}
+
+.TodayRow__detailPr {
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
color: var(--today-ink);
- text-decoration: underline;
- text-decoration-color: color-mix(in oklab, var(--today-ink) 45%, transparent);
- text-underline-offset: 5px;
&:hover {
- color: var(--primary);
+ text-decoration: underline;
}
}
-// Recent work on the home
+.TodayRow__detailActions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ align-items: center;
+}
+
+.TodayRow__undo {
+ position: relative;
+ z-index: 1;
+}
-.TodayHome__recents {
- margin-top: 56px;
+.TodayRow__arrow {
+ width: 14px;
+ height: 14px;
color: var(--today-muted);
+ opacity: 0;
+ transition:
+ opacity 0.12s var(--today-ease),
+ transform 0.12s var(--today-ease);
+ transform: translateX(-3px);
}
-.TodayRecentList {
- padding: 0;
- margin: 0 0 10px;
- list-style: none;
+.TodayRows__footer {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 16px;
+ align-items: center;
+ justify-content: space-between;
}
-.TodayRecentRow {
- --today-link: var(--today-ink);
+.TodayRows__inbox {
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+ font-size: 14px;
+ color: var(--today-muted);
+ transition: color 0.12s var(--today-ease);
- display: flex;
- gap: 10px;
+ &:hover {
+ color: var(--today-ink);
+ }
+}
+
+.TodayRows__more {
+ display: grid;
+ grid-template-columns: 26px auto;
+ gap: 12px;
align-items: center;
- min-width: 0;
- padding: 3px 0;
+ align-self: flex-start;
+ height: auto;
+ padding: 6px 12px;
+ margin: 0 -12px;
+ font-size: 14px;
+ font-weight: inherit;
+ color: var(--today-muted);
- .TodayRecentIcon {
- flex-shrink: 0;
- margin-right: 0;
+ &:hover {
+ color: var(--today-ink);
+ }
+}
- > span {
- transition: transform 0.18s;
- }
+.TodayRows__moreIcon {
+ justify-self: center;
+ width: 16px;
+ height: 16px;
+}
+
+.TodayReportNav {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+ height: 28px;
+ margin: -58px 0 30px;
+ font-size: 13px;
+ color: var(--today-muted);
+
+ @container main-content (max-width: 600px) {
+ margin: 0 0 16px;
}
+}
- &:hover .TodayRecentIcon > span,
- &:focus-within .TodayRecentIcon > span {
- transform: rotate(-6deg) scale(1.08);
+.TodayReportNav__back {
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+ color: var(--today-muted);
+ transition: color 0.12s var(--today-ease);
- @media (prefers-reduced-motion: reduce) {
- transform: none;
- }
+ &:hover {
+ color: var(--today-ink);
}
}
-.TodayRecentRow__meta {
- flex-shrink: 0;
+.TodayReportNav__steps {
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+}
+
+.TodayReportNav__count {
+ margin-right: 6px;
+ font-variant-numeric: tabular-nums;
+}
+
+.TodayHome__meta {
+ margin: 0;
font-size: 14px;
- white-space: pre;
+ line-height: 20px;
+ color: var(--today-muted);
}
-.TodayRecentRow__time {
+.TodayHome__intro {
+ margin-top: 8px;
color: var(--today-faint);
}
-// A small type tile before each recent object, in the style of the report chips above it.
-.TodayRecentIcon {
+.TodayHome__greeting {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ margin-bottom: 4px;
+}
+
+.TodayHome__refresh {
+ opacity: 0;
+ transition: opacity 0.12s var(--today-ease);
+
+ .TodayHome__greeting:hover &,
+ &:focus-visible {
+ opacity: 1;
+ }
+}
+
+.TodayHome__badge {
display: inline-flex;
- margin-right: 5px;
- vertical-align: -3px;
+ gap: 6px;
+ align-items: center;
+ padding: 2px 8px;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--today-faint);
+ letter-spacing: 0;
+ border: 1px solid color-mix(in sRGB, var(--today-ink) 12%, transparent);
+ border-radius: 999px;
+}
- // The product icon wrapper sets `color` to the product's color, so the tile fills with it.
- > span {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- background: currentColor;
- border-radius: 5px;
+.TodayJumpList {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ padding: 0;
+ margin: 0 -12px;
+ list-style: none;
+
+ &--explore {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
}
- svg {
- width: 11px;
- height: 11px;
- color: #fff;
+ @container main-content (max-width: 700px) {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+.TodayJumpRow {
+ --quill-icon-stack-ring: var(--today-paper);
+
+ position: relative;
+ display: grid;
+ grid-template-columns: 26px minmax(0, 1fr);
+ gap: 12px;
+ align-items: start;
+ min-width: 0;
+ padding: 8px 12px;
+ border-radius: 8px;
+ transition: background-color 0.12s var(--today-ease);
+
+ &:hover {
+ --quill-icon-stack-ring: var(--today-soft);
+
+ background: var(--today-soft);
}
}
+.TodayJumpRow__link {
+ display: block;
+ overflow: hidden;
+ font-size: 14px;
+ line-height: 20px;
+ color: var(--today-ink);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.TodayJumpRow__meta {
+ display: block;
+ overflow: hidden;
+ font-size: 13px;
+ line-height: 18px;
+ color: var(--today-muted);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.TodayJumpRow__icon {
+ --icon-stack-size: 22px;
+
+ margin-top: 1px;
+ margin-left: -1px;
+}
+
.TodayHoverMark {
cursor: default;
outline: none;
@@ -620,13 +919,6 @@
// Keyframes
-@keyframes Today__page-in {
- from {
- opacity: 0;
- transform: translateY(2px);
- }
-}
-
@container main-content (max-width: 600px) {
.TodayHome__intro {
margin-top: 32px;
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index eae1a06d44db..c11b42b0e298 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -6,9 +6,8 @@ import { ReactNode } from 'react'
import { Card } from '@posthog/quill'
import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { App } from 'scenes/App'
-import { briefingItemReportCard } from 'scenes/project-homepage/today/todayBriefingItems'
-import { TodayReportHoverCard } from 'scenes/project-homepage/today/TodayReportHoverCard'
import { urls } from 'scenes/urls'
import { todayListAppearanceLogic } from '~/layout/today/todayListAppearanceLogic'
@@ -26,10 +25,10 @@ import {
reportMetricQueryHandler,
reportMetricsFixture,
} from 'products/signals/frontend/inbox/__mocks__/reportMetricMocks'
-import { SignalReportStatus } from 'products/signals/frontend/inbox/types'
+import { SignalReportPriority, SignalReportStatus } from 'products/signals/frontend/inbox/types'
import { 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'
+import type { BriefingApi, BriefingItemApi, HighlightsApi } from 'products/today/frontend/generated/api.schemas'
const ADA = {
id: 1,
@@ -402,8 +401,79 @@ const REPORTS = [
},
],
}),
+ makeReport({
+ id: 'report-5',
+ title: 'Webhook retries pile up for one destination',
+ summary: 'One webhook destination times out, so its retries fill the queue.',
+ summary_lead: 'One webhook destination times out, so its retries fill the queue.',
+ status: SignalReportStatus.READY,
+ signal_count: 3,
+ updated_at: '2026-09-27T16:00:00Z',
+ priority: 'P2',
+ actionability: 'immediately_actionable',
+ source_products: ['error_tracking'],
+ }),
+ makeReport({
+ id: 'report-6',
+ title: 'Most new teams skip the third onboarding step',
+ summary: 'The third onboarding step has the largest drop in the setup funnel.',
+ summary_lead: 'The third onboarding step has the largest drop in the setup funnel.',
+ status: SignalReportStatus.READY,
+ signal_count: 2,
+ updated_at: '2026-09-27T09:00:00Z',
+ priority: 'P3',
+ actionability: 'requires_human_input',
+ source_products: ['product_analytics'],
+ }),
+ makeReport({
+ id: 'report-7',
+ title: 'Mobile recordings stop after the app goes to the background',
+ summary: 'Recordings on mobile end when the app moves to the background and does not resume.',
+ summary_lead: 'Recordings on mobile end when the app moves to the background and does not resume.',
+ status: SignalReportStatus.READY,
+ signal_count: 5,
+ updated_at: '2026-09-26T12:00:00Z',
+ priority: 'P2',
+ actionability: 'immediately_actionable',
+ source_products: ['session_replay'],
+ }),
]
+const MORE_REPORTS = (
+ [
+ ['Invite emails land in spam for one domain', 'P2', 'error_tracking'],
+ ['Search returns no results for quoted terms', 'P3', 'session_replay'],
+ ['Export to CSV times out for large tables', 'P2', 'error_tracking'],
+ ['Onboarding checklist resets after a page reload', 'P3', 'session_replay'],
+ ['Billing page shows the wrong currency for some teams', 'P1', 'error_tracking'],
+ ['Dark mode toggle does not persist across sessions', 'P4', 'session_replay'],
+ ['Webhook signatures fail after a key rotation', 'P2', 'error_tracking'],
+ ['Free trial banner overlaps the navigation on small screens', 'P3', 'session_replay'],
+ ['Password reset links expire before people open them', 'P2', 'product_analytics'],
+ ['API rate limit errors spike during nightly syncs', 'P3', 'error_tracking'],
+ ['Team invite form accepts duplicate emails', 'P4', 'product_analytics'],
+ ['Chart tooltips cut off near the right edge', 'P4', 'session_replay'],
+ ['Slow first load on the pricing page', 'P3', 'product_analytics'],
+ ['Saved filters disappear after renaming a project', 'P2', 'error_tracking'],
+ ] as [string, SignalReportPriority, string][]
+).map(([title, priority, source], index) =>
+ makeReport({
+ id: `report-${index + 8}`,
+ title,
+ summary: title,
+ summary_lead: title,
+ status: SignalReportStatus.READY,
+ signal_count: 2 + (index % 5),
+ updated_at: `2026-09-${String(25 - (index % 9)).padStart(2, '0')}T10:00:00Z`,
+ priority,
+ actionability: 'requires_human_input',
+ source_products: [source],
+ })
+)
+
+const ALL_REPORTS = [...REPORTS, ...MORE_REPORTS]
+const OPEN_REPORT_COUNT = 46
+
function briefingItem(overrides: Partial<BriefingItemApi> & Pick<BriefingItemApi, 'key' | 'label'>): BriefingItemApi {
return {
title: overrides.label,
@@ -550,6 +620,7 @@ const PERSONAL_BRIEFING: BriefingApi = {
],
more_reports_count: 4,
open_reports_count: 37,
+ refresh_at: '2026-09-29T06:00:00Z',
status: 'ready',
writer: 'agent',
created_at: '2026-09-28T06:00:00Z',
@@ -576,7 +647,7 @@ function clearTodayStorage(
}
function mockReportPage(reportId: string): ReportPageApi {
- const report = REPORTS.find((candidate) => candidate.id === reportId) ?? REPORTS[0]
+ const report = ALL_REPORTS.find((candidate) => candidate.id === reportId) ?? REPORTS[0]
const signals = mockSignals(reportId, 6).map((signal) => {
const firstLine = signal.content.split('\n')[0]
return {
@@ -629,6 +700,142 @@ function mockReportPage(reportId: string): ReportPageApi {
}
}
+const DAILY = (base: number, step: number): number[] =>
+ Array.from({ length: 28 }, (_, day) => base + ((day * step) % 23) + (day % 7 >= 5 ? -base * 0.3 : 0))
+
+const PERIOD_STARTS = (count: number, unit: 'day' | 'week'): string[] =>
+ Array.from({ length: count }, (_, index) =>
+ dayjs('2026-09-28')
+ .startOf(unit)
+ .subtract(count - index, unit)
+ .format('YYYY-MM-DD')
+ )
+
+const HIGHLIGHTS: HighlightsApi = {
+ status: 'ready',
+ generated_at: '2026-09-28T18:00:00Z',
+ day: '2026-09-28',
+ refresh_at: '2026-09-29T00:00:00Z',
+ pulse: [
+ {
+ key: 'insight:wKu1pSx2',
+ name: 'Weekly file uploads',
+ value: 4210,
+ unit: 'number',
+ change_pct: 6.4,
+ series: [3100, 3250, 3300, 3420, 3380, 3600, 3710, 3690, 3850, 3920, 3956, 4210],
+ interval: 'week',
+ url: '/insights/wKu1pSx2',
+ value_format: null,
+ period_starts: PERIOD_STARTS(12, 'week'),
+ },
+ {
+ key: 'signup_event',
+ name: 'Sign-ups',
+ value: 1201,
+ unit: 'events',
+ change_pct: 18.1,
+ series: DAILY(170, 7),
+ interval: 'day',
+ url: null,
+ value_format: null,
+ period_starts: PERIOD_STARTS(28, 'day'),
+ },
+ {
+ key: 'payment_event',
+ name: 'Payments',
+ value: 342,
+ unit: 'events',
+ change_pct: -3.1,
+ series: DAILY(48, 5),
+ interval: 'day',
+ url: null,
+ value_format: null,
+ period_starts: PERIOD_STARTS(28, 'day'),
+ },
+ {
+ key: 'activity_event',
+ name: 'Active users',
+ value: 18300,
+ unit: 'people',
+ change_pct: 1.6,
+ series: DAILY(2600, 11),
+ interval: 'day',
+ url: null,
+ value_format: null,
+ period_starts: PERIOD_STARTS(28, 'day'),
+ },
+ ],
+ items: [
+ {
+ key: 'alert:chk01:Checkout conversion',
+ label: 'risk',
+ title: 'Alert ‘Checkout conversion’ is firing',
+ detail: 'Insight ‘Checkout funnel’',
+ url: '/insights/chk01',
+ series: null,
+ score: 0.85,
+ priority: 'P1',
+ source: 'alerts',
+ },
+ {
+ key: 'new_error:0195a0b2-0000-0000-0000-000000000001',
+ label: 'risk',
+ title: '214 users saw the new error ‘TypeError: Cannot read properties of null (reading ‘price’)’',
+ detail: 'Since Sep 26 · 1.8% of active users · No owner',
+ url: '/error_tracking/0195a0b2-0000-0000-0000-000000000001',
+ series: null,
+ score: 0.82,
+ priority: 'P1',
+ source: 'errors',
+ },
+ {
+ key: 'home:rev01',
+ label: 'risk',
+ title: '‘Refunds’ increased by 39% last week',
+ detail: '44 → 61',
+ url: '/insights/rev01',
+ series: [40, 43, 39, 45, 42, 41, 44, 61],
+ score: 0.6,
+ priority: 'P2',
+ source: 'home',
+ },
+ {
+ key: 'key_metric:payment_event',
+ label: 'risk',
+ title: '‘Payments’ decreased by 41% yesterday',
+ detail: '118 yesterday · 200 on an average Sunday',
+ url: null,
+ series: [196, 172, 168, 181, 175, 162, 204, 190, 178, 171, 183, 169, 158, 118],
+ score: 0.57,
+ priority: 'P2',
+ source: 'key_metrics',
+ },
+ {
+ key: 'experiment_ended:12',
+ label: 'opportunity',
+ title: 'Experiment ‘Pricing page layout’ ended yesterday',
+ detail: 'Read the results and decide whether to release the change',
+ url: '/experiments/12',
+ series: null,
+ score: 0.6,
+ priority: 'P3',
+ source: 'experiments',
+ },
+ {
+ key: 'assigned_quiet',
+ label: 'opportunity',
+ title: '2 of your issues had no events in the last 14 days',
+ detail: '‘TypeError: e.map is not a function’ and 1 more',
+ url: '/error_tracking',
+ series: null,
+ score: 0.35,
+ priority: 'P4',
+ source: 'errors',
+ },
+ ],
+}
+
const meta: Meta = {
component: App,
title: 'Scenes-App/Project Homepage/Today',
@@ -639,18 +846,39 @@ const meta: Meta = {
mswDecorator({
get: {
'/api/projects/:team_id/signals/reports/': { results: REPORTS, count: 7 },
- '/api/projects/:team_id/signals/reports/for_you/': { results: REPORTS, count: 7 },
+ '/api/projects/:team_id/signals/reports/for_you/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const limit = Number(params.get('limit') ?? REPORTS.length)
+ const offset = Number(params.get('offset') ?? 0)
+ const excluded = new Set(params.get('exclude')?.split(',') ?? [])
+ const ranked = ALL_REPORTS.filter((report) => !excluded.has(report.id))
+ return [
+ 200,
+ {
+ results: ranked.slice(offset, offset + limit),
+ count: OPEN_REPORT_COUNT - (ALL_REPORTS.length - ranked.length),
+ },
+ ]
+ },
+ '/api/projects/:team_id/signals/reports/available_reviewers/': {},
+ '/api/projects/:team_id/signals/reports/:id/pr_checks/': { checks: [] },
+ '/api/projects/:team_id/signals/reports/:id/pr_comments/': { comments: [] },
'/api/projects/:team_id/signals/reports/:id/': (req) => [
200,
- REPORTS.find((report) => report.id === req.params.id) ?? REPORTS[0],
+ ALL_REPORTS.find((report) => report.id === req.params.id) ?? REPORTS[0],
],
'/api/environments/:team_id/query/:kind/': reportMetricQueryHandler,
'/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/projects/:team_id/signals/reports/:id/signals/': (req) => [
+ 200,
+ { report: REPORTS.find((report) => report.id === req.params.id) ?? REPORTS[0], signals: [] },
+ ],
'/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/today/highlights/': HIGHLIGHTS,
'/api/projects/:team_id/task_channels/': SPACES,
'/api/projects/:team_id/task_channels/:id/': (req) => [
200,
@@ -722,6 +950,10 @@ const meta: Meta = {
},
post: {
'/api/environments/:team_id/query/:kind/': reportMetricQueryHandler,
+ '/api/projects/:team_id/signals/reports/:id/state/': (req) => [
+ 200,
+ REPORTS.find((report) => report.id === req.params.id) ?? REPORTS[0],
+ ],
'/api/projects/:team_id/tasks/summaries/': {
count: 2,
next: null,
@@ -817,6 +1049,14 @@ export const SampleReportPage: Story = {
parameters: { pageUrl: `${urls.todayReport('sample-pr')}?sample=1` },
}
+export const HomeWithReportsOnly: Story = {
+ decorators: [
+ mswDecorator({
+ get: { '/api/projects/:team_id/today/highlights/': { ...HIGHLIGHTS, items: [] } },
+ }),
+ ],
+}
+
export const HomeWithNoReports: Story = {
decorators: [
mswDecorator({
@@ -825,6 +1065,17 @@ export const HomeWithNoReports: Story = {
],
}
+export const HomeWithoutAiAndNothingNew: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/signals/reports/for_you/': { results: [], count: 0 },
+ '/api/projects/:team_id/today/highlights/': { ...HIGHLIGHTS, items: [] },
+ },
+ }),
+ ],
+}
+
export const HomeWhenReportsFailToLoad: Story = {
decorators: [
mswDecorator({
@@ -833,6 +1084,17 @@ export const HomeWhenReportsFailToLoad: Story = {
],
}
+export const HomeWithoutReportsWhenHighlightsFailToLoad: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/signals/reports/for_you/': { results: [], count: 0 },
+ '/api/projects/:team_id/today/highlights/': () => [500, { detail: 'Server error' }],
+ },
+ }),
+ ],
+}
+
export const ReportWithPullRequest: Story = {
parameters: { pageUrl: urls.todayReport('report-1') },
}
@@ -1064,34 +1326,6 @@ export const SessionHoverCard: Story = {
),
}
-export const ReportHoverCard: Story = {
- render: () => (
- <HoverCardFrame>
- <TodayReportHoverCard
- preview={{
- kind: 'report',
- card: briefingItemReportCard(PERSONAL_BRIEFING.items[0]),
- surface: 'sidebar',
- }}
- />
- </HoverCardFrame>
- ),
-}
-
-export const ReportHoverCardResolved: Story = {
- render: () => (
- <HoverCardFrame>
- <TodayReportHoverCard
- preview={{
- kind: 'report',
- card: briefingItemReportCard({ ...PERSONAL_BRIEFING.items[1], state: 'done' }),
- surface: 'sidebar',
- }}
- />
- </HoverCardFrame>
- ),
-}
-
// The details are picked through the logic, where the dialog saves them, so each session row shows a second line.
export const ChatsPaneWithListItemDetails: Story = {
play: async ({ canvasElement }) => {
diff --git a/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx b/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx
deleted file mode 100644
index 8cf48cb29cfe..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayBriefing.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconRefresh } from '@posthog/icons'
-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
-import { Text } from '@posthog/quill'
-
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
-import { urls } from 'scenes/urls'
-
-import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
-
-import { WALK_THROUGH_QUESTION } from './todayAskPrompt'
-import { TodayChipStack } from './TodayChipStack'
-import { TodayIcon } from './TodayIcon'
-import { todayLogic } from './todayLogic'
-import { TodayPartyPopper } from './TodayPartyPopper'
-import { TodayPersonalBriefing } from './TodayPersonalBriefing'
-import { TodayRecents } from './TodayRecents'
-import { TodaySampleBanner } from './TodaySampleBanner'
-import { TodayBriefingSegment, reportIcon, reportSource } from './todaySignalReports'
-
-const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { weekday: 'short', day: 'numeric', month: 'short' })
-const TIME_FORMAT = new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit' })
-
-function TodayMetaLine(): JSX.Element {
- const { now, currentTeam } = useValues(todayLogic)
- const date = new Date(now)
- return (
- <div className="TodayHome__meta">
- <TodayPartyPopper />
- <span className="whitespace-pre">{`${currentTeam?.name ?? 'Your project'} · ${DATE_FORMAT.format(date)} · `}</span>
- <time translate="no" dateTime={date.toISOString()}>
- {TIME_FORMAT.format(date)}
- </time>
- </div>
- )
-}
-
-function BriefingSegment({ segment }: { segment: TodayBriefingSegment }): JSX.Element {
- const { hoveredReportId, reports, teamReportPreviews, reportStateOverrides } = useValues(todayLogic)
- const { reportOpened, setHoveredReportId } = useActions(todayLogic)
- const { reportId } = segment
- if (!reportId) {
- return <span>{segment.text}</span>
- }
- // A briefing can link a report outside the top five, which has no row to open it from.
- const report = reports.find((candidate) => candidate.id === reportId)
- const link = (
- <LinkPrimitive
- to={urls.todayReport(reportId)}
- className="TodayInlineLink"
- data-active={hoveredReportId === reportId}
- data-state={reportStateOverrides[reportId] ?? 'open'}
- data-attr="today-briefing-report"
- onClick={() => report && reportOpened(report, 'briefing')}
- onMouseEnter={() => setHoveredReportId(reportId)}
- onMouseLeave={() => setHoveredReportId(null)}
- >
- {segment.text}
- </LinkPrimitive>
- )
- const preview = teamReportPreviews.briefing[reportId]
- const linkWithCard = preview ? (
- <TodayPreviewTrigger payload={preview} inline>
- {link}
- </TodayPreviewTrigger>
- ) : (
- link
- )
- return segment.highlight ? <span className="TodayHome__highlight">{linkWithCard}</span> : linkWithCard
-}
-
-function TodayBriefingReports(): JSX.Element {
- const { reportSummary, reports, briefing, hoveredReportId, moreReportCount } = useValues(todayLogic)
- const { askAi, openReport, setHoveredReportId } = useActions(todayLogic)
-
- return (
- <>
- <p className="TodayHome__count">
- <span>{reportSummary}</span>
- <TodayChipStack
- dataAttr="today-briefing-chip"
- chips={reports.map((report) => ({
- key: report.id,
- label: report.title ?? 'report',
- color: reportSource(report).color,
- icon: <TodayIcon icon={reportIcon(report)} />,
- active: hoveredReportId === report.id,
- onClick: () => openReport(report, 'chip'),
- onHoverChange: (hovered) => setHoveredReportId(hovered ? report.id : null),
- }))}
- />
- </p>
- {briefing.map((paragraph, index) => (
- <p key={index}>
- {paragraph.map((segment, segmentIndex) => (
- <BriefingSegment key={segmentIndex} segment={segment} />
- ))}
- </p>
- ))}
- <p className="TodayHome__foot">
- {moreReportCount > 0 && (
- <>
- <LinkPrimitive to={urls.inbox()} className="TodayInboxLink" data-attr="today-briefing-inbox">
- {`${moreReportCount} more for you in the Inbox`}
- </LinkPrimitive>
- <span>. </span>
- </>
- )}
- <span>Or </span>
- <button
- type="button"
- className="TodayInlineAction"
- data-attr="today-ask-about-edition"
- onClick={() => askAi(WALK_THROUGH_QUESTION, 'walk_through')}
- >
- ask PostHog AI to walk you through it
- </button>
- <span>.</span>
- </p>
- </>
- )
-}
-
-export function TodayBriefing(): JSX.Element {
- const {
- greeting,
- topReports,
- topReportsLoading,
- reportsFailed,
- reports,
- showPersonalBriefing,
- personalBriefing,
- briefingWaiting,
- } = useValues(todayLogic)
- const { loadTopReports, refreshBriefing } = useActions(todayLogic)
-
- return (
- <div className="TodayHome Today__page" data-quill>
- <TodaySampleBanner />
- <TodayMetaLine />
- <section className="TodayHome__prose TodayHome__intro" aria-label="Daily brief">
- <div className="TodayHome__greeting">
- <Text render={<h1 />} className="m-0 text-[21px] font-[560] tracking-[-0.015em]">
- {greeting}
- </Text>
- {briefingWaiting ? (
- <span className="TodayHome__badge" data-attr="today-briefing-writing">
- <Spinner textColored />
- <span>Writing your briefing…</span>
- </span>
- ) : showPersonalBriefing || personalBriefing?.status === 'failed' ? (
- <LemonButton
- size="xsmall"
- icon={<IconRefresh />}
- tooltip="Refresh briefing"
- onClick={() => refreshBriefing()}
- data-attr="today-briefing-refresh"
- />
- ) : null}
- </div>
- {showPersonalBriefing ? (
- <TodayPersonalBriefing />
- ) : topReports === null && reportsFailed ? (
- <LemonBanner
- type="error"
- action={{
- children: 'Try again',
- onClick: () => loadTopReports(),
- loading: topReportsLoading,
- 'data-attr': 'today-reports-retry',
- }}
- >
- Couldn’t load your reports. Try again, or open the Inbox to see them there.
- </LemonBanner>
- ) : topReports === null ? (
- <p>Reading what changed in your project…</p>
- ) : reports.length === 0 ? (
- <>
- <p className="TodayHome__count">Nothing needs your attention</p>
- <p>
- <span>
- Self-driving turns signals from across PostHog into reports worth acting on. New ones
- show up here as it finds them.{' '}
- </span>
- <LinkPrimitive to={urls.inbox()} className="TodayInboxLink" data-attr="today-empty-inbox">
- Open the Inbox
- </LinkPrimitive>
- <span> to see everything it’s tracking.</span>
- </p>
- </>
- ) : (
- <TodayBriefingReports />
- )}
- </section>
- <TodayRecents />
- </div>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayBriefingItemRow.tsx b/frontend/src/scenes/project-homepage/today/TodayBriefingItemRow.tsx
new file mode 100644
index 000000000000..510ead486c05
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayBriefingItemRow.tsx
@@ -0,0 +1,83 @@
+import { useActions, useValues } from 'kea'
+
+import type { BriefingItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { itemHref, itemReportId, itemStateLabel } from './todayBriefingItems'
+import { todayLogic } from './todayLogic'
+import { priorityTone } from './todayPriority'
+import { TodayReportRowDetail } from './TodayReportRowDetail'
+import { TodayRow } from './TodayRow'
+import { pullRequestFact, rowFacts } from './todayRowFacts'
+import { briefingItemIcon } from './todayRowIcons'
+import { TodayVerdictButtons } from './TodayVerdictButtons'
+import type { TodayReportVerdictTarget } from './todayVerdictLogic'
+
+const SOURCE_LABELS: Record<BriefingItemApi['source'], string> = {
+ self_driving: 'Report',
+ product_analytics: 'Dashboard',
+ alerts: 'Alert',
+ support: 'Ticket',
+ error_tracking: 'Issue',
+ github: 'Pull request',
+}
+
+function withoutPriority(signal: string): string {
+ const rest = signal.replace(/^P\d,\s*/, '')
+ return rest.charAt(0).toUpperCase() + rest.slice(1)
+}
+
+export function TodayBriefingItemRow({ item, done }: { item: BriefingItemApi; done: boolean }): JSX.Element {
+ const { reportPreviews, expandedReportRows } = useValues(todayLogic)
+ const { itemOpened, toggleReportRow } = useActions(todayLogic)
+ const priority = item.report ? item.report.priority : 'P2'
+ const kind = item.report ? null : item.group === 'dashboard' ? 'Dashboard' : SOURCE_LABELS[item.source]
+ const reportId = itemReportId(item)
+ const preview = reportPreviews[item.key]
+ const to = itemHref(item)
+ const target: TodayReportVerdictTarget | null = reportId
+ ? {
+ reportId,
+ title: item.title,
+ hasOpenPullRequest:
+ !!item.report?.pull_request_url &&
+ item.report.pull_request_state !== 'closed' &&
+ item.report.pull_request_state !== 'merged',
+ }
+ : null
+ return (
+ <TodayRow
+ tone={priorityTone(priority)}
+ icon={briefingItemIcon(item)}
+ title={item.title}
+ label={priority ?? undefined}
+ facts={
+ done
+ ? rowFacts([itemStateLabel(item)])
+ : rowFacts([kind, withoutPriority(item.signal), pullRequestFact(item.report?.pull_request_state)])
+ }
+ to={to}
+ onOpen={() => itemOpened(item)}
+ expansion={
+ preview && target
+ ? {
+ expanded: !!expandedReportRows[item.key],
+ onToggle: () => toggleReportRow(item.key, target.reportId),
+ detail: (
+ <TodayReportRowDetail
+ preview={preview}
+ to={to}
+ onOpen={() => itemOpened(item)}
+ actions={done ? null : <TodayVerdictButtons target={target} labelled />}
+ dataAttr="today-list-briefing-item"
+ />
+ ),
+ }
+ : undefined
+ }
+ actions={target ? <TodayVerdictButtons target={target} /> : undefined}
+ done={done}
+ reportId={reportId ?? undefined}
+ dataAttr="today-list-briefing-item"
+ />
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayChipStack.tsx b/frontend/src/scenes/project-homepage/today/TodayChipStack.tsx
deleted file mode 100644
index 64e0db258bf9..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayChipStack.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { IconStack, IconStackItem } from '@posthog/quill'
-
-export interface TodayChip {
- key: string
- /** Read out for the chip, which shows only an icon. */
- label: string
- color: string
- icon: JSX.Element
- /** Lifted, because the matching item is hovered elsewhere on the page. */
- active?: boolean
- onClick: () => void
- onHoverChange: (hovered: boolean) => void
-}
-
-interface TodayChipStackProps {
- chips: TodayChip[]
- dataAttr: string
-}
-
-export function TodayChipStack({ chips, dataAttr }: TodayChipStackProps): JSX.Element | null {
- if (chips.length === 0) {
- return null
- }
- return (
- <IconStack className="TodayChipStack">
- {chips.map((chip) => (
- <IconStackItem
- key={chip.key}
- color={chip.color}
- active={chip.active}
- render={
- <button
- type="button"
- aria-label={`Open ${chip.label}`}
- data-attr={dataAttr}
- onClick={chip.onClick}
- onMouseEnter={() => chip.onHoverChange(true)}
- onMouseLeave={() => chip.onHoverChange(false)}
- />
- }
- >
- {chip.icon}
- </IconStackItem>
- ))}
- </IconStack>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayExplore.tsx b/frontend/src/scenes/project-homepage/today/TodayExplore.tsx
new file mode 100644
index 000000000000..212a454d0120
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayExplore.tsx
@@ -0,0 +1,40 @@
+import { useActions, useValues } from 'kea'
+import { useId } from 'react'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { TodayObjectIcon } from '~/layout/today/TodayObjectIcon'
+
+import { TodayHomeHeading } from './TodayHomeHeading'
+import { todayLogic } from './todayLogic'
+
+export function TodayExplore(): JSX.Element {
+ const { exploreItems } = useValues(todayLogic)
+ const { exploreOpened } = useActions(todayLogic)
+ const titleId = useId()
+ return (
+ <section className="TodayHome__list" aria-labelledby={titleId}>
+ <div className="TodayHome__headingRow">
+ <TodayHomeHeading id={titleId}>Explore</TodayHomeHeading>
+ </div>
+ <ul className="TodayJumpList TodayJumpList--explore">
+ {exploreItems.map((item, position) => (
+ <li key={item.product} className="TodayJumpRow">
+ <TodayObjectIcon type={item.icon} className="TodayJumpRow__icon" />
+ <div className="min-w-0">
+ <LinkPrimitive
+ to={item.to()}
+ className="TodayJumpRow__link"
+ onClick={() => exploreOpened(item.product, position)}
+ data-attr="today-home-explore"
+ >
+ {item.name}
+ </LinkPrimitive>
+ <span className="TodayJumpRow__meta">{item.description}</span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayForYou.tsx b/frontend/src/scenes/project-homepage/today/TodayForYou.tsx
new file mode 100644
index 000000000000..cfdaab73ebb8
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayForYou.tsx
@@ -0,0 +1,128 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArrowRight, IconChevronDown } from '@posthog/icons'
+import { Button, Skeleton } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { TodayBriefingItemRow } from './TodayBriefingItemRow'
+import { type TodayForYouRow } from './todayForYouRows'
+import { TodayHighlightRow } from './TodayHighlightRow'
+import { TodayHomeHeading } from './TodayHomeHeading'
+import { todayLogic } from './todayLogic'
+import { TodayReportRow } from './TodayReportRow'
+
+function TodayRowsSkeleton(): JSX.Element {
+ return (
+ <ol className="TodayRows" aria-busy aria-label="Loading">
+ {['w-3/5', 'w-4/5', 'w-1/2'].map((width) => (
+ <li key={width} className="TodayRow">
+ <Skeleton className="TodayRow__iconSkeleton" />
+ <div className="flex flex-col gap-2 py-1">
+ <Skeleton className={`h-3.5 ${width}`} />
+ <Skeleton className="h-3 w-2/5" />
+ </div>
+ </li>
+ ))}
+ </ol>
+ )
+}
+
+function renderRow(row: TodayForYouRow): JSX.Element {
+ switch (row.kind) {
+ case 'briefing':
+ return <TodayBriefingItemRow key={row.key} item={row.item} done={row.done} />
+ case 'report':
+ return <TodayReportRow key={row.key} report={row.report} source={row.source} done={row.done} />
+ case 'highlight':
+ return <TodayHighlightRow key={row.key} item={row.item} position={row.position} done={row.done} />
+ }
+}
+
+export function TodayForYou(): JSX.Element {
+ const {
+ forYouReady,
+ forYouRows,
+ forYouVisibleRows,
+ forYouOpenCount,
+ forYouFailedNote,
+ forYouCanShowMore,
+ forYouCanShowLess,
+ shownReportIds,
+ moreReportsLoading,
+ listExpanded,
+ isNewProject,
+ } = useValues(todayLogic)
+ const { showMoreForYou, setListExpanded, retryFailedLoads } = useActions(todayLogic)
+
+ return (
+ <section className="TodayHome__list" aria-label="For you today">
+ <div className="TodayHome__headingRow">
+ <TodayHomeHeading count={forYouReady ? forYouOpenCount : undefined}>For you today</TodayHomeHeading>
+ </div>
+ {!forYouReady ? (
+ <TodayRowsSkeleton />
+ ) : forYouRows.rows.length === 0 ? (
+ !forYouFailedNote && (
+ <p className="TodayHome__note">
+ {isNewProject
+ ? 'Once your project sends events, changes that need you show up here.'
+ : 'Nothing needs you today. Changes in your data that need you show up here.'}
+ </p>
+ )
+ ) : (
+ <ol className="TodayRows">{forYouVisibleRows.map(renderRow)}</ol>
+ )}
+ {forYouFailedNote && (
+ <div className="TodayHome__note flex flex-wrap items-center gap-x-2">
+ <span>{forYouFailedNote}</span>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => retryFailedLoads()}
+ data-attr="today-reports-retry"
+ >
+ Try again
+ </Button>
+ </div>
+ )}
+ {forYouReady && (forYouCanShowMore || listExpanded.for_you || shownReportIds.length > 0) && (
+ <div className="TodayRows__footer">
+ {forYouCanShowMore ? (
+ <Button
+ className="TodayRows__more"
+ loading={moreReportsLoading}
+ onClick={() => showMoreForYou()}
+ data-attr="today-more-reports-show"
+ >
+ <IconChevronDown className="TodayRows__moreIcon" aria-hidden />
+ <span>Show more</span>
+ </Button>
+ ) : forYouCanShowLess ? (
+ <Button
+ className="TodayRows__more"
+ onClick={() => setListExpanded('for_you', false)}
+ data-attr="today-more-reports-hide"
+ >
+ <IconChevronDown className="TodayRows__moreIcon rotate-180" aria-hidden />
+ <span>Show less</span>
+ </Button>
+ ) : (
+ <span />
+ )}
+ {shownReportIds.length > 0 && (
+ <LinkPrimitive
+ to={urls.inbox()}
+ className="TodayRows__inbox"
+ data-attr="today-more-reports-inbox"
+ >
+ <span>Open the Inbox</span>
+ <IconArrowRight className="size-3.5" aria-hidden />
+ </LinkPrimitive>
+ )}
+ </div>
+ )}
+ </section>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayHighlightRow.tsx b/frontend/src/scenes/project-homepage/today/TodayHighlightRow.tsx
new file mode 100644
index 000000000000..8245f70eb0b5
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayHighlightRow.tsx
@@ -0,0 +1,64 @@
+import { useActions } from 'kea'
+
+import { IconHide } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import type { HighlightItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { todayHighlightsLogic } from './todayHighlightsLogic'
+import { priorityTone } from './todayPriority'
+import { TodayRow } from './TodayRow'
+import { highlightIcon } from './todayRowIcons'
+
+export function TodayHighlightRow({
+ item,
+ position,
+ done,
+}: {
+ item: HighlightItemApi
+ position: number
+ done: boolean
+}): JSX.Element {
+ const { highlightOpened, hideHighlight, unhideHighlight } = useActions(todayHighlightsLogic)
+ return (
+ <TodayRow
+ tone={priorityTone(item.priority)}
+ icon={highlightIcon(item)}
+ title={item.title}
+ label={item.priority}
+ facts={item.detail.split(' · ')}
+ to={item.url ?? undefined}
+ onOpen={() => highlightOpened(item, position)}
+ actions={
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="link-muted"
+ size="icon-sm"
+ aria-label="Hide for today"
+ onClick={() => hideHighlight(item, position)}
+ data-attr="today-highlight-hide"
+ />
+ }
+ >
+ <IconHide className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipContent side="bottom">Hide for today</TooltipContent>
+ </Tooltip>
+ }
+ doneActions={
+ <Button
+ variant="link-muted"
+ size="sm"
+ onClick={() => unhideHighlight(item, position)}
+ data-attr="today-highlight-unhide"
+ >
+ Undo
+ </Button>
+ }
+ done={done}
+ dataAttr="today-highlight"
+ />
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayHome.tsx b/frontend/src/scenes/project-homepage/today/TodayHome.tsx
index dbf8ee8c9fdb..166de0b2ba3f 100644
--- a/frontend/src/scenes/project-homepage/today/TodayHome.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayHome.tsx
@@ -1,21 +1,21 @@
import './Today.scss'
-import { useValues } from 'kea'
+import { useMountedLogic, useValues } from 'kea'
import { Suspense } from 'react'
import { Skeleton } from '@posthog/quill'
import { lazyWithRetry } from 'lib/utils/retryImport'
-import { TodayPreviewCardProvider } from '~/layout/today/TodayPreviewCardProvider'
-
-import { TodayBriefing } from './TodayBriefing'
+import { TodayHomePage } from './TodayHomePage'
import { todayLogic } from './todayLogic'
+import { todayReportQueueLogic } from './todayReportQueueLogic'
const TodayReportPage = lazyWithRetry(() => import('./TodayReportPage').then((m) => ({ default: m.TodayReportPage })))
/** The Today homepage: the daily briefing at `/home`, or one report at `/home/reports/:reportId`. */
export function TodayHome(): JSX.Element {
+ useMountedLogic(todayReportQueueLogic)
const { reportId } = useValues(todayLogic)
return (
@@ -33,9 +33,7 @@ export function TodayHome(): JSX.Element {
<TodayReportPage key={reportId} reportId={reportId} />
</Suspense>
) : (
- <TodayPreviewCardProvider>
- <TodayBriefing />
- </TodayPreviewCardProvider>
+ <TodayHomePage />
)}
</div>
)
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomeHeading.tsx b/frontend/src/scenes/project-homepage/today/TodayHomeHeading.tsx
new file mode 100644
index 000000000000..a71c1e8381b9
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayHomeHeading.tsx
@@ -0,0 +1,20 @@
+export function TodayHomeHeading({
+ id,
+ count,
+ children,
+}: {
+ id?: string
+ count?: number
+ children: string
+}): JSX.Element {
+ return (
+ <h2 id={id} className="TodayHome__heading">
+ <span>{children}</span>
+ {count ? (
+ <span className="TodayHome__headingCount" translate="no">
+ {count}
+ </span>
+ ) : null}
+ </h2>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
new file mode 100644
index 000000000000..b183062f6f12
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
@@ -0,0 +1,129 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useLayoutEffect, useRef } from 'react'
+
+import { IconRefresh } from '@posthog/icons'
+import { Button, Skeleton, Spinner, Text, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { todayBriefingLogic } from './todayBriefingLogic'
+import { TodayExplore } from './TodayExplore'
+import { TodayForYou } from './TodayForYou'
+import { todayHighlightsLogic } from './todayHighlightsLogic'
+import { reportIdFromPath, todayLogic } from './todayLogic'
+import { TodayPulse } from './TodayPulse'
+import { TodayRecents } from './TodayRecents'
+import { TodaySampleBanner } from './TodaySampleBanner'
+
+const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { weekday: 'long', day: 'numeric', month: 'long' })
+
+function TodayPulseSkeleton(): JSX.Element {
+ return (
+ <ul className="TodayPulse" aria-busy aria-label="Loading key numbers">
+ {['w-14', 'w-16', 'w-20'].map((width) => (
+ <li key={width} className="TodayPulse__metric">
+ <span className="TodayPulse__name">
+ <Skeleton className={`inline-block h-3 align-middle ${width}`} />
+ </span>
+ <span className="TodayPulse__row">
+ <span className="TodayPulse__value">
+ <Skeleton className="inline-block h-4 w-28 align-middle" />
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ )
+}
+
+function TodayMetaLine(): JSX.Element {
+ const { now, currentTeam } = useValues(todayLogic)
+ const date = new Date(now)
+ return (
+ <p className="TodayHome__meta">
+ <time translate="no" dateTime={date.toISOString()}>
+ {DATE_FORMAT.format(date)}
+ </time>
+ <span className="whitespace-pre">{` · ${currentTeam?.name ?? 'Your project'}`}</span>
+ </p>
+ )
+}
+
+export function TodayHomePage(): JSX.Element {
+ const { greeting, showPersonalBriefing, isNewProject, recentObjects, returnFocusReportId } = useValues(todayLogic)
+ const { setReturnFocusReportId } = useActions(todayLogic)
+ const { personalBriefing, briefingWaiting } = useValues(todayBriefingLogic)
+ const { refreshBriefing } = useActions(todayBriefingLogic)
+ const { highlights, highlightsPending } = useValues(todayHighlightsLogic)
+ const rootRef = useRef<HTMLDivElement>(null)
+
+ useLayoutEffect(() => {
+ const scroller = rootRef.current?.closest('main')
+ const savedTop = todayLogic.values.homeScrollTop
+ if (scroller && typeof savedTop === 'number') {
+ scroller.scrollTop = savedTop
+ todayLogic.actions.setHomeScrollTop(null)
+ }
+ return () => {
+ if (scroller && reportIdFromPath(router.values.location.pathname)) {
+ todayLogic.actions.setHomeScrollTop(scroller.scrollTop)
+ }
+ }
+ }, [])
+
+ useLayoutEffect(() => {
+ if (returnFocusReportId === null) {
+ return
+ }
+ rootRef.current
+ ?.querySelector<HTMLElement>(`[data-today-report="${CSS.escape(returnFocusReportId)}"]`)
+ ?.focus({ preventScroll: true })
+ setReturnFocusReportId(null)
+ }, [returnFocusReportId, setReturnFocusReportId])
+
+ return (
+ <div ref={rootRef} className="TodayHome Today__page" data-quill>
+ <TodaySampleBanner />
+ <section className="TodayHome__intro" aria-label="Today">
+ <div className="TodayHome__greeting">
+ <Text render={<h1 />} className="m-0 text-[21px] font-[560] tracking-[-0.015em]">
+ {greeting}
+ </Text>
+ {briefingWaiting ? (
+ <span className="TodayHome__badge" data-attr="today-briefing-writing">
+ <Spinner />
+ <span>Writing your briefing…</span>
+ </span>
+ ) : showPersonalBriefing || personalBriefing?.status === 'failed' ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="link-muted"
+ size="icon-sm"
+ className="TodayHome__refresh"
+ aria-label="Refresh briefing"
+ onClick={() => refreshBriefing()}
+ data-attr="today-briefing-refresh"
+ />
+ }
+ >
+ <IconRefresh className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent>Refresh briefing</TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
+ <TodayMetaLine />
+ </section>
+ <div className="TodayHome__body">
+ {highlightsPending ? (
+ <TodayPulseSkeleton />
+ ) : highlights && highlights.pulse.length > 0 ? (
+ <TodayPulse metrics={highlights.pulse} />
+ ) : null}
+ {isNewProject && recentObjects.length === 0 ? <TodayExplore /> : <TodayRecents />}
+ <TodayForYou />
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx b/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx
deleted file mode 100644
index 3ab75702c34c..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-
-import { IconHome, IconPlus } from '@posthog/icons'
-import { Button, MenuLabel, Skeleton } from '@posthog/quill'
-
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { urls } from 'scenes/urls'
-
-import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
-
-import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/utils/reportPresentation'
-
-import { isExternalHref, itemHref, itemReportId, itemSource, itemStateLabel } from './todayBriefingItems'
-import { TodayIcon } from './TodayIcon'
-import { todayLogic } from './todayLogic'
-import { TodayMoreReports } from './TodayMoreReports'
-import { TodayNavItem } from './TodayNavItem'
-import { TodayReportNavItem } from './TodayReportNavItem'
-
-function PersonalBriefingNavItems(): JSX.Element {
- const { briefingItems, reportPreviews, hoveredItemKey, reportStateOverrides } = useValues(todayLogic)
- const { itemOpened, setHoveredItemKey } = useActions(todayLogic)
- const { location } = useValues(router)
- const currentPath = removeProjectIdIfPresent(location.pathname)
-
- return (
- <>
- {briefingItems.map((item) => {
- const href = itemHref(item)
- const source = itemSource(item)
- const preview = reportPreviews.sidebar[item.key]
- const reportId = itemReportId(item)
- const state = (reportId ? reportStateOverrides[reportId] : undefined) ?? item.state
- const row = (
- <TodayNavItem
- key={item.key}
- title={displayConventionalCommitTitle(item.title, 'Untitled report')}
- meta={itemStateLabel({ state }) ?? (item.signal || source.label)}
- color={source.color}
- icon={<TodayIcon icon={source.icon} />}
- to={href}
- target={isExternalHref(href) ? '_blank' : undefined}
- active={hoveredItemKey === item.key}
- current={removeProjectIdIfPresent(href) === currentPath}
- state={state}
- dataAttr="today-nav-item"
- onClick={() => itemOpened(item, 'sidebar')}
- onHoverChange={(hovered) => setHoveredItemKey(hovered ? item.key : null)}
- />
- )
- return preview ? (
- <TodayPreviewTrigger key={item.key} payload={preview}>
- {row}
- </TodayPreviewTrigger>
- ) : (
- row
- )
- })}
- </>
- )
-}
-
-export function TodayHomeSidebar(): JSX.Element {
- const {
- reportId,
- reports,
- topReports,
- reportsFailed,
- reportSummary,
- showPersonalBriefing,
- personalBriefing,
- teamReportPreviews,
- } = useValues(todayLogic)
-
- // The team reports stand in until the personal briefing is written, so only their own load counts.
- const loading = topReports === null && !reportsFailed
- const homeMeta = showPersonalBriefing
- ? (personalBriefing?.headline ?? '')
- : loading
- ? 'Reading your project…'
- : topReports === null
- ? 'Reports didn’t load'
- : reportSummary
-
- return (
- <div className="TodayPane" data-quill>
- <Button
- elevated
- variant="outline"
- size="lg"
- className="mb-1 w-full"
- nativeButton={false}
- render={<LinkPrimitive to={urls.taskNewSession()} />}
- data-attr="today-new-chat"
- >
- <IconPlus />
- New chat
- </Button>
- <div className="TodayPane__scroll">
- <div className="TodaySidebar__list">
- <TodayNavItem
- title="Home"
- meta={homeMeta}
- color="var(--color-text-secondary)"
- icon={<IconHome />}
- to={urls.projectHomepage()}
- current={reportId === null}
- dataAttr="today-nav-home"
- />
- {(loading || showPersonalBriefing || reports.length > 0) && (
- <MenuLabel className="mt-3">{showPersonalBriefing ? 'Your briefing' : 'Reports'}</MenuLabel>
- )}
- {showPersonalBriefing ? (
- <PersonalBriefingNavItems />
- ) : loading ? (
- <>
- <Skeleton className="h-13" />
- <Skeleton className="h-13" />
- </>
- ) : (
- reports.map((report) => (
- <TodayReportNavItem
- key={report.id}
- report={report}
- preview={teamReportPreviews.sidebar[report.id]}
- source="sidebar"
- dataAttr="today-nav-report"
- />
- ))
- )}
- <TodayMoreReports />
- </div>
- </div>
- </div>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx b/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx
index 31ddc5c62e04..866d6c8430c5 100644
--- a/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx
@@ -9,12 +9,22 @@ import type { TodayMarkedFigure } from './todayFigureSources'
import { TodayKeyClauseMark } from './TodayKeyClauseMark'
import { TodayMarkedPiece, markedRuns } from './todayMarkedRuns'
-function MarkedPiece({ piece, reportId }: { piece: TodayMarkedPiece; reportId: string }): JSX.Element {
+function MarkedPiece({
+ piece,
+ reportId,
+ plainLinks,
+}: {
+ piece: TodayMarkedPiece
+ reportId: string
+ plainLinks?: boolean
+}): JSX.Element {
switch (piece.kind) {
case 'code':
return <code className="text-[0.9em]">{piece.text}</code>
case 'link':
- return (
+ return plainLinks ? (
+ <span>{piece.text}</span>
+ ) : (
<LinkPrimitive to={piece.href} target="_blank" className="underline underline-offset-2">
{piece.text}
</LinkPrimitive>
@@ -41,17 +51,21 @@ export function TodayMarkedText({
marked,
keyClauses,
reportId,
+ plainLinks,
}: {
markdown: string
marked: TodayMarkedFigure[]
keyClauses: KeyClauseApi[]
reportId: string
+ plainLinks?: boolean
}): JSX.Element {
const runs = markedRuns(markdown, marked, keyClauses)
return (
<>
{runs.map(({ keyClause, pieces }) => {
- const content = pieces.map((piece) => <MarkedPiece key={piece.key} piece={piece} reportId={reportId} />)
+ const content = pieces.map((piece) => (
+ <MarkedPiece key={piece.key} piece={piece} reportId={reportId} plainLinks={plainLinks} />
+ ))
return keyClause ? (
<TodayKeyClauseMark key={pieces[0].key} keyClause={keyClause} reportId={reportId}>
{content}
diff --git a/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx b/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx
deleted file mode 100644
index 01ba5a79e514..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { Button, Spinner } from '@posthog/quill'
-
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { urls } from 'scenes/urls'
-
-import { todayLogic } from './todayLogic'
-import { TodayReportNavItem } from './TodayReportNavItem'
-
-/** The reports for the person past the ones the sidebar lists, loaded on request. */
-export function TodayMoreReports(): JSX.Element | null {
- const {
- canLoadMoreReports,
- moreReports,
- moreReportsLoading,
- sidebarMoreReports,
- moreReportPreviews,
- moreReportsInInbox,
- } = useValues(todayLogic)
- const { loadMoreReports } = useActions(todayLogic)
-
- if (canLoadMoreReports) {
- return (
- <Button
- variant="link-muted"
- size="sm"
- className="TodaySidebar__more"
- // The spinner sits next to the label rather than over it: quill's `loading` overlays the
- // button's box, which on this left-aligned link lands above the text.
- disabled={moreReportsLoading}
- onClick={loadMoreReports}
- data-attr="today-nav-load-more"
- >
- {moreReportsLoading && <Spinner />}
- Show more reports
- </Button>
- )
- }
- if (!moreReports) {
- return null
- }
- return (
- <>
- {sidebarMoreReports.map((report) => (
- <TodayReportNavItem
- key={report.id}
- report={report}
- preview={moreReportPreviews.sidebar[report.id]}
- source="sidebar_more"
- dataAttr="today-nav-more-report"
- />
- ))}
- {moreReportsInInbox > 0 ? (
- <Button
- variant="link-muted"
- size="sm"
- className="TodaySidebar__more"
- nativeButton={false}
- render={<LinkPrimitive to={urls.inbox()} />}
- data-attr="today-nav-more-inbox"
- >
- {moreReportsInInbox} more for you in the Inbox
- </Button>
- ) : sidebarMoreReports.length === 0 ? (
- <p className="TodaySidebar__more TodaySidebar__more--empty">No other reports need you right now</p>
- ) : null}
- </>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayNavItem.tsx b/frontend/src/scenes/project-homepage/today/TodayNavItem.tsx
deleted file mode 100644
index 55d066389c49..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayNavItem.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle, cn } from '@posthog/quill'
-
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-
-import type { BriefingItemStateEnumApi } from 'products/today/frontend/generated/api.schemas'
-
-interface TodayNavItemProps {
- title: string
- meta: string
- color: string
- icon: JSX.Element
- to: string
- target?: string
- /** Highlighted because the matching report is hovered elsewhere on the page. */
- active?: boolean
- current?: boolean
- /** Crossed out when the item was resolved after the briefing was written, faded when it was dismissed. */
- state?: BriefingItemStateEnumApi
- onClick?: () => void
- onHoverChange?: (hovered: boolean) => void
- dataAttr?: string
-}
-
-export function TodayNavItem({
- title,
- meta,
- color,
- icon,
- to,
- target,
- active = false,
- current = false,
- state = 'open',
- onClick,
- onHoverChange,
- dataAttr,
-}: TodayNavItemProps): JSX.Element {
- return (
- <Item
- variant="menuItem"
- size="xs"
- render={<LinkPrimitive to={to} target={target} />}
- className={cn(
- 'TodayNavItem flex-nowrap pl-[11px] text-foreground no-underline hover:text-foreground',
- (active || current) && 'bg-[var(--fill-selected)]'
- )}
- data-active={active || current}
- aria-current={current ? 'page' : undefined}
- data-state={state}
- data-attr={dataAttr}
- onClick={onClick}
- onMouseEnter={() => onHoverChange?.(true)}
- onMouseLeave={() => onHoverChange?.(false)}
- // eslint-disable-next-line react/forbid-dom-props
- style={{ '--report-color': color } as React.CSSProperties}
- >
- <ItemMedia className="TodayNavItem__marker" aria-hidden>
- {icon}
- </ItemMedia>
- <ItemContent className="min-w-0 gap-0.5">
- <ItemTitle className="TodayNavItem__title w-full font-semibold">
- <span className="truncate">{title}</span>
- </ItemTitle>
- {meta && <ItemDescription className="truncate">{meta}</ItemDescription>}
- </ItemContent>
- </Item>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayPartyPopper.tsx b/frontend/src/scenes/project-homepage/today/TodayPartyPopper.tsx
deleted file mode 100644
index 3edd1aef06a3..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayPartyPopper.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-export function TodayPartyPopper(): JSX.Element {
- return (
- <svg className="TodayPartyPopper" width="17" height="17" viewBox="0 0 17 17" fill="none" aria-hidden>
- <g strokeWidth="1.01037" strokeLinecap="round" strokeLinejoin="round">
- <path
- d="M11.4847 10.1154C11.8337 10.4639 11.7022 11.0568 11.2388 11.2252L2.70407 14.3257C2.16645 14.5211 1.64545 13.9997 1.84113 13.4622L4.94442 4.93839C5.1129 4.47563 5.7048 4.34421 6.05329 4.69217L11.4847 10.1154Z"
- stroke="#FFA81C"
- />
- <path
- d="M9.46262 1.17871C9.46262 1.17871 9.58582 1.89818 9.46262 2.56228C9.32999 3.27755 8.76978 3.94585 8.76978 3.94585"
- stroke="#1490E8"
- />
- <path d="M10.5037 5.67518L11.1964 4.9834" stroke="#FFA81C" />
- <path d="M12.4429 3.08116L12.7546 2.21643" stroke="#FF5C1C" />
- <path d="M13.6216 5.32929L14.3144 4.9834" stroke="#1490E8" />
- <path
- d="M12.2349 7.40479C12.2349 7.40479 12.7587 7.42688 13.2741 7.59157C13.7386 7.73996 14.3133 8.09655 14.3133 8.09655"
- stroke="#FF5C1C"
- />
- </g>
- </svg>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx b/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx
deleted file mode 100644
index b3226e129630..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayPersonalBriefing.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { pluralize } from 'lib/utils/strings'
-import { urls } from 'scenes/urls'
-
-import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
-
-import type { BriefingSegmentApi } from 'products/today/frontend/generated/api.schemas'
-
-import { WALK_THROUGH_QUESTION } from './todayAskPrompt'
-import { isExternalHref, itemHref, itemSource } from './todayBriefingItems'
-import { TodayChipStack } from './TodayChipStack'
-import { TodayIcon } from './TodayIcon'
-import { todayLogic } from './todayLogic'
-
-function PersonalBriefingSegment({ segment }: { segment: BriefingSegmentApi }): JSX.Element {
- const { briefingItems, reportPreviews, hoveredItemKey } = useValues(todayLogic)
- const { itemOpened, setHoveredItemKey } = useActions(todayLogic)
- const item = segment.item_key ? briefingItems.find((candidate) => candidate.key === segment.item_key) : undefined
- if (!item) {
- return <span>{segment.text}</span>
- }
- const href = itemHref(item)
- const link = (
- <LinkPrimitive
- to={href}
- target={isExternalHref(href) ? '_blank' : undefined}
- className="TodayInlineLink"
- data-active={hoveredItemKey === item.key}
- data-state={item.state}
- data-attr="today-briefing-item"
- onClick={() => itemOpened(item, 'briefing')}
- onMouseEnter={() => setHoveredItemKey(item.key)}
- onMouseLeave={() => setHoveredItemKey(null)}
- >
- {segment.text}
- </LinkPrimitive>
- )
- const preview = reportPreviews.briefing[item.key]
- const linkWithCard = preview ? (
- <TodayPreviewTrigger payload={preview} inline>
- {link}
- </TodayPreviewTrigger>
- ) : (
- link
- )
- return segment.highlight ? <span className="TodayHome__highlight">{linkWithCard}</span> : linkWithCard
-}
-
-function PersonalBriefingChips(): JSX.Element | null {
- const { briefingItems, hoveredItemKey } = useValues(todayLogic)
- const { openItem, setHoveredItemKey } = useActions(todayLogic)
- return (
- <TodayChipStack
- dataAttr="today-briefing-item-chip"
- chips={briefingItems.map((item) => {
- const source = itemSource(item)
- return {
- key: item.key,
- label: item.label,
- color: source.color,
- icon: <TodayIcon icon={source.icon} />,
- active: hoveredItemKey === item.key,
- onClick: () => openItem(item, 'chip'),
- onHoverChange: (hovered) => setHoveredItemKey(hovered ? item.key : null),
- }
- })}
- />
- )
-}
-
-export function TodayPersonalBriefing(): JSX.Element | null {
- const { personalBriefing, inboxMore, briefingProgress } = useValues(todayLogic)
- const { askAi } = useActions(todayLogic)
-
- if (!personalBriefing) {
- return null
- }
- if (personalBriefing.items.length === 0) {
- return (
- <>
- <p className="TodayHome__count">{personalBriefing.headline || 'Nothing needs you right now'}</p>
- <p>
- <span>
- Reports that wait for you, that you claimed or review, and urgent reports nobody owns show up
- here. Your briefing updates every morning at 8:00.{' '}
- </span>
- <LinkPrimitive to={urls.inbox()} className="TodayInboxLink" data-attr="today-empty-briefing-inbox">
- Open the Inbox
- </LinkPrimitive>
- <span> to see every report.</span>
- </p>
- </>
- )
- }
- return (
- <>
- <p className="TodayHome__count">
- <span>{personalBriefing.headline}</span>
- <PersonalBriefingChips />
- </p>
- {briefingProgress && (
- <p className="TodayHome__progress" data-attr="today-briefing-progress">
- {`${briefingProgress.done} of ${briefingProgress.total} done`}
- </p>
- )}
- {personalBriefing.paragraphs.map((paragraph, index) => (
- <p key={index}>
- {paragraph.map((segment, segmentIndex) => (
- <PersonalBriefingSegment key={segmentIndex} segment={segment} />
- ))}
- </p>
- ))}
- <p className="TodayHome__foot">
- {inboxMore && (
- <>
- <LinkPrimitive to={urls.inbox()} className="TodayInboxLink" data-attr="today-briefing-inbox">
- {inboxMore.scope === 'for_you'
- ? `${inboxMore.count} more for you in the Inbox`
- : `${inboxMore.count} other open ${pluralize(inboxMore.count, 'report', undefined, false)} in the Inbox`}
- </LinkPrimitive>
- <span>. </span>
- </>
- )}
- <span>Or </span>
- <button
- type="button"
- className="TodayInlineAction"
- data-attr="today-ask-about-edition"
- onClick={() => askAi(WALK_THROUGH_QUESTION, 'walk_through')}
- >
- ask PostHog AI to walk you through it
- </button>
- <span>.</span>
- </p>
- </>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
new file mode 100644
index 000000000000..cecf3471100c
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
@@ -0,0 +1,113 @@
+import { useValues } from 'kea'
+
+import { dayjs } from 'lib/dayjs'
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'
+
+import type { HighlightMetricApi } from 'products/today/frontend/generated/api.schemas'
+
+import { todayNumber } from './todayNumbers'
+import { TodaySparkline, type TodayTone, useTodayTonePalette } from './TodaySparkline'
+
+const CHANGE_THRESHOLD = 3
+const MIN_ABSOLUTE_CHANGE = 5
+
+function metricTone(change: number | null, value: number): TodayTone {
+ if (change === null || Math.abs(change) < CHANGE_THRESHOLD) {
+ return 'neutral'
+ }
+ const before = value / (1 + change / 100)
+ if (Math.abs(value - before) < MIN_ABSOLUTE_CHANGE) {
+ return 'neutral'
+ }
+ return change > 0 ? 'good' : 'risk'
+}
+
+const PERIOD_FORMATS: Record<HighlightMetricApi['interval'], string> = {
+ day: 'ddd, D MMM',
+ week: '[Week of] D MMM',
+ month: 'MMM YYYY',
+}
+
+function seriesLabels(metric: HighlightMetricApi): string[] {
+ return metric.period_starts.map((start) => dayjs(start).format(PERIOD_FORMATS[metric.interval]))
+}
+
+function metricFormatter(metric: HighlightMetricApi, currency: CurrencyCode): (value: number) => string {
+ const format = metric.value_format
+ if (!format) {
+ return humanFriendlyNumber
+ }
+ const trendsFilter: TrendsFilter = {
+ aggregationAxisFormat: (format.format ?? undefined) as TrendsFilter['aggregationAxisFormat'],
+ aggregationAxisPrefix: format.prefix ?? undefined,
+ aggregationAxisPostfix: format.postfix ?? undefined,
+ decimalPlaces: format.decimal_places ?? undefined,
+ }
+ return (value) => formatAggregationAxisValue(trendsFilter, value, currency)
+}
+
+function TodayChange({ change, tone }: { change: number | null; tone: TodayTone }): JSX.Element | null {
+ const palette = useTodayTonePalette()
+ if (change === null) {
+ return null
+ }
+ const rounded = Math.round(change)
+ return (
+ <span
+ className="TodayChange"
+ translate="no"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={tone === 'neutral' ? undefined : { color: palette[tone] }}
+ >
+ {rounded === 0 ? '0%' : `${rounded > 0 ? '+' : '−'}${Math.abs(rounded)}%`}
+ </span>
+ )
+}
+
+export function TodayPulse({ metrics }: { metrics: HighlightMetricApi[] }): JSX.Element {
+ const { baseCurrency } = useValues(teamLogic)
+ return (
+ <ul className="TodayPulse" aria-label="Key numbers, against the period before">
+ {metrics.map((metric) => {
+ const tone = metric.key.startsWith('insight:') ? 'neutral' : metricTone(metric.change_pct, metric.value)
+ const formatValue = metricFormatter(metric, baseCurrency)
+ return (
+ <li key={metric.key} className="TodayPulse__metric">
+ {metric.url ? (
+ <LinkPrimitive
+ to={metric.url}
+ className="TodayPulse__name TodayPulse__link"
+ title={metric.name}
+ data-attr="today-pulse-insight"
+ >
+ {metric.name}
+ </LinkPrimitive>
+ ) : (
+ <span className="TodayPulse__name">{metric.name}</span>
+ )}
+ <span className="TodayPulse__row">
+ <span className="TodayPulse__value" translate="no">
+ {metric.value_format ? formatValue(metric.value) : todayNumber(metric.value)}
+ </span>
+ <TodayChange change={metric.change_pct} tone={tone} />
+ <span className="TodayPulse__spark">
+ <TodaySparkline
+ values={metric.series}
+ labels={seriesLabels(metric)}
+ emphasizeLast={metric.interval === 'day' ? 7 : 1}
+ tone={tone}
+ formatValue={formatValue}
+ />
+ </span>
+ </span>
+ </li>
+ )
+ })}
+ </ul>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayRecents.tsx b/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
index e1c2cdf532b5..c69438d05048 100644
--- a/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayRecents.tsx
@@ -1,88 +1,104 @@
-import { useActions, useValues } from 'kea'
-import { useId } from 'react'
+import { Collapsible } from '@base-ui/react/collapsible'
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useId, useMemo } from 'react'
+
+import { IconChevronDown } from '@posthog/icons'
-import { dayjs } from 'lib/dayjs'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { libraryObjectHref, libraryObjectName, libraryTypeLabel } from 'scenes/library/libraryUtils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
-import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { todayObjectGlanceLogic } from '~/layout/today/todayObjectGlanceLogic'
+import { TodayObjectIcon } from '~/layout/today/TodayObjectIcon'
+import { TodayPreviewCardProvider } from '~/layout/today/TodayPreviewCardProvider'
+import { objectPreview } from '~/layout/today/todayPreviewCards'
+import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
import { todayShellLogic } from '~/layout/today/todayShellLogic'
-import { FileSystemEntry, FileSystemIconType } from '~/queries/schema/schema-general'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
-import { todayLogic } from './todayLogic'
-import { TodaySectionTitle } from './TodaySectionTitle'
+import { TodayHomeHeading } from './TodayHomeHeading'
+import { RECENT_OBJECT_COUNT, todayLogic } from './todayLogic'
function RecentObjectRow({ entry }: { entry: FileSystemEntry }): JSX.Element {
- const typeLabel = libraryTypeLabel(entry.type)
+ const preview = useMemo(() => objectPreview(entry), [entry])
return (
- <li className="TodayRecentRow">
- <span className="TodayRecentIcon" aria-hidden>
- {iconForType(entry.type as FileSystemIconType | undefined)}
- </span>
- <LinkPrimitive
- to={libraryObjectHref(entry) ?? undefined}
- className="TodayInlineLink truncate"
- data-attr="today-home-recent-object"
- >
- {libraryObjectName(entry)}
- </LinkPrimitive>
- <span className="TodayRecentRow__meta">
- {typeLabel && <span>{typeLabel}</span>}
- {typeLabel && entry.last_viewed_at && <span className="TodayRecentRow__time"> · </span>}
- {entry.last_viewed_at && (
- <time className="TodayRecentRow__time" dateTime={entry.last_viewed_at}>
- {dayjs(entry.last_viewed_at).fromNow()}
- </time>
+ <li className="TodayJumpRow">
+ <TodayObjectIcon type={entry.type} className="TodayJumpRow__icon" />
+ <TodayPreviewTrigger payload={preview}>
+ <LinkPrimitive
+ to={preview.href ?? undefined}
+ className="TodayJumpRow__link"
+ data-attr="today-home-recent-object"
+ >
+ {preview.name}
+ </LinkPrimitive>
+ {preview.typeLabel && (
+ <span className="TodayJumpRow__meta">{capitalizeFirstLetter(preview.typeLabel)}</span>
)}
- </span>
+ </TodayPreviewTrigger>
</li>
)
}
export function TodayRecents(): JSX.Element {
- const { recentObjects, recentsHasLoaded } = useValues(todayLogic)
+ useMountedLogic(todayObjectGlanceLogic)
+ const { recentObjects, recentsHasLoaded, listExpanded } = useValues(todayLogic)
+ const { setListExpanded } = useActions(todayLogic)
const { pickPane } = useActions(todayShellLogic)
const titleId = useId()
-
- const productsButton = (
- <button
- type="button"
- className="TodayInlineAction"
- data-attr="today-home-recent-library"
- onClick={() => pickPane('products')}
- >
- Products
- </button>
- )
+ const shown = recentObjects.slice(0, RECENT_OBJECT_COUNT)
+ const more = recentObjects.slice(RECENT_OBJECT_COUNT)
return (
- <section
- className="TodayHome__prose TodayHome__recents group/colorful-product-icons colorful-product-icons-true flex flex-col gap-2.5"
- aria-labelledby={titleId}
+ <Collapsible.Root
+ open={listExpanded.recents}
+ onOpenChange={(open) => setListExpanded('recents', open)}
+ render={<section className="TodayHome__list" aria-labelledby={titleId} />}
>
- <TodaySectionTitle id={titleId}>Recent</TodaySectionTitle>
+ <div className="TodayHome__headingRow">
+ <TodayHomeHeading id={titleId}>Jump back in</TodayHomeHeading>
+ {recentsHasLoaded && more.length > 0 && (
+ <Collapsible.Trigger className="TodayHome__headingLink" data-attr="today-home-recent-more">
+ <span>{listExpanded.recents ? 'Less' : 'More'}</span>
+ <IconChevronDown className="TodayHome__headingChevron size-3" aria-hidden />
+ </Collapsible.Trigger>
+ )}
+ </div>
{!recentsHasLoaded ? (
- <p>Finding what you looked at last…</p>
+ <p className="TodayHome__note">Finding what you looked at last…</p>
) : recentObjects.length === 0 ? (
- <p>
- <span>Dashboards, insights and other things you open show up here. Find them in the </span>
- {productsButton}
+ <p className="TodayHome__note">
+ <span>
+ Anything you open, like a dashboard or a feature flag, shows up here. Find things to open
+ in{' '}
+ </span>
+ <button
+ type="button"
+ className="TodayHome__noteLink"
+ data-attr="today-home-recent-library"
+ onClick={() => pickPane('products')}
+ >
+ Products
+ </button>
<span>.</span>
</p>
) : (
- <>
- <ul className="TodayRecentList">
- {recentObjects.map((entry) => (
+ <TodayPreviewCardProvider>
+ <ul className="TodayJumpList">
+ {shown.map((entry) => (
<RecentObjectRow key={entry.id} entry={entry} />
))}
</ul>
- <p>
- <span>Everything else is in </span>
- {productsButton}
- <span>.</span>
- </p>
- </>
+ {more.length > 0 && (
+ <Collapsible.Panel className="TodayJumpList__more">
+ <ul className="TodayJumpList">
+ {more.map((entry) => (
+ <RecentObjectRow key={entry.id} entry={entry} />
+ ))}
+ </ul>
+ </Collapsible.Panel>
+ )}
+ </TodayPreviewCardProvider>
)}
- </section>
+ </Collapsible.Root>
)
}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx
index c84c28adbd12..bc53dd4d8e66 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx
@@ -15,18 +15,10 @@ export function TodayReportAbstract({ report }: { report: SignalReport }): JSX.E
impactText,
impactMarks,
shownKeyClauses,
- 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>
- )
+ return null
}
if (numbers.length === 0) {
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx b/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx
index 04f8fc499fbf..2564d3984dbe 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportBody.tsx
@@ -24,12 +24,12 @@ export function TodayReportBody({
live: TodayReportLiveState | null
}): JSX.Element {
return (
- <article className="TodayReportArticle flex max-w-150 flex-col gap-10">
+ <article className="TodayReportArticle flex 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">
+ <section className="flex flex-col gap-4 empty:hidden" aria-label="Proposal">
<TodayReportProposal reportId={report.id} />
<TodayReportNextStep
report={report}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx
index d847a8563a55..98dc5dc8d821 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconCheckCircle, IconDocument, IconEllipsis, IconHide } from '@posthog/icons'
-import { Badge, Button, Heading, Text, cn } from '@posthog/quill'
+import { Badge, Button, Heading, IconStack, IconStackItem, Text, cn } from '@posthog/quill'
import { dayjs } from 'lib/dayjs'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
@@ -20,12 +20,14 @@ import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/
import { TodayActionButton } from './TodayActionButton'
import { itemStateLabel } from './todayBriefingItems'
import { TodayEvidenceAge } from './TodayEvidenceAge'
-import { TodayReportVerdict, todayLogic } from './todayLogic'
import { TodayMarkedText } from './TodayMarkedText'
import { resolveDisabledReason } from './todayNextStep'
+import { priorityTone } from './todayPriority'
import { todayReportLogic } from './todayReportLogic'
+import { reportIcon } from './todayRowIcons'
import { SAMPLE_REPORT_REASON } from './todaySampleReports'
-import { priorityBadgeVariant, reportSourceLine, reportTitle } from './todaySignalReports'
+import { reportSourceLine, reportTitle } from './todaySignalReports'
+import { type TodayReportVerdict, todayVerdictLogic } from './todayVerdictLogic'
function PhoneActions({
report,
@@ -101,7 +103,7 @@ function PhoneActions({
}
export function TodayReportHeader({ report }: { report: SignalReport }): JSX.Element {
- const { requestReportVerdict } = useActions(todayLogic)
+ const { requestReportVerdict } = useActions(todayVerdictLogic)
const { phoneLayout } = useValues(todayShellLogic)
const { lead, leadMarks, shownKeyClauses, reportState, isSample } = useValues(
todayReportLogic({ reportId: report.id })
@@ -112,6 +114,7 @@ export function TodayReportHeader({ report }: { report: SignalReport }): JSX.Ele
<Badge variant={reportState === 'done' ? 'completed' : 'default'}>{stateLabel}</Badge>
) : null
const sources = reportSourceLine(report)
+ const icon = reportIcon(report)
const updated = dayjs(report.updated_at)
const stillInvestigating = !report.summary?.trim()
@@ -134,12 +137,14 @@ export function TodayReportHeader({ report }: { report: SignalReport }): JSX.Ele
phoneLayout ? 'min-w-0' : 'min-w-64'
)}
>
+ <IconStack className="TodayReportHeader__icon" title={sources.title || sources.line}>
+ <IconStackItem color={icon.color}>{icon.glyph}</IconStackItem>
+ </IconStack>
{report.priority && (
- <Badge variant={priorityBadgeVariant(report.priority)}>{report.priority}</Badge>
+ <span className="TodayRow__label" data-tone={priorityTone(report.priority)}>
+ {report.priority}
+ </span>
)}
- <span className="min-w-0 truncate" title={sources.title || undefined}>
- {sources.line}
- </span>
<span aria-hidden className="-mx-0.5">
·
</span>
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx
deleted file mode 100644
index a28f99bca1b4..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx
+++ /dev/null
@@ -1,280 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { Suspense, useEffect } from 'react'
-
-import { IconCheckCircle, IconHide, IconLeave, IconPullRequest } from '@posthog/icons'
-import {
- Badge,
- Button,
- Item,
- ItemActions,
- ItemContent,
- ItemDescription,
- ItemSeparator,
- ItemTitle,
- Skeleton,
- Text,
- cn,
-} from '@posthog/quill'
-
-import { dayjs } from 'lib/dayjs'
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { lazyWithRetry } from 'lib/utils/retryImport'
-import { pluralize } from 'lib/utils/strings'
-
-import type { TodayReportPreview } from '~/layout/today/todayPreviewCards'
-
-import { reportChartGraphQuery } from 'products/signals/frontend/inbox/utils/reportChartQuery'
-import {
- asReportMetricAggregateQuery,
- asReportMetricSeriesQuery,
- reportMetricRowParts,
- selectReportCardImpactMetric,
-} from 'products/signals/frontend/inbox/utils/reportMetrics'
-import { pullRequestStateMeta } from 'products/tasks/frontend/spaces/TaskPullRequestChip'
-
-import { itemStateLabel } from './todayBriefingItems'
-import { TodayReportVerdict, todayLogic } from './todayLogic'
-import { isSampleReportId } from './todaySampleReports'
-
-// The charts load on the first hover: the card sits in the app shell, and the query and chart code
-// they need must stay out of the bundle every page loads.
-const TodayReportHoverCardMetric = lazyWithRetry(() =>
- import('./TodayReportHoverCardMetric').then((m) => ({ default: m.TodayReportHoverCardMetric }))
-)
-const TodayReportHoverCardChart = lazyWithRetry(() =>
- import('./TodayReportHoverCardChart').then((m) => ({ default: m.TodayReportHoverCardChart }))
-)
-
-// The card lists a few more metrics by their saved value. A chart for each would run two live queries per metric on every hover.
-const LISTED_METRIC_COUNT = 2
-
-/**
- * A report's hover card, on its left-bar row and on its links in the briefing text: its priority, why the
- * briefing picked it, what happened to it since, its implementation pull request, summary and headline
- * metric. The text comes with the page. The metric runs its live query while the card is open, and a
- * report without a metric shows the card without it.
- */
-export function TodayReportHoverCard({ preview }: { preview: TodayReportPreview }): JSX.Element {
- const { card } = preview
- const { reportStateOverrides } = useValues(todayLogic)
- const { reportPreviewed, requestReportVerdict, leaveReportReview } = useActions(todayLogic)
- // Keyed on the report, not the card object: a poll replaces the object while the card stays open.
- useEffect(() => {
- reportPreviewed(card.key, preview.surface)
- }, [card.key, preview.surface, reportPreviewed])
-
- // Read live, not from the card: the card stays open after a click, and keeps the payload it opened with.
- const override = card.reportId ? reportStateOverrides[card.reportId] : undefined
- const stateLabel = override ? itemStateLabel({ state: override }) : card.stateLabel
- const resolved = override ? override === 'done' : card.resolved
- const { reportId } = card
- const giveVerdict = (verdict: TodayReportVerdict): void => {
- if (reportId) {
- requestReportVerdict(
- {
- reportId,
- title: card.title,
- hasOpenPullRequest: card.pullRequestState === 'open' || card.pullRequestState === 'draft',
- },
- verdict,
- preview.surface
- )
- }
- }
- const isSample = !!reportId && isSampleReportId(reportId)
- const pullRequestState = pullRequestStateMeta(card.pullRequestState)
- const metric = selectReportCardImpactMetric(card.metrics)
- const aggregateQuery = metric ? asReportMetricAggregateQuery(metric.query) : null
- const seriesQuery = metric ? asReportMetricSeriesQuery(metric) : null
- const lead = [card.priority, card.reason].filter(Boolean).join(' · ')
- const hasMetricChart = !!(metric && aggregateQuery && seriesQuery)
- // A report without a metric to chart shows the first chart from its body instead.
- const bodyChart = hasMetricChart
- ? null
- : card.charts.map((chart) => ({ chart, query: reportChartGraphQuery(chart) })).find(({ query }) => query)
- const hasChart = hasMetricChart || !!bodyChart
- const otherMetrics = card.metrics.flatMap((candidate) => {
- const parts = hasMetricChart && candidate === metric ? null : reportMetricRowParts(candidate, candidate.value)
- return parts ? [{ metric: candidate, value: [parts.value, parts.unit].filter(Boolean).join(' ') }] : []
- })
- const listedMetrics = otherMetrics.slice(0, LISTED_METRIC_COUNT)
- const unlistedMetricCount = otherMetrics.length - listedMetrics.length
- const activity = [
- card.signalCount ? pluralize(card.signalCount, 'signal') : null,
- card.updatedAt ? `updated ${dayjs(card.updatedAt).fromNow()}` : null,
- ]
- .filter(Boolean)
- .join(' · ')
-
- return (
- <div className="flex flex-col" data-attr="today-report-hover-card">
- <Item size="xs" className="items-start">
- <ItemContent className="min-w-0 gap-0.5">
- {/* The badge shares a row with the title alone, so it narrows the title and not the
- line below, which has to stay on one line. */}
- <div className="flex items-start justify-between gap-2">
- {/* `wrap-anywhere`: the title sizes to its content, so a long title would widen the card. */}
- <ItemTitle className="min-w-0 wrap-anywhere">
- <span className="min-w-0 font-semibold">{card.title}</span>
- </ItemTitle>
- {stateLabel && (
- <ItemActions className="shrink-0">
- <Badge variant={resolved ? 'completed' : 'default'}>{stateLabel}</Badge>
- </ItemActions>
- )}
- </div>
- {/* The lead gives up room to the mark, which is short and must stay whole. */}
- {(lead || card.pullRequestUrl) && (
- <ItemDescription className="flex flex-nowrap items-center gap-x-2">
- {lead && <span className="truncate">{lead}</span>}
- {card.pullRequestUrl && (
- <span className="flex shrink-0 items-center gap-1.5">
- <LinkPrimitive
- to={card.pullRequestUrl}
- target="_blank"
- data-attr="today-report-hover-card-pr"
- // Dotted at rest, so the one mark that opens something reads as a link.
- className="flex min-w-0 items-center gap-1 font-normal text-foreground underline decoration-dotted underline-offset-2"
- >
- <IconPullRequest
- className={cn('size-3 shrink-0', pullRequestState?.iconClassName)}
- />
- <span className="truncate">
- {pullRequestState
- ? `PR ${pullRequestState.label.toLowerCase()}`
- : 'Pull request'}
- </span>
- </LinkPrimitive>
- </span>
- )}
- </ItemDescription>
- )}
- </ItemContent>
- </Item>
- {card.summary && (
- // Its own row, so the summary uses the full card width, not the column beside the state badge.
- <Item size="xs" className="pt-0">
- <ItemContent className="min-w-0">
- {/* A few lines say what the report is about. Without a chart below, the summary gets the room. */}
- <Text
- size="xs"
- variant="muted"
- className={cn('leading-snug break-words', hasChart ? 'line-clamp-3' : 'line-clamp-8')}
- >
- {card.summary}
- </Text>
- </ItemContent>
- </Item>
- )}
- {(hasChart || listedMetrics.length > 0) && (
- <>
- <ItemSeparator className="my-0" />
- <Item size="xs">
- <ItemContent className="min-w-0 gap-1.5">
- {/* The metric and report charts are `h-36`, so the card keeps its size while they load. */}
- <Suspense fallback={hasChart ? <Skeleton className="h-36 w-full" /> : null}>
- {metric && aggregateQuery && seriesQuery && (
- <TodayReportHoverCardMetric
- cardKey={card.key}
- metric={metric}
- aggregateQuery={aggregateQuery.source}
- seriesQuery={seriesQuery.source}
- />
- )}
- {bodyChart?.query && (
- <TodayReportHoverCardChart
- cardKey={card.key}
- chart={bodyChart.chart}
- query={bodyChart.query}
- />
- )}
- </Suspense>
- {listedMetrics.map(({ metric: listed, value }) => (
- <div
- key={listed.metric_id}
- className="flex items-baseline justify-between gap-2"
- data-attr="today-report-hover-card-listed-metric"
- >
- <Text
- size="xs"
- variant="muted"
- render={<span title={listed.title} />}
- className="truncate"
- >
- {listed.title}
- </Text>
- <Text
- size="xs"
- render={<span translate="no" />}
- className="shrink-0 font-semibold tabular-nums"
- >
- {value}
- </Text>
- </div>
- ))}
- {unlistedMetricCount > 0 && (
- <Text size="xs" variant="muted" render={<span />}>
- {`${pluralize(unlistedMetricCount, 'more metric')} in the report`}
- </Text>
- )}
- </ItemContent>
- </Item>
- </>
- )}
- <ItemSeparator className="my-0" />
- {/* Each half wraps as a whole, so a narrow card never leaves one word on its own line. */}
- <div className="flex flex-wrap justify-between gap-x-3 px-3 py-2">
- <Text size="xs" variant="muted" render={<span />} className="whitespace-nowrap">
- {card.sourceLabel}
- </Text>
- {activity && (
- <Text size="xs" variant="muted" render={<span />} className="whitespace-nowrap">
- {activity}
- </Text>
- )}
- </div>
- {reportId && !stateLabel && (
- <>
- <ItemSeparator className="my-0" />
- <div className="flex flex-wrap justify-between gap-1.5 px-3 py-2">
- <Button
- variant="outline"
- size="xs"
- disabled={isSample}
- onClick={() => giveVerdict('resolve')}
- data-attr="today-report-hover-card-resolve"
- >
- <IconCheckCircle />
- Resolve
- </Button>
- {/* The click gives the report a state label, which takes this whole row off the
- card, so the request cannot be sent twice and needs no in-flight state. */}
- {card.canLeaveReview && (
- <Button
- variant="outline"
- size="xs"
- disabled={isSample}
- title="Remove yourself from this report’s reviewers"
- onClick={() => leaveReportReview(reportId, preview.surface)}
- data-attr="today-report-hover-card-leave-review"
- >
- <IconLeave />
- Not me
- </Button>
- )}
- <Button
- variant="outline"
- size="xs"
- disabled={isSample}
- onClick={() => giveVerdict('dismiss')}
- data-attr="today-report-hover-card-dismiss"
- >
- <IconHide />
- Dismiss
- </Button>
- </div>
- </>
- )}
- </div>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHoverCardChart.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHoverCardChart.tsx
deleted file mode 100644
index 44aeed30a4e5..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayReportHoverCardChart.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Text } from '@posthog/quill'
-
-import { Query } from '~/queries/Query/Query'
-import type { Node } from '~/queries/schema/schema-general'
-
-import type { ReportChartApi } from 'products/signals/frontend/generated/api.schemas'
-import { OBSERVATION_CHART_HEIGHT_CLASS } from 'products/signals/frontend/inbox/components/detail/ReportObservationChart'
-
-/** A chart from the report body without its frame: its title, then the graph at the metric chart's height. */
-export function TodayReportHoverCardChart({
- cardKey,
- chart,
- query,
-}: {
- cardKey: string
- chart: ReportChartApi
- query: Node
-}): JSX.Element {
- // The SQLEditor prefix lets a SQL graph size to its box rather than to the window.
- const uniqueKey = `SQLEditor-today-report-chart-${cardKey}-${chart.chart_id}`
-
- return (
- <div className="flex flex-col gap-1.5" data-attr="today-report-hover-card-chart">
- <Text size="xs" variant="muted" render={<span title={chart.title} />} className="truncate">
- {chart.title}
- </Text>
- <div className={`flex flex-col ${OBSERVATION_CHART_HEIGHT_CLASS}`}>
- {/* Keyed, so moving to another report's card does not reuse this chart's query logic. */}
- <Query key={uniqueKey} query={query} uniqueKey={uniqueKey} readOnly embedded />
- </div>
- </div>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHoverCardMetric.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHoverCardMetric.tsx
deleted file mode 100644
index 0967cb028c68..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayReportHoverCardMetric.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { useValues } from 'kea'
-
-import { Skeleton, Text } from '@posthog/quill'
-
-import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import type { TrendsQuery } from '~/queries/schema/schema-general'
-
-import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'
-import {
- OBSERVATION_CHART_HEIGHT_CLASS,
- ReportObservationChart,
-} from 'products/signals/frontend/inbox/components/detail/ReportObservationChart'
-import {
- reportMetricAggregate,
- reportMetricChartType,
- reportMetricRowParts,
- reportMetricSeriesPoints,
- reportMetricWindowLabel,
-} from 'products/signals/frontend/inbox/utils/reportMetrics'
-
-/**
- * The report detail's live chart without its frame: what the metric measures and its live value on one
- * line, then the chart. The saved value shows until the live query answers.
- */
-export function TodayReportHoverCardMetric({
- cardKey,
- metric,
- aggregateQuery,
- seriesQuery,
-}: {
- cardKey: string
- metric: ReportMetricApi
- aggregateQuery: TrendsQuery
- seriesQuery: TrendsQuery
-}): JSX.Element {
- const aggregateProps: DataNodeLogicProps = {
- key: `TodayReportMetricAggregate.${cardKey}.${metric.metric_id}`,
- query: aggregateQuery,
- autoLoad: true,
- }
- const seriesProps: DataNodeLogicProps = {
- key: `TodayReportMetricSeries.${cardKey}.${metric.metric_id}`,
- query: seriesQuery,
- autoLoad: true,
- }
- const { response } = useValues(dataNodeLogic(aggregateProps))
- const { response: seriesResponse, responseError: seriesError } = useValues(dataNodeLogic(seriesProps))
-
- const parts = reportMetricRowParts(metric, reportMetricAggregate(response) ?? metric.value)
- const points = reportMetricSeriesPoints(seriesResponse)
- const window = reportMetricWindowLabel(metric.query)
- const label = window ? `${metric.title}, ${window.toLowerCase()}` : metric.title
-
- return (
- <div className="flex flex-col gap-1.5" data-attr="today-report-hover-card-metric">
- <div className="flex items-baseline justify-between gap-2">
- <Text size="xs" variant="muted" render={<span title={label} />} className="truncate">
- {label}
- </Text>
- {parts && (
- <Text size="xs" render={<span translate="no" />} className="shrink-0 font-semibold tabular-nums">
- {`${parts.value} ${parts.unit}`}
- </Text>
- )}
- </div>
- {points ? (
- <ReportObservationChart
- metric={metric}
- points={points}
- type={reportMetricChartType(metric)}
- interval={seriesQuery.interval}
- />
- ) : !seriesError && seriesResponse == null ? (
- <Skeleton className={`${OBSERVATION_CHART_HEIGHT_CLASS} w-full`} />
- ) : null}
- </div>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportNav.tsx b/frontend/src/scenes/project-homepage/today/TodayReportNav.tsx
new file mode 100644
index 000000000000..2b307dc7fd35
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayReportNav.tsx
@@ -0,0 +1,125 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { IconArrowLeft, IconChevronDown } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { type HotkeyInterface, useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { todayLogic } from './todayLogic'
+import { todayReportLogic } from './todayReportLogic'
+import { todayReportQueueLogic } from './todayReportQueueLogic'
+import { isPlainClick } from './todayViewTransition'
+
+function isTyping(target: EventTarget | null): boolean {
+ return (
+ target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))
+ )
+}
+
+function overlayOpen(): boolean {
+ return Array.from(
+ document.querySelectorAll('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')
+ ).some((element) => !element.closest('aside, [inert], [aria-hidden="true"]'))
+}
+
+function reportShortcut(run: () => void): HotkeyInterface {
+ return {
+ action: (event) => {
+ if (!isTyping(event.target) && !overlayOpen()) {
+ run()
+ }
+ },
+ }
+}
+
+function TodayReportPrefetch({ reportId }: { reportId: string }): null {
+ useMountedLogic(todayReportLogic({ reportId }))
+ return null
+}
+
+function StepButton({
+ step,
+ label,
+ shortcut,
+ disabled,
+}: {
+ step: 1 | -1
+ label: string
+ shortcut: string
+ disabled: boolean
+}): JSX.Element {
+ const { openAdjacentReport } = useActions(todayReportQueueLogic)
+ const { moreReportsLoading } = useValues(todayLogic)
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon"
+ aria-label={label}
+ disabled={disabled || moreReportsLoading}
+ onClick={() => openAdjacentReport(step)}
+ data-attr={step === 1 ? 'today-report-next' : 'today-report-previous'}
+ />
+ }
+ >
+ <IconChevronDown className={step === -1 ? 'size-4 rotate-180' : 'size-4'} />
+ </TooltipTrigger>
+ <TooltipContent>{`${label} (${shortcut})`}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+export function TodayReportNav(): JSX.Element {
+ const { reportPosition, reportQueueIds, adjacentReportIds, atQueueEnd, restInInbox } =
+ useValues(todayReportQueueLogic)
+ const { openAdjacentReport, leaveReport } = useActions(todayReportQueueLogic)
+
+ useKeyboardHotkeys(
+ {
+ escape: reportShortcut(leaveReport),
+ j: reportShortcut(() => openAdjacentReport(1)),
+ k: reportShortcut(() => openAdjacentReport(-1)),
+ },
+ [leaveReport, openAdjacentReport]
+ )
+
+ return (
+ <nav className="TodayReportNav" aria-label="Reports">
+ {adjacentReportIds.map((id) => (
+ <TodayReportPrefetch key={id} reportId={id} />
+ ))}
+ <LinkPrimitive
+ to={urls.projectHomepage()}
+ className="TodayReportNav__back"
+ onClick={(event) => {
+ if (isPlainClick(event)) {
+ event.preventDefault()
+ leaveReport()
+ }
+ }}
+ data-attr="today-report-back"
+ >
+ <IconArrowLeft className="size-3.5" />
+ <span>Home</span>
+ </LinkPrimitive>
+ {reportPosition !== null && (
+ <span className="TodayReportNav__steps">
+ <span className="TodayReportNav__count" translate="no">
+ {`${reportPosition} of ${reportQueueIds.length}`}
+ </span>
+ <StepButton step={-1} label="Previous report" shortcut="K" disabled={reportPosition <= 1} />
+ <StepButton
+ step={1}
+ label={restInInbox ? 'Open the Inbox for the rest' : 'Next report'}
+ shortcut="J"
+ disabled={atQueueEnd && !restInInbox}
+ />
+ </span>
+ )}
+ </nav>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx b/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx
deleted file mode 100644
index a9d362850ebe..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { urls } from 'scenes/urls'
-
-import type { TodayReportPreview } from '~/layout/today/todayPreviewCards'
-import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
-
-import { SignalReport } from 'products/signals/frontend/inbox/types'
-import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/utils/reportPresentation'
-
-import { itemStateLabel } from './todayBriefingItems'
-import { TodayIcon } from './TodayIcon'
-import { TodayReportOpenSource, todayLogic } from './todayLogic'
-import { TodayNavItem } from './TodayNavItem'
-import { reportIcon, reportMeta, reportSource } from './todaySignalReports'
-
-interface TodayReportNavItemProps {
- report: SignalReport
- preview: TodayReportPreview
- source: Extract<TodayReportOpenSource, 'sidebar' | 'sidebar_more'>
- dataAttr: string
-}
-
-export function TodayReportNavItem({ report, preview, source, dataAttr }: TodayReportNavItemProps): JSX.Element {
- const { reportId, hoveredReportId, reportStateOverrides } = useValues(todayLogic)
- const { reportOpened, setHoveredReportId } = useActions(todayLogic)
- const override = reportStateOverrides[report.id]
-
- return (
- <TodayPreviewTrigger payload={preview}>
- <TodayNavItem
- title={displayConventionalCommitTitle(report.title, 'Untitled report')}
- meta={itemStateLabel({ state: override ?? 'open' }) ?? reportMeta(report)}
- color={reportSource(report).color}
- icon={<TodayIcon icon={reportIcon(report)} />}
- to={urls.todayReport(report.id)}
- active={hoveredReportId === report.id}
- current={reportId === report.id}
- state={override}
- dataAttr={dataAttr}
- onClick={() => reportOpened(report, source)}
- onHoverChange={(hovered) => setHoveredReportId(hovered ? report.id : null)}
- />
- </TodayPreviewTrigger>
- )
-}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx b/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx
index 870c493b627d..e42496a04035 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportPage.tsx
@@ -1,26 +1,31 @@
import { useActions, useValues } from 'kea'
+import { useEffect, useLayoutEffect, useRef } from 'react'
import { Button, Heading, Skeleton, Text } from '@posthog/quill'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
import { urls } from 'scenes/urls'
+import { projectHomepageLogic } from '../projectHomepageLogic'
import { TodayReportBody } from './TodayReportBody'
+import { TodayReportHeader } from './TodayReportHeader'
import { TodayReportLiveBody } from './TodayReportLiveBody'
import { todayReportLogic } from './todayReportLogic'
+import { TodayReportNav } from './TodayReportNav'
import { TodaySampleBanner } from './TodaySampleBanner'
+import { reportTitle } from './todaySignalReports'
function ReportFailed({ reportId }: { reportId: string }): JSX.Element {
const logic = todayReportLogic({ reportId })
const { fullReportLoading, pageLoading } = useValues(logic)
const { loadFullReport, loadPage } = useActions(logic)
return (
- <div className="flex max-w-150 flex-col gap-3">
+ <div className="flex 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.
+ It may have been deleted, or the request failed. Try again, or go back to Home.
</Text>
<div className="mt-3 flex flex-wrap gap-2">
<Button
@@ -47,21 +52,23 @@ function ReportFailed({ reportId }: { reportId: string }): JSX.Element {
)
}
-function ReportSkeleton(): JSX.Element {
+function ReportSkeleton({ header }: { header: JSX.Element | null }): 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>
- <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 className="flex flex-col gap-10" aria-busy>
+ {header ?? (
+ <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>
+ <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>
- <Skeleton className="mt-3 h-3.5 w-3/5" />
- </div>
+ )}
<div className="flex flex-col gap-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-3.5 w-full" />
@@ -90,17 +97,31 @@ function ReportSkeleton(): JSX.Element {
export function TodayReportPage({ reportId }: { reportId: string }): JSX.Element {
const { currentReport, page, reportFailed, isSample } = useValues(todayReportLogic({ reportId }))
+ const { setTodayReportTitle } = useActions(projectHomepageLogic)
+ const title = currentReport ? reportTitle(currentReport) : null
+ const rootRef = useRef<HTMLDivElement>(null)
+
+ useLayoutEffect(() => {
+ rootRef.current?.closest('main')?.scrollTo({ top: 0 })
+ }, [reportId])
+
+ useEffect(() => {
+ setTodayReportTitle(title)
+ return () => setTodayReportTitle(null)
+ }, [title, setTodayReportTitle])
if ((!currentReport || !page) && !reportFailed) {
return (
- <div className="TodayReport Today__page" data-quill>
- <ReportSkeleton />
+ <div ref={rootRef} className="TodayReport Today__page" data-quill>
+ <TodayReportNav />
+ <ReportSkeleton header={currentReport ? <TodayReportHeader report={currentReport} /> : null} />
</div>
)
}
return (
- <div className="TodayReport Today__page" data-quill>
+ <div ref={rootRef} className="TodayReport Today__page" data-quill>
+ <TodayReportNav />
<TodaySampleBanner />
{reportFailed && <ReportFailed reportId={reportId} />}
{currentReport && isSample && <TodayReportBody report={currentReport} live={null} />}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx
index e2eca069a4e4..81d167d0dbad 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx
@@ -2,15 +2,20 @@ import { useValues } from 'kea'
import { Text } from '@posthog/quill'
+import { hasActiveReportPullRequest } from 'products/signals/frontend/inbox/utils/reportPullRequests'
+
import { TodayMarkedText } from './TodayMarkedText'
import { todayReportLogic } from './todayReportLogic'
import { TodaySectionTitle } from './TodaySectionTitle'
-export function TodayReportProposal({ reportId }: { reportId: string }): JSX.Element {
- const { proposal, shownKeyClauses } = useValues(todayReportLogic({ reportId }))
+export function TodayReportProposal({ reportId }: { reportId: string }): JSX.Element | null {
+ const { proposal, shownKeyClauses, currentReport, reportState } = useValues(todayReportLogic({ reportId }))
+ if (!proposal && reportState !== 'open') {
+ return null
+ }
return (
<div className="flex flex-col gap-2">
- <TodaySectionTitle>Proposal</TodaySectionTitle>
+ <TodaySectionTitle>{proposal ? 'Proposal' : 'Next step'}</TodaySectionTitle>
{proposal ? (
<Text size="sm" render={<p />} className="leading-relaxed text-pretty">
<TodayMarkedText
@@ -20,11 +25,11 @@ export function TodayReportProposal({ reportId }: { reportId: string }): JSX.Ele
reportId={reportId}
/>
</Text>
- ) : (
+ ) : hasActiveReportPullRequest(currentReport) ? (
<Text size="sm" variant="muted" render={<p />}>
- No fix proposed yet.
+ A fix is ready for review.
</Text>
- )}
+ ) : null}
</div>
)
}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportRow.tsx b/frontend/src/scenes/project-homepage/today/TodayReportRow.tsx
new file mode 100644
index 000000000000..a97f7e3f5095
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayReportRow.tsx
@@ -0,0 +1,83 @@
+import { useActions, useValues } from 'kea'
+
+import { dayjs } from 'lib/dayjs'
+import { urls } from 'scenes/urls'
+
+import { SignalReport } from 'products/signals/frontend/inbox/types'
+import { hasOpenImplementationPr } from 'products/signals/frontend/inbox/utils/reportActions'
+
+import { itemStateLabel } from './todayBriefingItems'
+import { todayLogic, type TodayReportOpenSource } from './todayLogic'
+import { priorityTone } from './todayPriority'
+import { TodayReportRowDetail } from './TodayReportRowDetail'
+import { TodayRow } from './TodayRow'
+import { pullRequestFact, rowFacts } from './todayRowFacts'
+import { reportIcon } from './todayRowIcons'
+import { reportTitle } from './todaySignalReports'
+import { TodayVerdictButtons } from './TodayVerdictButtons'
+import { type TodayReportVerdictTarget, todayVerdictLogic } from './todayVerdictLogic'
+
+export function TodayReportRow({
+ report,
+ source,
+ done,
+}: {
+ report: SignalReport
+ source: TodayReportOpenSource
+ done: boolean
+}): JSX.Element {
+ const { reportPreviews, expandedReportRows } = useValues(todayLogic)
+ const { reportStateOverrides } = useValues(todayVerdictLogic)
+ const { reportOpened, toggleReportRow } = useActions(todayLogic)
+ const state = reportStateOverrides[report.id]
+ const preview = reportPreviews[report.id]
+ const to = urls.todayReport(report.id)
+ const target: TodayReportVerdictTarget = {
+ reportId: report.id,
+ title: reportTitle(report),
+ hasOpenPullRequest: hasOpenImplementationPr(report),
+ }
+ return (
+ <TodayRow
+ tone={priorityTone(report.priority)}
+ icon={reportIcon(report)}
+ title={target.title}
+ label={report.priority ?? undefined}
+ facts={rowFacts(
+ state
+ ? [itemStateLabel({ state })]
+ : [
+ pullRequestFact(
+ report.implementation_pr_merged
+ ? 'merged'
+ : (report.implementation_pr_state ?? (report.implementation_pr_url ? 'open' : null))
+ ),
+ `Updated ${dayjs(report.updated_at).fromNow()}`,
+ ]
+ )}
+ to={to}
+ onOpen={() => reportOpened(report, source)}
+ expansion={
+ preview
+ ? {
+ expanded: !!expandedReportRows[report.id],
+ onToggle: () => toggleReportRow(report.id, report.id),
+ detail: (
+ <TodayReportRowDetail
+ preview={preview}
+ to={to}
+ onOpen={() => reportOpened(report, source)}
+ actions={done ? null : <TodayVerdictButtons target={target} labelled />}
+ dataAttr="today-list-report"
+ />
+ ),
+ }
+ : undefined
+ }
+ actions={<TodayVerdictButtons target={target} />}
+ done={done}
+ reportId={report.id}
+ dataAttr="today-list-report"
+ />
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportRowDetail.tsx b/frontend/src/scenes/project-homepage/today/TodayReportRowDetail.tsx
new file mode 100644
index 000000000000..4fbfc6dfa727
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayReportRowDetail.tsx
@@ -0,0 +1,92 @@
+import type { MouseEvent, ReactNode } from 'react'
+
+import { IconArrowRight, IconArrowUpRight, IconPullRequest } from '@posthog/icons'
+import { Button } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import type { TodayReportPreview } from './todayReportPreviews'
+import { isPlainClick, navigateWithCrossfade } from './todayViewTransition'
+
+const PULL_REQUEST_STATES: Record<string, string> = {
+ open: 'ready for review',
+ draft: 'draft',
+ merged: 'merged',
+ closed: 'closed',
+}
+
+function PullRequestLink({
+ pullRequest,
+}: {
+ pullRequest: NonNullable<TodayReportPreview['pullRequest']>
+}): JSX.Element {
+ const number = pullRequest.url.match(/\/pull\/(\d+)/)?.[1]
+ const state = PULL_REQUEST_STATES[pullRequest.state ?? '']
+ return (
+ <LinkPrimitive
+ to={pullRequest.url}
+ target="_blank"
+ className="TodayRow__detailPr"
+ data-attr="today-list-report-pr"
+ >
+ <IconPullRequest className="size-3.5" aria-hidden />
+ <span>{[number ? `Pull request #${number}` : 'Pull request', state].filter(Boolean).join(', ')}</span>
+ <IconArrowUpRight className="size-3" aria-hidden />
+ </LinkPrimitive>
+ )
+}
+
+export function TodayReportRowDetail({
+ preview,
+ to,
+ onOpen,
+ actions,
+ dataAttr,
+}: {
+ preview: TodayReportPreview
+ to: string
+ onOpen: () => void
+ actions?: ReactNode
+ dataAttr: string
+}): JSX.Element {
+ const openReport = (event: MouseEvent<HTMLElement>): void => {
+ onOpen()
+ if (isPlainClick(event)) {
+ event.preventDefault()
+ navigateWithCrossfade(to)
+ }
+ }
+ const facts = [preview.sources, preview.metric && `${preview.metric.title}: ${preview.metric.value}`].filter(
+ (fact): fact is string => !!fact
+ )
+ return (
+ <div className="TodayRow__detailBody">
+ {preview.lead && <p className="TodayRow__detailLead">{preview.lead}</p>}
+ <div className="TodayRow__detailFooter">
+ <p className="TodayRow__detailFacts">
+ <span>{facts.join(' · ')}</span>
+ {preview.pullRequest && (
+ <>
+ {facts.length > 0 && ' · '}
+ <PullRequestLink pullRequest={preview.pullRequest} />
+ </>
+ )}
+ </p>
+ <div className="TodayRow__detailActions">
+ {actions}
+ <Button
+ variant="outline"
+ size="sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={to} />}
+ onClick={openReport}
+ data-attr={dataAttr}
+ >
+ Open report
+ <IconArrowRight />
+ </Button>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx b/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx
index 53068e5323da..6eb6c6325f63 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportSignalRow.tsx
@@ -15,6 +15,7 @@ import type { SignalPreviewApi, SignalViewApi } from 'products/today/frontend/ge
import { TodaySignalDestination, previewOpen, shownPreview, signalDestination } from './todayEvidence'
import { TodayEvidenceDetail } from './TodayEvidenceDetail'
import { TodayIcon } from './TodayIcon'
+import { TodayMarkedText } from './TodayMarkedText'
import { shortDate } from './todayProse'
import { todayReportLogic } from './todayReportLogic'
import { sourceStyle } from './todaySignalReports'
@@ -146,7 +147,13 @@ export function TodayReportSignalRow({ reportId, signal }: { reportId: string; s
>
<ItemContent className="min-w-0">
<ItemTitle className={cn('font-normal text-foreground', !expanded && 'line-clamp-2')}>
- {expanded ? signal.lead : signal.headline}
+ <TodayMarkedText
+ markdown={expanded ? signal.lead : signal.headline}
+ marked={[]}
+ keyClauses={[]}
+ reportId={reportId}
+ plainLinks
+ />
</ItemTitle>
{phoneLayout && !expanded && <PhoneRowMeta signal={signal} sourceLabel={sourceLabel} />}
</ItemContent>
diff --git a/frontend/src/scenes/project-homepage/today/TodayRow.tsx b/frontend/src/scenes/project-homepage/today/TodayRow.tsx
new file mode 100644
index 000000000000..8e3bb5f90004
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayRow.tsx
@@ -0,0 +1,127 @@
+import { Collapsible } from '@base-ui/react/collapsible'
+import type { MouseEvent, ReactNode } from 'react'
+
+import { IconArrowRight, IconChevronDown } from '@posthog/icons'
+import { IconStack, IconStackItem } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { isExternalHref } from './todayBriefingItems'
+import type { TodayRowIcon } from './todayRowIcons'
+import { isPlainClick, navigateWithCrossfade } from './todayViewTransition'
+
+export type TodayRowTone = 'risk' | 'neutral' | 'quiet'
+
+interface TodayRowExpansion {
+ expanded: boolean
+ onToggle: () => void
+ detail: ReactNode
+}
+
+interface TodayRowProps {
+ tone: TodayRowTone
+ icon: TodayRowIcon
+ title: string
+ label?: string
+ facts: string[]
+ to?: string
+ onOpen?: () => void
+ expansion?: TodayRowExpansion
+ actions?: ReactNode
+ doneActions?: ReactNode
+ done?: boolean
+ reportId?: string
+ dataAttr: string
+}
+
+export function TodayRow({
+ tone,
+ icon,
+ title,
+ label,
+ facts,
+ to,
+ onOpen,
+ expansion,
+ actions,
+ doneActions,
+ done,
+ reportId,
+ dataAttr,
+}: TodayRowProps): JSX.Element {
+ const external = !!to && isExternalHref(to)
+ const expanded = !!expansion?.expanded
+ const openReport = (event: MouseEvent<HTMLElement>): void => {
+ onOpen?.()
+ if (to && reportId && isPlainClick(event)) {
+ event.preventDefault()
+ navigateWithCrossfade(to)
+ }
+ }
+ const content = (
+ <>
+ <IconStack className="TodayRow__icons">
+ <IconStackItem color={icon.color}>{icon.glyph}</IconStackItem>
+ </IconStack>
+ <div className="min-w-0">
+ {expansion ? (
+ <Collapsible.Trigger
+ className="TodayRow__title TodayRow__link TodayRow__toggle"
+ data-today-report={reportId}
+ data-attr={`${dataAttr}-toggle`}
+ >
+ {title}
+ </Collapsible.Trigger>
+ ) : to ? (
+ <LinkPrimitive
+ to={to}
+ target={external ? '_blank' : undefined}
+ className="TodayRow__title TodayRow__link"
+ onClick={openReport}
+ data-today-report={reportId}
+ data-attr={dataAttr}
+ >
+ {title}
+ </LinkPrimitive>
+ ) : (
+ <span className="TodayRow__title">{title}</span>
+ )}
+ <p className="TodayRow__meta">
+ {[label, ...facts].filter(Boolean).map((part, index) => (
+ <span
+ key={`${index}-${part}`}
+ className={index === 0 && label ? 'TodayRow__label' : undefined}
+ data-tone={index === 0 && label ? tone : undefined}
+ >
+ {index === 0 ? part : ` · ${part}`}
+ </span>
+ ))}
+ </p>
+ </div>
+ <div className="TodayRow__end">
+ {actions && !done && !expanded && <div className="TodayRow__actions">{actions}</div>}
+ {doneActions && done && <div className="TodayRow__undo">{doneActions}</div>}
+ {expansion ? (
+ <IconChevronDown className="TodayRow__chevron" aria-hidden />
+ ) : (
+ to && <IconArrowRight className="TodayRow__arrow" aria-hidden />
+ )}
+ </div>
+ {expansion && <Collapsible.Panel className="TodayRow__detail">{expansion.detail}</Collapsible.Panel>}
+ </>
+ )
+ const rowProps = {
+ className: 'TodayRow',
+ 'data-interactive': to || expansion ? true : undefined,
+ 'data-expanded': expanded || undefined,
+ 'data-done': done || undefined,
+ }
+ if (!expansion) {
+ return <li {...rowProps}>{content}</li>
+ }
+ return (
+ <Collapsible.Root open={expanded} onOpenChange={expansion.onToggle} render={<li {...rowProps} />}>
+ {content}
+ </Collapsible.Root>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodaySparkline.tsx b/frontend/src/scenes/project-homepage/today/TodaySparkline.tsx
new file mode 100644
index 000000000000..320de305587d
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodaySparkline.tsx
@@ -0,0 +1,113 @@
+import { useValues } from 'kea'
+import { useCallback, useMemo } from 'react'
+
+import {
+ AnomalyPointsLayer,
+ LineChart,
+ type LineChartConfig,
+ type Series,
+ type TooltipContext,
+} from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+export type TodayTone = 'risk' | 'good' | 'neutral'
+
+interface TodayTonePalette {
+ risk: string
+ good: string
+ neutral: string
+ line: string
+}
+
+const PALETTE: Record<'light' | 'dark', TodayTonePalette> = {
+ light: { risk: '#d6453a', good: '#1f9d55', neutral: '#55554f', line: '#c4c4bc' },
+ dark: { risk: '#ff7b6e', good: '#5fd38d', neutral: '#c9c9c2', line: '#55554f' },
+}
+
+export function useTodayTonePalette(): TodayTonePalette {
+ const { isDarkModeOn } = useValues(themeLogic)
+ return isDarkModeOn ? PALETTE.dark : PALETTE.light
+}
+
+export function TodaySparkline({
+ values,
+ labels,
+ tone,
+ emphasizeLast,
+ formatValue,
+}: {
+ values: number[]
+ labels: string[]
+ tone: TodayTone
+ emphasizeLast: number
+ formatValue: (value: number) => string
+}): JSX.Element {
+ const theme = useChartTheme()
+ const palette = useTodayTonePalette()
+ const last = values.length - 1
+ const from = Math.max(0, values.length - 1 - emphasizeLast)
+ const series = useMemo<Series[]>(
+ () => [
+ { key: 'trend', label: 'Value', data: values, color: palette.line },
+ {
+ key: 'recent',
+ label: 'Recent',
+ data: values.map((value, index) => (index >= from ? value : NaN)),
+ color: palette[tone],
+ visibility: { tooltip: false },
+ },
+ ],
+ [values, from, palette, tone]
+ )
+ const config = useChartConfig<LineChartConfig>(
+ () => ({
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ showAxisLines: false,
+ showTickMarks: false,
+ showCrosshair: true,
+ curve: 'linear',
+ floatBaseline: true,
+ margins: { top: 4, right: 4, bottom: 4, left: 1 },
+ tooltip: { enabled: true, placement: 'follow-data' },
+ }),
+ []
+ )
+ const tooltip = useCallback(
+ (context: TooltipContext): JSX.Element | null => {
+ const value = context.seriesData[0]?.value
+ if (value === undefined || Number.isNaN(value)) {
+ return null
+ }
+ return (
+ <div className="rounded-md border border-border bg-background px-2 py-1 shadow-sm">
+ <div className="text-xs text-muted-foreground">{context.label}</div>
+ <div className="text-xs font-medium tabular-nums text-foreground">{formatValue(value)}</div>
+ </div>
+ )
+ },
+ [formatValue]
+ )
+
+ return (
+ <LineChart
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={config}
+ tooltip={tooltip}
+ className="h-full w-full"
+ >
+ <AnomalyPointsLayer
+ radius={2.5}
+ markers={
+ last >= 0 ? [{ dataIndex: last, value: values[last], color: palette[tone], yAxisId: 'left' }] : []
+ }
+ />
+ </LineChart>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayVerdictButtons.tsx b/frontend/src/scenes/project-homepage/today/TodayVerdictButtons.tsx
new file mode 100644
index 000000000000..af4cd3a8b7c5
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayVerdictButtons.tsx
@@ -0,0 +1,61 @@
+import { useActions } from 'kea'
+
+import { IconCheckCircle, IconHide } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { isSampleReportId } from './todaySampleReports'
+import { type TodayReportVerdict, type TodayReportVerdictTarget, todayVerdictLogic } from './todayVerdictLogic'
+
+const VERDICT_BUTTONS: { verdict: TodayReportVerdict; label: string; icon: JSX.Element }[] = [
+ { verdict: 'resolve', label: 'Resolve', icon: <IconCheckCircle className="size-3.5" /> },
+ { verdict: 'dismiss', label: 'Dismiss', icon: <IconHide className="size-3.5" /> },
+]
+
+export function TodayVerdictButtons({
+ target,
+ labelled = false,
+}: {
+ target: TodayReportVerdictTarget
+ labelled?: boolean
+}): JSX.Element {
+ const { requestReportVerdict } = useActions(todayVerdictLogic)
+ const disabled = isSampleReportId(target.reportId)
+ return (
+ <>
+ {VERDICT_BUTTONS.map(({ verdict, label, icon }) => {
+ const onClick = (): void => requestReportVerdict(target, verdict, 'briefing')
+ return labelled ? (
+ <Button
+ key={verdict}
+ variant="link-muted"
+ size="sm"
+ disabled={disabled}
+ onClick={onClick}
+ data-attr={`today-list-${verdict}`}
+ >
+ {icon}
+ {label}
+ </Button>
+ ) : (
+ <Tooltip key={verdict}>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="link-muted"
+ size="icon-sm"
+ aria-label={label}
+ disabled={disabled}
+ onClick={onClick}
+ data-attr={`today-list-${verdict}`}
+ />
+ }
+ >
+ {icon}
+ </TooltipTrigger>
+ <TooltipContent side="bottom">{label}</TooltipContent>
+ </Tooltip>
+ )
+ })}
+ </>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayBriefingItems.ts b/frontend/src/scenes/project-homepage/today/todayBriefingItems.ts
index 4be4eadc1a38..ae16bc8998ad 100644
--- a/frontend/src/scenes/project-homepage/today/todayBriefingItems.ts
+++ b/frontend/src/scenes/project-homepage/today/todayBriefingItems.ts
@@ -1,45 +1,11 @@
import { urls } from 'scenes/urls'
-import type { TodayReportCard } from '~/layout/today/todayPreviewCards'
-
import type {
BriefingApi,
BriefingItemApi,
BriefingItemStateEnumApi,
- TodayItemReasonEnumApi,
} from 'products/today/frontend/generated/api.schemas'
-import { TodayReportSource, sourceStyle } from './todaySignalReports'
-
-/** Where an item was opened from, sent with the `today item opened` event. */
-export type TodayItemOpenSurface = 'briefing' | 'chip' | 'sidebar'
-
-/** A report takes the style of the product its signals came from, the way the inbox shows it. */
-export function itemSource(item: Pick<BriefingItemApi, 'source' | 'source_product'>): TodayReportSource {
- return sourceStyle(item.source_product ?? item.source)
-}
-
-const REASON_LABELS: Record<TodayItemReasonEnumApi, string> = {
- claimed_by_you: 'You claimed it',
- waiting_for_you: 'Waiting for your input',
- suggested_reviewer: 'You are a suggested reviewer',
- urgent_for_project: 'Urgent, and nobody owns it',
- dashboard_you_viewed: 'A dashboard you viewed',
- dashboard_you_starred: 'A dashboard you starred',
- insight_you_viewed: 'An insight you viewed',
- insight_you_starred: 'An insight you starred',
- alert_firing: 'An alert you follow is firing',
- assigned_ticket: 'Assigned to you',
- assigned_error_issue: 'Assigned to you or your role',
- review_requested: 'Your review was requested',
- your_pull_request: 'Your pull request',
-}
-
-/** Why the briefing picked the item, as the hover card says it. */
-export function itemReasonLabel(item: Pick<BriefingItemApi, 'reason'>): string {
- return REASON_LABELS[item.reason]
-}
-
const STATE_LABELS: Record<BriefingItemStateEnumApi, string | null> = {
open: null,
done: 'Resolved',
@@ -52,13 +18,6 @@ export function itemStateLabel(item: Pick<BriefingItemApi, 'state'>): string | n
return STATE_LABELS[item.state]
}
-// The briefing reasons a report gets when it names the person, the reports the for_you count covers.
-const NAMES_PERSON_REASONS: ReadonlySet<TodayItemReasonEnumApi> = new Set(['waiting_for_you', 'suggested_reviewer'])
-
-export function itemNamesPerson(item: Pick<BriefingItemApi, 'reason'>): boolean {
- return NAMES_PERSON_REASONS.has(item.reason)
-}
-
const REPORT_STATUS_STATES: Record<string, BriefingItemStateEnumApi> = {
resolved: 'done',
suppressed: 'dismissed',
@@ -70,27 +29,6 @@ export function reportItemState(status: string): BriefingItemStateEnumApi {
return REPORT_STATUS_STATES[status] ?? 'open'
}
-export function briefingItemReportCard(item: BriefingItemApi): TodayReportCard {
- return {
- key: item.key,
- reportId: itemReportId(item),
- title: item.title,
- reason: itemReasonLabel(item),
- stateLabel: itemStateLabel(item),
- resolved: item.state === 'done',
- canLeaveReview: itemNamesPerson(item),
- priority: item.report?.priority ?? null,
- summary: item.report?.summary || null,
- pullRequestState: item.report?.pull_request_state ?? null,
- pullRequestUrl: item.report?.pull_request_url ?? null,
- signalCount: item.report?.signal_count ?? null,
- updatedAt: item.report?.updated_at ?? null,
- metrics: item.report?.metrics ?? [],
- charts: item.report?.charts ?? [],
- sourceLabel: itemSource(item).label,
- }
-}
-
/** The report id of a `report:<id>` item, else null. */
export function itemReportId(item: Pick<BriefingItemApi, 'key'>): string | null {
return item.key.startsWith('report:') ? item.key.slice('report:'.length) : null
@@ -111,11 +49,6 @@ export function hasBriefingText(briefing: BriefingApi | null): boolean {
return !!briefing && (!!briefing.headline || briefing.paragraphs.length > 0)
}
-/** The briefing day the browser's clock is in. It matches the backend: a day starts at 8:00, so 7:59 is still yesterday. */
-export function briefingDayKey(now: number): string {
- return new Date(now - 8 * 60 * 60 * 1000).toDateString()
-}
-
export function isBriefingSettled(briefing: Pick<BriefingApi, 'status'>): boolean {
return briefing.status === 'ready' || briefing.status === 'failed'
}
diff --git a/frontend/src/scenes/project-homepage/today/todayBriefingLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayBriefingLogic.test.ts
new file mode 100644
index 000000000000..9d130908020d
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayBriefingLogic.test.ts
@@ -0,0 +1,86 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { BRIEFING_POLL_MS, todayBriefingLogic } from './todayBriefingLogic'
+import { makeBriefing } from './todayTestFixtures'
+
+describe('todayBriefingLogic', () => {
+ let briefingResponses: [number, any][]
+ let briefingCalls: number
+
+ beforeEach(() => {
+ briefingResponses = []
+ briefingCalls = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/today/briefing/': () => {
+ briefingCalls += 1
+ return briefingResponses.length > 1 ? briefingResponses.shift()! : briefingResponses[0]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/today/briefing/refresh/': () => [
+ 200,
+ makeBriefing({ id: 'b-next', status: 'writing' }),
+ ],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('keeps the last briefing on screen, polls while the next is written, and stops when it is ready', async () => {
+ jest.useFakeTimers()
+ const previous = makeBriefing({ id: 'b-previous', status: 'writing' })
+ const ready = makeBriefing()
+ briefingResponses = [
+ [200, previous],
+ [200, ready],
+ ]
+ const logic = todayBriefingLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadPersonalBriefing()
+ })
+ .toDispatchActions(['loadPersonalBriefingSuccess'])
+ .toMatchValues({ briefingWaiting: true, personalBriefing: previous })
+
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(BRIEFING_POLL_MS)
+ })
+ .toDispatchActions(['pollBriefing', 'loadPersonalBriefingSuccess'])
+ .toMatchValues({ briefingWaiting: false, personalBriefing: ready })
+
+ await jest.advanceTimersByTimeAsync(BRIEFING_POLL_MS * 3)
+ expect(briefingCalls).toBe(2)
+ })
+
+ it('keeps waiting from the refresh click until the reloaded briefing says it is written', async () => {
+ const shown = makeBriefing()
+ briefingResponses = [
+ [200, shown],
+ [200, { ...shown, status: 'writing' }],
+ ]
+ const logic = todayBriefingLogic()
+ logic.mount()
+ await expectLogic(logic, () => {
+ logic.actions.loadPersonalBriefing()
+ })
+ .toDispatchActions(['loadPersonalBriefingSuccess'])
+ .toMatchValues({ briefingWaiting: false })
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshBriefing()
+ })
+ .toDispatchActions(['refreshBriefing', 'refreshBriefingSuccess'])
+ .toMatchValues({ briefingWaiting: true })
+ .toDispatchActions(['loadPersonalBriefing', 'loadPersonalBriefingSuccess'])
+ .toMatchValues({ briefingWaiting: true })
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayBriefingLogic.ts b/frontend/src/scenes/project-homepage/today/todayBriefingLogic.ts
new file mode 100644
index 000000000000..4c153b9cc7ad
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayBriefingLogic.ts
@@ -0,0 +1,241 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getLocalTimeZone } from 'lib/utils/timezones'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { todayBriefingRefreshCreate, todayBriefingRetrieve } from 'products/today/frontend/generated/api'
+import type { BriefingApi } from 'products/today/frontend/generated/api.schemas'
+
+import { isBriefingSettled } from './todayBriefingItems'
+
+export const BRIEFING_POLL_MS = 5_000
+// The run's budget is 10 minutes (RUN_TIMEOUT in logic/generate.py). Stop asking a little after that.
+const MAX_BRIEFING_POLLS = 132
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayBriefingLogicValues {
+ currentProjectId: number | string // teamLogic
+ briefingPolls: number
+ briefingWaiting: boolean
+ gaveUpWaitingFor: string | null
+ personalBriefing: BriefingApi | null
+ personalBriefingLoading: boolean
+ refreshedBriefing: BriefingApi | null
+ refreshedBriefingLoading: boolean
+ reloadingAfterRefresh: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayBriefingLogicActions {
+ loadPersonalBriefing: () => any
+ loadPersonalBriefingFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPersonalBriefingSuccess: (
+ personalBriefing: BriefingApi | null,
+ payload?: any
+ ) => {
+ personalBriefing: BriefingApi | null
+ payload?: any
+ }
+ pollBriefing: () => {
+ value: true
+ }
+ refreshBriefing: () => any
+ refreshBriefingFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ refreshBriefingSuccess: (
+ refreshedBriefing: BriefingApi | null,
+ payload?: any
+ ) => {
+ refreshedBriefing: BriefingApi | null
+ payload?: any
+ }
+ stopWaitingForBriefing: (briefingId: string) => {
+ briefingId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayBriefingLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ briefingWaiting: (
+ personalBriefing: BriefingApi | null,
+ gaveUpWaitingFor: string | null,
+ refreshedBriefingLoading: boolean,
+ reloadingAfterRefresh: boolean
+ ) => boolean
+ }
+}
+
+export type todayBriefingLogicType = MakeLogicType<
+ todayBriefingLogicValues,
+ todayBriefingLogicActions,
+ Record<string, any>,
+ todayBriefingLogicMeta
+>
+
+export const todayBriefingLogic = kea<todayBriefingLogicType>([
+ path(['scenes', 'project-homepage', 'today', 'todayBriefingLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ pollBriefing: true,
+ stopWaitingForBriefing: (briefingId: string) => ({ briefingId }),
+ }),
+ loaders(({ values }) => ({
+ personalBriefing: [
+ null as BriefingApi | null,
+ {
+ loadPersonalBriefing: async (): Promise<BriefingApi | null> => {
+ if (values.currentProjectId === null) {
+ return null
+ }
+ try {
+ return await todayBriefingRetrieve(String(values.currentProjectId), {
+ timezone: getLocalTimeZone(),
+ })
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) {
+ return null
+ }
+ throw error
+ }
+ },
+ },
+ ],
+ refreshedBriefing: [
+ null as BriefingApi | null,
+ {
+ refreshBriefing: async (): Promise<BriefingApi | null> => {
+ if (values.currentProjectId === null) {
+ return null
+ }
+ return await todayBriefingRefreshCreate(String(values.currentProjectId), {
+ timezone: getLocalTimeZone(),
+ })
+ },
+ },
+ ],
+ })),
+ reducers({
+ // The briefing the page stopped waiting for after the poll budget ran out, so a later one still polls.
+ gaveUpWaitingFor: [
+ null as string | null,
+ {
+ stopWaitingForBriefing: (_, { briefingId }) => briefingId,
+ refreshBriefingSuccess: () => null,
+ },
+ ],
+ // Polls spent on the briefing in progress. A settled briefing closes the count, so the next
+ // one starts with the whole budget.
+ briefingPolls: [
+ 0,
+ {
+ pollBriefing: (count) => count + 1,
+ loadPersonalBriefingSuccess: (count, { personalBriefing }) =>
+ personalBriefing && isBriefingSettled(personalBriefing) ? 0 : count,
+ refreshBriefingSuccess: () => 0,
+ stopWaitingForBriefing: () => 0,
+ },
+ ],
+ // The refresh call returns before the page reloads the briefing. Until that reload returns
+ // the `writing` briefing, the page still waits, so the badge does not flip back to the button.
+ reloadingAfterRefresh: [
+ false,
+ {
+ refreshBriefingSuccess: () => true,
+ loadPersonalBriefingSuccess: () => false,
+ loadPersonalBriefingFailure: () => false,
+ },
+ ],
+ }),
+ selectors({
+ // While a newer briefing is written, the server returns the shown one as `writing`, so the
+ // text stays on screen and the page keeps asking until the new one is ready.
+ briefingWaiting: [
+ (s) => [s.personalBriefing, s.gaveUpWaitingFor, s.refreshedBriefingLoading, s.reloadingAfterRefresh],
+ (
+ personalBriefing: BriefingApi | null,
+ gaveUpWaitingFor: string | null,
+ refreshedBriefingLoading: boolean,
+ reloadingAfterRefresh: boolean
+ ): boolean =>
+ refreshedBriefingLoading ||
+ reloadingAfterRefresh ||
+ (!!personalBriefing &&
+ personalBriefing.id !== gaveUpWaitingFor &&
+ !isBriefingSettled(personalBriefing)),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ const schedulePoll = (): void => {
+ cache.disposables.add(() => {
+ const poll = window.setTimeout(() => actions.pollBriefing(), BRIEFING_POLL_MS)
+ return () => clearTimeout(poll)
+ }, 'briefingPoll')
+ }
+ return {
+ loadPersonalBriefingSuccess: ({ personalBriefing }) => {
+ if (!personalBriefing) {
+ return
+ }
+ if (values.briefingWaiting) {
+ if (values.briefingPolls >= MAX_BRIEFING_POLLS) {
+ actions.stopWaitingForBriefing(personalBriefing.id)
+ return
+ }
+ schedulePoll()
+ return
+ }
+ if (cache.viewedBriefingId === personalBriefing.id) {
+ return
+ }
+ cache.viewedBriefingId = personalBriefing.id
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('today briefing viewed', {
+ status: personalBriefing.status,
+ writer: personalBriefing.writer,
+ item_count: personalBriefing.items.length,
+ done_item_count: personalBriefing.items.filter((item) => item.state === 'done').length,
+ dismissed_item_count: personalBriefing.items.filter((item) => item.state === 'dismissed').length,
+ more_reports_count: personalBriefing.more_reports_count,
+ })
+ },
+ loadPersonalBriefingFailure: () => {
+ // A poll that fails while the briefing is written keeps polling.
+ if (values.briefingWaiting && values.briefingPolls < MAX_BRIEFING_POLLS) {
+ schedulePoll()
+ }
+ },
+ pollBriefing: () => {
+ actions.loadPersonalBriefing()
+ },
+ refreshBriefing: () => {
+ // pinned: analytics event name. Renaming it breaks dashboards.
+ posthog.capture('today refresh clicked', { writer: values.personalBriefing?.writer ?? null })
+ },
+ refreshBriefingSuccess: () => {
+ actions.loadPersonalBriefing()
+ },
+ refreshBriefingFailure: ({ errorObject }) => {
+ const detail = errorObject instanceof ApiError ? errorObject.detail : null
+ lemonToast.error(detail || 'Couldn’t refresh your briefing. Try again in a minute.')
+ },
+ }
+ }),
+])
diff --git a/frontend/src/scenes/project-homepage/today/todayExploreItems.ts b/frontend/src/scenes/project-homepage/today/todayExploreItems.ts
new file mode 100644
index 000000000000..66f4da1cbd93
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayExploreItems.ts
@@ -0,0 +1,88 @@
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { FileSystemIconType } from '~/queries/schema/schema-general'
+
+export interface TodayExploreItem {
+ product: string
+ name: string
+ description: string
+ icon: FileSystemIconType
+ sceneKey: Scene
+ to: () => string
+}
+
+export const EXPLORE_ITEMS: TodayExploreItem[] = [
+ {
+ product: 'product_analytics',
+ name: 'Product analytics',
+ description: 'Charts from your events',
+ icon: 'product_analytics',
+ sceneKey: Scene.SavedInsights,
+ to: () => urls.savedInsights(),
+ },
+ {
+ product: 'session_replay',
+ name: 'Session replay',
+ description: 'Watch real user sessions',
+ icon: 'session_replay',
+ sceneKey: Scene.Replay,
+ to: () => urls.replay(),
+ },
+ {
+ product: 'feature_flags',
+ name: 'Feature flags',
+ description: 'Roll out changes safely',
+ icon: 'feature_flag',
+ sceneKey: Scene.FeatureFlags,
+ to: () => urls.featureFlags(),
+ },
+ {
+ product: 'ai_observability',
+ name: 'AI observability',
+ description: 'Trace LLM calls and cost',
+ icon: 'llm_analytics',
+ sceneKey: Scene.AIObservability,
+ to: () => urls.aiObservabilityDashboard(),
+ },
+ {
+ product: 'mcp_analytics',
+ name: 'MCP analytics',
+ description: 'Tool calls from agents',
+ icon: 'mcp_analytics',
+ sceneKey: Scene.MCPAnalytics,
+ to: () => urls.mcpAnalytics(),
+ },
+ {
+ product: 'error_tracking',
+ name: 'Error tracking',
+ description: 'Catch and fix exceptions',
+ icon: 'error_tracking',
+ sceneKey: Scene.ErrorTracking,
+ to: () => urls.errorTracking(),
+ },
+ {
+ product: 'experiments',
+ name: 'Experiments',
+ description: 'Test what a change does',
+ icon: 'experiment',
+ sceneKey: Scene.Experiments,
+ to: () => urls.experiments(),
+ },
+ {
+ product: 'web_analytics',
+ name: 'Web analytics',
+ description: 'Traffic and top pages',
+ icon: 'web_analytics',
+ sceneKey: Scene.WebAnalytics,
+ to: () => urls.webAnalytics(),
+ },
+ {
+ product: 'logs',
+ name: 'Logs',
+ description: 'Search your app logs',
+ icon: 'logs',
+ sceneKey: Scene.Logs,
+ to: () => urls.logs(),
+ },
+]
diff --git a/frontend/src/scenes/project-homepage/today/todayForYouRows.test.ts b/frontend/src/scenes/project-homepage/today/todayForYouRows.test.ts
new file mode 100644
index 000000000000..b2543e40e212
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayForYouRows.test.ts
@@ -0,0 +1,38 @@
+import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'
+import type { HighlightItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { forYouReportIds, forYouRows } from './todayForYouRows'
+
+function highlight(key: string, label: HighlightItemApi['label']): HighlightItemApi {
+ return {
+ key,
+ label,
+ priority: label === 'risk' ? 'P2' : 'P4',
+ title: key,
+ detail: '',
+ url: null,
+ series: null,
+ score: 1,
+ source: 'alerts',
+ }
+}
+
+describe('forYouRows', () => {
+ it('keeps the server order, puts reports before highlights and more reports last, and steps through reports in list order', () => {
+ const reports = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => makeReport({ id }))
+ const { rows, limit } = forYouRows({
+ showPersonalBriefing: false,
+ briefingItems: [],
+ reports,
+ loadedMoreReports: [makeReport({ id: 'more' })],
+ highlights: [highlight('risk-1', 'risk'), highlight('opportunity-1', 'opportunity')],
+ doneHighlightKeys: ['risk-1'],
+ reportStateOverrides: { b: 'resolved' },
+ })
+
+ expect(limit).toBe(5)
+ expect(rows.map((row) => row.key)).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'risk-1', 'opportunity-1', 'more'])
+ expect(rows.filter((row) => row.done).map((row) => row.key)).toEqual(['b', 'risk-1'])
+ expect(forYouReportIds(rows)).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'more'])
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayForYouRows.ts b/frontend/src/scenes/project-homepage/today/todayForYouRows.ts
new file mode 100644
index 000000000000..5f377856139d
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayForYouRows.ts
@@ -0,0 +1,75 @@
+import { SignalReport } from 'products/signals/frontend/inbox/types'
+import type { BriefingItemApi, HighlightItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { itemReportId } from './todayBriefingItems'
+
+export const VISIBLE_ROWS = 5
+
+export type TodayForYouRow =
+ | { kind: 'briefing'; key: string; item: BriefingItemApi; reportId: string | null; done: boolean }
+ | { kind: 'report'; key: string; report: SignalReport; source: 'list' | 'more'; done: boolean }
+ | { kind: 'highlight'; key: string; item: HighlightItemApi; position: number; done: boolean }
+
+type TodayForYouBriefingRow = Extract<TodayForYouRow, { kind: 'briefing' }>
+type TodayForYouReportRow = Extract<TodayForYouRow, { kind: 'report' }>
+
+export interface TodayForYouRows {
+ rows: TodayForYouRow[]
+ limit: number
+}
+
+interface TodayForYouInput {
+ showPersonalBriefing: boolean
+ briefingItems: BriefingItemApi[]
+ reports: SignalReport[]
+ loadedMoreReports: SignalReport[]
+ highlights: HighlightItemApi[]
+ doneHighlightKeys: string[]
+ reportStateOverrides: Record<string, string>
+}
+
+export function rowReportId(row: TodayForYouRow): string | null {
+ return row.kind === 'report' ? row.key : row.kind === 'briefing' ? row.reportId : null
+}
+
+function reportRow(report: SignalReport, source: 'list' | 'more', overrides: Record<string, string>): TodayForYouRow {
+ const state = overrides[report.id]
+ return { kind: 'report', key: report.id, report, source, done: !!state && state !== 'open' }
+}
+
+export function forYouRows(input: TodayForYouInput): TodayForYouRows {
+ const reportRows: TodayForYouRow[] = input.showPersonalBriefing
+ ? input.briefingItems.map((item) => ({
+ kind: 'briefing',
+ key: item.key,
+ item,
+ reportId: itemReportId(item),
+ done: item.state !== 'open',
+ }))
+ : input.reports.map((report) => reportRow(report, 'list', input.reportStateOverrides))
+ const highlightRows: TodayForYouRow[] = input.highlights.map((item, position) => ({
+ kind: 'highlight',
+ key: item.key,
+ item,
+ position,
+ done: input.doneHighlightKeys.includes(item.key),
+ }))
+ const base = [...reportRows, ...highlightRows]
+ const moreRows = input.loadedMoreReports.map((report) => reportRow(report, 'more', input.reportStateOverrides))
+ return { rows: [...base, ...moreRows], limit: base.length <= VISIBLE_ROWS + 1 ? base.length : VISIBLE_ROWS }
+}
+
+export function forYouReportIds(rows: TodayForYouRow[]): string[] {
+ return rows.flatMap((row) => {
+ const id = rowReportId(row)
+ return id ? [id] : []
+ })
+}
+
+export function briefingRows(rows: TodayForYouRow[]): TodayForYouBriefingRow[] {
+ return rows.filter((row): row is TodayForYouBriefingRow => row.kind === 'briefing')
+}
+
+export function reportRows(rows: TodayForYouRow[], source: 'list' | 'more'): TodayForYouReportRow[] {
+ return rows.filter((row): row is TodayForYouReportRow => row.kind === 'report' && row.source === source)
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
new file mode 100644
index 000000000000..b8c9a945bf40
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
@@ -0,0 +1,86 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { HIGHLIGHTS_POLL_MS, todayHighlightsLogic } from './todayHighlightsLogic'
+import { makeHighlightItem, makeHighlights } from './todayTestFixtures'
+
+describe('todayHighlightsLogic', () => {
+ let highlightResponses: [number, any][]
+ let highlightCalls: number
+
+ beforeEach(() => {
+ highlightResponses = [[200, makeHighlights()]]
+ highlightCalls = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/today/highlights/': () => {
+ highlightCalls += 1
+ return highlightResponses.length > 1 ? highlightResponses.shift()! : highlightResponses[0]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each([
+ { status: 404, failed: false },
+ { status: 500, failed: true },
+ ])('reads a $status from highlights as failed: $failed', async ({ status, failed }) => {
+ highlightResponses = [[status, { detail: 'Error' }]]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({ highlights: null, highlightsFailed: failed, highlightsPending: false })
+ })
+
+ it('shows the skeleton until there is content, keeps the last ready content while new highlights compute, and polls until they are ready', async () => {
+ jest.useFakeTimers()
+ const item = makeHighlightItem()
+ highlightResponses = [
+ [200, makeHighlights({ status: 'computing', generated_at: null })],
+ [200, makeHighlights({ status: 'computing', items: [item] })],
+ [200, makeHighlights({ items: [item] })],
+ ]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadHighlightsSuccess']).toMatchValues({ highlightsPending: true })
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(HIGHLIGHTS_POLL_MS)
+ })
+ .toDispatchActions(['loadHighlights', 'loadHighlightsSuccess'])
+ .toMatchValues({ highlightsPending: false, forYouHighlights: [item] })
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(HIGHLIGHTS_POLL_MS)
+ })
+ .toDispatchActions(['loadHighlights', 'loadHighlightsSuccess'])
+ .toMatchValues({ highlights: makeHighlights({ items: [item] }) })
+
+ await jest.advanceTimersByTimeAsync(HIGHLIGHTS_POLL_MS * 3)
+ expect(highlightCalls).toBe(3)
+ })
+
+ it('keeps a highlight hidden in another project visible here, and forgets earlier days', async () => {
+ const item = makeHighlightItem()
+ highlightResponses = [[200, makeHighlights({ items: [item] })]]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const today = makeHighlights().day
+ logic.actions.setHiddenHighlights({ '1:alert:a': today, '997:old': '2020-01-01' })
+
+ expect(logic.values.forYouHighlights.map((highlight) => highlight.key)).toEqual(['alert:a'])
+
+ logic.actions.hideHighlight(item, 0)
+ expect(logic.values.hiddenHighlights).toEqual({ '1:alert:a': today, '997:alert:a': today })
+ expect(logic.values.doneHighlightKeys).toEqual(['alert:a'])
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
new file mode 100644
index 000000000000..a0a1143520a4
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
@@ -0,0 +1,257 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { todayHighlightsRetrieve } from 'products/today/frontend/generated/api'
+import type { HighlightItemApi, HighlightsApi } from 'products/today/frontend/generated/api.schemas'
+
+export const HIGHLIGHTS_POLL_MS = 2_000
+const HIGHLIGHTS_WAIT_MS = 2_000
+
+function hiddenHighlightKey(projectId: number | string, key: string): string {
+ return `${projectId}:${key}`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayHighlightsLogicValues {
+ currentProjectId: number | string // teamLogic
+ doneHighlightKeys: string[]
+ forYouHighlights: HighlightItemApi[]
+ hiddenHighlights: Record<string, string>
+ highlights: HighlightsApi | null
+ highlightsFailed: boolean
+ highlightsHiddenNow: string[]
+ highlightsLoading: boolean
+ highlightsPending: boolean
+ highlightsWaitOver: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayHighlightsLogicActions {
+ hideHighlight: (
+ item: HighlightItemApi,
+ position: number
+ ) => {
+ item: HighlightItemApi
+ position: number
+ }
+ highlightOpened: (
+ item: HighlightItemApi,
+ position: number
+ ) => {
+ item: HighlightItemApi
+ position: number
+ }
+ loadHighlights: () => any
+ loadHighlightsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHighlightsSuccess: (
+ highlights: HighlightsApi | null,
+ payload?: any
+ ) => {
+ highlights: HighlightsApi | null
+ payload?: any
+ }
+ setHiddenHighlights: (hidden: Record<string, string>) => {
+ hidden: Record<string, string>
+ }
+ stopWaitingForHighlights: () => {
+ value: true
+ }
+ unhideHighlight: (
+ item: HighlightItemApi,
+ position: number
+ ) => {
+ item: HighlightItemApi
+ position: number
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayHighlightsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ highlightsPending: (highlights: HighlightsApi | null, highlightsLoading: boolean) => boolean
+ doneHighlightKeys: (
+ highlights: HighlightsApi | null,
+ hiddenHighlights: Record<string, string>,
+ highlightsHiddenNow: string[],
+ currentProjectId: number | string
+ ) => string[]
+ forYouHighlights: (
+ highlights: HighlightsApi | null,
+ hiddenHighlights: Record<string, string>,
+ doneHighlightKeys: string[],
+ currentProjectId: number | string
+ ) => HighlightItemApi[]
+ }
+}
+
+export type todayHighlightsLogicType = MakeLogicType<
+ todayHighlightsLogicValues,
+ todayHighlightsLogicActions,
+ Record<string, any>,
+ todayHighlightsLogicMeta
+>
+
+export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
+ path(['scenes', 'project-homepage', 'today', 'todayHighlightsLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ highlightOpened: (item: HighlightItemApi, position: number) => ({ item, position }),
+ hideHighlight: (item: HighlightItemApi, position: number) => ({ item, position }),
+ unhideHighlight: (item: HighlightItemApi, position: number) => ({ item, position }),
+ setHiddenHighlights: (hidden: Record<string, string>) => ({ hidden }),
+ stopWaitingForHighlights: true,
+ }),
+ loaders(({ values }) => ({
+ highlights: [
+ null as HighlightsApi | null,
+ {
+ loadHighlights: async (): Promise<HighlightsApi | null> => {
+ if (values.currentProjectId === null) {
+ return null
+ }
+ try {
+ return await todayHighlightsRetrieve(String(values.currentProjectId))
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) {
+ return null
+ }
+ throw error
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ hiddenHighlights: [
+ {} as Record<string, string>,
+ { persist: true },
+ { setHiddenHighlights: (_, { hidden }) => hidden },
+ ],
+ highlightsHiddenNow: [
+ [] as string[],
+ {
+ hideHighlight: (state, { item }) => [...state, item.key],
+ unhideHighlight: (state, { item }) => state.filter((key) => key !== item.key),
+ },
+ ],
+ highlightsWaitOver: [false, { stopWaitingForHighlights: () => true }],
+ highlightsFailed: [
+ false,
+ {
+ loadHighlights: () => false,
+ loadHighlightsFailure: () => true,
+ },
+ ],
+ highlights: {
+ loadHighlightsFailure: () => null,
+ },
+ }),
+ selectors({
+ highlightsPending: [
+ (s) => [s.highlights, s.highlightsLoading],
+ (highlights: HighlightsApi | null, highlightsLoading: boolean): boolean =>
+ highlights ? highlights.status === 'computing' && highlights.generated_at === null : highlightsLoading,
+ ],
+ doneHighlightKeys: [
+ (s) => [s.highlights, s.hiddenHighlights, s.highlightsHiddenNow, s.currentProjectId],
+ (
+ highlights: HighlightsApi | null,
+ hiddenHighlights: Record<string, string>,
+ highlightsHiddenNow: string[],
+ currentProjectId: number | string
+ ): string[] =>
+ highlightsHiddenNow.filter(
+ (key) => hiddenHighlights[hiddenHighlightKey(currentProjectId, key)] === highlights?.day
+ ),
+ ],
+ forYouHighlights: [
+ (s) => [s.highlights, s.hiddenHighlights, s.doneHighlightKeys, s.currentProjectId],
+ (
+ highlights: HighlightsApi | null,
+ hiddenHighlights: Record<string, string>,
+ doneHighlightKeys: string[],
+ currentProjectId: number | string
+ ): HighlightItemApi[] =>
+ (highlights?.items ?? []).filter(
+ (item) =>
+ hiddenHighlights[hiddenHighlightKey(currentProjectId, item.key)] !== highlights?.day ||
+ doneHighlightKeys.includes(item.key)
+ ),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ hideHighlight: ({ item, position }) => {
+ const day = values.highlights?.day
+ if (!day) {
+ return
+ }
+ const kept = Object.fromEntries(
+ Object.entries(values.hiddenHighlights).filter(([, hiddenOn]) => hiddenOn === day)
+ )
+ actions.setHiddenHighlights({ ...kept, [hiddenHighlightKey(values.currentProjectId, item.key)]: day })
+ posthog.capture('today highlight hidden', {
+ label: item.label,
+ source: item.source,
+ position,
+ score: item.score,
+ })
+ },
+ unhideHighlight: ({ item, position }) => {
+ const { [hiddenHighlightKey(values.currentProjectId, item.key)]: _, ...rest } = values.hiddenHighlights
+ actions.setHiddenHighlights(rest)
+ posthog.capture('today highlight unhidden', {
+ label: item.label,
+ source: item.source,
+ position,
+ score: item.score,
+ })
+ },
+ highlightOpened: ({ item, position }) => {
+ posthog.capture('today highlight opened', {
+ label: item.label,
+ source: item.source,
+ position,
+ score: item.score,
+ })
+ },
+ loadHighlightsSuccess: ({ highlights }) => {
+ if (!highlights) {
+ return
+ }
+ if (highlights.status === 'computing') {
+ cache.disposables.add(() => {
+ const poll = window.setTimeout(() => actions.loadHighlights(), HIGHLIGHTS_POLL_MS)
+ return () => clearTimeout(poll)
+ }, 'highlightsPoll')
+ return
+ }
+ posthog.capture('today highlights loaded', {
+ status: highlights.status,
+ item_count: highlights.items.length,
+ risk_count: highlights.items.filter((item) => item.label === 'risk').length,
+ opportunity_count: highlights.items.filter((item) => item.label === 'opportunity').length,
+ sources: highlights.items.map((item) => item.source),
+ pulse_count: highlights.pulse.length,
+ })
+ },
+ })),
+ afterMount(({ actions, cache }) => {
+ actions.loadHighlights()
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => actions.stopWaitingForHighlights(), HIGHLIGHTS_WAIT_MS)
+ return () => clearTimeout(timer)
+ }, 'highlightsWait')
+ }),
+])
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
index 6fa627469fba..cd0ce8f30e7d 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
@@ -4,69 +4,34 @@ import posthog from 'posthog-js'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { userMessageDisplayText } from 'products/posthog_ai/frontend/utils/userMessageDisplay'
import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'
import { SignalReportStatus } from 'products/signals/frontend/inbox/types'
-import type { BriefingApi, BriefingItemReportApi } from 'products/today/frontend/generated/api.schemas'
-import { itemStateLabel } from './todayBriefingItems'
-import { BRIEFING_POLL_MS, MORE_REPORTS_LIMIT, TOP_REPORT_COUNT, reportIdFromPath, todayLogic } from './todayLogic'
+import { todayHighlightsLogic } from './todayHighlightsLogic'
+import { MORE_REPORTS_PAGE_SIZE, TOP_REPORT_COUNT, isTodayPath, reportIdFromPath, todayLogic } from './todayLogic'
import { todayReportLogic } from './todayReportLogic'
import { isSampleReportId } from './todaySampleReports'
-import { briefingForReports } from './todaySignalReports'
-
-function makeBriefing(overrides: Partial<BriefingApi> = {}): BriefingApi {
- return {
- id: 'briefing-1',
- local_day: '2026-09-30',
- headline: 'One report needs your input',
- paragraphs: [[{ text: 'Signup form rejects emails', item_key: 'report:a', highlight: true }]],
- items: [
- {
- key: 'report:a',
- title: 'Signup form rejects emails',
- label: 'Signup form rejects emails',
- signal: 'P1, waits for you',
- url: '/project/1/inbox/reports/a',
- rank: 1,
- group: 'report',
- source: 'self_driving',
- reason: 'waiting_for_you',
- state: 'open',
- source_product: null,
- report: null,
- },
- ],
- more_reports_count: 0,
- open_reports_count: 0,
- status: 'ready',
- writer: 'agent',
- created_at: '2026-09-30T06:00:00Z',
- ready_at: '2026-09-30T06:00:20Z',
- ...overrides,
- }
-}
+import { makeBriefing, makeHighlightItem, makeHighlights } from './todayTestFixtures'
+import { todayVerdictLogic } from './todayVerdictLogic'
describe('todayLogic', () => {
let listResponse: [number, any]
let listParams: URLSearchParams | null
let briefingResponses: [number, any][]
let briefingCalls: number
- let stateResponse: [number, any]
let reportResponse: [number, any] | null
- let leaveReviewersResponse: [number, any]
- let stateCalls: number
+ let highlightResponses: [number, any][]
beforeEach(() => {
+ highlightResponses = [[200, makeHighlights()]]
listResponse = [200, { results: [], count: 0 }]
listParams = null
briefingResponses = [[404, { detail: 'Not found.' }]]
briefingCalls = 0
- stateResponse = [200, {}]
reportResponse = null
- leaveReviewersResponse = [204, {}]
- stateCalls = 0
useMocks({
get: {
'/api/projects/:team_id/signals/reports/for_you/': ({ request }) => {
@@ -74,6 +39,8 @@ describe('todayLogic', () => {
return listResponse
},
'/api/projects/:team_id/signals/reports/:id/': () => reportResponse ?? [404, {}],
+ '/api/projects/:team_id/today/highlights/': () =>
+ highlightResponses.length > 1 ? highlightResponses.shift()! : highlightResponses[0],
'/api/projects/:team_id/today/briefing/': () => {
briefingCalls += 1
return briefingResponses.length > 1 ? briefingResponses.shift()! : briefingResponses[0]
@@ -84,13 +51,7 @@ describe('todayLogic', () => {
200,
makeBriefing({ id: 'b-next', status: 'writing' }),
],
- '/api/projects/:team_id/signals/reports/:id/state/': () => {
- stateCalls += 1
- return stateResponse
- },
- },
- delete: {
- '/api/projects/:team_id/signals/reports/:id/reviewers/me/': () => leaveReviewersResponse,
+ '/api/projects/:team_id/signals/reports/:id/state/': () => [200, {}],
},
})
initKeaTests()
@@ -108,7 +69,7 @@ describe('todayLogic', () => {
await expectLogic(logic).toFinishAllListeners().toMatchValues({
reports,
- personalBriefingFailed: true,
+ personalBriefing: null,
briefingWaiting: false,
showPersonalBriefing: false,
briefingItems: [],
@@ -233,27 +194,6 @@ describe('todayLogic', () => {
}
)
- it.each([
- ['keeps a verdict the API accepts', 200, 'done'],
- ['takes back a verdict the API refuses', 409, 'open'],
- ])('%s', async (_, status, finalState) => {
- briefingResponses = [[200, makeBriefing()]]
- stateResponse = [status, { detail: 'Refused.' }]
- const logic = todayLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.requestReportVerdict(
- { reportId: 'a', title: 'Signup form rejects emails', hasOpenPullRequest: false },
- 'resolve',
- 'sidebar'
- )
- expect(logic.values.briefingItems[0].state).toEqual('done')
-
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.briefingItems[0].state).toEqual(finalState)
- })
-
it('sends the Inbox ranking label events for the reports the home shows and acts on', async () => {
const capture = jest.spyOn(posthog, 'capture')
briefingResponses = [[200, makeBriefing()]]
@@ -264,17 +204,16 @@ describe('todayLogic', () => {
logic.actions.loadPersonalBriefing()
await expectLogic(logic).toFinishAllListeners()
- logic.actions.itemOpened(logic.values.briefingItems[0], 'sidebar')
- logic.actions.setReportVerdict(
+ logic.actions.itemOpened(logic.values.briefingItems[0])
+ todayVerdictLogic.actions.setReportVerdict(
{ reportId: 'a', title: 'Signup form rejects emails', hasOpenPullRequest: false },
'dismiss',
'report_page'
)
- logic.actions.leaveReportReview('a', 'sidebar')
- await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(todayVerdictLogic).toFinishAllListeners()
const inboxEvents = capture.mock.calls.filter(([event]) => event.startsWith('Inbox '))
- expect(inboxEvents).toHaveLength(4)
+ expect(inboxEvents).toHaveLength(3)
expect(inboxEvents).toEqual(
expect.arrayContaining([
[
@@ -296,162 +235,90 @@ describe('todayLogic', () => {
expect.objectContaining({ report_id: 'a', action_type: 'dismiss', surface: 'today' }),
undefined,
],
- [
- 'Inbox report action',
- expect.objectContaining({
- report_id: 'a',
- action_type: 'remove_suggested_reviewer',
- surface: 'today',
- }),
- undefined,
- ],
])
)
})
- it('keeps the last briefing on screen, polls while the next is written, and stops when it is ready', async () => {
- jest.useFakeTimers()
- const previous = makeBriefing({ id: 'b-previous', status: 'writing' })
- const ready = makeBriefing()
- briefingResponses = [
- [200, previous],
- [200, ready],
- ]
+ it('ranks the report list events by the position the list shows them in', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ const [a, b] = [makeReport({ id: 'a', priority: 'P2' }), makeReport({ id: 'b', priority: 'P1' })]
+ listResponse = [200, { results: [a, b], count: 2 }]
const logic = todayLogic()
logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
- await expectLogic(logic).toDispatchActions(['loadPersonalBriefingSuccess']).toMatchValues({
- showPersonalBriefing: true,
- briefingWaiting: true,
- personalBriefing: previous,
- })
-
- await expectLogic(logic, () => {
- jest.advanceTimersByTime(BRIEFING_POLL_MS)
- })
- .toDispatchActions(['pollBriefing', 'loadPersonalBriefingSuccess'])
- .toMatchValues({ briefingWaiting: false, personalBriefing: ready })
+ logic.actions.reportOpened(b, 'list')
- await jest.advanceTimersByTimeAsync(BRIEFING_POLL_MS * 3)
- expect(briefingCalls).toBe(2)
+ const events = capture.mock.calls.filter(([event]) => event.startsWith('Inbox '))
+ expect(events).toEqual([
+ [
+ 'Inbox reports impressed',
+ expect.objectContaining({
+ impressions: [
+ expect.objectContaining({ report_id: 'a', rank: 1 }),
+ expect.objectContaining({ report_id: 'b', rank: 2 }),
+ ],
+ }),
+ undefined,
+ ],
+ ['Inbox report opened', expect.objectContaining({ report_id: 'b', list: 'briefing', rank: 2 }), undefined],
+ ])
})
- it('keeps waiting from the refresh click until the reloaded briefing says it is written', async () => {
- const shown = makeBriefing()
- briefingResponses = [
- [200, shown],
- [200, { ...shown, status: 'writing' }],
- ]
+ it('sends one preview event when a report row opens in place, and none when it closes', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ briefingResponses = [[200, makeBriefing()]]
const logic = todayLogic()
logic.mount()
- await expectLogic(logic).toDispatchActions(['loadPersonalBriefingSuccess']).toMatchValues({
- briefingWaiting: false,
- })
+ await expectLogic(logic).toFinishAllListeners()
- await expectLogic(logic, () => {
- logic.actions.refreshBriefing()
- })
- .toDispatchActions(['refreshBriefing', 'refreshBriefingSuccess'])
- .toMatchValues({ briefingWaiting: true })
- .toDispatchActions(['loadPersonalBriefing', 'loadPersonalBriefingSuccess'])
- .toMatchValues({ briefingWaiting: true })
+ logic.actions.toggleReportRow('report:a', 'a')
+ expect(logic.values.expandedReportRows).toEqual({ 'report:a': true })
+ logic.actions.toggleReportRow('report:a', 'a')
+ expect(logic.values.expandedReportRows).toEqual({})
+
+ expect(capture.mock.calls.filter(([event]) => event === 'today report previewed')).toEqual([
+ ['today report previewed', expect.objectContaining({ list: 'personal', report_id: 'a', surface: 'list' })],
+ ])
})
it.each([
- ['crosses 8:00', new Date(2026, 8, 30, 7, 59, 45), null],
- ['sleeps from one afternoon to the next', new Date(2026, 8, 30, 14, 0, 0), new Date(2026, 9, 1, 14, 0, 0)],
- ])('reloads the briefing when an open tab %s', async (_name, start, wakeAt) => {
+ ['passes the refresh time', new Date('2026-10-01T05:59:45Z'), null],
+ ['sleeps through the refresh time', new Date('2026-09-30T14:00:00Z'), new Date('2026-10-01T14:00:00Z')],
+ ])('reloads the briefing and highlights when an open tab %s', async (_name, start, wakeAt) => {
jest.useFakeTimers()
jest.setSystemTime(start)
- briefingResponses = [[200, makeBriefing()]]
+ const item = makeHighlightItem()
+ briefingResponses = [
+ [200, makeBriefing({ refresh_at: '2026-10-01T06:00:00Z' })],
+ [200, makeBriefing({ refresh_at: '2026-10-02T06:00:00Z' })],
+ ]
+ highlightResponses = [
+ [200, makeHighlights({ items: [item], refresh_at: '2026-10-01T06:00:00Z' })],
+ [200, makeHighlights({ items: [item], day: '2026-10-01', refresh_at: '2026-10-02T06:00:00Z' })],
+ ]
const logic = todayLogic()
logic.mount()
- await expectLogic(logic).toDispatchActions(['loadPersonalBriefingSuccess'])
+ const highlightsLoaded = todayHighlightsLogic.actionTypes.loadHighlightsSuccess
+ await expectLogic(logic).toDispatchActionsInAnyOrder([highlightsLoaded, 'loadPersonalBriefingSuccess'])
+ todayHighlightsLogic.actions.hideHighlight(item, 0)
+ expect(logic.values.doneHighlightKeys).toEqual(['alert:a'])
await expectLogic(logic, () => {
if (wakeAt) {
jest.setSystemTime(wakeAt)
}
jest.advanceTimersByTime(30_000)
- }).toDispatchActions(['tick', 'loadPersonalBriefing', 'loadPersonalBriefingSuccess'])
+ })
+ .toDispatchActions(['tick', 'loadHighlights', 'loadPersonalBriefing'])
+ .toDispatchActionsInAnyOrder([highlightsLoaded, 'loadPersonalBriefingSuccess'])
+ .toMatchValues({ doneHighlightKeys: [], forYouHighlights: [item] })
expect(briefingCalls).toBe(2)
await jest.advanceTimersByTimeAsync(30_000)
expect(briefingCalls).toBe(2)
})
- test.each([
- ['nothing is off the list yet', ['open', 'open'], null],
- ['a resolved and a dismissed item both count', ['done', 'dismissed', 'open'], { done: 2, total: 3 }],
- ] as const)('counts briefing progress when %s', async (_name, states, expected) => {
- const [item] = makeBriefing().items
- briefingResponses = [
- [200, makeBriefing({ items: states.map((state, index) => ({ ...item, key: `report:${index}`, state })) })],
- ]
- const logic = todayLogic()
- logic.mount()
-
- await expectLogic(logic)
- .toDispatchActions(['loadPersonalBriefingSuccess'])
- .toMatchValues({ briefingProgress: expected })
- })
-
- it('gives a hover card to the reports of both lists, and only to items with report details', async () => {
- const [item] = makeBriefing().items
- const report: BriefingItemReportApi = {
- priority: 'P1',
- summary: 'Signups fail for plus-addressed emails.',
- pull_request_state: null,
- pull_request_url: null,
- signal_count: 3,
- updated_at: '2026-09-30T08:00:00Z',
- metrics: [],
- charts: [],
- }
- listResponse = [200, { results: [makeReport({ id: 'team-a' })], count: 1 }]
- briefingResponses = [
- [
- 200,
- makeBriefing({
- items: [
- { ...item, report },
- // A deleted report, and an item from an older briefing that is not a report.
- { ...item, key: 'report:deleted', state: 'dismissed' },
- { ...item, key: 'dashboard:12', group: 'dashboard', reason: 'dashboard_you_viewed' },
- ],
- }),
- ],
- ]
- const logic = todayLogic()
- logic.mount()
-
- await expectLogic(logic).toDispatchActions(['loadPersonalBriefingSuccess'])
- expect(Object.keys(logic.values.reportPreviews.briefing)).toEqual(['report:a'])
- expect(Object.keys(logic.values.reportPreviews.sidebar)).toEqual(['report:a'])
- expect(Object.keys(logic.values.teamReportPreviews.briefing)).toEqual(['team-a'])
- expect(Object.keys(logic.values.teamReportPreviews.sidebar)).toEqual(['team-a'])
- })
-
- test.each([
- ['takes a report the person steps off their list', 204, 'left', 'Not yours'],
- ['puts the report back when stepping off it fails', 500, 'open', null],
- ])('%s', async (_, status, finalState, finalLabel) => {
- briefingResponses = [[200, makeBriefing()]]
- leaveReviewersResponse = [status, { detail: 'Refused.' }]
- const logic = todayLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.leaveReportReview('a', 'sidebar')
- expect(logic.values.briefingItems[0].state).toEqual('left')
-
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.briefingItems[0].state).toEqual(finalState)
- expect(itemStateLabel({ state: logic.values.reportStateOverrides.a ?? 'open' })).toEqual(finalLabel)
- // Stepping off changes who the report is routed to, never the report's own state.
- expect(stateCalls).toEqual(0)
- })
-
it('asks for the top reports for the person and counts the rest', async () => {
const reports = [makeReport({ id: 'a' }), makeReport({ id: 'b' })]
listResponse = [200, { results: reports, count: 9 }]
@@ -465,53 +332,65 @@ describe('todayLogic', () => {
})
})
- it.each([
- ['one the list returns too', 'report:a', 'open', ['b', 'c'], 2],
- // The briefing can show a report the list ranks past its page; it is on screen, so it is not "more".
- ['one the list does not return', 'report:z', 'open', ['a', 'b', 'c'], 1],
- // The count holds only open reports, so a resolved one on screen does not take a report off it.
- ['a resolved one the list does not return', 'report:z', 'done', ['a', 'b', 'c'], 2],
- ] as const)(
- 'loads more reports past the briefing without the ones it shows, and counts the rest for the Inbox, when the briefing shows %s',
- async (_name, shownKey, shownState, listed, remaining) => {
- const [a, b, c] = ['a', 'b', 'c'].map((id) => makeReport({ id }))
- const byId = { a, b, c }
- listResponse = [200, { results: [a, b, c], count: 5 }]
- const briefing = makeBriefing({ more_reports_count: 4 })
- briefing.items[0].key = shownKey
- briefing.items[0].state = shownState
- briefing.paragraphs[0][0].item_key = shownKey
- briefingResponses = [[200, briefing]]
- const logic = todayLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners().toMatchValues({ canLoadMoreReports: true })
+ it('pages through the reports past the briefing without the ones it shows, and starts over when the briefing names other reports', async () => {
+ const page = (prefix: string, length: number): ReturnType<typeof makeReport>[] =>
+ Array.from({ length }, (_, index) => makeReport({ id: `${prefix}${index}` }))
+ briefingResponses = [[200, makeBriefing({ more_reports_count: 4 })]]
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ canLoadMoreReports: true })
- await expectLogic(logic, () => {
- logic.actions.loadMoreReports()
- })
- .toDispatchActions(['loadMoreReportsSuccess'])
- .toMatchValues({
- sidebarMoreReports: listed.map((id) => byId[id as keyof typeof byId]),
- moreReportsInInbox: remaining,
- canLoadMoreReports: false,
- })
- expect(Object.fromEntries(listParams!.entries())).toEqual({
- limit: String(MORE_REPORTS_LIMIT),
- include_unowned: 'false',
- })
+ const first = page('p', MORE_REPORTS_PAGE_SIZE)
+ listResponse = [200, { results: first, count: MORE_REPORTS_PAGE_SIZE + 5 }]
+ await expectLogic(logic, () => {
+ logic.actions.loadMoreReports()
+ })
+ .toDispatchActions(['loadMoreReportsSuccess'])
+ .toMatchValues({ loadedMoreReports: first, canLoadMoreReports: true, moreReportsInInbox: 0 })
+ expect(Object.fromEntries(listParams!.entries())).toEqual({
+ limit: String(MORE_REPORTS_PAGE_SIZE),
+ offset: '0',
+ exclude: 'a',
+ include_unowned: 'false',
+ })
- // A refresh writes a briefing over other reports, so the loaded list folds back up.
- await expectLogic(logic, () => {
- logic.actions.refreshBriefing()
+ const second = page('q', 3)
+ listResponse = [200, { results: second, count: MORE_REPORTS_PAGE_SIZE + 5 }]
+ await expectLogic(logic, () => {
+ logic.actions.loadMoreReports()
+ })
+ .toDispatchActions(['loadMoreReportsSuccess'])
+ .toMatchValues({
+ loadedMoreReports: [...first, ...second],
+ canLoadMoreReports: false,
+ moreReportsInInbox: 2,
})
- .toDispatchActions(['refreshBriefing'])
- .toMatchValues({ moreReports: null, sidebarMoreReports: [], canLoadMoreReports: true })
- // Let the reload the refresh triggers finish, so it cannot land in the next test.
- .toDispatchActions(['refreshBriefingSuccess', 'loadPersonalBriefingSuccess'])
- }
- )
+ expect(listParams!.get('offset')).toBe(String(MORE_REPORTS_PAGE_SIZE))
+
+ const other = makeBriefing({ id: 'briefing-2', more_reports_count: 4 })
+ other.items[0].key = 'report:z'
+ other.paragraphs[0][0].item_key = 'report:z'
+ briefingResponses = [[200, other]]
+ await expectLogic(logic, () => {
+ logic.actions.loadPersonalBriefing()
+ })
+ .toDispatchActions(['loadPersonalBriefingSuccess'])
+ .toMatchValues({ loadedMoreReports: [], canLoadMoreReports: true })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadMoreReports()
+ }).toDispatchActions(['loadMoreReportsSuccess'])
+ expect(Object.fromEntries(listParams!.entries())).toMatchObject({ offset: '0', exclude: 'z' })
- it('shows sample reports from ?sample=1 without asking the API, until ?sample=0', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.refreshBriefing()
+ })
+ .toDispatchActions(['refreshBriefing'])
+ .toMatchValues({ moreReports: null, canLoadMoreReports: true })
+ .toDispatchActions(['loadPersonalBriefingSuccess'])
+ })
+
+ it('shows sample reports from ?sample=1 without asking the API, until ?sample=0 even if the reload fails', async () => {
router.actions.push('/project/1/home', { sample: '1' })
const logic = todayLogic()
logic.mount()
@@ -522,44 +401,70 @@ describe('todayLogic', () => {
Array(TOP_REPORT_COUNT).fill(true)
)
+ listResponse = [500, { detail: 'Error' }]
router.actions.push('/project/1/home', { sample: '0' })
- await expectLogic(logic).toFinishAllListeners().toMatchValues({ useSampleData: false, reports: [] })
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({ useSampleData: false, reports: [], reportsFailed: true })
expect(listParams).not.toBeNull()
})
- it('keeps a failed load apart from an empty list', async () => {
- listResponse = [500, { detail: 'Server error' }]
+ it.each([
+ { status: 500, expected: { topReports: null, reportsFailed: true } },
+ { status: 403, expected: { topReports: { results: [], count: 0 }, reportsFailed: false } },
+ ])('keeps a failed load apart from an empty list, and treats $status that way', async ({ status, expected }) => {
+ listResponse = [status, { detail: 'Error' }]
const logic = todayLogic()
logic.mount()
- await expectLogic(logic).toFinishAllListeners().toMatchValues({ topReports: null, reportsFailed: true })
+ await expectLogic(logic).toFinishAllListeners().toMatchValues(expected)
})
- test.each([
- ['/project/1/home/reports/abc', 'abc'],
- ['/home/reports/abc/', 'abc'],
- ['/project/1/home', null],
- ['/project/1/home/reports/abc/signals', null],
- ['/project/1/inbox/reports/abc', null],
- ])('reads the report id from %s', (pathname, reportId) => {
- expect(reportIdFromPath(pathname)).toBe(reportId)
+ it('remembers the report to focus and the home scroll only while the person stays on Today', async () => {
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ router.actions.push('/project/997/home/reports/a')
+ logic.actions.setHomeScrollTop(320)
+ router.actions.push('/project/997/home')
+ expect(logic.values).toMatchObject({ returnFocusReportId: 'a', homeScrollTop: 320 })
+
+ router.actions.push('/project/997/home/reports/b')
+ router.actions.push('/project/997/insights')
+ expect(logic.values).toMatchObject({ returnFocusReportId: null, homeScrollTop: null })
})
- it('links every report from the briefing and keeps acronyms in titles', () => {
- const briefing = briefingForReports([
- makeReport({
- id: 'a',
- title: 'Signup form rejects emails',
- implementation_pr_url: 'https://example.com/1',
- }),
- makeReport({ id: 'b', title: 'Pricing page drops off' }),
- makeReport({ id: 'c', title: 'LLM costs doubled' }),
- ])
+ it('leaves out the Explore products the person has no access to', () => {
+ const appContext = window.POSTHOG_APP_CONTEXT!
+ window.POSTHOG_APP_CONTEXT = {
+ ...appContext,
+ effective_resource_access_control: {
+ ...appContext.effective_resource_access_control,
+ [AccessControlResourceType.FeatureFlag]: AccessControlLevel.None,
+ },
+ }
+ try {
+ const logic = todayLogic()
+ logic.mount()
+ const products = logic.values.exploreItems.map((item) => item.product)
+ expect(products).not.toContain('feature_flags')
+ expect(products).toContain('product_analytics')
+ } finally {
+ window.POSTHOG_APP_CONTEXT = appContext
+ }
+ })
- expect(briefing.flat().filter((segment) => segment.reportId)).toEqual([
- { text: 'Signup form rejects emails', reportId: 'a', highlight: true },
- { text: 'pricing page drops off', reportId: 'b' },
- { text: 'LLM costs doubled', reportId: 'c' },
- ])
+ test.each([
+ ['/project/1/home/reports/abc', 'abc', true],
+ ['/home/reports/abc/', 'abc', true],
+ ['/project/1/home', null, true],
+ ['/project/1', null, true],
+ ['/project/1/home/reports/abc/signals', null, false],
+ ['/project/1/inbox/reports/abc', null, false],
+ ['/project/1/insights/abc', null, false],
+ ])('reads the report id from %s', (pathname, reportId, onToday) => {
+ expect(reportIdFromPath(pathname)).toBe(reportId)
+ expect(isTodayPath(pathname)).toBe(onToday)
})
})
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.ts
index 64047b0e68a0..6006622d9796 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts
@@ -5,139 +5,68 @@ import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { navigateToHref } from 'lib/utils/navigateToHref'
-import { getLocalTimeZone } from 'lib/utils/timezones'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import type { TodayReportCard, TodayReportPreview } from '~/layout/today/todayPreviewCards'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
-import { TeamType, UserType } from '~/types'
+import { TeamPublicType, TeamType, UserType } from '~/types'
-import {
- signalsReportsForYouRetrieve,
- signalsReportsRetrieve,
- signalsReportsReviewersMeDestroy,
- signalsReportsStateCreate,
-} from 'products/signals/frontend/generated/api'
-import type {
- SignalReportStateEnumApi,
- SignalReportStateRequestApi,
-} from 'products/signals/frontend/generated/api.schemas'
-import { openDismissReportDialog } from 'products/signals/frontend/inbox/components/shell/DismissReportDialog'
-import { openResolveReportDialog } from 'products/signals/frontend/inbox/components/shell/ResolveReportDialog'
+import { signalsReportsForYouRetrieve, signalsReportsRetrieve } from 'products/signals/frontend/generated/api'
import {
TodayReportList,
TodayReportSnapshot,
- captureTodayReportAction,
captureTodayReportOpened,
captureTodayReportsImpressed,
} from 'products/signals/frontend/inbox/inboxAnalytics'
import { isActionCapableReport } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'
import { SignalReport } from 'products/signals/frontend/inbox/types'
-import { suppressDismissalPayload } from 'products/signals/frontend/inbox/utils/dismissalReasons'
import { reportPullRequests } from 'products/signals/frontend/inbox/utils/reportPullRequests'
-import { todayBriefingRefreshCreate, todayBriefingRetrieve } from 'products/today/frontend/generated/api'
import type {
BriefingApi,
BriefingItemApi,
BriefingItemStateEnumApi,
+ HighlightItemApi,
+ HighlightsApi,
} from 'products/today/frontend/generated/api.schemas'
-import type { TeamPublicType } from '../../../types'
import { TodayAskContext, todayAskPrompt } from './todayAskPrompt'
+import { hasBriefingText, itemReportId } from './todayBriefingItems'
+import { todayBriefingLogic } from './todayBriefingLogic'
+import { EXPLORE_ITEMS, type TodayExploreItem } from './todayExploreItems'
import {
- TodayItemOpenSurface,
- briefingDayKey,
- briefingItemReportCard,
- hasBriefingText,
- isBriefingSettled,
- isExternalHref,
- itemHref,
- itemNamesPerson,
- itemReportId,
-} from './todayBriefingItems'
+ VISIBLE_ROWS,
+ briefingRows,
+ forYouRows,
+ reportRows,
+ rowReportId,
+ type TodayForYouRow,
+ type TodayForYouRows,
+} from './todayForYouRows'
+import { todayHighlightsLogic } from './todayHighlightsLogic'
import { recentObjectsForHome } from './todayRecentObjects'
-import { SAMPLE_BRIEFING, isSampleReportId, parseSampleParam, sampleTopReports } from './todaySampleReports'
-import { TodayBriefingSegment, briefingForReports, teamReportCard } from './todaySignalReports'
+import { type TodayReportPreview, briefingItemPreview, reportPreview } from './todayReportPreviews'
+import { isSampleReportId, parseSampleParam, sampleTopReports } from './todaySampleReports'
+import { todayVerdictLogic } from './todayVerdictLogic'
export const TOP_REPORT_COUNT = 5
+export const MORE_REPORTS_PAGE_SIZE = 20
export const RECENT_OBJECT_COUNT = 4
-// The most reports the for_you endpoint returns in one call (MAX_FOR_YOU_REPORTS on the backend).
-export const MORE_REPORTS_LIMIT = 20
+const RECENT_OBJECT_MORE_COUNT = 8
const CLOCK_MS = 30_000
-export const BRIEFING_POLL_MS = 5_000
-// The run's budget is 10 minutes (RUN_TIMEOUT in logic/generate.py). Stop asking a little after that.
-const MAX_BRIEFING_POLLS = 132
/** Where a report was opened from, sent with the `today report opened` event. */
-export type TodayReportOpenSource = 'briefing' | 'chip' | 'sidebar' | 'sidebar_more'
+export type TodayReportOpenSource = 'list' | 'more'
/** Where a question to PostHog AI came from, sent with the `today ai asked` event. */
export type TodayAskSource = 'walk_through' | 'report_page'
-/** What a person decides about a report from Today. */
-export type TodayReportVerdict = 'resolve' | 'dismiss'
-
-/** Where the person gave the verdict, sent with the `today report state changed` event. */
-export type TodayReportVerdictSurface = TodayReportPreview['surface'] | 'report_page'
-
-/** The report a verdict acts on. */
-export interface TodayReportVerdictTarget {
- reportId: string
- title: string
- /** The backend closes an open implementation pull request on either verdict, so the person confirms first. */
- hasOpenPullRequest: boolean
-}
-
-interface TodayReportVerdictCopy {
- apiState: SignalReportStateEnumApi
- itemState: BriefingItemStateEnumApi
- success: string
- successClosingPullRequest: string
- failure: string
- confirmTitle: string
- confirmLabel: string
- reasonTitle: string
- reasonDescription: string
-}
-
-const VERDICTS: Record<TodayReportVerdict, TodayReportVerdictCopy> = {
- resolve: {
- apiState: 'resolved',
- itemState: 'done',
- success: 'Report resolved',
- successClosingPullRequest: 'Report resolved. Its pull request is closing.',
- failure: 'Couldn’t resolve the report. Try again, or resolve it from the Inbox.',
- confirmTitle: 'Resolve this report?',
- confirmLabel: 'Resolve and close PR',
- reasonTitle: 'Why did you resolve this report?',
- reasonDescription: 'The reason is saved on the report.',
- },
- dismiss: {
- apiState: 'suppressed',
- itemState: 'dismissed',
- success: 'Report dismissed',
- successClosingPullRequest: 'Report dismissed. Its pull request is closing.',
- failure: 'Couldn’t dismiss the report. Try again, or dismiss it from the Inbox.',
- confirmTitle: 'Dismiss this report?',
- confirmLabel: 'Dismiss and close PR',
- reasonTitle: 'Why did you dismiss this report?',
- reasonDescription:
- 'The reason is saved on the report. The agent that filed it reads your note on its next run.',
- },
-}
-
-/** The count behind the Inbox link: reports for the person beyond the shown ones, or open in the project. */
-export interface TodayInboxMore {
- count: number
- scope: 'for_you' | 'project'
-}
+export type TodayList = 'for_you' | 'recents'
export interface TodayReports {
results: SignalReport[]
@@ -145,7 +74,12 @@ export interface TodayReports {
count: number
}
-const COUNT_WORDS = ['No', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
+export interface TodayMoreReports {
+ exclude: string[]
+ results: SignalReport[]
+ count: number
+ hasMore: boolean
+}
/** The report a Today report page shows, read from a path such as `/project/1/home/reports/abc`. */
export function reportIdFromPath(pathname: string): string | null {
@@ -153,8 +87,8 @@ export function reportIdFromPath(pathname: string): string | null {
return match ? decodeURIComponent(match[1]) : null
}
-export function countWord(count: number): string {
- return COUNT_WORDS[count] ?? String(count)
+export function isTodayPath(pathname: string): boolean {
+ return /^\/(home(\/reports\/[^/]+)?\/?)?$/.test(removeProjectIdIfPresent(pathname))
}
export function greetingForHour(hour: number, name: string | null | undefined): string {
@@ -171,24 +105,6 @@ export function greetingForHour(hour: number, name: string | null | undefined):
return `Evening${suffix}`
}
-export function reportSummaryForHour(hour: number, count: number): string {
- if (count === 0) {
- return 'Nothing needs your attention'
- }
- const reports = `${countWord(count)} ${count === 1 ? 'report' : 'reports'}`
- const verb = count === 1 ? 'needs' : 'need'
- if (hour < 5) {
- return `${reports} ${count === 1 ? 'is' : 'are'} ready for tomorrow`
- }
- if (hour < 12) {
- return `${reports} ${verb} your attention this morning`
- }
- if (hour < 17) {
- return `${reports} ${verb} your attention this afternoon`
- }
- return `${reports} still ${verb} your attention`
-}
-
/**
* The page shows the report as it was when it loaded, but the action-or-answer framing must follow its current
* state: somebody can resolve the report or open a PR on it meanwhile. A failed refetch fails closed to answering.
@@ -210,10 +126,29 @@ async function currentReportContext(
return { report: current ?? report, canAct: !!current && isActionCapableReport(current) }
}
-/** How many of the briefing's items were resolved or dismissed since it was written. */
-export interface TodayBriefingProgress {
- done: number
- total: number
+function signalReportSnapshot(report: SignalReport): TodayReportSnapshot {
+ return {
+ reportId: report.id,
+ priority: report.priority ?? null,
+ hasPr: reportPullRequests(report).length > 0,
+ signalCount: report.signal_count,
+ sourceProducts: report.source_products ?? [],
+ }
+}
+
+function briefingItemSnapshot(item: BriefingItemApi, reportId: string): TodayReportSnapshot {
+ return {
+ reportId,
+ priority: item.report?.priority ?? null,
+ hasPr: !!item.report?.pull_request_url,
+ signalCount: item.report?.signal_count ?? null,
+ sourceProducts: item.source_product ? [item.source_product] : [],
+ }
+}
+
+interface TodayRankedReport {
+ report: TodayReportSnapshot
+ rank: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -222,43 +157,51 @@ export interface todayLogicValues {
recentsHasLoaded: boolean // recentItemsModel
currentProjectId: number | string // teamLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
+ briefingWaiting: boolean // todayBriefingLogic
+ personalBriefing: BriefingApi | null // todayBriefingLogic
+ personalBriefingLoading: boolean // todayBriefingLogic
+ doneHighlightKeys: string[] // todayHighlightsLogic
+ forYouHighlights: HighlightItemApi[] // todayHighlightsLogic
+ highlights: HighlightsApi | null // todayHighlightsLogic
+ highlightsFailed: boolean // todayHighlightsLogic
+ highlightsLoading: boolean // todayHighlightsLogic
+ highlightsPending: boolean // todayHighlightsLogic
+ highlightsWaitOver: boolean // todayHighlightsLogic
+ reportStateOverrides: Record<string, BriefingItemStateEnumApi> // todayVerdictLogic
user: UserType | null // userLogic
askingAi: boolean
- briefing: TodayBriefingSegment[][]
briefingItems: BriefingItemApi[]
- briefingPolls: number
- briefingProgress: TodayBriefingProgress | null
- briefingWaiting: boolean
canLoadMoreReports: boolean
- gaveUpWaitingFor: string | null
+ currentMoreReports: TodayMoreReports | null
+ expandedReportRows: Record<string, boolean>
+ exploreItems: TodayExploreItem[]
+ forYouCanShowLess: boolean
+ forYouCanShowMore: boolean
+ forYouFailedNote: string | null
+ forYouOpenCount: number
+ forYouReady: boolean
+ forYouRows: TodayForYouRows
+ forYouVisibleRows: TodayForYouRow[]
greeting: string
+ homeScrollTop: number | null
hour: number
- hoveredItemKey: string | null
- hoveredReportId: string | null
- inboxMore: TodayInboxMore | null
+ isNewProject: boolean
+ listExpanded: Record<TodayList, boolean>
+ loadedMoreReports: SignalReport[]
moreReportCount: number
- moreReportPreviews: Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
- moreReports: TodayReports | null
+ moreReports: TodayMoreReports | null
moreReportsInInbox: number
moreReportsLoading: boolean
now: number
- personalBriefing: BriefingApi | null
- personalBriefingFailed: boolean
- personalBriefingLoading: boolean
recentObjects: FileSystemEntry[]
- refreshedBriefing: BriefingApi | null
- refreshedBriefingLoading: boolean
- reloadingAfterRefresh: boolean
reportId: string | null
- reportPreviews: Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
- reportStateOverrides: Record<string, BriefingItemStateEnumApi>
- reportSummary: string
+ reportPreviews: Record<string, TodayReportPreview>
reports: SignalReport[]
+ reportsBroken: boolean
reportsFailed: boolean
+ returnFocusReportId: string | null
showPersonalBriefing: boolean
shownReportIds: string[]
- sidebarMoreReports: SignalReport[]
- teamReportPreviews: Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
topReports: TodayReports | null
topReportsLoading: boolean
useSampleData: boolean
@@ -287,13 +230,23 @@ export interface todayLogicActions {
searchParams: Record<string, any>
url: string
} // router
- addReportVerdictReason: (
- target: TodayReportVerdictTarget,
- verdict: TodayReportVerdict
+ loadPersonalBriefing: () => any // todayBriefingLogic
+ loadPersonalBriefingFailure: (
+ error: string,
+ errorObject?: any
) => {
- target: TodayReportVerdictTarget
- verdict: TodayReportVerdict
- }
+ error: string
+ errorObject?: any
+ } // todayBriefingLogic
+ loadPersonalBriefingSuccess: (
+ personalBriefing: BriefingApi | null,
+ payload?: any
+ ) => {
+ payload?: any
+ personalBriefing: BriefingApi | null
+ } // todayBriefingLogic
+ refreshBriefing: () => any // todayBriefingLogic
+ loadHighlights: () => any // todayHighlightsLogic
askAi: (
prompt: string,
source: TodayAskSource,
@@ -306,22 +259,15 @@ export interface todayLogicActions {
askAiFinished: () => {
value: true
}
- itemOpened: (
- item: BriefingItemApi,
- surface: TodayItemOpenSurface
- ) => {
- item: BriefingItemApi
- surface: TodayItemOpenSurface
- }
- leaveReportReview: (
- reportId: string,
- surface: TodayReportVerdictSurface
+ exploreOpened: (
+ product: string,
+ position: number
) => {
- reportId: string
- surface: TodayReportVerdictSurface
+ position: number
+ product: string
}
- leaveReportReviewFailure: (reportId: string) => {
- reportId: string
+ itemOpened: (item: BriefingItemApi) => {
+ item: BriefingItemApi
}
loadMoreReports: () => any
loadMoreReportsFailure: (
@@ -332,25 +278,10 @@ export interface todayLogicActions {
errorObject?: any
}
loadMoreReportsSuccess: (
- moreReports: TodayReports,
- payload?: any
- ) => {
- moreReports: TodayReports
- payload?: any
- }
- loadPersonalBriefing: () => any
- loadPersonalBriefingFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadPersonalBriefingSuccess: (
- personalBriefing: BriefingApi | null,
+ moreReports: TodayMoreReports | null,
payload?: any
) => {
- personalBriefing: BriefingApi | null
+ moreReports: TodayMoreReports | null
payload?: any
}
loadTopReports: () => any
@@ -368,88 +299,45 @@ export interface todayLogicActions {
topReports: TodayReports
payload?: any
}
- openItem: (
- item: BriefingItemApi,
- surface: TodayItemOpenSurface
- ) => {
- item: BriefingItemApi
- surface: TodayItemOpenSurface
- }
- openReport: (
+ reportOpened: (
report: SignalReport,
source: TodayReportOpenSource
) => {
report: SignalReport
source: TodayReportOpenSource
}
- pollBriefing: () => {
+ retryFailedLoads: () => {
value: true
}
- refreshBriefing: () => any
- refreshBriefingFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- refreshBriefingSuccess: (
- refreshedBriefing: BriefingApi | null,
- payload?: any
- ) => {
- refreshedBriefing: BriefingApi | null
- payload?: any
- }
- reportOpened: (
- report: SignalReport,
- source: TodayReportOpenSource
- ) => {
- report: SignalReport
- source: TodayReportOpenSource
- }
- reportPreviewed: (
- cardKey: string,
- surface: TodayReportPreview['surface']
- ) => {
- cardKey: string
- surface: 'briefing' | 'sidebar'
+ setHomeScrollTop: (top: number | null) => {
+ top: number | null
}
- requestReportVerdict: (
- target: TodayReportVerdictTarget,
- verdict: TodayReportVerdict,
- surface: TodayReportVerdictSurface
+ setListExpanded: (
+ list: TodayList,
+ expanded: boolean
) => {
- surface: TodayReportVerdictSurface
- target: TodayReportVerdictTarget
- verdict: TodayReportVerdict
- }
- setHoveredItemKey: (itemKey: string | null) => {
- itemKey: string | null
+ expanded: boolean
+ list: TodayList
}
- setHoveredReportId: (reportId: string | null) => {
+ setReturnFocusReportId: (reportId: string | null) => {
reportId: string | null
}
- setReportVerdict: (
- target: TodayReportVerdictTarget,
- verdict: TodayReportVerdict,
- surface: TodayReportVerdictSurface
- ) => {
- surface: TodayReportVerdictSurface
- target: TodayReportVerdictTarget
- verdict: TodayReportVerdict
- }
- setReportVerdictFailure: (reportId: string) => {
- reportId: string
- }
setUseSampleData: (useSampleData: boolean) => {
useSampleData: boolean
}
- stopWaitingForBriefing: (briefingId: string) => {
- briefingId: string
+ showMoreForYou: () => {
+ value: true
}
tick: () => {
value: true
}
+ toggleReportRow: (
+ rowKey: string,
+ reportId: string
+ ) => {
+ reportId: string
+ rowKey: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -458,96 +346,77 @@ export interface todayLogicMeta {
reportId: (location: { hash: string; pathname: string; search: string }) => string | null
reports: (topReports: TodayReports | null) => SignalReport[]
moreReportCount: (topReports: TodayReports | null) => number
- briefing: (reports: SignalReport[], useSampleData: boolean) => TodayBriefingSegment[][]
hour: (now: number) => number
greeting: (hour: number, user: UserType | null) => string
- reportSummary: (hour: number, reports: SignalReport[]) => string
recentObjects: (recents: FileSystemEntry[]) => FileSystemEntry[]
showPersonalBriefing: (personalBriefing: BriefingApi | null, useSampleData: boolean) => boolean
- inboxMore: (personalBriefing: BriefingApi | null) => TodayInboxMore | null
briefingItems: (
personalBriefing: BriefingApi | null,
showPersonalBriefing: boolean,
reportStateOverrides: Record<string, BriefingItemStateEnumApi>
) => BriefingItemApi[]
- reportPreviews: (
- briefingItems: BriefingItemApi[]
- ) => Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
- teamReportPreviews: (
- reports: SignalReport[]
- ) => Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
- briefingProgress: (briefingItems: BriefingItemApi[]) => TodayBriefingProgress | null
shownReportIds: (
showPersonalBriefing: boolean,
briefingItems: BriefingItemApi[],
reports: SignalReport[]
) => string[]
- sidebarMoreReports: (
- moreReports: TodayReports | null,
+ currentMoreReports: (
+ moreReports: TodayMoreReports | null,
shownReportIds: string[],
useSampleData: boolean
- ) => SignalReport[]
- moreReportPreviews: (
- sidebarMoreReports: SignalReport[]
- ) => Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
+ ) => TodayMoreReports | null
+ loadedMoreReports: (currentMoreReports: TodayMoreReports | null) => SignalReport[]
canLoadMoreReports: (
- moreReports: TodayReports | null,
+ currentMoreReports: TodayMoreReports | null,
useSampleData: boolean,
showPersonalBriefing: boolean,
personalBriefing: BriefingApi | null,
moreReportCount: number
) => boolean
- moreReportsInInbox: (
- moreReports: TodayReports | null,
+ moreReportsInInbox: (currentMoreReports: TodayMoreReports | null) => number
+ forYouRows: (
showPersonalBriefing: boolean,
briefingItems: BriefingItemApi[],
- reports: SignalReport[]
- ) => number
- briefingWaiting: (
- personalBriefing: BriefingApi | null,
- gaveUpWaitingFor: string | null,
- refreshedBriefingLoading: boolean,
- reloadingAfterRefresh: boolean
+ reports: SignalReport[],
+ loadedMoreReports: SignalReport[],
+ forYouHighlights: HighlightItemApi[],
+ doneHighlightKeys: string[],
+ reportStateOverrides: Record<string, BriefingItemStateEnumApi>
+ ) => TodayForYouRows
+ reportsBroken: (
+ reportsFailed: boolean,
+ topReports: TodayReports | null,
+ showPersonalBriefing: boolean
+ ) => boolean
+ forYouReady: (
+ showPersonalBriefing: boolean,
+ topReports: TodayReports | null,
+ reportsFailed: boolean,
+ highlightsPending: boolean,
+ highlightsWaitOver: boolean,
+ forYouRows: TodayForYouRows
+ ) => boolean
+ forYouFailedNote: (reportsBroken: boolean, highlightsFailed: boolean) => string | null
+ forYouOpenCount: (forYouRows: TodayForYouRows) => number
+ forYouVisibleRows: (forYouRows: TodayForYouRows, listExpanded: Record<TodayList, boolean>) => TodayForYouRow[]
+ forYouCanShowMore: (
+ forYouRows: TodayForYouRows,
+ listExpanded: Record<TodayList, boolean>,
+ canLoadMoreReports: boolean
) => boolean
+ forYouCanShowLess: (forYouRows: TodayForYouRows, listExpanded: Record<TodayList, boolean>) => boolean
+ isNewProject: (currentTeam: TeamPublicType | TeamType | null, useSampleData: boolean) => boolean
+ exploreItems: (currentTeam: TeamPublicType | TeamType | null) => TodayExploreItem[]
+ reportPreviews: (
+ reports: SignalReport[],
+ loadedMoreReports: SignalReport[],
+ briefingItems: BriefingItemApi[]
+ ) => Record<string, TodayReportPreview>
}
}
export type todayLogicType = MakeLogicType<todayLogicValues, todayLogicActions, Record<string, any>, todayLogicMeta>
-/** The same cards keyed for both surfaces. Each card is built once and shared by both. */
-function previewsBySurface(
- cards: [string, TodayReportCard][]
-): Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>> {
- const previews = (surface: TodayReportPreview['surface']): Record<string, TodayReportPreview> =>
- Object.fromEntries(cards.map(([key, card]) => [key, { kind: 'report', card, surface }]))
- return { briefing: previews('briefing'), sidebar: previews('sidebar') }
-}
-
-function signalReportSnapshot(report: SignalReport): TodayReportSnapshot {
- return {
- reportId: report.id,
- priority: report.priority ?? null,
- hasPr: reportPullRequests(report).length > 0,
- signalCount: report.signal_count,
- sourceProducts: report.source_products ?? [],
- }
-}
-
-function briefingItemSnapshot(item: BriefingItemApi, reportId: string): TodayReportSnapshot {
- return {
- reportId,
- priority: item.report?.priority ?? null,
- hasPr: !!item.report?.pull_request_url,
- signalCount: item.report?.signal_count ?? null,
- sourceProducts: item.source_product ? [item.source_product] : [],
- }
-}
-
-interface TodayRankedReport {
- report: TodayReportSnapshot
- rank: number
-}
-
export const todayLogic = kea<todayLogicType>([
path(['scenes', 'project-homepage', 'today', 'todayLogic']),
connect(() => ({
@@ -558,41 +427,45 @@ export const todayLogic = kea<todayLogicType>([
['currentTeam', 'currentProjectId'],
recentItemsModel,
['recents', 'recentsHasLoaded'],
+ todayBriefingLogic,
+ ['personalBriefing', 'personalBriefingLoading', 'briefingWaiting'],
+ todayHighlightsLogic,
+ [
+ 'highlights',
+ 'highlightsLoading',
+ 'highlightsFailed',
+ 'highlightsPending',
+ 'highlightsWaitOver',
+ 'forYouHighlights',
+ 'doneHighlightKeys',
+ ],
+ todayVerdictLogic,
+ ['reportStateOverrides'],
+ ],
+ actions: [
+ router,
+ ['locationChanged'],
+ todayBriefingLogic,
+ ['loadPersonalBriefing', 'loadPersonalBriefingSuccess', 'loadPersonalBriefingFailure', 'refreshBriefing'],
+ todayHighlightsLogic,
+ ['loadHighlights'],
],
- actions: [router, ['locationChanged']],
})),
actions({
// `report` is the report the person reads. Without it, the context is the briefing or the report list.
askAi: (prompt: string, source: TodayAskSource, report?: SignalReport) => ({ prompt, source, report }),
askAiFinished: true,
- setHoveredReportId: (reportId: string | null) => ({ reportId }),
- openReport: (report: SignalReport, source: TodayReportOpenSource) => ({ report, source }),
reportOpened: (report: SignalReport, source: TodayReportOpenSource) => ({ report, source }),
+ itemOpened: (item: BriefingItemApi) => ({ item }),
+ toggleReportRow: (rowKey: string, reportId: string) => ({ rowKey, reportId }),
+ exploreOpened: (product: string, position: number) => ({ product, position }),
+ setHomeScrollTop: (top: number | null) => ({ top }),
+ setReturnFocusReportId: (reportId: string | null) => ({ reportId }),
+ setListExpanded: (list: TodayList, expanded: boolean) => ({ list, expanded }),
+ showMoreForYou: true,
+ retryFailedLoads: true,
setUseSampleData: (useSampleData: boolean) => ({ useSampleData }),
tick: true,
- setHoveredItemKey: (itemKey: string | null) => ({ itemKey }),
- openItem: (item: BriefingItemApi, surface: TodayItemOpenSurface) => ({ item, surface }),
- itemOpened: (item: BriefingItemApi, surface: TodayItemOpenSurface) => ({ item, surface }),
- reportPreviewed: (cardKey: string, surface: TodayReportPreview['surface']) => ({ cardKey, surface }),
- pollBriefing: true,
- stopWaitingForBriefing: (briefingId: string) => ({ briefingId }),
- requestReportVerdict: (
- target: TodayReportVerdictTarget,
- verdict: TodayReportVerdict,
- surface: TodayReportVerdictSurface
- ) => ({ target, verdict, surface }),
- setReportVerdict: (
- target: TodayReportVerdictTarget,
- verdict: TodayReportVerdict,
- surface: TodayReportVerdictSurface
- ) => ({ target, verdict, surface }),
- setReportVerdictFailure: (reportId: string) => ({ reportId }),
- leaveReportReview: (reportId: string, surface: TodayReportVerdictSurface) => ({ reportId, surface }),
- leaveReportReviewFailure: (reportId: string) => ({ reportId }),
- addReportVerdictReason: (target: TodayReportVerdictTarget, verdict: TodayReportVerdict) => ({
- target,
- verdict,
- }),
}),
loaders(({ values }) => ({
topReports: [
@@ -607,10 +480,18 @@ export const todayLogic = kea<todayLogicType>([
}
// The person's own reports, ranked and counted the way the Today briefing ranks them.
// A P0 nobody owns ranks above every one of them, so Today leaves it to the Inbox.
- const response = await signalsReportsForYouRetrieve(String(values.currentProjectId), {
- limit: TOP_REPORT_COUNT,
- include_unowned: false,
- })
+ let response
+ try {
+ response = await signalsReportsForYouRetrieve(String(values.currentProjectId), {
+ limit: TOP_REPORT_COUNT,
+ include_unowned: false,
+ })
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 403) {
+ return { results: [], count: 0 }
+ }
+ throw error
+ }
// Today passes reports to the Inbox's helpers, which take the handwritten SignalReport. The
// generated row type is wider (string status and priority, read-only arrays), so the cast
// goes away when the Inbox moves to generated types.
@@ -618,45 +499,28 @@ export const todayLogic = kea<todayLogicType>([
},
},
],
- // Every report the endpoint ranks for the person. The sidebar drops the ones it already shows.
moreReports: [
- null as TodayReports | null,
+ null as TodayMoreReports | null,
{
- loadMoreReports: async (): Promise<TodayReports> => {
+ loadMoreReports: async (): Promise<TodayMoreReports | null> => {
if (values.currentProjectId === null) {
- return { results: [], count: 0 }
+ return null
}
+ const exclude = values.shownReportIds
+ const loaded = values.loadedMoreReports
const response = await signalsReportsForYouRetrieve(String(values.currentProjectId), {
- limit: MORE_REPORTS_LIMIT,
+ limit: MORE_REPORTS_PAGE_SIZE,
+ offset: loaded.length,
+ exclude: exclude.length > 0 ? exclude : undefined,
include_unowned: false,
})
- return { results: response.results as unknown as SignalReport[], count: response.count }
- },
- },
- ],
- personalBriefing: [
- null as BriefingApi | null,
- {
- loadPersonalBriefing: async (): Promise<BriefingApi | null> => {
- if (values.currentProjectId === null) {
- return null
- }
- return await todayBriefingRetrieve(String(values.currentProjectId), {
- timezone: getLocalTimeZone(),
- })
- },
- },
- ],
- refreshedBriefing: [
- null as BriefingApi | null,
- {
- refreshBriefing: async (): Promise<BriefingApi | null> => {
- if (values.currentProjectId === null) {
- return null
+ const results = [...loaded, ...(response.results as unknown as SignalReport[])]
+ return {
+ exclude,
+ results,
+ count: response.count,
+ hasMore: response.results.length === MORE_REPORTS_PAGE_SIZE && results.length < response.count,
}
- return await todayBriefingRefreshCreate(String(values.currentProjectId), {
- timezone: getLocalTimeZone(),
- })
},
},
],
@@ -666,88 +530,50 @@ export const todayLogic = kea<todayLogicType>([
useSampleData: [false, { persist: true }, { setUseSampleData: (_, { useSampleData }) => useSampleData }],
// A question about a report waits for the report's current state before PostHog AI opens.
askingAi: [false, { askAi: (_, { report }) => !!report, askAiFinished: () => false }],
- hoveredReportId: [
- null as string | null,
+ expandedReportRows: [
+ {} as Record<string, boolean>,
{
- setHoveredReportId: (_, { reportId }) => reportId,
- locationChanged: () => null,
+ toggleReportRow: (state, { rowKey }) => {
+ const { [rowKey]: open, ...rest } = state
+ return open ? rest : { ...state, [rowKey]: true }
+ },
},
],
- reportsFailed: [
- false,
+ homeScrollTop: [
+ null as number | null,
{
- loadTopReports: () => false,
- loadTopReportsFailure: () => true,
+ setHomeScrollTop: (_, { top }) => top,
+ locationChanged: (top, { pathname }) => (isTodayPath(pathname) ? top : null),
},
],
- now: [Date.now(), { tick: () => Date.now() }],
- hoveredItemKey: [
+ returnFocusReportId: [
null as string | null,
{
- setHoveredItemKey: (_, { itemKey }) => itemKey,
- locationChanged: () => null,
+ setReturnFocusReportId: (_, { reportId }) => reportId,
+ locationChanged: (reportId, { pathname }) =>
+ isTodayPath(pathname) ? (reportIdFromPath(pathname) ?? reportId) : null,
},
],
- personalBriefingFailed: [
+ reportsFailed: [
false,
{
- loadPersonalBriefingSuccess: () => false,
- loadPersonalBriefingFailure: () => true,
- },
- ],
- // The briefing the page stopped waiting for after the poll budget ran out, so a later one still polls.
- gaveUpWaitingFor: [
- null as string | null,
- {
- stopWaitingForBriefing: (_, { briefingId }) => briefingId,
- refreshBriefingSuccess: () => null,
- },
- ],
- // Polls spent on the briefing in progress. A settled briefing closes the count, so the next
- // one starts with the whole budget.
- briefingPolls: [
- 0,
- {
- pollBriefing: (count) => count + 1,
- loadPersonalBriefingSuccess: (count, { personalBriefing }) =>
- personalBriefing && isBriefingSettled(personalBriefing) ? 0 : count,
- refreshBriefingSuccess: () => 0,
- stopWaitingForBriefing: () => 0,
+ loadTopReports: () => false,
+ loadTopReportsFailure: () => true,
},
],
+ now: [Date.now(), { tick: () => Date.now() }],
// A refreshed briefing names other reports, so the list the sidebar loaded past the old one goes.
moreReports: {
refreshBriefing: () => null,
setUseSampleData: () => null,
},
- // The refresh call returns before the page reloads the briefing. Until that reload returns
- // the `writing` briefing, the page still waits, so the badge does not flip back to the button.
- // A verdict shows at once in the text, the left bar and the hover card. The next briefing load
- // gives the same state from the server, and a failed request takes the verdict back.
- reportStateOverrides: [
- {} as Record<string, BriefingItemStateEnumApi>,
- {
- setReportVerdict: (overrides, { target, verdict }) => ({
- ...overrides,
- [target.reportId]: VERDICTS[verdict].itemState,
- }),
- setReportVerdictFailure: (overrides, { reportId }) => {
- const { [reportId]: _, ...rest } = overrides
- return rest
- },
- leaveReportReview: (overrides, { reportId }) => ({ ...overrides, [reportId]: 'left' }),
- leaveReportReviewFailure: (overrides, { reportId }) => {
- const { [reportId]: _, ...rest } = overrides
- return rest
- },
- },
- ],
- reloadingAfterRefresh: [
- false,
+ topReports: {
+ setUseSampleData: () => null,
+ },
+ listExpanded: [
+ { for_you: false, recents: false } as Record<TodayList, boolean>,
{
- refreshBriefingSuccess: () => true,
- loadPersonalBriefingSuccess: () => false,
- loadPersonalBriefingFailure: () => false,
+ setListExpanded: (state, { list, expanded }) => ({ ...state, [list]: expanded }),
},
],
}),
@@ -765,43 +591,20 @@ export const todayLogic = kea<todayLogicType>([
(topReports: TodayReports | null): number =>
topReports ? Math.max(topReports.count - topReports.results.length, 0) : 0,
],
- briefing: [
- (s) => [s.reports, s.useSampleData],
- (reports: SignalReport[], useSampleData: boolean): TodayBriefingSegment[][] =>
- useSampleData ? SAMPLE_BRIEFING : briefingForReports(reports),
- ],
hour: [(s) => [s.now], (now: number): number => new Date(now).getHours()],
greeting: [
(s) => [s.hour, s.user],
(hour: number, user: UserType | null): string => greetingForHour(hour, user?.first_name),
],
- reportSummary: [
- (s) => [s.hour, s.reports],
- (hour: number, reports: SignalReport[]): string => reportSummaryForHour(hour, reports.length),
- ],
recentObjects: [
(s) => [s.recents],
- (recents: FileSystemEntry[]): FileSystemEntry[] => recentObjectsForHome(recents, RECENT_OBJECT_COUNT),
+ (recents: FileSystemEntry[]): FileSystemEntry[] => recentObjectsForHome(recents, RECENT_OBJECT_MORE_COUNT),
],
showPersonalBriefing: [
(s) => [s.personalBriefing, s.useSampleData],
(personalBriefing: BriefingApi | null, useSampleData: boolean): boolean =>
!useSampleData && hasBriefingText(personalBriefing),
],
- inboxMore: [
- (s) => [s.personalBriefing],
- (personalBriefing: BriefingApi | null): TodayInboxMore | null => {
- if (!personalBriefing) {
- return null
- }
- if (personalBriefing.more_reports_count > 0) {
- return { count: personalBriefing.more_reports_count, scope: 'for_you' }
- }
- return personalBriefing.open_reports_count > 0
- ? { count: personalBriefing.open_reports_count, scope: 'project' }
- : null
- },
- ],
briefingItems: [
(s) => [s.personalBriefing, s.showPersonalBriefing, s.reportStateOverrides],
(
@@ -819,31 +622,6 @@ export const todayLogic = kea<todayLogicType>([
})
},
],
- // The card stores its trigger's payload, so each report keeps one object per surface across renders.
- reportPreviews: [
- (s) => [s.briefingItems],
- (
- briefingItems: BriefingItemApi[]
- ): Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>> =>
- // Only items with report details: other items, and deleted reports, have nothing to show.
- previewsBySurface(
- briefingItems.filter((item) => item.report).map((item) => [item.key, briefingItemReportCard(item)])
- ),
- ],
- // The team's reports stand in until the personal briefing is written, and get the same card.
- teamReportPreviews: [
- (s) => [s.reports],
- (reports: SignalReport[]): Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>> =>
- previewsBySurface(reports.map((report) => [report.id, teamReportCard(report)])),
- ],
- // Shown once something is off the list: "0 of 5 done" reads as a nag, not progress.
- briefingProgress: [
- (s) => [s.briefingItems],
- (briefingItems: BriefingItemApi[]): TodayBriefingProgress | null => {
- const done = briefingItems.filter((item) => item.state !== 'open').length
- return done > 0 ? { done, total: briefingItems.length } : null
- },
- ],
shownReportIds: [
(s) => [s.showPersonalBriefing, s.briefingItems, s.reports],
(showPersonalBriefing: boolean, briefingItems: BriefingItemApi[], reports: SignalReport[]): string[] =>
@@ -851,81 +629,168 @@ export const todayLogic = kea<todayLogicType>([
? briefingItems.map(itemReportId).filter((id): id is string => id !== null)
: reports.map((report) => report.id),
],
- // Read against the list on screen now, so a briefing that loads later does not show a report twice.
- sidebarMoreReports: [
+ currentMoreReports: [
(s) => [s.moreReports, s.shownReportIds, s.useSampleData],
- (moreReports: TodayReports | null, shownReportIds: string[], useSampleData: boolean): SignalReport[] => {
- if (!moreReports || useSampleData) {
- return []
- }
- const shown = new Set(shownReportIds)
- return moreReports.results.filter((report) => !shown.has(report.id))
- },
- ],
- moreReportPreviews: [
- (s) => [s.sidebarMoreReports],
(
- sidebarMoreReports: SignalReport[]
- ): Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>> =>
- previewsBySurface(sidebarMoreReports.map((report) => [report.id, teamReportCard(report)])),
+ moreReports: TodayMoreReports | null,
+ shownReportIds: string[],
+ useSampleData: boolean
+ ): TodayMoreReports | null =>
+ moreReports && !useSampleData && objectsEqual(moreReports.exclude, shownReportIds) ? moreReports : null,
+ ],
+ loadedMoreReports: [
+ (s) => [s.currentMoreReports],
+ (currentMoreReports: TodayMoreReports | null): SignalReport[] => currentMoreReports?.results ?? [],
],
- // The endpoint has no next page, so the sidebar loads more one time and then links to the Inbox.
canLoadMoreReports: [
- (s) => [s.moreReports, s.useSampleData, s.showPersonalBriefing, s.personalBriefing, s.moreReportCount],
+ (s) => [
+ s.currentMoreReports,
+ s.useSampleData,
+ s.showPersonalBriefing,
+ s.personalBriefing,
+ s.moreReportCount,
+ ],
(
- moreReports: TodayReports | null,
+ currentMoreReports: TodayMoreReports | null,
useSampleData: boolean,
showPersonalBriefing: boolean,
personalBriefing: BriefingApi | null,
moreReportCount: number
): boolean => {
- if (moreReports || useSampleData) {
+ if (useSampleData) {
return false
}
+ if (currentMoreReports) {
+ return currentMoreReports.hasMore
+ }
return showPersonalBriefing ? (personalBriefing?.more_reports_count ?? 0) > 0 : moreReportCount > 0
},
],
- // The endpoint counts the loaded reports plus the other open reports that name the person.
- // What is neither loaded nor already on screen: the count covers the whole set for the person,
- // including briefing items the page ranked past the loaded ones.
moreReportsInInbox: [
- (s) => [s.moreReports, s.showPersonalBriefing, s.briefingItems, s.reports],
+ (s) => [s.currentMoreReports],
+ (currentMoreReports: TodayMoreReports | null): number =>
+ currentMoreReports && !currentMoreReports.hasMore
+ ? Math.max(currentMoreReports.count - currentMoreReports.results.length, 0)
+ : 0,
+ ],
+ forYouRows: [
+ (s) => [
+ s.showPersonalBriefing,
+ s.briefingItems,
+ s.reports,
+ s.loadedMoreReports,
+ s.forYouHighlights,
+ s.doneHighlightKeys,
+ s.reportStateOverrides,
+ ],
(
- moreReports: TodayReports | null,
showPersonalBriefing: boolean,
briefingItems: BriefingItemApi[],
- reports: SignalReport[]
- ): number => {
- if (!moreReports) {
- return 0
- }
- // Past the loaded page the count holds only open reports that name the person, so a resolved
- // item, or one the person only claimed, is not in it and must not be taken off it.
- const countedShownIds = showPersonalBriefing
- ? briefingItems
- .filter((item) => item.state === 'open' && itemNamesPerson(item))
- .map(itemReportId)
- .filter((id): id is string => id !== null)
- : reports.map((report) => report.id)
- const visible = new Set([...moreReports.results.map((report) => report.id), ...countedShownIds])
- return Math.max(moreReports.count - visible.size, 0)
- },
+ reports: SignalReport[],
+ loadedMoreReports: SignalReport[],
+ highlights: HighlightItemApi[],
+ doneHighlightKeys: string[],
+ reportStateOverrides: Record<string, BriefingItemStateEnumApi>
+ ): TodayForYouRows =>
+ forYouRows({
+ showPersonalBriefing,
+ briefingItems,
+ reports,
+ loadedMoreReports,
+ highlights,
+ doneHighlightKeys,
+ reportStateOverrides,
+ }),
+ ],
+ reportsBroken: [
+ (s) => [s.reportsFailed, s.topReports, s.showPersonalBriefing],
+ (reportsFailed: boolean, topReports: TodayReports | null, showPersonalBriefing: boolean): boolean =>
+ reportsFailed && topReports === null && !showPersonalBriefing,
],
- // While a newer briefing is written, the server returns the shown one as `writing`, so the
- // text stays on screen and the page keeps asking until the new one is ready.
- briefingWaiting: [
- (s) => [s.personalBriefing, s.gaveUpWaitingFor, s.refreshedBriefingLoading, s.reloadingAfterRefresh],
+ forYouReady: [
+ (s) => [
+ s.showPersonalBriefing,
+ s.topReports,
+ s.reportsFailed,
+ s.highlightsPending,
+ s.highlightsWaitOver,
+ s.forYouRows,
+ ],
(
- personalBriefing: BriefingApi | null,
- gaveUpWaitingFor: string | null,
- refreshedBriefingLoading: boolean,
- reloadingAfterRefresh: boolean
+ showPersonalBriefing: boolean,
+ topReports: TodayReports | null,
+ reportsFailed: boolean,
+ highlightsPending: boolean,
+ highlightsWaitOver: boolean,
+ { rows }: TodayForYouRows
): boolean =>
- refreshedBriefingLoading ||
- reloadingAfterRefresh ||
- (!!personalBriefing &&
- personalBriefing.id !== gaveUpWaitingFor &&
- !isBriefingSettled(personalBriefing)),
+ (showPersonalBriefing || topReports !== null || reportsFailed) &&
+ (!highlightsPending || (highlightsWaitOver && rows.length > 0)),
+ ],
+ forYouFailedNote: [
+ (s) => [s.reportsBroken, s.highlightsFailed],
+ (reportsBroken: boolean, highlightsFailed: boolean): string | null =>
+ reportsBroken && highlightsFailed
+ ? 'Reports and highlights didn’t load.'
+ : reportsBroken
+ ? 'Reports didn’t load.'
+ : highlightsFailed
+ ? 'Highlights didn’t load.'
+ : null,
+ ],
+ forYouOpenCount: [
+ (s) => [s.forYouRows],
+ ({ rows }: TodayForYouRows): number => rows.filter((row) => !row.done).length,
+ ],
+ forYouVisibleRows: [
+ (s) => [s.forYouRows, s.listExpanded],
+ ({ rows, limit }: TodayForYouRows, listExpanded: Record<TodayList, boolean>): TodayForYouRow[] =>
+ listExpanded.for_you ? rows : rows.slice(0, limit),
+ ],
+ forYouCanShowMore: [
+ (s) => [s.forYouRows, s.listExpanded, s.canLoadMoreReports],
+ (
+ { rows, limit }: TodayForYouRows,
+ listExpanded: Record<TodayList, boolean>,
+ canLoadMoreReports: boolean
+ ): boolean => (!listExpanded.for_you && rows.length > limit) || canLoadMoreReports,
+ ],
+ forYouCanShowLess: [
+ (s) => [s.forYouRows, s.listExpanded],
+ ({ rows }: TodayForYouRows, listExpanded: Record<TodayList, boolean>): boolean =>
+ listExpanded.for_you && rows.length > VISIBLE_ROWS + 1,
+ ],
+ isNewProject: [
+ (s) => [s.currentTeam, s.useSampleData],
+ (currentTeam: TeamPublicType | TeamType | null, useSampleData: boolean): boolean =>
+ !useSampleData && currentTeam?.ingested_event === false,
+ ],
+ exploreItems: [
+ (s) => [s.currentTeam],
+ (): TodayExploreItem[] => EXPLORE_ITEMS.filter((item) => !getProductAccessDisabledReason(item)),
+ ],
+ reportPreviews: [
+ (s) => [s.reports, s.loadedMoreReports, s.briefingItems],
+ (
+ reports: SignalReport[],
+ loadedMoreReports: SignalReport[],
+ briefingItems: BriefingItemApi[]
+ ): Record<string, TodayReportPreview> => {
+ const previews: Record<string, TodayReportPreview> = {}
+ for (const report of [...reports, ...loadedMoreReports]) {
+ const preview = reportPreview(report)
+ if (preview) {
+ previews[report.id] = preview
+ }
+ }
+ for (const item of briefingItems) {
+ const preview = briefingItemPreview(item)
+ if (preview) {
+ previews[item.key] = preview
+ }
+ }
+ return previews
+ },
],
}),
listeners(({ actions, values, cache }) => {
@@ -949,35 +814,30 @@ export const todayLogic = kea<todayLogicType>([
if (values.useSampleData) {
return
}
+ const { rows } = values.forYouRows
if (values.showPersonalBriefing) {
- const ranked = values.briefingItems.flatMap((item) => {
- const reportId = itemReportId(item)
- return reportId ? [{ report: briefingItemSnapshot(item, reportId), rank: item.rank }] : []
- })
+ const ranked = briefingRows(rows).flatMap((row, index) =>
+ row.reportId ? [{ report: briefingItemSnapshot(row.item, row.reportId), rank: index + 1 }] : []
+ )
impress('briefing', ranked, values.briefingItems.length)
} else if (!values.personalBriefingLoading) {
// The team list only stands in for the briefing, so it counts once the briefing is known to be absent.
impress(
'briefing',
- values.reports.map((report, index) => ({ report: signalReportSnapshot(report), rank: index + 1 })),
+ reportRows(rows, 'list').map((row, index) => ({
+ report: signalReportSnapshot(row.report),
+ rank: index + 1,
+ })),
values.reports.length
)
}
+ const moreRows = reportRows(rows, 'more')
impress(
'sidebar_more',
- values.sidebarMoreReports.map((report, index) => ({
- report: signalReportSnapshot(report),
- rank: index + 1,
- })),
- values.sidebarMoreReports.length
+ moreRows.map((row, index) => ({ report: signalReportSnapshot(row.report), rank: index + 1 })),
+ moreRows.length
)
}
- const schedulePoll = (): void => {
- cache.disposables.add(() => {
- const poll = window.setTimeout(() => actions.pollBriefing(), BRIEFING_POLL_MS)
- return () => clearTimeout(poll)
- }, 'briefingPoll')
- }
return {
askAi: async ({ prompt, source, report }, breakpoint) => {
let context: TodayAskContext
@@ -1006,17 +866,19 @@ export const todayLogic = kea<todayLogicType>([
})
},
tick: () => {
- // An open tab moves to the new day's briefing at 8:00 without a reload, including a laptop
- // that slept through it. The first tick, at mount, only records the day.
- const day = briefingDayKey(values.now)
- if (cache.day !== undefined && day !== cache.day && !values.useSampleData) {
+ const { now, highlights, personalBriefing } = values
+ if (highlights && !values.highlightsLoading && now >= Date.parse(highlights.refresh_at)) {
+ actions.loadHighlights()
+ }
+ if (
+ personalBriefing &&
+ !values.useSampleData &&
+ !values.personalBriefingLoading &&
+ !values.briefingWaiting &&
+ now >= Date.parse(personalBriefing.refresh_at)
+ ) {
actions.loadPersonalBriefing()
}
- cache.day = day
- },
- openReport: ({ report, source }) => {
- router.actions.push(urls.todayReport(report.id))
- actions.reportOpened(report, source)
},
setUseSampleData: ({ useSampleData }) => {
actions.loadTopReports()
@@ -1024,74 +886,22 @@ export const todayLogic = kea<todayLogicType>([
actions.loadPersonalBriefing()
}
},
- loadPersonalBriefingSuccess: ({ personalBriefing }) => {
+ loadPersonalBriefingSuccess: () => {
captureImpressions()
- if (!personalBriefing) {
- return
- }
- if (values.briefingWaiting) {
- if (values.briefingPolls >= MAX_BRIEFING_POLLS) {
- actions.stopWaitingForBriefing(personalBriefing.id)
- return
- }
- schedulePoll()
- return
- }
- if (cache.viewedBriefingId === personalBriefing.id) {
- return
- }
- cache.viewedBriefingId = personalBriefing.id
- // pinned: analytics event name and properties. Renaming them breaks dashboards.
- posthog.capture('today briefing viewed', {
- status: personalBriefing.status,
- writer: personalBriefing.writer,
- item_count: personalBriefing.items.length,
- done_item_count: personalBriefing.items.filter((item) => item.state === 'done').length,
- dismissed_item_count: personalBriefing.items.filter((item) => item.state === 'dismissed').length,
- more_reports_count: personalBriefing.more_reports_count,
- })
},
- loadPersonalBriefingFailure: ({ errorObject }) => {
+ loadPersonalBriefingFailure: () => {
captureImpressions()
- // A poll that fails while the briefing is written keeps polling; a 404 means there is no
- // briefing for this person, so the report list stays.
- const notFound = errorObject instanceof ApiError && errorObject.status === 404
- if (values.briefingWaiting && !notFound && values.briefingPolls < MAX_BRIEFING_POLLS) {
- schedulePoll()
- }
- },
- pollBriefing: () => {
- actions.loadPersonalBriefing()
- },
- refreshBriefing: () => {
- // pinned: analytics event name. Renaming it breaks dashboards.
- posthog.capture('today refresh clicked', { writer: values.personalBriefing?.writer ?? null })
},
- refreshBriefingSuccess: () => {
- actions.loadPersonalBriefing()
- },
- refreshBriefingFailure: ({ errorObject }) => {
- const detail = errorObject instanceof ApiError ? errorObject.detail : null
- lemonToast.error(detail || 'Couldn’t refresh your briefing. Try again in a minute.')
- },
- openItem: ({ item, surface }) => {
- const href = itemHref(item)
- if (isExternalHref(href)) {
- window.open(href, '_blank', 'noopener')
- } else {
- navigateToHref(href)
- }
- actions.itemOpened(item, surface)
- },
- itemOpened: ({ item, surface }) => {
+ itemOpened: ({ item }) => {
const reportId = itemReportId(item)
+ const rank = briefingRows(values.forYouRows.rows).findIndex((row) => row.key === item.key) + 1
if (reportId) {
captureTodayReportOpened({
report: briefingItemSnapshot(item, reportId),
list: 'briefing',
- rank: item.rank,
+ rank: rank || null,
listSize: values.briefingItems.length,
- source: surface,
+ source: 'list',
})
}
// pinned: analytics event name and properties. Renaming them breaks dashboards.
@@ -1099,53 +909,80 @@ export const todayLogic = kea<todayLogicType>([
group: item.group,
source: item.source,
reason: item.reason,
- rank: item.rank,
+ rank: rank || null,
state: item.state,
- surface,
+ surface: 'list',
})
},
- reportPreviewed: ({ cardKey, surface }) => {
- const item = values.briefingItems.find((candidate) => candidate.key === cardKey)
- if (item) {
+ exploreOpened: ({ product, position }) => {
+ posthog.capture('today explore opened', { product, position })
+ },
+ toggleReportRow: ({ rowKey, reportId }) => {
+ if (!values.expandedReportRows[rowKey] || values.useSampleData) {
+ return
+ }
+ const { rows } = values.forYouRows
+ const briefing = briefingRows(rows)
+ const briefingIndex = briefing.findIndex((row) => row.reportId === reportId)
+ if (briefingIndex !== -1) {
+ const { item } = briefing[briefingIndex]
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today report previewed', {
list: 'personal',
- report_id: itemReportId(item),
+ report_id: reportId,
source: item.source,
reason: item.reason,
- rank: item.rank,
+ rank: briefingIndex + 1,
state: item.state,
has_metric: !!item.report?.metrics.length,
- surface,
+ surface: 'list',
})
return
}
- if (values.useSampleData) {
- return
- }
- // The team list stays loaded under the personal briefing, but only the list on screen counts.
- for (const [list, reports] of [
- ['team', values.showPersonalBriefing ? [] : values.reports],
- ['more', values.sidebarMoreReports],
+ for (const [list, source] of [
+ ['team', 'list'],
+ ['more', 'more'],
] as const) {
- const rank = reports.findIndex((report) => teamReportCard(report).key === cardKey) + 1
- if (rank > 0) {
+ const listRows = reportRows(rows, source)
+ const index = listRows.findIndex((row) => row.report.id === reportId)
+ if (index !== -1) {
posthog.capture('today report previewed', {
list,
- report_id: reports[rank - 1].id,
- rank,
- has_metric: !!reports[rank - 1].metrics?.length,
- surface,
+ report_id: reportId,
+ rank: index + 1,
+ has_metric: !!listRows[index].report.metrics?.length,
+ surface: 'list',
})
return
}
}
},
+ showMoreForYou: () => {
+ actions.setListExpanded('for_you', true)
+ if (values.canLoadMoreReports) {
+ actions.loadMoreReports()
+ }
+ },
+ retryFailedLoads: () => {
+ if (values.reportsBroken) {
+ actions.loadTopReports()
+ }
+ if (values.highlightsFailed) {
+ actions.loadHighlights()
+ }
+ },
locationChanged: ({ searchParams }) => {
const useSampleData = parseSampleParam(searchParams.sample)
if (useSampleData !== null && useSampleData !== values.useSampleData) {
actions.setUseSampleData(useSampleData)
}
+ const { reportId, listExpanded } = values
+ if (reportId && !listExpanded.for_you) {
+ const { rows, limit } = values.forYouRows
+ if (rows.findIndex((row) => rowReportId(row) === reportId) >= limit) {
+ actions.setListExpanded('for_you', true)
+ }
+ }
},
loadTopReportsSuccess: ({ topReports }) => {
if (values.useSampleData) {
@@ -1158,120 +995,6 @@ export const todayLogic = kea<todayLogicType>([
more_report_count: values.moreReportCount,
})
},
- requestReportVerdict: ({ target, verdict, surface }) => {
- if (!target.hasOpenPullRequest) {
- actions.setReportVerdict(target, verdict, surface)
- return
- }
- const copy = VERDICTS[verdict]
- LemonDialog.open({
- title: copy.confirmTitle,
- description: 'This also closes the open pull request for this report.',
- primaryButton: {
- children: copy.confirmLabel,
- onClick: () => actions.setReportVerdict(target, verdict, surface),
- 'data-attr': `today-report-${verdict}-confirm`,
- },
- secondaryButton: { children: 'Cancel' },
- })
- },
- setReportVerdict: async ({ target, verdict, surface }) => {
- const copy = VERDICTS[verdict]
- try {
- await signalsReportsStateCreate(String(values.currentProjectId), target.reportId, {
- state: copy.apiState,
- })
- } catch (error) {
- actions.setReportVerdictFailure(target.reportId)
- lemonToast.error((error instanceof ApiError && error.detail) || copy.failure)
- return
- }
- // pinned: analytics event name and properties. Renaming them breaks dashboards.
- posthog.capture('today report state changed', {
- report_id: target.reportId,
- verdict,
- surface,
- closed_pull_request: target.hasOpenPullRequest,
- })
- captureTodayReportAction({
- reportId: target.reportId,
- actionType: verdict,
- todaySurface: surface,
- extra: { closed_pull_request: target.hasOpenPullRequest },
- })
- // A reason is optional, so the verdict is one click and the reason is one more.
- lemonToast.success(target.hasOpenPullRequest ? copy.successClosingPullRequest : copy.success, {
- button: { label: 'Add a reason', action: () => actions.addReportVerdictReason(target, verdict) },
- })
- },
- // No confirm dialog: unlike a verdict, this changes nothing for anyone but the person.
- leaveReportReview: async ({ reportId, surface }) => {
- try {
- await signalsReportsReviewersMeDestroy(String(values.currentProjectId), reportId)
- } catch (error) {
- actions.leaveReportReviewFailure(reportId)
- lemonToast.error(
- (error instanceof ApiError && error.detail) ||
- 'Couldn’t remove you from the reviewers. Try again, or change them from the Inbox.'
- )
- return
- }
- // pinned: analytics event name and properties. Renaming them breaks dashboards.
- posthog.capture('today report review left', { report_id: reportId, surface })
- captureTodayReportAction({
- reportId,
- actionType: 'remove_suggested_reviewer',
- todaySurface: surface,
- extra: { suggested_reviewer_uuid: values.user?.uuid },
- })
- lemonToast.success('Removed you from the reviewers')
- },
- addReportVerdictReason: ({ target, verdict }) => {
- const copy = VERDICTS[verdict]
- const dialogCopy = {
- title: copy.reasonTitle,
- description: copy.reasonDescription,
- submitLabel: 'Save reason',
- }
- // The state API takes the verdict the report already has and only saves the reason with it.
- const saveReason = async (body: SignalReportStateRequestApi): Promise<void> => {
- try {
- await signalsReportsStateCreate(String(values.currentProjectId), target.reportId, body)
- } catch (error) {
- lemonToast.error(
- (error instanceof ApiError && error.detail) || 'Couldn’t save the reason. Try again.'
- )
- // The dialog stays open, so the reason and the note are kept for the next try.
- throw error
- }
- // pinned: analytics event name and properties. Renaming them breaks dashboards.
- posthog.capture('today report reason added', {
- verdict,
- reason: body.dismissal_reason,
- has_note: !!body.dismissal_note,
- })
- lemonToast.success('Reason saved')
- }
- if (verdict === 'resolve') {
- openResolveReportDialog({
- reportTitle: target.title,
- copy: dialogCopy,
- onConfirm: ({ reason, note }) =>
- saveReason({
- state: copy.apiState,
- dismissal_reason: reason,
- ...(note ? { dismissal_note: note } : {}),
- }),
- })
- } else {
- openDismissReportDialog({
- reportTitle: target.title,
- copy: dialogCopy,
- onConfirm: (dismissal) =>
- saveReason({ state: copy.apiState, ...suppressDismissalPayload(dismissal) }),
- })
- }
- },
loadMoreReports: () => {
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today more reports clicked', { shown_report_count: values.shownReportIds.length })
@@ -1280,7 +1003,7 @@ export const todayLogic = kea<todayLogicType>([
captureImpressions()
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today more reports loaded', {
- report_count: values.sidebarMoreReports.length,
+ report_count: values.loadedMoreReports.length,
inbox_report_count: values.moreReportsInInbox,
})
},
@@ -1298,14 +1021,13 @@ export const todayLogic = kea<todayLogicType>([
has_pr: !!report.implementation_pr_url,
source,
})
- const list: TodayReportList = source === 'sidebar_more' ? 'sidebar_more' : 'briefing'
- const listReports = list === 'sidebar_more' ? values.sidebarMoreReports : values.reports
- const rank = listReports.findIndex((candidate) => candidate.id === report.id) + 1
+ const listRows = reportRows(values.forYouRows.rows, source)
+ const rank = listRows.findIndex((row) => row.report.id === report.id) + 1
captureTodayReportOpened({
report: signalReportSnapshot(report),
- list,
- rank: rank > 0 ? rank : null,
- listSize: listReports.length,
+ list: source === 'more' ? 'sidebar_more' : 'briefing',
+ rank: rank || null,
+ listSize: listRows.length,
source,
})
},
diff --git a/frontend/src/scenes/project-homepage/today/todayNumbers.test.ts b/frontend/src/scenes/project-homepage/today/todayNumbers.test.ts
new file mode 100644
index 000000000000..44a9b7568c0e
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayNumbers.test.ts
@@ -0,0 +1,17 @@
+import { todayNumber } from './todayNumbers'
+
+describe('todayNumber', () => {
+ test.each([
+ [342, '342'],
+ [1240, '1.2k'],
+ [967_000, '967k'],
+ [999_960, '1M'],
+ [999.96, '1k'],
+ [1_000, '1k'],
+ [2_350_000, '2.4M'],
+ [-6200, '-6.2k'],
+ [4.25, '4.3'],
+ ])('formats %s as %s', (value, expected) => {
+ expect(todayNumber(value)).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayNumbers.ts b/frontend/src/scenes/project-homepage/today/todayNumbers.ts
new file mode 100644
index 000000000000..845840e2700a
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayNumbers.ts
@@ -0,0 +1,21 @@
+const UNITS: [number, string][] = [
+ [1_000_000_000, 'B'],
+ [1_000_000, 'M'],
+ [1_000, 'k'],
+ [1, ''],
+]
+
+export function todayNumber(value: number): string {
+ const size = Math.abs(value)
+ const found = UNITS.findIndex(([threshold]) => size >= threshold)
+ for (let index = found === -1 ? UNITS.length - 1 : found; index >= 0; index--) {
+ const [threshold, suffix] = UNITS[index]
+ const scaled = value / threshold
+ const digits = threshold === 1 ? (Number.isInteger(value) ? 0 : 1) : Math.abs(scaled) < 100 ? 1 : 0
+ const text = scaled.toFixed(digits).replace(/\.0$/, '')
+ if (index === 0 || Math.abs(Number(text)) < 1000) {
+ return `${text}${suffix}`
+ }
+ }
+ return String(value)
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayPriority.ts b/frontend/src/scenes/project-homepage/today/todayPriority.ts
new file mode 100644
index 000000000000..a18d2bbd896e
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayPriority.ts
@@ -0,0 +1,8 @@
+import type { TodayRowTone } from './TodayRow'
+
+export function priorityTone(priority: string | null | undefined): TodayRowTone {
+ if (priority === 'P0' || priority === 'P1') {
+ return 'risk'
+ }
+ return priority === 'P2' ? 'neutral' : 'quiet'
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.ts
index 4b82d01dfdcf..0988585eed7f 100644
--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.ts
@@ -21,6 +21,7 @@ import {
todayReportsPageRetrieve,
} from 'products/today/frontend/generated/api'
import type {
+ BriefingItemStateEnumApi,
CodeFileApi,
FigureMarkApi,
FigureTextEnumApi,
@@ -34,16 +35,15 @@ import {
todayExcerptChoiceCreateBodyFindingMax,
} from 'products/today/frontend/generated/api.zod'
-import type { BriefingItemStateEnumApi } from '../../../../../products/today/frontend/generated/api.schemas'
import { reportItemState } from './todayBriefingItems'
import { type TodaySignalDestination } from './todayEvidence'
import { type TodayMarkedFigure, markedFigures, staleEvidenceDate } from './todayFigureSources'
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'
+import { todayVerdictLogic } from './todayVerdictLogic'
export type TodayCodeQuoteState = TodayCodeQuote | null | 'loading'
export type TodayMarkKind = 'impact' | 'figure' | 'key_clause'
@@ -64,8 +64,8 @@ export interface todayReportLogicValues {
currentProjectId: number | string // teamLogic
currentTeamId: number | null // teamLogic
askingAi: boolean // todayLogic
- reportStateOverrides: Record<string, BriefingItemStateEnumApi> // todayLogic
reports: SignalReport[] // todayLogic
+ reportStateOverrides: Record<string, BriefingItemStateEnumApi> // todayVerdictLogic
asksJev: boolean
codeQuotes: Record<string, TodayCodeQuoteState>
composerOpen: boolean
@@ -86,7 +86,6 @@ export interface todayReportLogicValues {
lastSeen: string | null
lead: string
leadMarks: TodayMarkedFigure[]
- leadStatesNumber: boolean
page: ReportPageApi | null
pageLoading: boolean
proposal: string
@@ -274,7 +273,6 @@ export interface todayReportLogicMeta {
leadMarks: (lead: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]
impactMarks: (impactText: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]
staleFiguresDate: (leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]) => string | null
- leadStatesNumber: (lead: string) => boolean
reportUrl: (currentTeamId: number | null) => string
}
}
@@ -295,7 +293,9 @@ export const todayReportLogic = kea<todayReportLogicType>([
teamLogic,
['currentTeamId', 'currentProjectId'],
todayLogic,
- ['reports', 'reportStateOverrides', 'askingAi'],
+ ['reports', 'askingAi'],
+ todayVerdictLogic,
+ ['reportStateOverrides'],
featureFlagLogic,
['featureFlags'],
],
@@ -495,7 +495,6 @@ export const todayReportLogic = kea<todayReportLogicType>([
(leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]): string | null =>
staleEvidenceDate([...leadMarks, ...impactMarks]),
],
- leadStatesNumber: [(s) => [s.lead], (lead: string): boolean => /\d/.test(renderedText(lead))],
reportUrl: [
(s) => [s.currentTeamId],
(currentTeamId: number | null): string =>
diff --git a/frontend/src/scenes/project-homepage/today/todayReportPreviews.ts b/frontend/src/scenes/project-homepage/today/todayReportPreviews.ts
new file mode 100644
index 000000000000..3bbbd0f8b0bd
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayReportPreviews.ts
@@ -0,0 +1,66 @@
+import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'
+import { SignalReport } from 'products/signals/frontend/inbox/types'
+import { formatReportMetricValue } from 'products/signals/frontend/inbox/utils/reportMetrics'
+import type { BriefingItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { reportSourceLine, reportTitle, sourceStyle } from './todaySignalReports'
+
+export interface TodayReportPreview {
+ sources: string | null
+ lead: string | null
+ metric: { title: string; value: string } | null
+ pullRequest: { url: string; state: string | null } | null
+}
+
+type PreviewMetric = Pick<ReportMetricApi, 'title' | 'unit' | 'value_format'> & { value?: number | null }
+
+function previewMetric(metrics: PreviewMetric[] | undefined): TodayReportPreview['metric'] {
+ for (const metric of metrics ?? []) {
+ const value = formatReportMetricValue(metric, metric.value)
+ if (value) {
+ return { title: metric.title, value }
+ }
+ }
+ return null
+}
+
+function comparable(text: string): string {
+ return text.toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
+}
+
+function distinctLead(lead: string | null | undefined, title: string): string | null {
+ const text = lead?.trim()
+ return text && comparable(text) !== comparable(title) ? text : null
+}
+
+function worthShowing(preview: TodayReportPreview): TodayReportPreview | null {
+ return preview.lead || preview.metric || preview.pullRequest ? preview : null
+}
+
+export function reportPreview(report: SignalReport): TodayReportPreview | null {
+ return worthShowing({
+ sources: report.source_products?.length || report.scout_name ? reportSourceLine(report).line : null,
+ lead: distinctLead(report.summary_lead, reportTitle(report)),
+ metric: previewMetric(report.metrics),
+ pullRequest: report.implementation_pr_url
+ ? {
+ url: report.implementation_pr_url,
+ state: report.implementation_pr_merged ? 'merged' : (report.implementation_pr_state ?? null),
+ }
+ : null,
+ })
+}
+
+export function briefingItemPreview(item: BriefingItemApi): TodayReportPreview | null {
+ if (!item.report) {
+ return null
+ }
+ return worthShowing({
+ sources: sourceStyle(item.source_product ?? item.source).label,
+ lead: distinctLead(item.report.summary, item.title),
+ metric: previewMetric(item.report.metrics),
+ pullRequest: item.report.pull_request_url
+ ? { url: item.report.pull_request_url, state: item.report.pull_request_state ?? null }
+ : null,
+ })
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.test.ts
new file mode 100644
index 000000000000..744e05c4b3b4
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.test.ts
@@ -0,0 +1,45 @@
+import { router } from 'kea-router'
+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 { todayBriefingLogic } from './todayBriefingLogic'
+import { todayReportQueueLogic } from './todayReportQueueLogic'
+import { makeBriefing, makeHighlights } from './todayTestFixtures'
+
+describe('todayReportQueueLogic', () => {
+ it('keeps the report order the person opened from while a later briefing names other reports', async () => {
+ const briefing = makeBriefing()
+ briefing.items[0].key = 'report:z'
+ briefing.paragraphs[0][0].item_key = 'report:z'
+ let briefingResponse: [number, any] = [404, { detail: 'Not found.' }]
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/reports/for_you/': {
+ results: [makeReport({ id: 'a' }), makeReport({ id: 'b' })],
+ count: 2,
+ },
+ '/api/projects/:team_id/today/highlights/': makeHighlights(),
+ '/api/projects/:team_id/today/briefing/': () => briefingResponse,
+ },
+ })
+ initKeaTests()
+ const logic = todayReportQueueLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ router.actions.push('/project/997/home/reports/b')
+ briefingResponse = [200, briefing]
+ await expectLogic(logic, () => {
+ todayBriefingLogic.actions.loadPersonalBriefing()
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ reportQueueIds: ['a', 'b', 'z'], reportPosition: 2 })
+
+ router.actions.push('/project/997/home')
+ expect(logic.values.reportQueueIds).toEqual(['z'])
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.ts b/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.ts
new file mode 100644
index 000000000000..d67136b4b07d
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayReportQueueLogic.ts
@@ -0,0 +1,198 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+import type { LocationChangedPayload } from 'kea-router/lib/types'
+import posthog from 'posthog-js'
+
+import { urls } from 'scenes/urls'
+
+import { forYouReportIds, type TodayForYouRows } from './todayForYouRows'
+import { type TodayMoreReports, todayLogic } from './todayLogic'
+import { navigateWithCrossfade } from './todayViewTransition'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayReportQueueLogicValues {
+ canLoadMoreReports: boolean // todayLogic
+ forYouRows: TodayForYouRows // todayLogic
+ moreReportsInInbox: number // todayLogic
+ moreReportsLoading: boolean // todayLogic
+ reportId: string | null // todayLogic
+ adjacentReportIds: string[]
+ atQueueEnd: boolean
+ reportPosition: number | null
+ reportQueue: string[] | null
+ reportQueueIds: string[]
+ restInInbox: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayReportQueueLogicActions {
+ locationChanged: ({
+ method,
+ pathname,
+ search,
+ searchParams,
+ hash,
+ hashParams,
+ initial,
+ url,
+ routerState,
+ }: LocationChangedPayload) => {
+ hash: string
+ hashParams: Record<string, any>
+ initial: boolean
+ method: 'POP' | 'PUSH' | 'REPLACE'
+ pathname: string
+ routerState: Record<string, any>
+ search: string
+ searchParams: Record<string, any>
+ url: string
+ } // router
+ loadMoreReports: () => any // todayLogic
+ loadMoreReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // todayLogic
+ loadMoreReportsSuccess: (
+ moreReports: TodayMoreReports | null,
+ payload?: any
+ ) => {
+ moreReports: TodayMoreReports | null
+ payload?: any
+ } // todayLogic
+ leaveReport: () => {
+ value: true
+ }
+ openAdjacentReport: (step: 1 | -1) => {
+ step: 1 | -1
+ }
+ setReportQueue: (reportIds: string[] | null) => {
+ reportIds: string[] | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayReportQueueLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ reportQueueIds: (reportQueue: string[] | null, forYouRows: TodayForYouRows) => string[]
+ reportPosition: (reportId: string | null, reportQueueIds: string[]) => number | null
+ adjacentReportIds: (reportPosition: number | null, reportQueueIds: string[]) => string[]
+ atQueueEnd: (reportPosition: number | null, reportQueueIds: string[], canLoadMoreReports: boolean) => boolean
+ restInInbox: (atQueueEnd: boolean, moreReportsInInbox: number) => boolean
+ }
+}
+
+export type todayReportQueueLogicType = MakeLogicType<
+ todayReportQueueLogicValues,
+ todayReportQueueLogicActions,
+ Record<string, any>,
+ todayReportQueueLogicMeta
+>
+
+export const todayReportQueueLogic = kea<todayReportQueueLogicType>([
+ path(['scenes', 'project-homepage', 'today', 'todayReportQueueLogic']),
+ connect(() => ({
+ values: [
+ todayLogic,
+ ['reportId', 'forYouRows', 'canLoadMoreReports', 'moreReportsLoading', 'moreReportsInInbox'],
+ ],
+ actions: [
+ router,
+ ['locationChanged'],
+ todayLogic,
+ ['loadMoreReports', 'loadMoreReportsSuccess', 'loadMoreReportsFailure'],
+ ],
+ })),
+ actions({
+ setReportQueue: (reportIds: string[] | null) => ({ reportIds }),
+ openAdjacentReport: (step: 1 | -1) => ({ step }),
+ leaveReport: true,
+ }),
+ reducers({
+ reportQueue: [null as string[] | null, { setReportQueue: (_, { reportIds }) => reportIds }],
+ }),
+ selectors({
+ reportQueueIds: [
+ (s) => [s.reportQueue, s.forYouRows],
+ (reportQueue: string[] | null, rows: TodayForYouRows): string[] => {
+ const live = forYouReportIds(rows.rows)
+ if (!reportQueue) {
+ return live
+ }
+ const queued = new Set(reportQueue)
+ return [...reportQueue, ...live.filter((id) => !queued.has(id))]
+ },
+ ],
+ reportPosition: [
+ (s) => [s.reportId, s.reportQueueIds],
+ (reportId: string | null, reportQueueIds: string[]): number | null => {
+ const index = reportId ? reportQueueIds.indexOf(reportId) : -1
+ return index === -1 ? null : index + 1
+ },
+ ],
+ adjacentReportIds: [
+ (s) => [s.reportPosition, s.reportQueueIds],
+ (reportPosition: number | null, reportQueueIds: string[]): string[] =>
+ reportPosition === null
+ ? []
+ : [reportQueueIds[reportPosition - 2], reportQueueIds[reportPosition]].filter(
+ (id): id is string => !!id
+ ),
+ ],
+ atQueueEnd: [
+ (s) => [s.reportPosition, s.reportQueueIds, s.canLoadMoreReports],
+ (reportPosition: number | null, reportQueueIds: string[], canLoadMoreReports: boolean): boolean =>
+ reportPosition !== null && reportPosition >= reportQueueIds.length && !canLoadMoreReports,
+ ],
+ restInInbox: [
+ (s) => [s.atQueueEnd, s.moreReportsInInbox],
+ (atQueueEnd: boolean, moreReportsInInbox: number): boolean => atQueueEnd && moreReportsInInbox > 0,
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ openAdjacentReport: ({ step }) => {
+ const { reportQueueIds, reportPosition, canLoadMoreReports, moreReportsLoading } = values
+ if (reportPosition === null || moreReportsLoading) {
+ return
+ }
+ const target = reportQueueIds[reportPosition - 1 + step]
+ if (target) {
+ posthog.capture('today report stepped', {
+ step,
+ position: reportPosition,
+ total: reportQueueIds.length,
+ })
+ router.actions.push(urls.todayReport(target))
+ } else if (step === 1 && canLoadMoreReports) {
+ cache.openNextAfterLoad = values.reportId
+ actions.loadMoreReports()
+ } else if (step === 1 && values.moreReportsInInbox > 0) {
+ router.actions.push(urls.inbox())
+ }
+ },
+ leaveReport: () => {
+ navigateWithCrossfade(urls.projectHomepage())
+ },
+ locationChanged: () => {
+ if (values.reportId === null) {
+ if (values.reportQueue !== null) {
+ actions.setReportQueue(null)
+ }
+ } else if (values.reportQueue === null) {
+ actions.setReportQueue(values.reportQueueIds)
+ }
+ },
+ loadMoreReportsSuccess: () => {
+ const openNextFrom = cache.openNextAfterLoad
+ cache.openNextAfterLoad = null
+ if (openNextFrom && openNextFrom === values.reportId) {
+ actions.openAdjacentReport(1)
+ }
+ },
+ loadMoreReportsFailure: () => {
+ cache.openNextAfterLoad = null
+ },
+ })),
+])
diff --git a/frontend/src/scenes/project-homepage/today/todayRowFacts.ts b/frontend/src/scenes/project-homepage/today/todayRowFacts.ts
new file mode 100644
index 000000000000..fb641bb45647
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayRowFacts.ts
@@ -0,0 +1,19 @@
+const PULL_REQUEST_FACTS: Record<string, string> = {
+ draft: 'Fix in progress',
+ open: 'Fix ready for review',
+ merged: 'Fix merged',
+}
+
+export function pullRequestFact(state: string | null | undefined): string | null {
+ return state ? (PULL_REQUEST_FACTS[state] ?? null) : null
+}
+
+export function rowFacts(parts: (string | null | undefined)[]): string[] {
+ const shown: string[] = []
+ for (const part of parts) {
+ if (part && !shown.some((earlier) => earlier.toLowerCase().includes(part.toLowerCase()))) {
+ shown.push(part)
+ }
+ }
+ return shown
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayRowIcons.tsx b/frontend/src/scenes/project-homepage/today/todayRowIcons.tsx
new file mode 100644
index 000000000000..2d9da68d11cc
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayRowIcons.tsx
@@ -0,0 +1,54 @@
+import {
+ IconBell,
+ IconDatabase,
+ IconFlask,
+ IconMessage,
+ IconRewindPlay,
+ IconToggle,
+ IconTrends,
+ IconWarning,
+} from '@posthog/icons'
+
+import { SignalReport } from 'products/signals/frontend/inbox/types'
+import type { BriefingItemApi, HighlightItemApi } from 'products/today/frontend/generated/api.schemas'
+
+import { TodayIcon } from './TodayIcon'
+import { sourceStyle } from './todaySignalReports'
+
+export interface TodayRowIcon {
+ color?: string
+ glyph: JSX.Element
+}
+
+const ANALYTICS: TodayRowIcon = {
+ color: 'var(--color-product-product-analytics-light)',
+ glyph: <IconTrends />,
+}
+
+const HIGHLIGHT_ICONS: Record<string, TodayRowIcon> = {
+ alerts: { color: 'var(--color-product-alerts-light)', glyph: <IconBell /> },
+ errors: { color: 'var(--color-product-error-tracking-light)', glyph: <IconWarning /> },
+ experiments: { color: 'var(--color-product-experiments-light)', glyph: <IconFlask /> },
+ flags: { color: 'var(--color-product-feature-flags-light)', glyph: <IconToggle /> },
+ rage: { color: 'var(--color-product-session-replay-light)', glyph: <IconRewindPlay /> },
+ surveys: { color: 'var(--color-product-surveys-light)', glyph: <IconMessage /> },
+ warehouse_syncs: { color: 'var(--color-product-data-warehouse-light)', glyph: <IconDatabase /> },
+}
+
+function sourceIcon(source: string | null | undefined): TodayRowIcon {
+ const style = sourceStyle(source)
+ const colored = style.color.startsWith('var(--color-product-')
+ return { color: colored ? style.color : undefined, glyph: <TodayIcon icon={style.icon} /> }
+}
+
+export function reportIcon(report: Pick<SignalReport, 'source_products'>): TodayRowIcon {
+ return sourceIcon(report.source_products?.[0])
+}
+
+export function briefingItemIcon(item: Pick<BriefingItemApi, 'source' | 'source_product'>): TodayRowIcon {
+ return sourceIcon(item.source_product ?? item.source)
+}
+
+export function highlightIcon(item: Pick<HighlightItemApi, 'source'>): TodayRowIcon {
+ return HIGHLIGHT_ICONS[item.source] ?? ANALYTICS
+}
diff --git a/frontend/src/scenes/project-homepage/today/todaySampleReports.ts b/frontend/src/scenes/project-homepage/today/todaySampleReports.ts
index c578bfd76350..73d6f746adb2 100644
--- a/frontend/src/scenes/project-homepage/today/todaySampleReports.ts
+++ b/frontend/src/scenes/project-homepage/today/todaySampleReports.ts
@@ -2,7 +2,6 @@ import type { ReportMetricApi } from 'products/signals/frontend/generated/api.sc
import { SignalReport, SignalReportStatus } from 'products/signals/frontend/inbox/types'
import type { TodayReports } from './todayLogic'
-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-'
@@ -170,32 +169,6 @@ const SAMPLE_SPECS: SampleReportSpec[] = [
},
]
-const BRIEFING_LINK = (id: string, text: string, highlight?: boolean): TodayBriefingSegment => ({
- text,
- reportId: `${SAMPLE_ID_PREFIX}${id}`,
- ...(highlight ? { highlight } : {}),
-})
-
-/** The hand-written briefing from the mock, which reads better than one built from report titles. */
-export const SAMPLE_BRIEFING: TodayBriefingSegment[][] = [
- [
- BRIEFING_LINK('safari', 'Safari users can’t pay'),
- { text: ' since Tuesday’s deploy, and ' },
- BRIEFING_LINK('pr', 'a fix is waiting', true),
- { text: ' for your review.' },
- ],
- [BRIEFING_LINK('exp', 'One-page checkout won'), { text: ' its experiment, and signups beat the forecast by 18%.' }],
- [
- { text: 'Keep an eye on ' },
- BRIEFING_LINK('error', 'one new error'),
- { text: ', LLM cost per user ' },
- BRIEFING_LINK('llm', 'up 31%'),
- { text: ', and ' },
- BRIEFING_LINK('nps', 'pricing that confuses people'),
- { text: '.' },
- ],
-]
-
function buildSampleReport(spec: SampleReportSpec, now: number): SignalReport {
const updatedAt = new Date(now - spec.hoursAgo * HOUR_MS).toISOString()
return {
diff --git a/frontend/src/scenes/project-homepage/today/todaySignalReports.ts b/frontend/src/scenes/project-homepage/today/todaySignalReports.ts
index 30fb40294d47..0111916f854b 100644
--- a/frontend/src/scenes/project-homepage/today/todaySignalReports.ts
+++ b/frontend/src/scenes/project-homepage/today/todaySignalReports.ts
@@ -1,8 +1,6 @@
import { dayjs } from 'lib/dayjs'
import { scoutDisplayName } from 'lib/signals/signalCardSourceLine'
-import type { TodayReportCard } from '~/layout/today/todayPreviewCards'
-
import { SignalReport } from 'products/signals/frontend/inbox/types'
export type TodayReportIcon =
@@ -25,14 +23,6 @@ export type TodayReportIcon =
| 'code'
| 'slack'
-/** One run of text in the briefing. A run with `reportId` links to that report. */
-export interface TodayBriefingSegment {
- text: string
- reportId?: string
- /** Marks the report that already has a pull request waiting for review. */
- highlight?: boolean
-}
-
export interface TodayReportSource {
label: string
color: string
@@ -88,36 +78,10 @@ export function sourceStyle(source: string | null | undefined): TodayReportSourc
}
/** The style of the product that contributed the report's first signal. */
-export function reportSource(report: Pick<SignalReport, 'source_products'>): TodayReportSource {
+function reportSource(report: Pick<SignalReport, 'source_products'>): TodayReportSource {
return sourceStyle(report.source_products?.[0])
}
-/** The hover card of one of the team's reports, shown while the personal briefing is not written yet. */
-export function teamReportCard(report: SignalReport): TodayReportCard {
- return {
- key: `team-report:${report.id}`,
- reportId: report.id,
- title: reportTitle(report),
- reason: null,
- stateLabel: null,
- resolved: false,
- canLeaveReview: report.is_suggested_reviewer,
- priority: report.priority ?? null,
- summary: report.summary_lead || null,
- pullRequestState: report.implementation_pr_merged ? 'merged' : (report.implementation_pr_state ?? null),
- pullRequestUrl: report.implementation_pr_url ?? null,
- signalCount: report.signal_count,
- updatedAt: report.updated_at,
- metrics: report.metrics ?? [],
- charts: report.charts ?? [],
- sourceLabel: reportSource(report).label,
- }
-}
-
-export function reportIcon(report: Pick<SignalReport, 'source_products' | 'implementation_pr_url'>): TodayReportIcon {
- return report.implementation_pr_url ? 'pr' : reportSource(report).icon
-}
-
export function reportMeta(report: Pick<SignalReport, 'source_products' | 'updated_at'>): string {
return `${reportSource(report).label} · ${dayjs(report.updated_at).fromNow()}`
}
@@ -127,27 +91,6 @@ export function lowerFirst(text: string): string {
return /^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text
}
-/** One linked sentence per report, so every report in the briefing opens from the text. */
-export function briefingForReports(reports: SignalReport[]): TodayBriefingSegment[][] {
- const [first, ...rest] = reports
- if (!first) {
- return []
- }
- const paragraphs: TodayBriefingSegment[][] = [
- [{ text: reportTitle(first), reportId: first.id, highlight: !!first.implementation_pr_url }, { text: '.' }],
- ]
- if (rest.length) {
- paragraphs.push([
- { text: 'Also on your list: ' },
- ...rest.flatMap((report, index): TodayBriefingSegment[] => [
- { text: lowerFirst(reportTitle(report)), reportId: report.id },
- { text: index === rest.length - 1 ? '.' : index === rest.length - 2 ? ', and ' : ', ' },
- ]),
- ])
- }
- return paragraphs
-}
-
const SHOWN_SOURCES = 2
const SOURCE_LINE_CHARS = 32
@@ -173,13 +116,6 @@ export function scoutLabel(skillName: string | null | undefined): string | null
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
diff --git a/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts b/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
index f3bc593dbaf4..7bc93c8d9802 100644
--- a/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
+++ b/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
@@ -1,4 +1,9 @@
-import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'
+import type {
+ BriefingApi,
+ HighlightItemApi,
+ HighlightsApi,
+ SignalViewApi,
+} from 'products/today/frontend/generated/api.schemas'
export function signal(overrides: Partial<SignalViewApi>): SignalViewApi {
return {
@@ -19,3 +24,63 @@ export function signal(overrides: Partial<SignalViewApi>): SignalViewApi {
...overrides,
}
}
+
+export function makeBriefing(overrides: Partial<BriefingApi> = {}): BriefingApi {
+ return {
+ id: 'briefing-1',
+ local_day: '2026-09-30',
+ headline: 'One report needs your input',
+ paragraphs: [[{ text: 'Signup form rejects emails', item_key: 'report:a', highlight: true }]],
+ items: [
+ {
+ key: 'report:a',
+ title: 'Signup form rejects emails',
+ label: 'Signup form rejects emails',
+ signal: 'P1, waits for you',
+ url: '/project/1/inbox/reports/a',
+ rank: 1,
+ group: 'report',
+ source: 'self_driving',
+ reason: 'waiting_for_you',
+ state: 'open',
+ source_product: null,
+ report: null,
+ },
+ ],
+ more_reports_count: 0,
+ open_reports_count: 0,
+ refresh_at: '2026-10-01T06:00:00Z',
+ status: 'ready',
+ writer: 'agent',
+ created_at: '2026-09-30T06:00:00Z',
+ ready_at: '2026-09-30T06:00:20Z',
+ ...overrides,
+ }
+}
+
+export function makeHighlightItem(overrides: Partial<HighlightItemApi> = {}): HighlightItemApi {
+ return {
+ key: 'alert:a',
+ label: 'risk',
+ priority: 'P1',
+ title: 'Alert',
+ detail: '',
+ url: null,
+ series: null,
+ score: 0.9,
+ source: 'alerts',
+ ...overrides,
+ }
+}
+
+export function makeHighlights(overrides: Partial<HighlightsApi> = {}): HighlightsApi {
+ return {
+ status: 'ready',
+ generated_at: '2026-09-30T06:00:00Z',
+ day: '2026-09-30',
+ refresh_at: '2026-10-01T00:00:00Z',
+ pulse: [],
+ items: [],
+ ...overrides,
+ }
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayVerdictLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.test.ts
new file mode 100644
index 000000000000..b72080433d8f
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.test.ts
@@ -0,0 +1,29 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { todayVerdictLogic } from './todayVerdictLogic'
+
+describe('todayVerdictLogic', () => {
+ it.each([
+ ['keeps a verdict the API accepts', 200, { a: 'done' }],
+ ['takes back a verdict the API refuses', 409, {}],
+ ])('%s', async (_, status, finalOverrides) => {
+ useMocks({
+ post: { '/api/projects/:team_id/signals/reports/:id/state/': () => [status, { detail: 'Refused.' }] },
+ })
+ initKeaTests()
+ const logic = todayVerdictLogic()
+ logic.mount()
+
+ logic.actions.requestReportVerdict(
+ { reportId: 'a', title: 'Signup form rejects emails', hasOpenPullRequest: false },
+ 'resolve',
+ 'briefing'
+ )
+ expect(logic.values.reportStateOverrides).toEqual({ a: 'done' })
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ reportStateOverrides: finalOverrides })
+ })
+})
diff --git a/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts
new file mode 100644
index 000000000000..0ab35cf33b2e
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts
@@ -0,0 +1,248 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { signalsReportsStateCreate } from 'products/signals/frontend/generated/api'
+import type {
+ SignalReportStateEnumApi,
+ SignalReportStateRequestApi,
+} from 'products/signals/frontend/generated/api.schemas'
+import { openDismissReportDialog } from 'products/signals/frontend/inbox/components/shell/DismissReportDialog'
+import { openResolveReportDialog } from 'products/signals/frontend/inbox/components/shell/ResolveReportDialog'
+import { captureTodayReportAction } from 'products/signals/frontend/inbox/inboxAnalytics'
+import { suppressDismissalPayload } from 'products/signals/frontend/inbox/utils/dismissalReasons'
+import type { BriefingItemStateEnumApi } from 'products/today/frontend/generated/api.schemas'
+
+/** What a person decides about a report from Today. */
+export type TodayReportVerdict = 'resolve' | 'dismiss'
+
+/** Where the person gave the verdict, sent with the `today report state changed` event. */
+export type TodayReportVerdictSurface = 'briefing' | 'report_page'
+
+/** The report a verdict acts on. */
+export interface TodayReportVerdictTarget {
+ reportId: string
+ title: string
+ /** The backend closes an open implementation pull request on either verdict, so the person confirms first. */
+ hasOpenPullRequest: boolean
+}
+
+interface TodayReportVerdictCopy {
+ apiState: SignalReportStateEnumApi
+ itemState: BriefingItemStateEnumApi
+ success: string
+ successClosingPullRequest: string
+ failure: string
+ confirmTitle: string
+ confirmLabel: string
+ reasonTitle: string
+ reasonDescription: string
+}
+
+const VERDICTS: Record<TodayReportVerdict, TodayReportVerdictCopy> = {
+ resolve: {
+ apiState: 'resolved',
+ itemState: 'done',
+ success: 'Report resolved',
+ successClosingPullRequest: 'Report resolved. Its pull request is closing.',
+ failure: 'Couldn’t resolve the report. Try again, or resolve it from the Inbox.',
+ confirmTitle: 'Resolve this report?',
+ confirmLabel: 'Resolve and close PR',
+ reasonTitle: 'Why did you resolve this report?',
+ reasonDescription: 'The reason is saved on the report.',
+ },
+ dismiss: {
+ apiState: 'suppressed',
+ itemState: 'dismissed',
+ success: 'Report dismissed',
+ successClosingPullRequest: 'Report dismissed. Its pull request is closing.',
+ failure: 'Couldn’t dismiss the report. Try again, or dismiss it from the Inbox.',
+ confirmTitle: 'Dismiss this report?',
+ confirmLabel: 'Dismiss and close PR',
+ reasonTitle: 'Why did you dismiss this report?',
+ reasonDescription:
+ 'The reason is saved on the report. The agent that filed it reads your note on its next run.',
+ },
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayVerdictLogicValues {
+ currentProjectId: number | string // teamLogic
+ reportStateOverrides: Record<string, BriefingItemStateEnumApi>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayVerdictLogicActions {
+ addReportVerdictReason: (
+ target: TodayReportVerdictTarget,
+ verdict: TodayReportVerdict
+ ) => {
+ target: TodayReportVerdictTarget
+ verdict: TodayReportVerdict
+ }
+ requestReportVerdict: (
+ target: TodayReportVerdictTarget,
+ verdict: TodayReportVerdict,
+ surface: TodayReportVerdictSurface
+ ) => {
+ surface: TodayReportVerdictSurface
+ target: TodayReportVerdictTarget
+ verdict: TodayReportVerdict
+ }
+ setReportVerdict: (
+ target: TodayReportVerdictTarget,
+ verdict: TodayReportVerdict,
+ surface: TodayReportVerdictSurface
+ ) => {
+ surface: TodayReportVerdictSurface
+ target: TodayReportVerdictTarget
+ verdict: TodayReportVerdict
+ }
+ setReportVerdictFailure: (reportId: string) => {
+ reportId: string
+ }
+}
+
+export type todayVerdictLogicType = MakeLogicType<todayVerdictLogicValues, todayVerdictLogicActions>
+
+export const todayVerdictLogic = kea<todayVerdictLogicType>([
+ path(['scenes', 'project-homepage', 'today', 'todayVerdictLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ requestReportVerdict: (
+ target: TodayReportVerdictTarget,
+ verdict: TodayReportVerdict,
+ surface: TodayReportVerdictSurface
+ ) => ({ target, verdict, surface }),
+ setReportVerdict: (
+ target: TodayReportVerdictTarget,
+ verdict: TodayReportVerdict,
+ surface: TodayReportVerdictSurface
+ ) => ({ target, verdict, surface }),
+ setReportVerdictFailure: (reportId: string) => ({ reportId }),
+ addReportVerdictReason: (target: TodayReportVerdictTarget, verdict: TodayReportVerdict) => ({
+ target,
+ verdict,
+ }),
+ }),
+ reducers({
+ // A verdict shows at once in the text and the left bar. The next briefing load
+ // gives the same state from the server, and a failed request takes the verdict back.
+ reportStateOverrides: [
+ {} as Record<string, BriefingItemStateEnumApi>,
+ {
+ setReportVerdict: (overrides, { target, verdict }) => ({
+ ...overrides,
+ [target.reportId]: VERDICTS[verdict].itemState,
+ }),
+ setReportVerdictFailure: (overrides, { reportId }) => {
+ const { [reportId]: _, ...rest } = overrides
+ return rest
+ },
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ requestReportVerdict: ({ target, verdict, surface }) => {
+ if (values.reportStateOverrides[target.reportId]) {
+ return
+ }
+ if (!target.hasOpenPullRequest) {
+ actions.setReportVerdict(target, verdict, surface)
+ return
+ }
+ const copy = VERDICTS[verdict]
+ LemonDialog.open({
+ title: copy.confirmTitle,
+ description: 'This also closes the open pull request for this report.',
+ primaryButton: {
+ children: copy.confirmLabel,
+ onClick: () => actions.setReportVerdict(target, verdict, surface),
+ 'data-attr': `today-report-${verdict}-confirm`,
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ setReportVerdict: async ({ target, verdict, surface }) => {
+ const copy = VERDICTS[verdict]
+ try {
+ await signalsReportsStateCreate(String(values.currentProjectId), target.reportId, {
+ state: copy.apiState,
+ })
+ } catch (error) {
+ actions.setReportVerdictFailure(target.reportId)
+ lemonToast.error((error instanceof ApiError && error.detail) || copy.failure)
+ return
+ }
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('today report state changed', {
+ report_id: target.reportId,
+ verdict,
+ surface,
+ closed_pull_request: target.hasOpenPullRequest,
+ })
+ captureTodayReportAction({
+ reportId: target.reportId,
+ actionType: verdict,
+ todaySurface: surface,
+ extra: { closed_pull_request: target.hasOpenPullRequest },
+ })
+ // A reason is optional, so the verdict is one click and the reason is one more.
+ lemonToast.success(target.hasOpenPullRequest ? copy.successClosingPullRequest : copy.success, {
+ button: { label: 'Add a reason', action: () => actions.addReportVerdictReason(target, verdict) },
+ })
+ },
+ addReportVerdictReason: ({ target, verdict }) => {
+ const copy = VERDICTS[verdict]
+ const dialogCopy = {
+ title: copy.reasonTitle,
+ description: copy.reasonDescription,
+ submitLabel: 'Save reason',
+ }
+ // The state API takes the verdict the report already has and only saves the reason with it.
+ const saveReason = async (body: SignalReportStateRequestApi): Promise<void> => {
+ try {
+ await signalsReportsStateCreate(String(values.currentProjectId), target.reportId, body)
+ } catch (error) {
+ lemonToast.error(
+ (error instanceof ApiError && error.detail) || 'Couldn’t save the reason. Try again.'
+ )
+ // The dialog stays open, so the reason and the note are kept for the next try.
+ throw error
+ }
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('today report reason added', {
+ verdict,
+ reason: body.dismissal_reason,
+ has_note: !!body.dismissal_note,
+ })
+ lemonToast.success('Reason saved')
+ }
+ if (verdict === 'resolve') {
+ openResolveReportDialog({
+ reportTitle: target.title,
+ copy: dialogCopy,
+ onConfirm: ({ reason, note }) =>
+ saveReason({
+ state: copy.apiState,
+ dismissal_reason: reason,
+ ...(note ? { dismissal_note: note } : {}),
+ }),
+ })
+ } else {
+ openDismissReportDialog({
+ reportTitle: target.title,
+ copy: dialogCopy,
+ onConfirm: (dismissal) =>
+ saveReason({ state: copy.apiState, ...suppressDismissalPayload(dismissal) }),
+ })
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/project-homepage/today/todayViewTransition.ts b/frontend/src/scenes/project-homepage/today/todayViewTransition.ts
new file mode 100644
index 000000000000..17645469bce1
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/todayViewTransition.ts
@@ -0,0 +1,22 @@
+import { router } from 'kea-router'
+import type { MouseEvent } from 'react'
+import { flushSync } from 'react-dom'
+
+export function isPlainClick(event: MouseEvent): boolean {
+ return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey
+}
+
+export function navigateWithCrossfade(to: string): void {
+ if (
+ typeof document.startViewTransition !== 'function' ||
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ) {
+ router.actions.push(to)
+ return
+ }
+ document.documentElement.dataset.todayTransition = ''
+ const transition = document.startViewTransition(() => flushSync(() => router.actions.push(to)))
+ void transition.finished.finally(() => {
+ delete document.documentElement.dataset.todayTransition
+ })
+}
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index ac7af773d1ca..15b4e145645b 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -87,6 +87,7 @@ class Product(StrEnum):
SIGNALS = "signals"
SQL_EDITOR = "sql_editor"
SURVEYS = "surveys"
+ TODAY = "today"
TRACING = "tracing"
WAREHOUSE = "warehouse"
WEB_ANALYTICS = "web_analytics"
diff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.py
index d7cda247dc16..24ba95779e78 100644
--- a/products/signals/backend/briefing_reports.py
+++ b/products/signals/backend/briefing_reports.py
@@ -327,7 +327,7 @@ def _likely_dismissed_as_wrong(candidate: _BriefingCandidate) -> bool:
return candidate.priority != "P0" and lift is not None and lift >= DISMISS_WRONG_HIDE_LIFT
-def _briefing_pick(candidates: Sequence[_BriefingCandidate], limit: int | None) -> list[_BriefingCandidate]:
+def _briefing_pick(candidates: Sequence[_BriefingCandidate]) -> list[_BriefingCandidate]:
"""The candidates in one order, without the ones likely dismissed as wrong.
P0 first. Then by the higher of two percentile ranks among the candidates: the chance of a
@@ -337,8 +337,8 @@ def _briefing_pick(candidates: Sequence[_BriefingCandidate], limit: int | None)
not by value. Ties go to the higher sum of the two ranks, then priority, then newest. A report
with neither score follows the scored ones.
- The order does not depend on `limit` or on the relation, so the top N reports are always the
- first N of the same list.
+ The order does not depend on the relation, so the top N reports are always the first N of the
+ same list.
"""
kept = [c for c in candidates if not _likely_dismissed_as_wrong(c)]
merge_ranks = _percentile_ranks({c.report_id: c.scores.pr_merged for c in kept if c.scores.pr_merged is not None})
@@ -351,12 +351,15 @@ def _briefing_pick(candidates: Sequence[_BriefingCandidate], limit: int | None)
0 if ranks else 1,
-max(ranks, default=0.0),
-sum(ranks),
- _PRIORITY_ORDER.get(candidate.priority or "", 5),
+ _priority_order(candidate),
-candidate.updated_at.timestamp(),
)
- ranked = sorted(kept, key=order)
- return ranked if limit is None else ranked[:limit]
+ return sorted(kept, key=order)
+
+
+def _priority_order(candidate: _BriefingCandidate) -> int:
+ return _PRIORITY_ORDER.get(candidate.priority or "", 5)
def _relation_to_person(team_id: int, user: User, *, include_unowned: bool) -> Case:
@@ -406,14 +409,23 @@ def _reports_for_person(team_id: int, user: User, *, include_unowned: bool) -> Q
def reports_for_briefing(
- *, team_id: int, user_id: int, limit: int | None = None, include_unowned: bool = True
+ *,
+ team_id: int,
+ user_id: int,
+ limit: int | None = None,
+ include_unowned: bool = True,
+ offset: int = 0,
+ exclude_report_ids: Sequence[str] = (),
) -> list[BriefingReport]:
"""Open, actionable reports for one person, in briefing order, each tagged with its strongest relation.
A report appears once, under the first `BriefingReportRelation` that matches. One query reads
every candidate with its relation, priority and served scores, up to `_CANDIDATE_LIMIT`, so the
model ranks the whole set and not only the newest reports. Urgent-unowned keeps only P0.
- `_briefing_pick` orders the candidates and `limit` keeps the best of them.
+ `_briefing_pick` orders the candidates. The excluded reports leave the list after it is ordered,
+ so the rest keep their order, and `offset` and `limit` then take one page of it. Priority does
+ not decide which reports make the page: it only orders the page for display, P0 first and
+ reports without a priority last, keeping the ranked order within a priority.
`include_unowned` false drops the urgent-unowned relation, so the result holds only reports the
person is named on or claimed. The Today briefing asks for that: a P0 nobody owns sorts above
@@ -426,19 +438,20 @@ def reports_for_briefing(
.order_by("-updated_at")
.values_list("id", "updated_at", "briefing_relation", "briefing_priority", "briefing_heads")[:_CANDIDATE_LIMIT]
)
- chosen = _briefing_pick(
- [
- _BriefingCandidate(
- report_id=str(report_id),
- relation=BriefingReportRelation(relation_value),
- priority=priority,
- updated_at=updated_at,
- scores=_served_scores(heads),
- )
- for report_id, updated_at, relation_value, priority, heads in rows
- ],
- limit,
- )
+ candidates = [
+ _BriefingCandidate(
+ report_id=str(report_id),
+ relation=BriefingReportRelation(relation_value),
+ priority=priority,
+ updated_at=updated_at,
+ scores=_served_scores(heads),
+ )
+ for report_id, updated_at, relation_value, priority, heads in rows
+ ]
+ excluded = set(exclude_report_ids)
+ ranked = [candidate for candidate in _briefing_pick(candidates) if candidate.report_id not in excluded]
+ page = ranked[offset:] if limit is None else ranked[offset : offset + limit]
+ chosen = sorted(page, key=_priority_order)
chosen_ids = [candidate.report_id for candidate in chosen]
reports = {
str(report.id): report
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index c930dbe88f57..a2d6e4491797 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -14,6 +14,7 @@ from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_fiel
from rest_framework import serializers
from rest_framework.request import Request
+from posthog.api.fields import RepeatedOrCommaSeparatedListField
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
@@ -1919,6 +1920,25 @@ class SignalReportsForYouQuerySerializer(serializers.Serializer):
max_value=MAX_FOR_YOU_REPORTS,
help_text=f"How many of the top reports to return, 1 to {MAX_FOR_YOU_REPORTS}. Defaults to 5.",
)
+ offset = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ help_text=(
+ "How many reports of the ranked list to skip, after `exclude` is applied. Pages of the same "
+ "query are slices of one ranked list. Defaults to 0."
+ ),
+ )
+ exclude = RepeatedOrCommaSeparatedListField(
+ child=serializers.UUIDField(),
+ required=False,
+ default=list,
+ max_length=MAX_FOR_YOU_REPORTS,
+ help_text=(
+ "Report ids to leave out of `results` and `count`, for example the reports a briefing already "
+ "shows, as repeated parameters or comma-separated. The other reports keep their order."
+ ),
+ )
include_unowned = serializers.BooleanField(
required=False,
default=True,
@@ -1934,17 +1954,19 @@ class SignalReportsForYouResponseSerializer(serializers.Serializer):
results = SignalReportListSerializer(
many=True,
help_text=(
- "The open, actionable reports that matter most to the current user, best first: reports "
- "waiting for their input, reports they claimed, reports naming them as a reviewer, then P0 "
- "reports that nobody owns unless `include_unowned` is false. The Today briefing ranks "
+ "One page of the open, actionable reports that matter most to the current user. The ranking "
+ "model picks which reports make the page; the page is then in display order: by priority, P0 "
+ "first and reports without a priority last, then best first within a priority. They are "
+ "reports waiting for their input, reports they claimed, reports naming them as a reviewer, "
+ "and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks "
"reports the same way."
),
)
count = serializers.IntegerField(
help_text=(
- "How many open reports are for the current user: the reports in `results`, plus the other "
- "open, actionable reports that name them as a reviewer. Counted over the same set as "
- "`results`, so it follows `include_unowned` too."
+ "How many open, actionable reports are for the current user, on every page together, "
+ "without the `exclude` ids. Counted over the same set as `results`, so it follows "
+ "`include_unowned` too."
),
)
diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.py
index 40fda307936e..72f63475832e 100644
--- a/products/signals/backend/test/test_briefing_reports.py
+++ b/products/signals/backend/test/test_briefing_reports.py
@@ -291,6 +291,32 @@ class TestReportsForBriefing(BaseTest):
assert (top.title, top.relation) == ("Report 5", BriefingReportRelation.SUGGESTED_REVIEWER)
+ def test_the_model_picks_the_reports_and_priority_only_orders_them(self) -> None:
+ for title, priority, pr_merged in [
+ ("A", None, 0.9),
+ ("B", "P3", 0.8),
+ ("C", "P2", 0.7),
+ ("D", None, 0.6),
+ ("E", "P3", 0.5),
+ ("Sixth P1", "P1", 0.1),
+ ]:
+ report = self._named_report(title)
+ self._score(report, pr_merged, readable=True, age=timedelta(hours=1))
+ if priority is not None:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content=json.dumps({"priority": priority}),
+ )
+
+ with patch(SOURCE_PRODUCTS, return_value={}):
+ top = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=5)
+ next_page = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=5, offset=4)
+
+ assert [report.title for report in top] == ["C", "B", "E", "A", "D"]
+ assert [report.title for report in next_page] == ["Sixth P1", "E"]
+
_Spec = tuple[str, BriefingReportRelation, str | None, float | None, float | None, float | None]
WAITING = BriefingReportRelation.WAITING_FOR_YOU
@@ -365,22 +391,7 @@ class TestBriefingPick(SimpleTestCase):
]
)
def test_briefing_pick(self, _name: str, specs: list[_Spec], expected: list[str]) -> None:
- assert [c.report_id for c in _briefing_pick(_candidates(specs), limit=None)] == expected
-
- def test_the_top_n_is_always_the_first_n_of_the_same_list(self) -> None:
- candidates = _candidates(
- [
- ("w1", WAITING, "P2", 0.05, 0.6, None),
- ("w2", WAITING, "P3", None, None, None),
- ("s1", REVIEW, "P3", 0.3, 0.1, None),
- ("s2", REVIEW, "P1", 0.2, None, None),
- ("c1", BriefingReportRelation.CLAIMED, "P4", 0.25, 0.3, None),
- ]
- )
- full = [c.report_id for c in _briefing_pick(candidates, limit=None)]
-
- for limit in range(1, len(candidates) + 1):
- assert [c.report_id for c in _briefing_pick(candidates, limit=limit)] == full[:limit]
+ assert [c.report_id for c in _briefing_pick(_candidates(specs))] == expected
class TestSummaryLead(SimpleTestCase):
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index da4cf261f0a1..087a522be252 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -1612,6 +1612,32 @@ class TestSignalReportListAPI(APIBaseTest):
assert [row["id"] for row in without_unowned.json()["results"]] == [str(mine.id)]
assert without_unowned.json()["count"] == 1
+ def test_for_you_pages_the_ranked_list_without_the_excluded_reports(self):
+ by_priority: dict[str | None, str] = {}
+ for priority in ["P3", None, "P1", "P2"]:
+ report = self._create_report(title=f"Priority {priority}")
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"user_uuid": str(self.user.uuid)}]),
+ )
+ self._priority_artefact(report, priority=priority)
+ by_priority[priority] = str(report.id)
+
+ def for_you(**query: object) -> dict:
+ response = self.client.get(f"{self._list_url()}for_you/?{urlencode(query)}")
+ assert response.status_code == status.HTTP_200_OK
+ return response.json()
+
+ everything = for_you(limit=20)
+ page = for_you(limit=1, offset=1, exclude=f"{by_priority['P1']},{by_priority['P2']}")
+
+ assert [row["id"] for row in everything["results"]] == [by_priority[p] for p in ["P1", "P2", "P3", None]]
+ assert everything["count"] == 4
+ assert [row["id"] for row in page["results"]] == [by_priority[None]]
+ assert page["count"] == 2
+
def test_is_suggested_reviewer_uses_latest_reviewers_row(self):
# suggested_reviewers is append-only: an older row listing the user must not keep them
# flagged after a newer row drops them (latest-wins).
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index e18ff23135bc..3077df35bee2 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2665,35 +2665,36 @@ class SignalReportViewSet(
responses={200: OpenApiResponse(response=SignalReportsForYouResponseSerializer)},
summary="List the reports that matter most to the current user",
description=(
- "The open, actionable reports for the current user, best first, and how many there are in "
- "total. Uses the same ranking and count as the Today briefing, so this is the short list to "
- "show someone who asks what needs them. Pass `include_unowned=false` to leave out the P0 "
- "reports nobody owns, which belong to the project rather than to this person."
+ "One page of the open, actionable reports for the current user, and how many there are in "
+ "total. The ranking picks the page and priority orders it for display. Uses the same ranking and count as the Today briefing, so this is the short "
+ "list to show someone who asks what needs them. Pass `exclude` to leave out reports already "
+ "on screen and `offset` to get the next page. Pass `include_unowned=false` to leave out the "
+ "P0 reports nobody owns, which belong to the project rather than to this person."
),
)
@action(detail=False, methods=["get"], url_path="for_you", required_scopes=["task:read"])
def for_you(self, request: ValidatedRequest, *args, **kwargs) -> Response:
user = cast(User, request.user)
- include_unowned = request.validated_query_data["include_unowned"]
+ query = request.validated_query_data
+ excluded = [str(report_id) for report_id in query["exclude"]]
ranked_ids = [
report.report_id
for report in reports_for_briefing(
team_id=self.team_id,
user_id=user.id,
- limit=request.validated_query_data["limit"],
- include_unowned=include_unowned,
+ limit=query["limit"],
+ include_unowned=query["include_unowned"],
+ offset=query["offset"],
+ exclude_report_ids=excluded,
)
]
by_id = {str(report.id): report for report in self.get_queryset().filter(id__in=ranked_ids)}
reports = [by_id[report_id] for report_id in ranked_ids if report_id in by_id]
- more = open_report_counts(
- team_id=self.team_id,
- user=user,
- exclude_report_ids=[str(report.id) for report in reports],
- include_unowned=include_unowned,
+ counts = open_report_counts(
+ team_id=self.team_id, user=user, exclude_report_ids=excluded, include_unowned=query["include_unowned"]
)
rows = self._render_report_rows(reports, include_source_metadata=True)
- return Response({"results": rows, "count": len(rows) + more.for_person})
+ return Response({"results": rows, "count": counts.for_person})
@extend_schema(
summary="List the org members who can be suggested as reviewers",
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index dec91a1f18e6..225ee020452e 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3229,9 +3229,9 @@ export interface SignalReportBulkStateResponseApi {
}
export interface SignalReportsForYouResponseApi {
- /** The open, actionable reports that matter most to the current user, best first: reports waiting for their input, reports they claimed, reports naming them as a reviewer, then P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
+ /** One page of the open, actionable reports that matter most to the current user. The ranking model picks which reports make the page; the page is then in display order: by priority, P0 first and reports without a priority last, then best first within a priority. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
results: SignalReportListApi[]
- /** How many open reports are for the current user: the reports in `results`, plus the other open, actionable reports that name them as a reviewer. Counted over the same set as `results`, so it follows `include_unowned` too. */
+ /** How many open, actionable reports are for the current user, on every page together, without the `exclude` ids. Counted over the same set as `results`, so it follows `include_unowned` too. */
count: number
}
@@ -7945,6 +7945,11 @@ export type SignalsReportsAvailableReviewersRetrieve200 = {
}
export type SignalsReportsForYouRetrieveParams = {
+ /**
+ * Report ids to leave out of `results` and `count`, for example the reports a briefing already shows, as repeated parameters or comma-separated. The other reports keep their order.
+ * @maxItems 20
+ */
+ exclude?: string[]
/**
* Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, and they rank above everything else, so a surface that only shows a person's own work passes false. Defaults to true.
*/
@@ -7955,6 +7960,11 @@ export type SignalsReportsForYouRetrieveParams = {
* @maximum 20
*/
limit?: number
+ /**
+ * How many reports of the ranked list to skip, after `exclude` is applied. Pages of the same query are slices of one ranked list. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number
}
export type SignalsReportsPrCiStatusesParams = {
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index cb2291e9c26d..a2981c15c40e 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1264,7 +1264,7 @@ export const getSignalsReportsForYouRetrieveUrl = (projectId: string, params?: S
}
/**
- * The open, actionable reports for the current user, best first, and how many there are in total. Uses the same ranking and count as the Today briefing, so this is the short list to show someone who asks what needs them. Pass `include_unowned=false` to leave out the P0 reports nobody owns, which belong to the project rather than to this person.
+ * One page of the open, actionable reports for the current user, and how many there are in total. The ranking picks the page and priority orders it for display. Uses the same ranking and count as the Today briefing, so this is the short list to show someone who asks what needs them. Pass `exclude` to leave out reports already on screen and `offset` to get the next page. Pass `include_unowned=false` to leave out the P0 reports nobody owns, which belong to the project rather than to this person.
* @summary List the reports that matter most to the current user
*/
export const signalsReportsForYouRetrieve = async (
diff --git a/products/today/backend/facade/api.py b/products/today/backend/facade/api.py
index cd47b3475eec..05246c6998df 100644
--- a/products/today/backend/facade/api.py
+++ b/products/today/backend/facade/api.py
@@ -13,6 +13,7 @@ from ..logic import (
briefings,
code_excerpts,
figure_sources,
+ highlights,
report_page as report_pages,
)
from ..logic.jev import GatewayJev
@@ -46,8 +47,9 @@ def refresh_briefing(
def delete_briefings_for_teams(team_ids: list[int]) -> None:
- """Remove every briefing of the given teams. Called from team deletion, which no foreign key covers."""
+ """Remove every briefing and highlights row of the given teams. Called from team deletion, which no foreign key covers."""
briefings.delete_for_teams(team_ids)
+ highlights.delete_for_teams(team_ids)
def list_candidates(*, team: Team, user: User, timezone_name: str | None) -> contracts.CandidateList:
@@ -81,3 +83,7 @@ def report_figure_marks(*, team: Team, user: User, report_id: str) -> list[contr
return None
artefacts = signals.report_agent_texts(team=team, report_id=report_id, types=figure_sources.RESEARCH_TYPES)
return report_pages.figure_marks(page, artefacts, _jev(team, user, figure_sources.FIGURE_MODEL))
+
+
+def get_highlights(*, team: Team, user: User, scopes: frozenset[str] | None) -> contracts.Highlights:
+ return highlights.get_highlights(team=team, user=user, scopes=scopes)
diff --git a/products/today/backend/facade/contracts.py b/products/today/backend/facade/contracts.py
index ce8772fa1288..383c44703ef3 100644
--- a/products/today/backend/facade/contracts.py
+++ b/products/today/backend/facade/contracts.py
@@ -1,5 +1,6 @@
"""Contract types for today: what the product returns to its API, MCP tools and other products."""
+from dataclasses import field
from datetime import date, datetime
from typing import Any
@@ -11,6 +12,11 @@ from .enums import (
CitedSource,
FigureSourceKind,
FigureText,
+ HighlightInterval,
+ HighlightLabel,
+ HighlightPriority,
+ HighlightsStatus,
+ HighlightUnit,
ImpactNumberKey,
ItemGroup,
ItemReason,
@@ -96,6 +102,7 @@ class Briefing:
open_reports_count: int
created_at: datetime
ready_at: datetime | None
+ refresh_at: datetime
@dataclass(frozen=True)
@@ -249,3 +256,48 @@ class FigureMark:
class JevTimedOut(Exception):
pass
+
+
+@dataclass(frozen=True)
+class HighlightValueFormat:
+ format: str | None
+ prefix: str | None
+ postfix: str | None
+ decimal_places: int | None
+
+
+@dataclass(frozen=True)
+class HighlightMetric:
+ key: str
+ name: str
+ value: float
+ unit: HighlightUnit
+ change_pct: float | None
+ series: list[float]
+ interval: HighlightInterval = HighlightInterval.DAY
+ url: str | None = None
+ value_format: HighlightValueFormat | None = None
+ period_starts: list[date] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class HighlightItem:
+ key: str
+ source: str
+ label: HighlightLabel
+ priority: HighlightPriority
+ title: str
+ detail: str
+ url: str | None
+ series: list[float] | None
+ score: float
+
+
+@dataclass(frozen=True)
+class Highlights:
+ status: HighlightsStatus
+ generated_at: datetime | None
+ day: date
+ refresh_at: datetime
+ pulse: list[HighlightMetric]
+ items: list[HighlightItem]
diff --git a/products/today/backend/facade/enums.py b/products/today/backend/facade/enums.py
index 7cfe71dd173d..f5060c0f7642 100644
--- a/products/today/backend/facade/enums.py
+++ b/products/today/backend/facade/enums.py
@@ -87,3 +87,33 @@ class ImpactNumberKey(LabeledStrEnum):
class FigureSourceKind(LabeledStrEnum):
SIGNAL = "signal", "Signal"
RESEARCH = "research", "Agent's research"
+
+
+class HighlightLabel(LabeledStrEnum):
+ RISK = "risk", "Risk"
+ OPPORTUNITY = "opportunity", "Opportunity"
+
+
+class HighlightsStatus(LabeledStrEnum):
+ COMPUTING = "computing", "Computing"
+ READY = "ready", "Ready"
+ FAILED = "failed", "Failed"
+
+
+class HighlightPriority(LabeledStrEnum):
+ P1 = "P1", "P1"
+ P2 = "P2", "P2"
+ P3 = "P3", "P3"
+ P4 = "P4", "P4"
+
+
+class HighlightUnit(LabeledStrEnum):
+ EVENTS = "events", "Events"
+ PEOPLE = "people", "People"
+ NUMBER = "number", "Number"
+
+
+class HighlightInterval(LabeledStrEnum):
+ DAY = "day", "Day"
+ WEEK = "week", "Week"
+ MONTH = "month", "Month"
diff --git a/products/today/backend/facade/temporal.py b/products/today/backend/facade/temporal.py
index 47df689c5380..641df9c399b6 100644
--- a/products/today/backend/facade/temporal.py
+++ b/products/today/backend/facade/temporal.py
@@ -4,9 +4,25 @@ activities and schedule."""
from collections.abc import Callable
from typing import Any
-from ..temporal.activities import mark_failed_activity, start_due_briefings_activity, write_briefing_activity
+from ..temporal.activities import (
+ finalize_highlights_activity,
+ mark_failed_activity,
+ run_highlight_source_activity,
+ start_due_briefings_activity,
+ write_briefing_activity,
+)
from ..temporal.schedule import create_today_briefing_schedule as create_today_briefing_schedule
-from ..temporal.workflows import GenerateTodayBriefingWorkflow, TodayBriefingSchedulerWorkflow
+from ..temporal.workflows import (
+ ComputeTodayHighlightsWorkflow,
+ GenerateTodayBriefingWorkflow,
+ TodayBriefingSchedulerWorkflow,
+)
-WORKFLOWS = [GenerateTodayBriefingWorkflow, TodayBriefingSchedulerWorkflow]
-ACTIVITIES: list[Callable[..., Any]] = [write_briefing_activity, mark_failed_activity, start_due_briefings_activity]
+WORKFLOWS = [GenerateTodayBriefingWorkflow, TodayBriefingSchedulerWorkflow, ComputeTodayHighlightsWorkflow]
+ACTIVITIES: list[Callable[..., Any]] = [
+ write_briefing_activity,
+ mark_failed_activity,
+ start_due_briefings_activity,
+ run_highlight_source_activity,
+ finalize_highlights_activity,
+]
diff --git a/products/today/backend/logic/briefings.py b/products/today/backend/logic/briefings.py
index 2a0d3c7f2f17..af9044135fac 100644
--- a/products/today/backend/logic/briefings.py
+++ b/products/today/backend/logic/briefings.py
@@ -22,7 +22,7 @@ from ..facade.enums import BriefingStatus, BriefingTrigger, BriefingWriter, Item
from ..models import DailyBriefing
from ..temporal.inputs import GENERATE_WORKFLOW_NAME, GenerateBriefingInputs, generate_workflow_id
from .content import BriefingContent
-from .eligibility import briefing_day, resolve_timezone
+from .eligibility import briefing_day, day_start, resolve_timezone
from .fact_sheet import FactSheet, FactSheetItem, stored_fact_sheet
VIEW_STAMP_EVERY = timedelta(hours=1)
@@ -35,6 +35,7 @@ _REPORT_STATES = {
"suppressed": ItemState.DISMISSED,
_DELETED_REPORT_STATUS: ItemState.DISMISSED,
}
+_PRIORITY_RANK = {f"P{number}": number for number in range(5)}
def start_generation(briefing: DailyBriefing) -> None:
@@ -274,6 +275,10 @@ def _report_contract(detail: signals.BriefingReportDetails) -> contracts.Briefin
)
+def _priority_rank(report: contracts.BriefingItemReport | None) -> int:
+ return _PRIORITY_RANK.get((report and report.priority) or "", len(_PRIORITY_RANK))
+
+
def to_contract(
briefing: DailyBriefing,
team: Team,
@@ -284,6 +289,8 @@ def to_contract(
) -> contracts.Briefing:
"""The briefing as the page shows it: only the items the text names, with live states and counts.
+ Items are in display order: by the live priority of their report, then by their rank when written.
+
`status` overrides the row's own: while a newer briefing is being written, the
page gets the last ready one as `writing`, so it keeps showing the text and keeps polling.
`metric_access` is the viewer's access to report metrics, so the briefing hides what the Inbox hides.
@@ -295,6 +302,8 @@ def to_contract(
states = _live_states(reports)
states |= dict.fromkeys(_left_item_keys(team, user, shown, states), ItemState.LEFT)
counts = _inbox_counts(team, user, shown)
+ cards = {key: _report_contract(detail) for key, detail in reports.items()}
+ ordered = sorted(shown, key=lambda item: (_priority_rank(cards.get(item.key)), item.rank))
return contracts.Briefing(
id=str(briefing.id),
status=status or BriefingStatus(briefing.status),
@@ -318,17 +327,18 @@ def to_contract(
label=content.labels.get(item.key) or item.title,
signal=content.signals.get(item.key, ""),
url=item.url,
- rank=item.rank,
+ rank=rank,
state=states.get(item.key, ItemState.OPEN),
source_product=item.source_product,
- report=_report_contract(reports[item.key]) if item.key in reports else None,
+ report=cards.get(item.key),
)
- for item in shown
+ for rank, item in enumerate(ordered, start=1)
],
more_reports_count=counts.more_for_you,
open_reports_count=counts.open_in_project,
created_at=briefing.created_at,
ready_at=briefing.ready_at,
+ refresh_at=day_start(briefing.local_day + timedelta(days=1), resolve_timezone(briefing.timezone, team)),
)
diff --git a/products/today/backend/logic/eligibility.py b/products/today/backend/logic/eligibility.py
index bbc2aec52916..17c481f21d0c 100644
--- a/products/today/backend/logic/eligibility.py
+++ b/products/today/backend/logic/eligibility.py
@@ -1,6 +1,6 @@
"""Which day a briefing belongs to, and when the scheduler starts it."""
-from datetime import date, datetime, timedelta
+from datetime import date, datetime, time, timedelta
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from posthog.models import Team
@@ -27,6 +27,10 @@ def briefing_day(now: datetime, timezone_name: str) -> date:
return (local - timedelta(hours=DAY_START_HOUR)).date()
+def day_start(day: date, timezone_name: str) -> datetime:
+ return datetime.combine(day, time(DAY_START_HOUR), ZoneInfo(timezone_name))
+
+
def due_day(now: datetime, timezone_name: str, window_minutes: int) -> date | None:
"""The briefing day that starts within the next window, so the scheduler can write it before it starts."""
soon = briefing_day(now + timedelta(minutes=window_minutes), timezone_name)
diff --git a/products/today/backend/logic/highlight_registry.py b/products/today/backend/logic/highlight_registry.py
new file mode 100644
index 000000000000..dab386884efa
--- /dev/null
+++ b/products/today/backend/logic/highlight_registry.py
@@ -0,0 +1,15 @@
+import pkgutil
+import importlib
+from functools import cache
+from typing import cast
+
+from . import highlight_sources
+from .highlight_types import Source
+
+
+@cache
+def load_sources() -> tuple[Source, ...]:
+ return tuple(
+ cast(Source, importlib.import_module(f"{highlight_sources.__name__}.{name}").SOURCE)
+ for name in sorted(module.name for module in pkgutil.iter_modules(highlight_sources.__path__))
+ )
diff --git a/products/today/backend/logic/highlight_sources/__init__.py b/products/today/backend/logic/highlight_sources/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/today/backend/logic/highlight_types.py b/products/today/backend/logic/highlight_types.py
new file mode 100644
index 000000000000..3380af22d54a
--- /dev/null
+++ b/products/today/backend/logic/highlight_types.py
@@ -0,0 +1,128 @@
+from collections.abc import Callable
+from datetime import date
+from typing import TypeVar, cast
+
+from django.core.cache import cache
+
+import structlog
+
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team, User
+from posthog.scopes import APIScopeObject, scopes_not_covered
+
+from products.access_control.backend.facade.api import get_restricted_properties_with_group_type_index_for_team
+from products.access_control.backend.facade.property_access import restriction_fingerprint
+from products.access_control.backend.facade.user_access_control import (
+ ACCESS_CONTROL_RESOURCES,
+ RESOURCE_INHERITANCE_MAP,
+ UserAccessControl,
+)
+
+from ..facade import contracts
+from ..facade.enums import HighlightLabel
+
+logger = structlog.get_logger(__name__)
+T = TypeVar("T")
+
+CACHE_SECONDS = 15 * 60
+DAILY_CACHE_SECONDS = 24 * 60 * 60
+DAILY_LOCK_SECONDS = 30
+
+
+class DailyValueNotReady(Exception):
+ pass
+
+
+def property_restrictions(team: Team, user: User) -> str:
+ return restriction_fingerprint(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team.id)
+ )[:16]
+
+
+@frozen
+class Candidate:
+ key: str
+ label: HighlightLabel
+ family: str
+ importance: float
+ relevance: float
+ title: str
+ detail: str
+ url: str | None = None
+ series: list[float] | None = None
+ ref: str | None = None
+ source: str = ""
+
+ @property
+ def score(self) -> float:
+ floor = 0.5 if self.importance >= 0.9 else 0.2
+ return self.importance * (floor + (1 - floor) * self.relevance)
+
+
+@frozen
+class Found:
+ items: tuple[Candidate, ...] = ()
+ pulse: tuple[contracts.HighlightMetric, ...] = ()
+
+
+class Context:
+ def __init__(self, team: Team, user: User, today: date, scopes: frozenset[str] | None = None) -> None:
+ self.team = team
+ self.user = user
+ self.today = today
+ self.scopes = scopes
+ self.failures: list[str] = []
+ self.access = UserAccessControl(user=user, team=team)
+ self.restrictions = property_restrictions(team, user)
+
+ def allows(self, *required: str) -> bool:
+ covered = self.scopes is None or "*" in self.scopes or not scopes_not_covered(self.scopes, required)
+ return covered and all(self._can_view(scope.split(":")[0]) for scope in required)
+
+ def _can_view(self, resource: str) -> bool:
+ governed = RESOURCE_INHERITANCE_MAP.get(cast(APIScopeObject, resource), resource)
+ if governed not in ACCESS_CONTROL_RESOURCES:
+ return True
+ return self.access.check_access_level_for_resource(cast(APIScopeObject, resource), "viewer")
+
+ def daily(self, name: str, compute: Callable[[], T]) -> T:
+ key = f"today_highlights:daily:v1:{self.team.id}:{self.restrictions}:{self.today.isoformat()}:{name}"
+ cached = cache.get(key)
+ if isinstance(cached, tuple):
+ return cast(T, cached[0])
+ lock = f"{key}:lock"
+ if not cache.add(lock, True, DAILY_LOCK_SECONDS):
+ raise DailyValueNotReady(name)
+ try:
+ cached = cache.get(key)
+ if isinstance(cached, tuple):
+ return cast(T, cached[0])
+ value = compute()
+ cache.set(key, (value,), DAILY_CACHE_SECONDS)
+ return value
+ finally:
+ cache.delete(lock)
+
+ def guard(self, name: str, provider: Callable[[], T], default: T) -> T:
+ try:
+ return provider()
+ except DailyValueNotReady:
+ self.failures.append(name)
+ return default
+ except Exception as error:
+ logger.warning("today_highlights_provider_failed", provider=name, team_id=self.team.id, error=str(error))
+ if not isinstance(error, ExposedHogQLError):
+ self.failures.append(name)
+ capture_exception(error, {"provider": name, "team_id": self.team.id})
+ return default
+
+
+@frozen
+class Source:
+ name: str
+ find: Callable[[Context], Found]
+ scopes: tuple[str, ...] = ()
+ pulse_order: int = 0
diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.py
new file mode 100644
index 000000000000..b4ae8ffd6ee2
--- /dev/null
+++ b/products/today/backend/logic/highlights.py
@@ -0,0 +1,233 @@
+import asyncio
+import hashlib
+from collections.abc import Mapping, Sequence
+from contextlib import suppress
+from dataclasses import replace
+from datetime import date, datetime, time, timedelta
+from functools import partial
+
+from django.conf import settings
+from django.core.cache import cache
+from django.utils import timezone
+
+import structlog
+from dateutil.relativedelta import relativedelta
+from pydantic import TypeAdapter, ValidationError
+from temporalio.common import WorkflowIDReusePolicy
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team, User
+from posthog.temporal.common.client import sync_connect
+from posthog.week_start_day import WeekStartDay
+
+from ..facade import contracts
+from ..facade.enums import HighlightInterval, HighlightLabel, HighlightPriority, HighlightsStatus
+from ..models import TodayHighlights
+from ..temporal.inputs import (
+ HIGHLIGHTS_WORKFLOW_NAME,
+ ComputeHighlightsInputs,
+ FinalizeHighlightsInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
+ highlights_workflow_id,
+)
+from .highlight_registry import load_sources
+from .highlight_types import CACHE_SECONDS, Candidate, Context, Found, Source, property_restrictions
+
+logger = structlog.get_logger(__name__)
+
+FAILED_CACHE_SECONDS = 60
+COMPUTING_SECONDS = 2 * 60
+START_LOCK_SECONDS = 30
+MAX_ITEMS = 6
+MAX_PER_FAMILY = 2
+MIN_SCORE = 0.2
+PULSE_TILES = 4
+URGENT_RISK_SCORE = 0.75
+MINOR_OPPORTUNITY_SCORE = 0.4
+
+_FOUND = TypeAdapter(Found)
+_HIGHLIGHTS = TypeAdapter(contracts.Highlights)
+
+
+def get_highlights(*, team: Team, user: User, scopes: frozenset[str] | None) -> contracts.Highlights:
+ now = timezone.now()
+ day = now.astimezone(team.timezone_info).date()
+ key = _key(team, user, scopes)
+ rows = (
+ TodayHighlights.objects.for_team(team.id)
+ .filter(user_id=user.id, key=key, local_day=day)
+ .order_by("-created_at")
+ )
+ latest = rows.first()
+ if latest is None or _is_due(latest, now):
+ _start(team, user, scopes, day, key)
+ status = HighlightsStatus.COMPUTING
+ else:
+ status = HighlightsStatus(latest.status)
+ ready = (
+ latest
+ if latest is not None and latest.status == HighlightsStatus.READY
+ else rows.filter(status=HighlightsStatus.READY).first()
+ )
+ if ready is not None:
+ with suppress(ValidationError):
+ return replace(_HIGHLIGHTS.validate_python(ready.content), status=status)
+ return contracts.Highlights(
+ status=status, generated_at=None, day=day, refresh_at=_refresh_at(team, day), pulse=[], items=[]
+ )
+
+
+def _key(team: Team, user: User, scopes: frozenset[str] | None) -> str:
+ granted = "session" if scopes is None else ",".join(sorted(scopes))
+ return hashlib.sha256(f"{granted}:{property_restrictions(team, user)}".encode()).hexdigest()[:32]
+
+
+def _is_due(row: TodayHighlights, now: datetime) -> bool:
+ if row.status == HighlightsStatus.COMPUTING:
+ return row.created_at < now - timedelta(seconds=COMPUTING_SECONDS)
+ fresh_seconds = FAILED_CACHE_SECONDS if row.failed_sources else CACHE_SECONDS
+ return row.ready_at is None or row.ready_at < now - timedelta(seconds=fresh_seconds)
+
+
+def _start(team: Team, user: User, scopes: frozenset[str] | None, day: date, key: str) -> None:
+ if not cache.add(f"today_highlights:start:{team.id}:{user.id}:{key}:{day.isoformat()}", True, START_LOCK_SECONDS):
+ return
+ row = TodayHighlights.objects.for_team(team.id).create(team_id=team.id, user_id=user.id, local_day=day, key=key)
+ inputs = ComputeHighlightsInputs(
+ team_id=team.id,
+ user_id=user.id,
+ highlights_id=str(row.id),
+ local_day=day.isoformat(),
+ scopes=None if scopes is None else sorted(scopes),
+ source_names=[source.name for source in load_sources()],
+ )
+ try:
+ asyncio.run(
+ sync_connect().start_workflow(
+ HIGHLIGHTS_WORKFLOW_NAME,
+ inputs,
+ id=highlights_workflow_id(team.id, user.id, str(row.id)),
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,
+ )
+ )
+ except Exception as error:
+ logger.exception("today_highlights_start_failed", highlights_id=str(row.id))
+ capture_exception(error, {"highlights_id": str(row.id), "product": "today"})
+
+
+def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:
+ source = next((source for source in load_sources() if source.name == inputs.source_name), None)
+ context = Context(
+ Team.objects.get(id=inputs.team_id),
+ User.objects.get(id=inputs.user_id),
+ date.fromisoformat(inputs.local_day),
+ None if inputs.scopes is None else frozenset(inputs.scopes),
+ )
+ if source is None or not context.allows(*source.scopes):
+ return HighlightSourceResult(source_name=inputs.source_name, found=None, failed=False)
+ with tags_context(product=Product.TODAY, feature=Feature.QUERY, team_id=context.team.id):
+ found = context.guard(source.name, partial(source.find, context), Found())
+ return HighlightSourceResult(
+ source_name=source.name, found=_FOUND.dump_json(found).decode(), failed=bool(context.failures)
+ )
+
+
+def finalize(inputs: FinalizeHighlightsInputs) -> None:
+ row = TodayHighlights.objects.for_team(inputs.team_id).filter(id=inputs.highlights_id).first()
+ if row is None:
+ return
+ found = {result.source_name: _FOUND.validate_json(result.found) for result in inputs.results if result.found}
+ highlights = build_highlights(load_sources(), found, Team.objects.get(id=inputs.team_id), row.local_day)
+ failed = [result for result in inputs.results if result.failed]
+ row.status = HighlightsStatus.FAILED if failed and len(failed) == len(inputs.results) else HighlightsStatus.READY
+ row.content = _HIGHLIGHTS.dump_python(highlights, mode="json")
+ row.failed_sources = bool(failed)
+ row.ready_at = timezone.now()
+ row.save(update_fields=["status", "content", "failed_sources", "ready_at"])
+ if row.status == HighlightsStatus.READY:
+ TodayHighlights.objects.for_team(inputs.team_id).filter(
+ user_id=row.user_id, key=row.key, created_at__lt=row.created_at
+ ).delete()
+
+
+def delete_for_teams(team_ids: list[int]) -> None:
+ TodayHighlights.objects.unscoped().filter(team_id__in=team_ids).delete()
+
+
+def build_highlights(
+ sources: Sequence[Source], found: Mapping[str, Found], team: Team, day: date
+) -> contracts.Highlights:
+ pulse = [
+ metric
+ for source in sorted(sources, key=lambda source: source.pulse_order)
+ if source.name in found
+ for metric in found[source.name].pulse
+ ][:PULSE_TILES]
+ ranked = rank([replace(c, source=name) for name, result in found.items() for c in result.items])
+ return contracts.Highlights(
+ status=HighlightsStatus.READY,
+ generated_at=timezone.now(),
+ day=day,
+ refresh_at=_refresh_at(team, day),
+ pulse=[
+ metric if metric.period_starts else replace(metric, period_starts=_period_starts(metric, team, day))
+ for metric in pulse
+ ],
+ items=sorted((_item(c) for c in ranked), key=lambda item: item.priority),
+ )
+
+
+def _refresh_at(team: Team, day: date) -> datetime:
+ return datetime.combine(day + timedelta(days=1), time.min, team.timezone_info)
+
+
+def _item(candidate: Candidate) -> contracts.HighlightItem:
+ score = round(candidate.score, 3)
+ return contracts.HighlightItem(
+ key=candidate.key,
+ source=candidate.source,
+ label=candidate.label,
+ priority=priority(candidate.label, score),
+ title=candidate.title,
+ detail=candidate.detail,
+ url=candidate.url,
+ series=candidate.series,
+ score=score,
+ )
+
+
+def priority(label: HighlightLabel, score: float) -> HighlightPriority:
+ if label == HighlightLabel.RISK:
+ return HighlightPriority.P1 if score >= URGENT_RISK_SCORE else HighlightPriority.P2
+ return HighlightPriority.P3 if score >= MINOR_OPPORTUNITY_SCORE else HighlightPriority.P4
+
+
+def _period_starts(metric: contracts.HighlightMetric, team: Team, day: date) -> list[date]:
+ back = range(len(metric.series), 0, -1)
+ if metric.interval == HighlightInterval.WEEK:
+ first_weekday = 0 if team.week_start_day == WeekStartDay.MONDAY else 6
+ this_week = day - timedelta(days=(day.weekday() - first_weekday) % 7)
+ return [this_week - timedelta(weeks=weeks) for weeks in back]
+ if metric.interval == HighlightInterval.MONTH:
+ return [day.replace(day=1) - relativedelta(months=months) for months in back]
+ return [day - timedelta(days=days) for days in back]
+
+
+def rank(candidates: list[Candidate]) -> list[Candidate]:
+ shown: list[Candidate] = []
+ for candidate in sorted(candidates, key=lambda c: -c.score):
+ if candidate.score < MIN_SCORE or len(shown) == MAX_ITEMS:
+ break
+ if sum(1 for s in shown if s.family == candidate.family) >= MAX_PER_FAMILY:
+ continue
+ if any(
+ s.family != candidate.family
+ and (s.title == candidate.title or (candidate.ref is not None and s.ref == candidate.ref))
+ for s in shown
+ ):
+ continue
+ shown.append(candidate)
+ return shown
diff --git a/products/today/backend/migrations/0002_todayhighlights.py b/products/today/backend/migrations/0002_todayhighlights.py
new file mode 100644
index 000000000000..78cf6d362d92
--- /dev/null
+++ b/products/today/backend/migrations/0002_todayhighlights.py
@@ -0,0 +1,50 @@
+# Generated by Django 5.2.18 on 2026-10-15 07:54
+
+import django.db.models.manager
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("today", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TodayHighlights",
+ fields=[
+ ("team_id", models.BigIntegerField(db_index=True)),
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("user_id", models.BigIntegerField()),
+ ("local_day", models.DateField()),
+ ("key", models.CharField(max_length=32)),
+ (
+ "status",
+ models.CharField(
+ choices=[("computing", "Computing"), ("ready", "Ready"), ("failed", "Failed")],
+ default="computing",
+ max_length=16,
+ ),
+ ),
+ ("content", models.JSONField(default=dict)),
+ ("failed_sources", models.BooleanField(default=False)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("ready_at", models.DateTimeField(blank=True, null=True)),
+ ],
+ options={
+ "abstract": False,
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(fields=["team_id", "user_id", "key", "-created_at"], name="today_highlights_key_idx")
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/today/backend/migrations/max_migration.txt b/products/today/backend/migrations/max_migration.txt
index cbab66dde92a..30cd33a74558 100644
--- a/products/today/backend/migrations/max_migration.txt
+++ b/products/today/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_todayhighlights
diff --git a/products/today/backend/models.py b/products/today/backend/models.py
index b84ec0012554..1eb84aa2b5c5 100644
--- a/products/today/backend/models.py
+++ b/products/today/backend/models.py
@@ -5,7 +5,7 @@ from django.db import models
from posthog.models.scoping.product_mixin import ProductTeamModel
from posthog.models.utils import uuid7
-from .facade.enums import BriefingStatus, BriefingTrigger, BriefingWriter
+from .facade.enums import BriefingStatus, BriefingTrigger, BriefingWriter, HighlightsStatus
class DailyBriefing(ProductTeamModel):
@@ -51,3 +51,23 @@ class DailyBriefing(ProductTeamModel):
def __str__(self) -> str:
return f"{self.user_id} {self.local_day} {self.status}"
+
+
+class TodayHighlights(ProductTeamModel):
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ user_id = models.BigIntegerField()
+ local_day = models.DateField()
+ key = models.CharField(max_length=32)
+ status = models.CharField(max_length=16, choices=HighlightsStatus.choices, default=HighlightsStatus.COMPUTING.value)
+ content = models.JSONField(default=dict)
+ failed_sources = models.BooleanField(default=False)
+ created_at = models.DateTimeField(auto_now_add=True)
+ ready_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta(ProductTeamModel.Meta):
+ indexes = [
+ models.Index(fields=["team_id", "user_id", "key", "-created_at"], name="today_highlights_key_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.user_id} {self.local_day} {self.status}"
diff --git a/products/today/backend/presentation/serializers.py b/products/today/backend/presentation/serializers.py
index 4b7a8874b69b..616733523a08 100644
--- a/products/today/backend/presentation/serializers.py
+++ b/products/today/backend/presentation/serializers.py
@@ -18,6 +18,10 @@ from ..facade.contracts import (
CodeFile,
FigureMark,
FigureQuote,
+ HighlightItem,
+ HighlightMetric,
+ Highlights,
+ HighlightValueFormat,
ImpactNumber,
ImpactWorking,
KeyClause,
@@ -30,7 +34,18 @@ from ..facade.contracts import (
SignalPreview,
SignalView,
)
-from ..facade.enums import CitedSource, FigureSourceKind, FigureText, ImpactNumberKey, KeyClauseRole
+from ..facade.enums import (
+ CitedSource,
+ FigureSourceKind,
+ FigureText,
+ HighlightInterval,
+ HighlightLabel,
+ HighlightPriority,
+ HighlightsStatus,
+ HighlightUnit,
+ ImpactNumberKey,
+ KeyClauseRole,
+)
class TodayQuerySerializer(serializers.Serializer):
@@ -124,7 +139,7 @@ class BriefingItemSerializer(DataclassSerializer):
help_text="Short fact under the label, at most 40 characters, for example 'Spend down 37%'."
)
url = serializers.CharField(help_text="Where the item opens: an app path, or a GitHub URL for pull requests.")
- rank = serializers.IntegerField(help_text="Position in the briefing, 1 is the top item.")
+ rank = serializers.IntegerField(help_text="Position in `items`, 1 is the first item.")
source_product = serializers.CharField(
allow_null=True,
help_text="For a report, the product its signals came from, for example error_tracking or session_replay. Null for every other item.",
@@ -146,13 +161,17 @@ class BriefingItemSerializer(DataclassSerializer):
class BriefingSerializer(DataclassSerializer):
id = serializers.CharField(help_text="Briefing id.")
local_day = serializers.DateField(help_text="The day this briefing is for, in the person's timezone.")
- headline = serializers.CharField(help_text="One sentence that counts what needs the person.")
+ headline = serializers.CharField(
+ allow_blank=True,
+ help_text="One sentence that counts what needs the person. Empty while the briefing is collecting.",
+ )
paragraphs = serializers.ListField(
child=BriefingSegmentSerializer(many=True),
help_text="Up to 3 paragraphs, each a list of text runs; runs with an item_key are links.",
)
items = BriefingItemSerializer(
- many=True, help_text="The items the text names, in rank order: what the page and the left bar show."
+ many=True,
+ help_text="The items the text names, in display order: by the report's current priority, P0 first and items without one last, then in the order the briefing ranked them.",
)
more_reports_count = serializers.IntegerField(
help_text="Other open reports for the person, beyond the ones the briefing shows."
@@ -160,6 +179,9 @@ class BriefingSerializer(DataclassSerializer):
open_reports_count = serializers.IntegerField(
help_text="Open reports in the whole project beyond the ones the briefing shows, whoever they are for."
)
+ refresh_at = serializers.DateTimeField(
+ help_text="When the next briefing day starts, at 8:00 in the briefing's timezone. Load the briefing again then."
+ )
class Meta:
dataclass = Briefing
@@ -412,3 +434,103 @@ class FigureMarkSerializer(DataclassSerializer):
class FigureMarksSerializer(serializers.Serializer):
marks = FigureMarkSerializer(many=True, help_text="The numbers to mark, at most 4, each with its source.")
+
+
+class HighlightValueFormatSerializer(DataclassSerializer):
+ format = serializers.CharField(
+ allow_null=True, help_text="Number format of the insight, for example numeric, percentage or currency."
+ )
+ prefix = serializers.CharField(allow_null=True, help_text="Text the insight shows before each value.")
+ postfix = serializers.CharField(allow_null=True, help_text="Text the insight shows after each value.")
+ decimal_places = serializers.IntegerField(allow_null=True, help_text="Most decimal places the insight shows.")
+
+ class Meta:
+ dataclass = HighlightValueFormat
+
+
+class HighlightMetricSerializer(DataclassSerializer):
+ key = serializers.CharField(
+ help_text="Stable key of the metric: a key metric setting such as signup_event, or insight:<short_id>."
+ )
+ name = serializers.CharField(help_text="Name of the key metric or of the insight, for example Sign-ups.")
+ value = serializers.FloatField(
+ help_text="Value for the last complete period: the last 7 complete days, or the last complete week or month."
+ )
+ unit = serializers.ChoiceField(
+ choices=HighlightUnit.choices,
+ help_text="`events` for a count of events, `people` for unique people, `number` for an insight value.",
+ )
+ change_pct = serializers.FloatField(
+ allow_null=True,
+ help_text="Change against the period before, in percent. Null when the period before is 0.",
+ )
+ series = serializers.ListField(
+ child=serializers.FloatField(),
+ help_text="Values oldest first: daily for the last 28 complete days, or one value per week or month.",
+ )
+ interval = serializers.ChoiceField(
+ choices=HighlightInterval.choices, help_text="What one value in `series` covers: a day, a week or a month."
+ )
+ url = serializers.CharField(
+ allow_null=True, help_text="Path of the insight the metric comes from. Null for a key metric."
+ )
+ value_format = HighlightValueFormatSerializer(
+ allow_null=True,
+ help_text="How the insight formats its values. Null for a key metric and for an insight with plain numbers.",
+ )
+ period_starts = serializers.ListField(
+ child=serializers.DateField(),
+ help_text="The first day of the period each value in `series` covers, in the project's timezone. Same length and order as `series`.",
+ )
+
+ class Meta:
+ dataclass = HighlightMetric
+
+
+class HighlightItemSerializer(DataclassSerializer):
+ key = serializers.CharField(help_text="Stable key of the item for this person and day.")
+ label = serializers.ChoiceField( # type: ignore[assignment]
+ choices=HighlightLabel.choices,
+ help_text="`risk` when something got worse or broke, `opportunity` when the person can act to gain.",
+ )
+ priority = serializers.ChoiceField(
+ choices=HighlightPriority.choices,
+ help_text="Priority on the same scale as report priorities. `P1` for a risk with a score of 0.75 or more, `P2` for another risk, `P3` for an opportunity with a score of 0.4 or more, `P4` for another opportunity.",
+ )
+ title = serializers.CharField(help_text="One sentence that says what happened, with numbers.")
+ detail = serializers.CharField(help_text="One or two short sentences with the comparison and the next action.")
+ url = serializers.CharField(allow_null=True, help_text="Path in the app to open, relative to the project.")
+ series = serializers.ListField(
+ child=serializers.FloatField(),
+ allow_null=True,
+ help_text="Values behind the item for a small trend line, oldest first. Null when the item has no trend.",
+ )
+ score = serializers.FloatField(help_text="Importance weighted by relevance, from 0 to 1.")
+
+ class Meta:
+ dataclass = HighlightItem
+ extra_kwargs = {
+ "source": {"help_text": "Name of the highlight source that found the item, for example alerts."},
+ }
+
+
+class HighlightsSerializer(DataclassSerializer):
+ status = serializers.ChoiceField(
+ choices=HighlightsStatus.choices,
+ help_text="`ready` when the content is fresh. `computing` while new highlights are being computed: the content is the last ready highlights of the day, or empty, so poll again every 2 seconds until the status changes. `failed` when the last computation failed: the content is the last ready highlights of the day, or empty.",
+ )
+ generated_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the content was computed. Null when no highlights were computed yet today."
+ )
+ day = serializers.DateField(help_text="The day the highlights are for, in the project's timezone.")
+ refresh_at = serializers.DateTimeField(
+ help_text="Midnight at the end of `day` in the project's timezone, when the next day's highlights start. Load them again then."
+ )
+ pulse = HighlightMetricSerializer(many=True, help_text="Key metrics of the project from its settings.")
+ items = HighlightItemSerializer(
+ many=True,
+ help_text="Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first.",
+ )
+
+ class Meta:
+ dataclass = Highlights
diff --git a/products/today/backend/presentation/views.py b/products/today/backend/presentation/views.py
index ca1b24e70bd5..2eb76af821d7 100644
--- a/products/today/backend/presentation/views.py
+++ b/products/today/backend/presentation/views.py
@@ -17,6 +17,7 @@ from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.llm.system_one import SystemOneNotConfigured, SystemOneRequestFailed
from posthog.models import User
+from posthog.permissions import get_authenticator_scopes
from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle
from posthog.utils import UUID_REGEX
@@ -29,6 +30,7 @@ from .serializers import (
ExcerptChoiceRequestSerializer,
ExcerptChoiceSerializer,
FigureMarksSerializer,
+ HighlightsSerializer,
KeyClausesQuerySerializer,
ReportKeyClausesSerializer,
ReportPageSerializer,
@@ -72,7 +74,7 @@ def _jev_errors_as_responses(team_id: int) -> Iterator[None]:
class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "today"
- scope_object_read_actions = ["briefing", "candidates", "excerpt_choice"]
+ scope_object_read_actions = ["briefing", "candidates", "excerpt_choice", "highlights"]
scope_object_write_actions = ["refresh"]
def _user(self) -> User:
@@ -140,6 +142,20 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
return Response(CandidateListSerializer(candidates).data)
+ @validated_request(
+ responses={200: OpenApiResponse(response=HighlightsSerializer)},
+ summary="Get today's highlights",
+ description="The project's key metrics and up to 6 ranked items, each labeled risk or opportunity. Queries, rules and copy templates make every item; no AI is used. The highlights are computed in the background and stay fresh for 15 minutes per person, or 1 minute when a source failed. The call never waits: while they are computed, it returns `computing` with the last ready highlights of the day, so poll every 2 seconds until the status is `ready` or `failed`. 404 when the person does not have the new navigation. A scoped key needs query:read as well, because every highlight runs a query.",
+ )
+ @action(detail=False, methods=["get"], url_path="highlights", required_scopes=["today:read", "query:read"])
+ def highlights(self, request: Request, **kwargs) -> Response:
+ user = cast(User, request.user)
+ if not api.is_enabled_for(user, self.team):
+ raise NotFound()
+ scopes = get_authenticator_scopes(request.successful_authenticator)
+ found = api.get_highlights(team=self.team, user=user, scopes=None if scopes is None else frozenset(scopes))
+ return Response(HighlightsSerializer(found).data)
+
@validated_request(
responses={200: OpenApiResponse(response=ReportPageSerializer)},
summary="Get a report's page",
diff --git a/products/today/backend/temporal/activities.py b/products/today/backend/temporal/activities.py
index 51375cd14a3a..abfaf257a0d5 100644
--- a/products/today/backend/temporal/activities.py
+++ b/products/today/backend/temporal/activities.py
@@ -1,4 +1,4 @@
-"""Temporal activities. Each one only calls logic. Payloads carry ids only."""
+"""Temporal activities. Each one only calls logic. Payloads carry ids and small results only."""
from datetime import datetime, timedelta
@@ -16,13 +16,16 @@ from posthog.temporal.common.heartbeat import Heartbeater
from ..facade.enums import BriefingStatus, BriefingTrigger
from ..feature_flags import may_get_briefing
-from ..logic import generate
+from ..logic import generate, highlights
from ..logic.briefings import create_briefing
from ..logic.eligibility import due_day
from ..models import DailyBriefing
from .inputs import (
GENERATE_WORKFLOW_NAME,
+ FinalizeHighlightsInputs,
GenerateBriefingInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
MarkFailedInputs,
SchedulerInputs,
generate_workflow_id,
@@ -127,3 +130,13 @@ async def start_due_briefings_activity(inputs: SchedulerInputs) -> int:
except WorkflowAlreadyStartedError:
continue
return started
+
+
+async def run_highlight_source_activity(inputs: HighlightSourceInputs) -> HighlightSourceResult:
+ return await database_sync_to_async(highlights.run_source, thread_sensitive=False)(inputs)
+
+
+async def finalize_highlights_activity(inputs: FinalizeHighlightsInputs) -> None:
+ await database_sync_to_async(highlights.finalize, thread_sensitive=False)(inputs)
diff --git a/products/today/backend/temporal/inputs.py b/products/today/backend/temporal/inputs.py
index 342e8680af7f..3493c8446d73 100644
--- a/products/today/backend/temporal/inputs.py
+++ b/products/today/backend/temporal/inputs.py
@@ -4,6 +4,7 @@ import dataclasses
GENERATE_WORKFLOW_NAME = "today-generate-briefing"
SCHEDULER_WORKFLOW_NAME = "today-briefing-scheduler"
+HIGHLIGHTS_WORKFLOW_NAME = "today-compute-highlights"
@dataclasses.dataclass(frozen=True)
@@ -24,5 +25,42 @@ class SchedulerInputs:
pass
[email protected](frozen=True)
+class ComputeHighlightsInputs:
+ team_id: int
+ user_id: int
+ highlights_id: str
+ local_day: str
+ scopes: list[str] | None
+ source_names: list[str]
+
+
[email protected](frozen=True)
+class HighlightSourceInputs:
+ team_id: int
+ user_id: int
+ local_day: str
+ scopes: list[str] | None
+ source_name: str
+
+
[email protected](frozen=True)
+class HighlightSourceResult:
+ source_name: str
+ found: str | None
+ failed: bool
+
+
[email protected](frozen=True)
+class FinalizeHighlightsInputs:
+ team_id: int
+ highlights_id: str
+ results: list[HighlightSourceResult]
+
+
def generate_workflow_id(briefing_id: str) -> str:
return f"today-briefing-{briefing_id}"
+
+
+def highlights_workflow_id(team_id: int, user_id: int, highlights_id: str) -> str:
+ return f"today-highlights-{team_id}-{user_id}-{highlights_id}"
diff --git a/products/today/backend/temporal/workflows.py b/products/today/backend/temporal/workflows.py
index c58070ae8d8e..691d48ebe0be 100644
--- a/products/today/backend/temporal/workflows.py
+++ b/products/today/backend/temporal/workflows.py
@@ -1,5 +1,6 @@
-"""Temporal workflows: generate one briefing, and start the scheduled ones before 8:00 local time."""
+"""Temporal workflows: generate one briefing, start the scheduled ones before 8:00 local time, and compute highlights."""
+import asyncio
from datetime import timedelta
import temporalio.common
@@ -10,17 +11,30 @@ from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
from ..logic.generate import ATTEMPT_TIMEOUT, ATTEMPTS, RETRY_INTERVAL, RUN_TIMEOUT
- from .activities import mark_failed_activity, start_due_briefings_activity, write_briefing_activity
+ from .activities import (
+ finalize_highlights_activity,
+ mark_failed_activity,
+ run_highlight_source_activity,
+ start_due_briefings_activity,
+ write_briefing_activity,
+ )
from .inputs import (
GENERATE_WORKFLOW_NAME,
+ HIGHLIGHTS_WORKFLOW_NAME,
SCHEDULER_WORKFLOW_NAME,
+ ComputeHighlightsInputs,
+ FinalizeHighlightsInputs,
GenerateBriefingInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
MarkFailedInputs,
SchedulerInputs,
)
MARK_FAILED_TIMEOUT = timedelta(seconds=30)
SCHEDULER_TIMEOUT = timedelta(minutes=10)
+HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=30)
+FINALIZE_HIGHLIGHTS_TIMEOUT = timedelta(seconds=30)
def _error_message(error: Exception) -> str:
@@ -66,3 +80,36 @@ class TodayBriefingSchedulerWorkflow(PostHogWorkflow):
start_to_close_timeout=SCHEDULER_TIMEOUT,
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=2),
)
+
+
[email protected](name=HIGHLIGHTS_WORKFLOW_NAME)
+class ComputeTodayHighlightsWorkflow(PostHogWorkflow):
+ inputs_cls = ComputeHighlightsInputs
+
+ @temporalio.workflow.run
+ async def run(self, inputs: ComputeHighlightsInputs) -> None:
+ results = await asyncio.gather(*(_run_source(inputs, name) for name in inputs.source_names))
+ await temporalio.workflow.execute_activity(
+ finalize_highlights_activity,
+ FinalizeHighlightsInputs(team_id=inputs.team_id, highlights_id=inputs.highlights_id, results=list(results)),
+ start_to_close_timeout=FINALIZE_HIGHLIGHTS_TIMEOUT,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+
+
+async def _run_source(inputs: ComputeHighlightsInputs, source_name: str) -> HighlightSourceResult:
+ try:
+ return await temporalio.workflow.execute_activity(
+ run_highlight_source_activity,
+ HighlightSourceInputs(
+ team_id=inputs.team_id,
+ user_id=inputs.user_id,
+ local_day=inputs.local_day,
+ scopes=inputs.scopes,
+ source_name=source_name,
+ ),
+ start_to_close_timeout=HIGHLIGHT_SOURCE_TIMEOUT,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=2),
+ )
+ except ActivityError:
+ return HighlightSourceResult(source_name=source_name, found=None, failed=True)
diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.py
index 1ecbd608e5cc..d9b56fc5f7ad 100644
--- a/products/today/backend/tests/test_api.py
+++ b/products/today/backend/tests/test_api.py
@@ -1,6 +1,7 @@
import json
from dataclasses import replace
from datetime import UTC, datetime
+from typing import TYPE_CHECKING
import time_machine
from posthog.test.base import APIBaseTest
@@ -27,13 +28,23 @@ from products.access_control.backend.models.access_control import AccessControl
from products.signals.backend.facade import api as signals
from products.signals.backend.models import SignalReport
from products.today.backend.facade.enums import BriefingStatus, BriefingTrigger
-from products.today.backend.logic import briefings
+from products.today.backend.logic import briefings, highlights
+from products.today.backend.logic.highlight_types import Found, Source
from products.today.backend.logic.jev import JevPick
from products.today.backend.models import DailyBriefing
+from products.today.backend.temporal.inputs import (
+ ComputeHighlightsInputs,
+ FinalizeHighlightsInputs,
+ HighlightSourceInputs,
+)
from products.today.backend.tests.conftest import TodayTeamScopedTestMixin
from products.today.backend.tests.factories import AGREEING, FakeJev, SameAnswerJev, page_source
+from products.today.backend.tests.test_highlights import candidate, metric
from products.today.backend.tests.test_key_clauses import CART_TEXT, CAUSE, CAUSE_EXPLAINED, SUMMARY
+if TYPE_CHECKING:
+ from rest_framework.response import _MonkeyPatchedResponse
+
REPORT_ID = "01a10212-6f09-0000-0ed6-46b2df6f81ca"
FIGURE_LEAD = "🚨 The export failed for 212 users."
FIGURE_SOURCE = "On Monday 🚨 the export failed for 212 users."
@@ -125,6 +136,10 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
assert early["local_day"] == "2026-09-29"
assert today["local_day"] == "2026-09-30"
+ assert [datetime.fromisoformat(briefing["refresh_at"]) for briefing in (early, today)] == [
+ datetime(2026, 9, 30, 6, 0, tzinfo=UTC),
+ datetime(2026, 10, 1, 6, 0, tzinfo=UTC),
+ ]
assert early["id"] != today["id"]
assert without_timezone["id"] == early["id"]
assert sync_connect.return_value.start_workflow.call_count == 2
@@ -372,14 +387,33 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("the page with only today", "get", "page", ["today:read"], status.HTTP_403_FORBIDDEN),
- ("the page with today and signals", "get", "page", ["today:read", "task:read"], status.HTTP_200_OK),
- ("key clauses with only today", "get", "key_clauses", ["today:read"], status.HTTP_403_FORBIDDEN),
- ("figure marks with only today", "get", "figure_marks", ["today:read"], status.HTTP_403_FORBIDDEN),
+ ("the page with only today", "get", f"reports/{REPORT_ID}/page", ["today:read"], status.HTTP_403_FORBIDDEN),
+ (
+ "the page with today and signals",
+ "get",
+ f"reports/{REPORT_ID}/page",
+ ["today:read", "task:read"],
+ status.HTTP_200_OK,
+ ),
+ (
+ "key clauses with only today",
+ "get",
+ f"reports/{REPORT_ID}/key_clauses",
+ ["today:read"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "figure marks with only today",
+ "get",
+ f"reports/{REPORT_ID}/figure_marks",
+ ["today:read"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ ("highlights with only today", "get", "highlights", ["today:read"], status.HTTP_403_FORBIDDEN),
]
)
- def test_a_scoped_key_reads_report_data_only_with_the_signals_scope(
- self, _sync_connect: MagicMock, _name: str, method: str, endpoint: str, scopes: list[str], expected: int
+ def test_a_scoped_key_reads_data_only_with_its_underlying_scope(
+ self, _sync_connect: MagicMock, _name: str, method: str, path: str, scopes: list[str], expected: int
) -> None:
raw_key = "today_report_page_key"
PersonalAPIKey.objects.create(
@@ -391,7 +425,7 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),
):
response = getattr(self.client, method)(
- f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/{endpoint}/",
+ f"/api/projects/{self.team.id}/today/{path}/",
HTTP_AUTHORIZATION=f"Bearer {raw_key}",
)
@@ -444,3 +478,77 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{report.id}/page/")
assert response.status_code == status.HTTP_404_NOT_FOUND
+
+
+def _temporal() -> MagicMock:
+ connect = MagicMock()
+ connect.return_value.start_workflow = AsyncMock()
+ return connect
+
+
+class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
+ def _get(self, connect: MagicMock, flag: bool = True) -> "_MonkeyPatchedResponse":
+ source = Source(
+ name="alerts", find=lambda _c: Found(items=(candidate("alert:1", "alerts", 0.8),), pulse=(metric("k1"),))
+ )
+ with (
+ patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=flag),
+ patch.object(highlights, "load_sources", return_value=(source,)),
+ patch.object(highlights, "sync_connect", connect),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/today/highlights/")
+ if response.status_code == status.HTTP_200_OK and connect.return_value.start_workflow.called:
+ inputs: ComputeHighlightsInputs = connect.return_value.start_workflow.call_args.args[1]
+ results = [
+ highlights.run_source(
+ HighlightSourceInputs(
+ team_id=inputs.team_id,
+ user_id=inputs.user_id,
+ local_day=inputs.local_day,
+ scopes=inputs.scopes,
+ source_name=name,
+ )
+ )
+ for name in inputs.source_names
+ ]
+ highlights.finalize(
+ FinalizeHighlightsInputs(
+ team_id=inputs.team_id, highlights_id=inputs.highlights_id, results=results
+ )
+ )
+ return response
+
+ @parameterized.expand([("flag on", True, status.HTTP_200_OK), ("flag off", False, status.HTTP_404_NOT_FOUND)])
+ def test_highlights_need_the_flag_but_not_ai(self, _name: str, flag: bool, expected: int) -> None:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ cache.clear()
+
+ response = self._get(_temporal(), flag)
+
+ self.assertEqual(response.status_code, expected)
+
+ @time_machine.travel(datetime(2026, 10, 13, 12, 0, tzinfo=UTC), tick=False)
+ def test_the_first_call_starts_the_computation_and_a_later_call_serves_its_result(self) -> None:
+ cache.clear()
+ connect = _temporal()
+
+ first = self._get(_temporal()).json()
+ second = self._get(connect).json()
+
+ self.assertEqual(
+ (
+ (first["status"], first["generated_at"], first["pulse"], first["items"]),
+ second["status"],
+ [(m["key"], m["interval"], m["value_format"], len(m["period_starts"])) for m in second["pulse"]],
+ [(i["key"], i["source"], i["label"], i["priority"], i["series"]) for i in second["items"]],
+ connect.return_value.start_workflow.called,
+ ),
+ (
+ ("computing", None, [], []),
+ "ready",
+ [("k1", "day", None, 1)],
+ [("alert:1", "alerts", "risk", "P1", None)],
+ False,
+ ),
+ )
diff --git a/products/today/backend/tests/test_briefing_items.py b/products/today/backend/tests/test_briefing_items.py
index cd3699e92db4..65fc0ee58d03 100644
--- a/products/today/backend/tests/test_briefing_items.py
+++ b/products/today/backend/tests/test_briefing_items.py
@@ -8,6 +8,7 @@ from django.test import SimpleTestCase
from posthog.models import Team, User
from products.signals.backend.facade import api as signals
+from products.today.backend.facade import contracts
from products.today.backend.facade.enums import BriefingStatus, ItemGroup, ItemReason, ItemSource, ItemState
from products.today.backend.logic import briefings
from products.today.backend.logic.fact_sheet import FactSheet, FactSheetItem
@@ -20,7 +21,7 @@ MISSING_REPORT = uuid.UUID("00000000-0000-4000-8000-000000000004")
DELETED_REPORT = uuid.UUID("00000000-0000-4000-8000-000000000005")
-def _item(report_id: uuid.UUID) -> FactSheetItem:
+def _item(report_id: uuid.UUID, rank: int = 1) -> FactSheetItem:
return FactSheetItem(
key=f"report:{report_id}",
group=ItemGroup.REPORT,
@@ -28,16 +29,18 @@ def _item(report_id: uuid.UUID) -> FactSheetItem:
reason=ItemReason.WAITING_FOR_YOU,
title=str(report_id),
url="/project/1/inbox",
- rank=1,
+ rank=rank,
facts={},
)
-def _report_details(report_id: uuid.UUID, status: str) -> signals.BriefingReportDetails:
+def _report_details(
+ report_id: uuid.UUID, status: str = "ready", priority: str | None = "P1"
+) -> signals.BriefingReportDetails:
return signals.BriefingReportDetails(
report_id=str(report_id),
status=status,
- priority="P1",
+ priority=priority,
summary="Checkout fails for some users",
pull_request_state="merged",
pull_request_url="https://github.com/example/app/pull/1",
@@ -60,45 +63,46 @@ def _report_details(report_id: uuid.UUID, status: str) -> signals.BriefingReport
)
+def _contract(items: list[FactSheetItem], details: list[signals.BriefingReportDetails]) -> contracts.Briefing:
+ briefing = DailyBriefing(
+ id=uuid.uuid4(),
+ team_id=1,
+ user_id=1,
+ local_day=date(2026, 10, 1),
+ status=BriefingStatus.READY,
+ facts=FactSheet(items=items).model_dump(mode="json"),
+ content={},
+ created_at=datetime(2026, 10, 1, 6, 0, tzinfo=UTC),
+ )
+ with (
+ patch.object(briefings.signals, "report_details", return_value=details),
+ patch.object(
+ briefings.signals,
+ "open_report_counts",
+ return_value=signals.OpenReportCounts(for_person=0, in_project=0),
+ ),
+ ):
+ return briefings.to_contract(briefing, Team(id=1), User(id=1), metric_access=MagicMock())
+
+
class TestBriefingItemStates(SimpleTestCase):
def test_items_show_what_was_resolved_or_dismissed_since_the_briefing_was_written(self) -> None:
- items = [
- _item(RESOLVED_REPORT),
- _item(DISMISSED_REPORT),
- _item(OPEN_REPORT),
- _item(MISSING_REPORT),
- _item(DELETED_REPORT),
- ]
- briefing = DailyBriefing(
- id=uuid.uuid4(),
- team_id=1,
- user_id=1,
- local_day=date(2026, 10, 1),
- status=BriefingStatus.READY,
- facts=FactSheet(items=items).model_dump(mode="json"),
- content={},
- created_at=datetime(2026, 10, 1, 6, 0, tzinfo=UTC),
+ contract = _contract(
+ [
+ _item(RESOLVED_REPORT),
+ _item(DISMISSED_REPORT),
+ _item(OPEN_REPORT),
+ _item(MISSING_REPORT),
+ _item(DELETED_REPORT),
+ ],
+ [
+ _report_details(RESOLVED_REPORT, "resolved"),
+ _report_details(DISMISSED_REPORT, "suppressed"),
+ _report_details(OPEN_REPORT, "ready"),
+ _report_details(DELETED_REPORT, "deleted"),
+ ],
)
- with (
- patch.object(
- briefings.signals,
- "report_details",
- return_value=[
- _report_details(RESOLVED_REPORT, "resolved"),
- _report_details(DISMISSED_REPORT, "suppressed"),
- _report_details(OPEN_REPORT, "ready"),
- _report_details(DELETED_REPORT, "deleted"),
- ],
- ),
- patch.object(
- briefings.signals,
- "open_report_counts",
- return_value=signals.OpenReportCounts(for_person=0, in_project=0),
- ),
- ):
- contract = briefings.to_contract(briefing, Team(id=1), User(id=1), metric_access=MagicMock())
-
assert {item.key: item.state for item in contract.items} == {
f"report:{RESOLVED_REPORT}": ItemState.DONE,
f"report:{DISMISSED_REPORT}": ItemState.DISMISSED,
@@ -115,3 +119,15 @@ class TestBriefingItemStates(SimpleTestCase):
)
reports_without_details = [item.key for item in contract.items if item.report is None]
assert reports_without_details == [f"report:{MISSING_REPORT}", f"report:{DELETED_REPORT}"]
+
+ def test_items_follow_the_live_priority_of_their_report_then_the_written_rank(self) -> None:
+ contract = _contract(
+ [_item(MISSING_REPORT, rank=1), _item(OPEN_REPORT, rank=2), _item(RESOLVED_REPORT, rank=3)],
+ [_report_details(OPEN_REPORT, priority="P2"), _report_details(RESOLVED_REPORT, priority="P0")],
+ )
+
+ assert [(item.key, item.rank) for item in contract.items] == [
+ (f"report:{RESOLVED_REPORT}", 1),
+ (f"report:{OPEN_REPORT}", 2),
+ (f"report:{MISSING_REPORT}", 3),
+ ]
diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.py
new file mode 100644
index 000000000000..74d69868d566
--- /dev/null
+++ b/products/today/backend/tests/test_highlights.py
@@ -0,0 +1,400 @@
+from dataclasses import replace
+from datetime import UTC, date, datetime, timedelta
+from functools import partial
+from typing import Any
+from zoneinfo import ZoneInfo
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+from pydantic import TypeAdapter
+
+from posthog.constants import AvailableFeature
+from posthog.models import Team, User
+
+from products.access_control.backend.facade.testing import create_access_control
+from products.today.backend.facade import contracts
+from products.today.backend.facade.enums import (
+ HighlightInterval,
+ HighlightLabel,
+ HighlightPriority,
+ HighlightsStatus,
+ HighlightUnit,
+)
+from products.today.backend.logic import highlight_types, highlights
+from products.today.backend.logic.highlight_types import Candidate, Context, Found, Source
+from products.today.backend.logic.highlights import MAX_ITEMS, rank
+from products.today.backend.models import TodayHighlights
+from products.today.backend.temporal.inputs import (
+ FinalizeHighlightsInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
+)
+
+DAY = date(2026, 10, 13)
+FOUND = TypeAdapter(Found)
+HIGHLIGHTS = TypeAdapter(contracts.Highlights)
+
+
+def candidate(key: str, family: str, importance: float, title: str | None = None, ref: str | None = None) -> Candidate:
+ return Candidate(
+ key=key,
+ label=HighlightLabel.RISK,
+ family=family,
+ importance=importance,
+ relevance=1.0,
+ title=title or key,
+ detail="",
+ ref=ref,
+ )
+
+
+def metric(key: str) -> contracts.HighlightMetric:
+ return contracts.HighlightMetric(
+ key=key, name=key, value=1.0, unit=HighlightUnit.EVENTS, change_pct=None, series=[1.0]
+ )
+
+
+ALERT_RESULT = HighlightSourceResult(
+ source_name="alerts",
+ found=FOUND.dump_json(Found(items=(candidate("alert", "alerts", 0.8),))).decode(),
+ failed=False,
+)
+FAILED_RESULT = HighlightSourceResult(source_name="errors", found=None, failed=True)
+READY_CONTENT = HIGHLIGHTS.dump_python(
+ contracts.Highlights(
+ status=HighlightsStatus.READY,
+ generated_at=datetime(2026, 10, 13, 11, 0, tzinfo=UTC),
+ day=DAY,
+ refresh_at=datetime(2026, 10, 14, tzinfo=UTC),
+ pulse=[metric("k1")],
+ items=[],
+ ),
+ mode="json",
+)
+
+
+class TestHighlightRanking(SimpleTestCase):
+ def test_one_family_cannot_fill_the_list(self) -> None:
+ ranked = rank([candidate(f"flag {i}", "flags", 0.9) for i in range(5)] + [candidate("alert", "alerts", 0.5)])
+ self.assertEqual([c.family for c in ranked], ["flags", "flags", "alerts"])
+
+ def test_the_list_keeps_the_highest_scores_and_drops_weak_items(self) -> None:
+ candidates = [candidate(f"item {i}", f"family {i}", 0.9 - i * 0.05) for i in range(8)]
+ candidates.append(candidate("weak", "weak", 0.1))
+ ranked = rank(candidates)
+ self.assertEqual(len(ranked), MAX_ITEMS)
+ self.assertEqual([c.key for c in ranked], [f"item {i}" for i in range(MAX_ITEMS)])
+
+ @parameterized.expand(
+ [
+ ("title", {"title": "Postgres sync failed once in the last 7 days"}),
+ ("reference", {"ref": "insight-abc"}),
+ ]
+ )
+ def test_a_repeated_title_or_reference_is_dropped_only_across_families(
+ self, _name: str, shared: dict[str, str]
+ ) -> None:
+ ranked = rank(
+ [
+ candidate("first", "alerts", 0.75, **shared),
+ candidate("second", "alerts", 0.74, **shared),
+ candidate("other area", "home", 0.7, **shared),
+ ]
+ )
+ self.assertEqual([c.key for c in ranked], ["first", "second"])
+
+ @parameterized.expand(
+ [
+ ("urgent risk", HighlightLabel.RISK, 0.75, HighlightPriority.P1),
+ ("risk", HighlightLabel.RISK, 0.749, HighlightPriority.P2),
+ ("opportunity", HighlightLabel.OPPORTUNITY, 0.4, HighlightPriority.P3),
+ ("minor opportunity", HighlightLabel.OPPORTUNITY, 0.399, HighlightPriority.P4),
+ ]
+ )
+ def test_priority_follows_the_label_and_the_score(
+ self, _name: str, label: HighlightLabel, score: float, expected: HighlightPriority
+ ) -> None:
+ self.assertEqual(highlights.priority(label, score), expected)
+
+
+class TestBuildHighlights(SimpleTestCase):
+ def test_the_pulse_follows_the_source_order_and_the_items_follow_priority(self) -> None:
+ sources = (
+ Source(name="key_metrics", find=lambda _c: Found(), pulse_order=2),
+ Source(name="routine", find=lambda _c: Found(), pulse_order=1),
+ Source(name="experiments", find=lambda _c: Found()),
+ Source(name="alerts", find=lambda _c: Found()),
+ )
+ found = {
+ "key_metrics": Found(pulse=(metric("k1"), metric("k2"), metric("k3"))),
+ "routine": Found(pulse=(metric("r1"), metric("r2"))),
+ "experiments": Found(
+ items=(replace(candidate("win", "experiments", 0.9), label=HighlightLabel.OPPORTUNITY),)
+ ),
+ "alerts": Found(items=(candidate("alert", "alerts", 0.5),)),
+ }
+
+ built = highlights.build_highlights(sources, found, Team(timezone="Europe/Prague"), DAY)
+
+ self.assertEqual(
+ (
+ [m.key for m in built.pulse],
+ [(i.key, i.source, i.priority) for i in built.items],
+ built.day,
+ built.refresh_at,
+ ),
+ (
+ ["r1", "r2", "k1", "k2"],
+ [("alert", "alerts", HighlightPriority.P2), ("win", "experiments", HighlightPriority.P3)],
+ DAY,
+ datetime(2026, 10, 14, tzinfo=ZoneInfo("Europe/Prague")),
+ ),
+ )
+
+ @parameterized.expand(
+ [
+ ("days", HighlightInterval.DAY, None, 3, [date(2026, 10, 10), date(2026, 10, 11), date(2026, 10, 12)]),
+ ("weeks from Sunday", HighlightInterval.WEEK, None, 2, [date(2026, 9, 27), date(2026, 10, 4)]),
+ ("weeks from Monday", HighlightInterval.WEEK, 1, 2, [date(2026, 9, 28), date(2026, 10, 5)]),
+ ("months", HighlightInterval.MONTH, None, 2, [date(2026, 8, 1), date(2026, 9, 1)]),
+ ]
+ )
+ def test_each_pulse_value_gets_the_start_of_its_complete_period(
+ self, _name: str, interval: HighlightInterval, week_start_day: int | None, count: int, expected: list[date]
+ ) -> None:
+ tile = replace(metric("k"), series=[1.0] * count, interval=interval)
+ source = Source(name="metrics", find=lambda _c: Found())
+
+ built = highlights.build_highlights(
+ (source,), {"metrics": Found(pulse=(tile,))}, Team(week_start_day=week_start_day), DAY
+ )
+
+ self.assertEqual(built.pulse[0].period_starts, expected)
+
+
+class TestRunSource(BaseTest):
+ def _run(self, source: Source, user: User | None = None, scopes: list[str] | None = None) -> HighlightSourceResult:
+ inputs = HighlightSourceInputs(
+ team_id=self.team.id,
+ user_id=(user or self.user).id,
+ local_day=DAY.isoformat(),
+ scopes=scopes,
+ source_name=source.name,
+ )
+ with patch.object(highlights, "load_sources", return_value=(source,)):
+ return highlights.run_source(inputs)
+
+ @parameterized.expand(
+ [
+ ("a session", None, True),
+ ("a key without the scope", ["query:read", "today:read"], False),
+ ("a key with the write scope", ["alert:write"], True),
+ ("a key with every scope", ["*"], True),
+ ]
+ )
+ def test_a_source_runs_only_when_the_credential_covers_its_scopes(
+ self, _name: str, scopes: list[str] | None, runs: bool
+ ) -> None:
+ source = Source(
+ name="alerts", find=lambda _c: Found(items=(candidate("alert", "alerts", 0.8),)), scopes=("alert:read",)
+ )
+
+ result = self._run(source, scopes=scopes)
+
+ self.assertEqual((result.found is not None, result.failed), (runs, False))
+
+ @parameterized.expand(
+ [
+ ("no rule", "error_tracking", None, True),
+ ("viewer", "error_tracking", "viewer", True),
+ ("no access", "error_tracking", "none", False),
+ ("no access to the parent of a child resource", "warehouse_objects", "none", False),
+ ]
+ )
+ def test_a_source_runs_only_when_the_person_can_view_its_resource(
+ self, _name: str, resource: str, access_level: str | None, runs: bool
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ if access_level:
+ create_access_control(team_id=self.team.id, resource=resource, access_level=access_level)
+ source = Source(
+ name="errors",
+ find=lambda _c: Found(items=(candidate("error", "errors", 0.8),)),
+ scopes=("warehouse_view:read",) if resource == "warehouse_objects" else ("error_tracking:read",),
+ )
+
+ result = self._run(source, user=self._create_user("[email protected]"))
+
+ self.assertEqual(result.found is not None, runs)
+
+ def test_a_broken_source_reports_a_failure_instead_of_raising(self) -> None:
+ def broken(_context: Context) -> Found:
+ raise ValueError("boom")
+
+ result = self._run(Source(name="broken", find=broken))
+
+ self.assertEqual((result.failed, FOUND.validate_json(result.found or "")), (True, Found()))
+
+
+class TestFinalizeHighlights(BaseTest):
+ @parameterized.expand(
+ [
+ ("one source failed", [ALERT_RESULT, FAILED_RESULT], HighlightsStatus.READY, ["alert"], False),
+ ("every source failed", [FAILED_RESULT], HighlightsStatus.FAILED, [], True),
+ ]
+ )
+ def test_a_ready_computation_replaces_the_older_rows(
+ self,
+ _name: str,
+ results: list[HighlightSourceResult],
+ status: HighlightsStatus,
+ items: list[str],
+ keeps_older: bool,
+ ) -> None:
+ rows = TodayHighlights.objects.for_team(self.team.id)
+ older = rows.create(team_id=self.team.id, user_id=self.user.id, local_day=DAY, key="k")
+ rows.filter(id=older.id).update(created_at=older.created_at - timedelta(minutes=20))
+ computing = rows.create(team_id=self.team.id, user_id=self.user.id, local_day=DAY, key="k")
+
+ highlights.finalize(
+ FinalizeHighlightsInputs(team_id=self.team.id, highlights_id=str(computing.id), results=results)
+ )
+
+ computing.refresh_from_db()
+ content = HIGHLIGHTS.validate_python(computing.content)
+ self.assertEqual(
+ (
+ computing.status,
+ computing.failed_sources,
+ [i.key for i in content.items],
+ rows.filter(id=older.id).exists(),
+ ),
+ (status, True, items, keeps_older),
+ )
+
+
+@time_machine.travel(datetime(2026, 10, 13, 12, 0, tzinfo=UTC), tick=False)
+class TestGetHighlights(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ @parameterized.expand(
+ [
+ ("nothing yet", None, HighlightsStatus.COMPUTING, 1, []),
+ (
+ "a fresh ready row",
+ {"status": HighlightsStatus.READY, "ready_at": timedelta(minutes=1)},
+ HighlightsStatus.READY,
+ 0,
+ ["k1"],
+ ),
+ ("a recent computing row", {"created_at": timedelta(minutes=1)}, HighlightsStatus.COMPUTING, 0, []),
+ ("a lost computing row", {"created_at": timedelta(minutes=5)}, HighlightsStatus.COMPUTING, 1, []),
+ (
+ "a stale ready row",
+ {"status": HighlightsStatus.READY, "ready_at": timedelta(minutes=20)},
+ HighlightsStatus.COMPUTING,
+ 1,
+ ["k1"],
+ ),
+ (
+ "a ready row with a failed source",
+ {"status": HighlightsStatus.READY, "ready_at": timedelta(minutes=2), "failed_sources": True},
+ HighlightsStatus.COMPUTING,
+ 1,
+ ["k1"],
+ ),
+ (
+ "a fresh failure",
+ {"status": HighlightsStatus.FAILED, "ready_at": timedelta(seconds=30), "failed_sources": True},
+ HighlightsStatus.FAILED,
+ 0,
+ [],
+ ),
+ (
+ "a ready row from yesterday",
+ {"status": HighlightsStatus.READY, "ready_at": timedelta(minutes=1), "local_day": date(2026, 10, 12)},
+ HighlightsStatus.COMPUTING,
+ 1,
+ [],
+ ),
+ ]
+ )
+ def test_the_request_never_waits_for_a_computation(
+ self,
+ _name: str,
+ row: dict[str, Any] | None,
+ status: HighlightsStatus,
+ starts: int,
+ pulse: list[str],
+ ) -> None:
+ connect = MagicMock()
+ connect.return_value.start_workflow = AsyncMock()
+ with patch.object(highlights, "sync_connect", connect):
+ if row is not None:
+ highlights.get_highlights(team=self.team, user=self.user, scopes=None)
+ now = timezone.now()
+ TodayHighlights.objects.for_team(self.team.id).update(
+ content=READY_CONTENT,
+ **{name: now - value if isinstance(value, timedelta) else value for name, value in row.items()},
+ )
+ connect.return_value.start_workflow.reset_mock()
+ cache.clear()
+ found = highlights.get_highlights(team=self.team, user=self.user, scopes=None)
+
+ self.assertEqual(
+ (found.status, connect.return_value.start_workflow.call_count, [m.key for m in found.pulse]),
+ (status, starts, pulse),
+ )
+
+
+class TestDailyCache(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _context(self) -> Context:
+ return Context(self.team, self.user, date(2026, 10, 13))
+
+ @parameterized.expand([("a value", False, 1), ("an error", True, 2)])
+ def test_a_daily_value_is_computed_once_unless_computing_it_raises(
+ self, _name: str, fails: bool, computes: int
+ ) -> None:
+ calls: list[int] = []
+
+ def compute() -> int:
+ calls.append(1)
+ if fails:
+ raise ValueError("boom")
+ return 7
+
+ for context in (self._context(), self._context()):
+ context.guard("value", partial(context.daily, "value", compute), 0)
+
+ self.assertEqual(len(calls), computes)
+
+ def test_a_request_skips_a_daily_value_another_request_is_computing(self) -> None:
+ context = self._context()
+ key = f"today_highlights:daily:v1:{self.team.id}:{context.restrictions}:2026-10-13:value"
+ cache.add(f"{key}:lock", True, 60)
+ calls: list[int] = []
+
+ def compute() -> int:
+ calls.append(1)
+ return 7
+
+ with patch.object(highlight_types, "capture_exception") as captured:
+ found = context.guard("value", lambda: context.daily("value", compute), 0)
+
+ self.assertEqual((found, calls, context.failures, captured.call_count), (0, [], ["value"], 0))
diff --git a/products/today/backend/tests/test_workflows.py b/products/today/backend/tests/test_workflows.py
index 3b4d25f6c835..9dd511c17ae3 100644
--- a/products/today/backend/tests/test_workflows.py
+++ b/products/today/backend/tests/test_workflows.py
@@ -12,8 +12,17 @@ from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from products.today.backend.logic.generate import ATTEMPTS
-from products.today.backend.temporal.inputs import GENERATE_WORKFLOW_NAME, GenerateBriefingInputs, MarkFailedInputs
-from products.today.backend.temporal.workflows import GenerateTodayBriefingWorkflow
+from products.today.backend.temporal.inputs import (
+ GENERATE_WORKFLOW_NAME,
+ HIGHLIGHTS_WORKFLOW_NAME,
+ ComputeHighlightsInputs,
+ FinalizeHighlightsInputs,
+ GenerateBriefingInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
+ MarkFailedInputs,
+)
+from products.today.backend.temporal.workflows import ComputeTodayHighlightsWorkflow, GenerateTodayBriefingWorkflow
@pytest_asyncio.fixture(scope="module")
@@ -55,3 +64,48 @@ async def test_a_failing_attempt_is_retried_then_marks_the_briefing_failed_once(
assert attempts == ATTEMPTS
assert [failed.error for failed in marked_failed] == ["The LLM reply was not a briefing."]
+
+
+async def test_a_source_that_keeps_failing_is_finalized_as_failed_with_the_others(
+ environment: WorkflowEnvironment,
+) -> None:
+ finalized: list[FinalizeHighlightsInputs] = []
+
+ @activity.defn(name="run_highlight_source_activity")
+ async def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:
+ if inputs.source_name == "broken":
+ raise ApplicationError("The source query failed.")
+ return HighlightSourceResult(source_name=inputs.source_name, found="{}", failed=False)
+
+ @activity.defn(name="finalize_highlights_activity")
+ async def finalize(inputs: FinalizeHighlightsInputs) -> None:
+ finalized.append(inputs)
+
+ async with Worker(
+ environment.client,
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ workflows=[ComputeTodayHighlightsWorkflow],
+ activities=[run_source, finalize],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ await environment.client.execute_workflow(
+ HIGHLIGHTS_WORKFLOW_NAME,
+ ComputeHighlightsInputs(
+ team_id=1,
+ user_id=2,
+ highlights_id="h-1",
+ local_day="2026-10-13",
+ scopes=None,
+ source_names=["alerts", "broken"],
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ )
+
+ assert [inputs.results for inputs in finalized] == [
+ [
+ HighlightSourceResult(source_name="alerts", found="{}", failed=False),
+ HighlightSourceResult(source_name="broken", found=None, failed=True),
+ ]
+ ]
diff --git a/products/today/frontend/generated/api.schemas.ts b/products/today/frontend/generated/api.schemas.ts
index caa4eb9157b8..ddaa57a4d1b1 100644
--- a/products/today/frontend/generated/api.schemas.ts
+++ b/products/today/frontend/generated/api.schemas.ts
@@ -263,7 +263,7 @@ export interface BriefingItemApi {
signal: string
/** Where the item opens: an app path, or a GitHub URL for pull requests. */
url: string
- /** Position in the briefing, 1 is the top item. */
+ /** Position in `items`, 1 is the first item. */
rank: number
/**
* For a report, the product its signals came from, for example error_tracking or session_replay. Null for every other item.
@@ -313,16 +313,18 @@ export interface BriefingApi {
id: string
/** The day this briefing is for, in the person's timezone. */
local_day: string
- /** One sentence that counts what needs the person. */
+ /** One sentence that counts what needs the person. Empty while the briefing is collecting. */
headline: string
/** Up to 3 paragraphs, each a list of text runs; runs with an item_key are links. */
paragraphs: BriefingSegmentApi[][]
- /** The items the text names, in rank order: what the page and the left bar show. */
+ /** The items the text names, in display order: by the report's current priority, P0 first and items without one last, then in the order the briefing ranked them. */
items: BriefingItemApi[]
/** Other open reports for the person, beyond the ones the briefing shows. */
more_reports_count: number
/** Open reports in the whole project beyond the ones the briefing shows, whoever they are for. */
open_reports_count: number
+ /** When the next briefing day starts, at 8:00 in the briefing's timezone. Load the briefing again then. */
+ refresh_at: string
status: BriefingStatusEnumApi
writer: WriterEnumApi | null
created_at: string
@@ -385,6 +387,188 @@ export interface ExcerptChoiceApi {
index: number | null
}
+/**
+ * * `computing` - Computing
+ * * `ready` - Ready
+ * * `failed` - Failed
+ */
+export type HighlightsStatusEnumApi = (typeof HighlightsStatusEnumApi)[keyof typeof HighlightsStatusEnumApi]
+
+export const HighlightsStatusEnumApi = {
+ Computing: 'computing',
+ Ready: 'ready',
+ Failed: 'failed',
+} as const
+
+/**
+ * * `events` - Events
+ * * `people` - People
+ * * `number` - Number
+ */
+export type HighlightUnitEnumApi = (typeof HighlightUnitEnumApi)[keyof typeof HighlightUnitEnumApi]
+
+export const HighlightUnitEnumApi = {
+ Events: 'events',
+ People: 'people',
+ Number: 'number',
+} as const
+
+/**
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month
+ */
+export type CalendarUnitEnumApi = (typeof CalendarUnitEnumApi)[keyof typeof CalendarUnitEnumApi]
+
+export const CalendarUnitEnumApi = {
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+} as const
+
+export interface HighlightValueFormatApi {
+ /**
+ * Number format of the insight, for example numeric, percentage or currency.
+ * @nullable
+ */
+ format: string | null
+ /**
+ * Text the insight shows before each value.
+ * @nullable
+ */
+ prefix: string | null
+ /**
+ * Text the insight shows after each value.
+ * @nullable
+ */
+ postfix: string | null
+ /**
+ * Most decimal places the insight shows.
+ * @nullable
+ */
+ decimal_places: number | null
+}
+
+export interface HighlightMetricApi {
+ /** Stable key of the metric: a key metric setting such as signup_event, or insight:<short_id>. */
+ key: string
+ /** Name of the key metric or of the insight, for example Sign-ups. */
+ name: string
+ /** Value for the last complete period: the last 7 complete days, or the last complete week or month. */
+ value: number
+ /** `events` for a count of events, `people` for unique people, `number` for an insight value.
+ *
+ * * `events` - Events
+ * * `people` - People
+ * * `number` - Number */
+ unit: HighlightUnitEnumApi
+ /**
+ * Change against the period before, in percent. Null when the period before is 0.
+ * @nullable
+ */
+ change_pct: number | null
+ /** Values oldest first: daily for the last 28 complete days, or one value per week or month. */
+ series: number[]
+ /** What one value in `series` covers: a day, a week or a month.
+ *
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: CalendarUnitEnumApi
+ /**
+ * Path of the insight the metric comes from. Null for a key metric.
+ * @nullable
+ */
+ url: string | null
+ /** How the insight formats its values. Null for a key metric and for an insight with plain numbers. */
+ value_format: HighlightValueFormatApi | null
+ /** The first day of the period each value in `series` covers, in the project's timezone. Same length and order as `series`. */
+ period_starts: string[]
+}
+
+/**
+ * * `risk` - Risk
+ * * `opportunity` - Opportunity
+ */
+export type HighlightLabelEnumApi = (typeof HighlightLabelEnumApi)[keyof typeof HighlightLabelEnumApi]
+
+export const HighlightLabelEnumApi = {
+ Risk: 'risk',
+ Opportunity: 'opportunity',
+} as const
+
+/**
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4
+ */
+export type HighlightPriorityEnumApi = (typeof HighlightPriorityEnumApi)[keyof typeof HighlightPriorityEnumApi]
+
+export const HighlightPriorityEnumApi = {
+ P1: 'P1',
+ P2: 'P2',
+ P3: 'P3',
+ P4: 'P4',
+} as const
+
+export interface HighlightItemApi {
+ /** Stable key of the item for this person and day. */
+ key: string
+ /** `risk` when something got worse or broke, `opportunity` when the person can act to gain.
+ *
+ * * `risk` - Risk
+ * * `opportunity` - Opportunity */
+ label: HighlightLabelEnumApi
+ /** Priority on the same scale as report priorities. `P1` for a risk with a score of 0.75 or more, `P2` for another risk, `P3` for an opportunity with a score of 0.4 or more, `P4` for another opportunity.
+ *
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ priority: HighlightPriorityEnumApi
+ /** One sentence that says what happened, with numbers. */
+ title: string
+ /** One or two short sentences with the comparison and the next action. */
+ detail: string
+ /**
+ * Path in the app to open, relative to the project.
+ * @nullable
+ */
+ url: string | null
+ /**
+ * Values behind the item for a small trend line, oldest first. Null when the item has no trend.
+ * @nullable
+ */
+ series: number[] | null
+ /** Importance weighted by relevance, from 0 to 1. */
+ score: number
+ /** Name of the highlight source that found the item, for example alerts. */
+ source: string
+}
+
+export interface HighlightsApi {
+ /** `ready` when the content is fresh. `computing` while new highlights are being computed: the content is the last ready highlights of the day, or empty, so poll again every 2 seconds until the status changes. `failed` when the last computation failed: the content is the last ready highlights of the day, or empty.
+ *
+ * * `computing` - Computing
+ * * `ready` - Ready
+ * * `failed` - Failed */
+ status: HighlightsStatusEnumApi
+ /**
+ * When the content was computed. Null when no highlights were computed yet today.
+ * @nullable
+ */
+ generated_at: string | null
+ /** The day the highlights are for, in the project's timezone. */
+ day: string
+ /** Midnight at the end of `day` in the project's timezone, when the next day's highlights start. Load them again then. */
+ refresh_at: string
+ /** Key metrics of the project from its settings. */
+ pulse: HighlightMetricApi[]
+ /** Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first. */
+ items: HighlightItemApi[]
+}
+
/**
* * `lead` - Lead
* * `impact` - Impact
diff --git a/products/today/frontend/generated/api.ts b/products/today/frontend/generated/api.ts
index 5587036f2b87..94a0c5cf442c 100644
--- a/products/today/frontend/generated/api.ts
+++ b/products/today/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
ExcerptChoiceApi,
ExcerptChoiceRequestApi,
FigureMarksApi,
+ HighlightsApi,
ReportKeyClausesApi,
ReportPageApi,
TodayBriefingRefreshCreateParams,
@@ -136,6 +137,21 @@ export const todayExcerptChoiceCreate = async (
})
}
+export const getTodayHighlightsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/today/highlights/`
+}
+
+/**
+ * The project's key metrics and up to 6 ranked items, each labeled risk or opportunity. Queries, rules and copy templates make every item; no AI is used. The highlights are computed in the background and stay fresh for 15 minutes per person, or 1 minute when a source failed. The call never waits: while they are computed, it returns `computing` with the last ready highlights of the day, so poll every 2 seconds until the status is `ready` or `failed`. 404 when the person does not have the new navigation. A scoped key needs query:read as well, because every highlight runs a query.
+ * @summary Get today's highlights
+ */
+export const todayHighlightsRetrieve = async (projectId: string, options?: RequestInit): Promise<HighlightsApi> => {
+ return apiMutator<HighlightsApi>(getTodayHighlightsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTodayReportsFigureMarksRetrieveUrl = (projectId: string, reportId: string) => {
return `/api/projects/${projectId}/today/reports/${reportId}/figure_marks/`
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6f75dc1145f7..45c9ccfb7a46 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19135,7 +19135,7 @@ export namespace Schemas {
signal: string;
/** Where the item opens: an app path, or a GitHub URL for pull requests. */
url: string;
- /** Position in the briefing, 1 is the top item. */
+ /** Position in `items`, 1 is the first item. */
rank: number;
/**
* For a report, the product its signals came from, for example error_tracking or session_replay. Null for every other item.
@@ -19187,16 +19187,18 @@ export namespace Schemas {
id: string;
/** The day this briefing is for, in the person's timezone. */
local_day: string;
- /** One sentence that counts what needs the person. */
+ /** One sentence that counts what needs the person. Empty while the briefing is collecting. */
headline: string;
/** Up to 3 paragraphs, each a list of text runs; runs with an item_key are links. */
paragraphs: BriefingSegment[][];
- /** The items the text names, in rank order: what the page and the left bar show. */
+ /** The items the text names, in display order: by the report's current priority, P0 first and items without one last, then in the order the briefing ranked them. */
items: BriefingItem[];
/** Other open reports for the person, beyond the ones the briefing shows. */
more_reports_count: number;
/** Open reports in the whole project beyond the ones the briefing shows, whoever they are for. */
open_reports_count: number;
+ /** When the next briefing day starts, at 8:00 in the briefing's timezone. Load the briefing again then. */
+ refresh_at: string;
status: BriefingStatusEnum;
writer: WriterEnum | null;
created_at: string;
@@ -54952,6 +54954,179 @@ export namespace Schemas {
AnyUser: 'any-user',
} as const;
+ /**
+ * * `risk` - Risk
+ * * `opportunity` - Opportunity
+ */
+ export type HighlightLabelEnum = typeof HighlightLabelEnum[keyof typeof HighlightLabelEnum];
+
+
+ export const HighlightLabelEnum = {
+ Risk: 'risk',
+ Opportunity: 'opportunity',
+ } as const;
+
+ /**
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4
+ */
+ export type HighlightPriorityEnum = typeof HighlightPriorityEnum[keyof typeof HighlightPriorityEnum];
+
+
+ export const HighlightPriorityEnum = {
+ P1: 'P1',
+ P2: 'P2',
+ P3: 'P3',
+ P4: 'P4',
+ } as const;
+
+ export interface HighlightItem {
+ /** Stable key of the item for this person and day. */
+ key: string;
+ /** `risk` when something got worse or broke, `opportunity` when the person can act to gain.
+ *
+ * * `risk` - Risk
+ * * `opportunity` - Opportunity */
+ label: HighlightLabelEnum;
+ /** Priority on the same scale as report priorities. `P1` for a risk with a score of 0.75 or more, `P2` for another risk, `P3` for an opportunity with a score of 0.4 or more, `P4` for another opportunity.
+ *
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ priority: HighlightPriorityEnum;
+ /** One sentence that says what happened, with numbers. */
+ title: string;
+ /** One or two short sentences with the comparison and the next action. */
+ detail: string;
+ /**
+ * Path in the app to open, relative to the project.
+ * @nullable
+ */
+ url: string | null;
+ /**
+ * Values behind the item for a small trend line, oldest first. Null when the item has no trend.
+ * @nullable
+ */
+ series: number[] | null;
+ /** Importance weighted by relevance, from 0 to 1. */
+ score: number;
+ /** Name of the highlight source that found the item, for example alerts. */
+ source: string;
+ }
+
+ /**
+ * * `events` - Events
+ * * `people` - People
+ * * `number` - Number
+ */
+ export type HighlightUnitEnum = typeof HighlightUnitEnum[keyof typeof HighlightUnitEnum];
+
+
+ export const HighlightUnitEnum = {
+ Events: 'events',
+ People: 'people',
+ Number: 'number',
+ } as const;
+
+ export interface HighlightValueFormat {
+ /**
+ * Number format of the insight, for example numeric, percentage or currency.
+ * @nullable
+ */
+ format: string | null;
+ /**
+ * Text the insight shows before each value.
+ * @nullable
+ */
+ prefix: string | null;
+ /**
+ * Text the insight shows after each value.
+ * @nullable
+ */
+ postfix: string | null;
+ /**
+ * Most decimal places the insight shows.
+ * @nullable
+ */
+ decimal_places: number | null;
+ }
+
+ export interface HighlightMetric {
+ /** Stable key of the metric: a key metric setting such as signup_event, or insight:<short_id>. */
+ key: string;
+ /** Name of the key metric or of the insight, for example Sign-ups. */
+ name: string;
+ /** Value for the last complete period: the last 7 complete days, or the last complete week or month. */
+ value: number;
+ /** `events` for a count of events, `people` for unique people, `number` for an insight value.
+ *
+ * * `events` - Events
+ * * `people` - People
+ * * `number` - Number */
+ unit: HighlightUnitEnum;
+ /**
+ * Change against the period before, in percent. Null when the period before is 0.
+ * @nullable
+ */
+ change_pct: number | null;
+ /** Values oldest first: daily for the last 28 complete days, or one value per week or month. */
+ series: number[];
+ /** What one value in `series` covers: a day, a week or a month.
+ *
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: CalendarUnitEnum;
+ /**
+ * Path of the insight the metric comes from. Null for a key metric.
+ * @nullable
+ */
+ url: string | null;
+ /** How the insight formats its values. Null for a key metric and for an insight with plain numbers. */
+ value_format: HighlightValueFormat | null;
+ /** The first day of the period each value in `series` covers, in the project's timezone. Same length and order as `series`. */
+ period_starts: string[];
+ }
+
+ /**
+ * * `computing` - Computing
+ * * `ready` - Ready
+ * * `failed` - Failed
+ */
+ export type HighlightsStatusEnum = typeof HighlightsStatusEnum[keyof typeof HighlightsStatusEnum];
+
+
+ export const HighlightsStatusEnum = {
+ Computing: 'computing',
+ Ready: 'ready',
+ Failed: 'failed',
+ } as const;
+
+ export interface Highlights {
+ /** `ready` when the content is fresh. `computing` while new highlights are being computed: the content is the last ready highlights of the day, or empty, so poll again every 2 seconds until the status changes. `failed` when the last computation failed: the content is the last ready highlights of the day, or empty.
+ *
+ * * `computing` - Computing
+ * * `ready` - Ready
+ * * `failed` - Failed */
+ status: HighlightsStatusEnum;
+ /**
+ * When the content was computed. Null when no highlights were computed yet today.
+ * @nullable
+ */
+ generated_at: string | null;
+ /** The day the highlights are for, in the project's timezone. */
+ day: string;
+ /** Midnight at the end of `day` in the project's timezone, when the next day's highlights start. Load them again then. */
+ refresh_at: string;
+ /** Key metrics of the project from its settings. */
+ pulse: HighlightMetric[];
+ /** Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first. */
+ items: HighlightItem[];
+ }
+
/**
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
@@ -101898,9 +102073,9 @@ export namespace Schemas {
}
export interface SignalReportsForYouResponse {
- /** The open, actionable reports that matter most to the current user, best first: reports waiting for their input, reports they claimed, reports naming them as a reviewer, then P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
+ /** One page of the open, actionable reports that matter most to the current user. The ranking model picks which reports make the page; the page is then in display order: by priority, P0 first and reports without a priority last, then best first within a priority. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
results: SignalReportList[];
- /** How many open reports are for the current user: the reports in `results`, plus the other open, actionable reports that name them as a reviewer. Counted over the same set as `results`, so it follows `include_unowned` too. */
+ /** How many open, actionable reports are for the current user, on every page together, without the `exclude` ids. Counted over the same set as `results`, so it follows `include_unowned` too. */
count: number;
}
@@ -129446,6 +129621,11 @@ export namespace Schemas {
}};
export type SignalsReportsForYouRetrieveParams = {
+ /**
+ * Report ids to leave out of `results` and `count`, for example the reports a briefing already shows, as repeated parameters or comma-separated. The other reports keep their order.
+ * @maxItems 20
+ */
+ exclude?: string[];
/**
* Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, and they rank above everything else, so a surface that only shows a person's own work passes false. Defaults to true.
*/
@@ -129456,6 +129636,11 @@ export namespace Schemas {
* @maximum 20
*/
limit?: number;
+ /**
+ * How many reports of the ranked list to skip, after `exclude` is applied. Pages of the same query are slices of one ranked list. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number;
};
export type SignalsReportsPrCiStatusesParams = {
diff --git a/tach.toml b/tach.toml
index 2a7cb8c245f7..d9fee748bbab 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1636,6 +1636,7 @@ path = "products.today"
depends_on = [
"ee",
"posthog",
+ "products.access_control",
"products.signals",
"products.tasks",
]